text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as Platform from '../platform/platform.js';
import * as Root from '../root/root.js';
export class ParsedURL {
isValid: boolean;
url: string;
scheme: string;
user: string;
host: string;
port: string;
path: string;
queryParams: string;
fragment: string;
folderPathComponents: string;
lastPathComponent: string;
readonly blobInnerScheme: string|undefined;
#displayNameInternal?: string;
#dataURLDisplayNameInternal?: string;
constructor(url: string) {
this.isValid = false;
this.url = url;
this.scheme = '';
this.user = '';
this.host = '';
this.port = '';
this.path = '';
this.queryParams = '';
this.fragment = '';
this.folderPathComponents = '';
this.lastPathComponent = '';
const isBlobUrl = this.url.startsWith('blob:');
const urlToMatch = isBlobUrl ? url.substring(5) : url;
const match = urlToMatch.match(ParsedURL.urlRegex());
if (match) {
this.isValid = true;
if (isBlobUrl) {
this.blobInnerScheme = match[2].toLowerCase();
this.scheme = 'blob';
} else {
this.scheme = match[2].toLowerCase();
}
this.user = match[3];
this.host = match[4];
this.port = match[5];
this.path = match[6] || '/';
this.queryParams = match[7] || '';
this.fragment = match[8];
} else {
if (this.url.startsWith('data:')) {
this.scheme = 'data';
return;
}
if (this.url.startsWith('blob:')) {
this.scheme = 'blob';
return;
}
if (this.url === 'about:blank') {
this.scheme = 'about';
return;
}
this.path = this.url;
}
const lastSlashIndex = this.path.lastIndexOf('/');
if (lastSlashIndex !== -1) {
this.folderPathComponents = this.path.substring(0, lastSlashIndex);
this.lastPathComponent = this.path.substring(lastSlashIndex + 1);
} else {
this.lastPathComponent = this.path;
}
}
static fromString(string: string): ParsedURL|null {
const parsedURL = new ParsedURL(string.toString());
if (parsedURL.isValid) {
return parsedURL;
}
return null;
}
static rawPathToUrlString(fileSystemPath: Platform.DevToolsPath.RawPathString): Platform.DevToolsPath.UrlString {
let rawPath: string = fileSystemPath;
rawPath = rawPath.replace(/\\/g, '/');
if (!rawPath.startsWith('file://')) {
if (rawPath.startsWith('/')) {
rawPath = 'file://' + rawPath;
} else {
rawPath = 'file:///' + rawPath;
}
}
return rawPath as Platform.DevToolsPath.UrlString;
}
static capFilePrefix(fileURL: Platform.DevToolsPath.RawPathString, isWindows?: boolean):
Platform.DevToolsPath.RawPathString {
console.assert(fileURL.startsWith('file://'), 'This must be a file URL.');
if (isWindows) {
return fileURL.substr('file:///'.length).replace(/\//g, '\\') as Platform.DevToolsPath.RawPathString;
}
return fileURL.substr('file://'.length) as Platform.DevToolsPath.RawPathString;
}
static urlWithoutHash(url: string): string {
const hashIndex = url.indexOf('#');
if (hashIndex !== -1) {
return url.substr(0, hashIndex);
}
return url;
}
static urlRegex(): RegExp {
if (ParsedURL.urlRegexInstance) {
return ParsedURL.urlRegexInstance;
}
// RegExp groups:
// 1 - scheme, hostname, ?port
// 2 - scheme (using the RFC3986 grammar)
// 3 - ?user:password
// 4 - hostname
// 5 - ?port
// 6 - ?path
// 7 - ?query
// 8 - ?fragment
const schemeRegex = /([A-Za-z][A-Za-z0-9+.-]*):\/\//;
const userRegex = /(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;
const hostRegex = /((?:\[::\d?\])|(?:[^\s\/:]*))/;
const portRegex = /(?::([\d]+))?/;
const pathRegex = /(\/[^#?]*)?/;
const queryRegex = /(?:\?([^#]*))?/;
const fragmentRegex = /(?:#(.*))?/;
ParsedURL.urlRegexInstance = new RegExp(
'^(' + schemeRegex.source + userRegex.source + hostRegex.source + portRegex.source + ')' + pathRegex.source +
queryRegex.source + fragmentRegex.source + '$');
return ParsedURL.urlRegexInstance;
}
static extractPath(url: string): string {
const parsedURL = this.fromString(url);
return parsedURL ? parsedURL.path : '';
}
static extractOrigin(url: string): string {
const parsedURL = this.fromString(url);
return parsedURL ? parsedURL.securityOrigin() : '';
}
static extractExtension(url: string): string {
url = ParsedURL.urlWithoutHash(url);
const indexOfQuestionMark = url.indexOf('?');
if (indexOfQuestionMark !== -1) {
url = url.substr(0, indexOfQuestionMark);
}
const lastIndexOfSlash = url.lastIndexOf('/');
if (lastIndexOfSlash !== -1) {
url = url.substr(lastIndexOfSlash + 1);
}
const lastIndexOfDot = url.lastIndexOf('.');
if (lastIndexOfDot !== -1) {
url = url.substr(lastIndexOfDot + 1);
const lastIndexOfPercent = url.indexOf('%');
if (lastIndexOfPercent !== -1) {
return url.substr(0, lastIndexOfPercent);
}
return url;
}
return '';
}
static extractName(url: string): string {
let index = url.lastIndexOf('/');
const pathAndQuery = index !== -1 ? url.substr(index + 1) : url;
index = pathAndQuery.indexOf('?');
return index < 0 ? pathAndQuery : pathAndQuery.substr(0, index);
}
static completeURL(baseURL: string, href: string): string|null {
// Return special URLs as-is.
const trimmedHref = href.trim();
if (trimmedHref.startsWith('data:') || trimmedHref.startsWith('blob:') || trimmedHref.startsWith('javascript:') ||
trimmedHref.startsWith('mailto:')) {
return href;
}
// Return absolute URLs as-is.
const parsedHref = this.fromString(trimmedHref);
if (parsedHref && parsedHref.scheme) {
return trimmedHref;
}
const parsedURL = this.fromString(baseURL);
if (!parsedURL) {
return null;
}
if (parsedURL.isDataURL()) {
return href;
}
if (href.length > 1 && href.charAt(0) === '/' && href.charAt(1) === '/') {
// href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
return parsedURL.scheme + ':' + href;
}
const securityOrigin = parsedURL.securityOrigin();
const pathText = parsedURL.path;
const queryText = parsedURL.queryParams ? '?' + parsedURL.queryParams : '';
// Empty href resolves to a URL without fragment.
if (!href.length) {
return securityOrigin + pathText + queryText;
}
if (href.charAt(0) === '#') {
return securityOrigin + pathText + queryText + href;
}
if (href.charAt(0) === '?') {
return securityOrigin + pathText + href;
}
const hrefMatches = href.match(/^[^#?]*/);
if (!hrefMatches || !href.length) {
throw new Error('Invalid href');
}
let hrefPath: string = hrefMatches[0];
const hrefSuffix = href.substring(hrefPath.length);
if (hrefPath.charAt(0) !== '/') {
hrefPath = parsedURL.folderPathComponents + '/' + hrefPath;
}
return securityOrigin + Root.Runtime.Runtime.normalizePath(hrefPath) + hrefSuffix;
}
static splitLineAndColumn(string: string): {
url: string,
lineNumber: (number|undefined),
columnNumber: (number|undefined),
} {
// Only look for line and column numbers in the path to avoid matching port numbers.
const beforePathMatch = string.match(ParsedURL.urlRegex());
let beforePath = '';
let pathAndAfter: string = string;
if (beforePathMatch) {
beforePath = beforePathMatch[1];
pathAndAfter = string.substring(beforePathMatch[1].length);
}
const lineColumnRegEx = /(?::(\d+))?(?::(\d+))?$/;
const lineColumnMatch = lineColumnRegEx.exec(pathAndAfter);
let lineNumber;
let columnNumber;
console.assert(Boolean(lineColumnMatch));
if (!lineColumnMatch) {
return {url: string, lineNumber: 0, columnNumber: 0};
}
if (typeof (lineColumnMatch[1]) === 'string') {
lineNumber = parseInt(lineColumnMatch[1], 10);
// Immediately convert line and column to 0-based numbers.
lineNumber = isNaN(lineNumber) ? undefined : lineNumber - 1;
}
if (typeof (lineColumnMatch[2]) === 'string') {
columnNumber = parseInt(lineColumnMatch[2], 10);
columnNumber = isNaN(columnNumber) ? undefined : columnNumber - 1;
}
let url: string = beforePath + pathAndAfter.substring(0, pathAndAfter.length - lineColumnMatch[0].length);
if (lineColumnMatch[1] === undefined && lineColumnMatch[2] === undefined) {
const wasmCodeOffsetRegex = /wasm-function\[\d+\]:0x([a-z0-9]+)$/g;
const wasmCodeOffsetMatch = wasmCodeOffsetRegex.exec(pathAndAfter);
if (wasmCodeOffsetMatch && typeof (wasmCodeOffsetMatch[1]) === 'string') {
url = ParsedURL.removeWasmFunctionInfoFromURL(url);
columnNumber = parseInt(wasmCodeOffsetMatch[1], 16);
columnNumber = isNaN(columnNumber) ? undefined : columnNumber;
}
}
return {url, lineNumber, columnNumber};
}
static removeWasmFunctionInfoFromURL(url: string): string {
const wasmFunctionRegEx = /:wasm-function\[\d+\]/;
const wasmFunctionIndex = url.search(wasmFunctionRegEx);
if (wasmFunctionIndex === -1) {
return url;
}
return url.substring(0, wasmFunctionIndex);
}
static isRelativeURL(url: string): boolean {
return !(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));
}
get displayName(): string {
if (this.#displayNameInternal) {
return this.#displayNameInternal;
}
if (this.isDataURL()) {
return this.dataURLDisplayName();
}
if (this.isBlobURL()) {
return this.url;
}
if (this.isAboutBlank()) {
return this.url;
}
this.#displayNameInternal = this.lastPathComponent;
if (!this.#displayNameInternal) {
this.#displayNameInternal = (this.host || '') + '/';
}
if (this.#displayNameInternal === '/') {
this.#displayNameInternal = this.url;
}
return this.#displayNameInternal;
}
dataURLDisplayName(): string {
if (this.#dataURLDisplayNameInternal) {
return this.#dataURLDisplayNameInternal;
}
if (!this.isDataURL()) {
return '';
}
this.#dataURLDisplayNameInternal = Platform.StringUtilities.trimEndWithMaxLength(this.url, 20);
return this.#dataURLDisplayNameInternal;
}
isAboutBlank(): boolean {
return this.url === 'about:blank';
}
isDataURL(): boolean {
return this.scheme === 'data';
}
isHttpOrHttps(): boolean {
return this.scheme === 'http' || this.scheme === 'https';
}
isBlobURL(): boolean {
return this.url.startsWith('blob:');
}
lastPathComponentWithFragment(): string {
return this.lastPathComponent + (this.fragment ? '#' + this.fragment : '');
}
domain(): string {
if (this.isDataURL()) {
return 'data:';
}
return this.host + (this.port ? ':' + this.port : '');
}
securityOrigin(): string {
if (this.isDataURL()) {
return 'data:';
}
const scheme = this.isBlobURL() ? this.blobInnerScheme : this.scheme;
return scheme + '://' + this.domain();
}
urlWithoutScheme(): string {
if (this.scheme && this.url.startsWith(this.scheme + '://')) {
return this.url.substring(this.scheme.length + 3);
}
return this.url;
}
static urlRegexInstance: RegExp|null = null;
} | the_stack |
import { oneLineTrim } from 'common-tags';
import { DOMParser } from 'prosemirror-model';
import WysiwygEditor from '@/wysiwyg/wwEditor';
import EventEmitter from '@/event/eventEmitter';
import CommandManager from '@/commands/commandManager';
import { WwToDOMAdaptor } from '@/wysiwyg/adaptor/wwToDOMAdaptor';
import { cls } from '@/utils/dom';
const CODE_BLOCK_CLS = cls('ww-code-block');
describe('wysiwyg commands', () => {
let wwe: WysiwygEditor, em: EventEmitter, cmd: CommandManager;
function setTextToEditor(text: string) {
const { state, dispatch } = wwe.view;
const { tr, doc } = state;
const lines = text.split('\n');
const node = lines.map((lineText) =>
wwe.schema.nodes.paragraph.create(null, wwe.schema.text(lineText))
);
dispatch(tr.replaceWith(0, doc.content.size, node));
}
function setContent(content: string) {
const wrapper = document.createElement('div');
wrapper.innerHTML = content;
const nodes = DOMParser.fromSchema(wwe.schema).parse(wrapper);
wwe.setModel(nodes);
}
beforeEach(() => {
const toDOMAdaptor = new WwToDOMAdaptor({}, {});
em = new EventEmitter();
wwe = new WysiwygEditor(em, { toDOMAdaptor });
cmd = new CommandManager(em, {}, wwe.commands, () => 'wysiwyg');
});
afterEach(() => {
wwe.destroy();
});
describe('heading command', () => {
it('should add empty heading element', () => {
cmd.exec('heading', { level: 1 });
expect(wwe.getHTML()).toBe('<h1><br></h1>');
});
it('should add heading element to selection', () => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('heading', { level: 2 });
expect(wwe.getHTML()).toBe('<h2>foo</h2>');
});
it('should change heading element by level', () => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('heading', { level: 3 });
expect(wwe.getHTML()).toBe('<h3>foo</h3>');
cmd.exec('selectAll');
cmd.exec('heading', { level: 4 });
expect(wwe.getHTML()).toBe('<h4>foo</h4>');
cmd.exec('selectAll');
cmd.exec('heading', { level: 5 });
expect(wwe.getHTML()).toBe('<h5>foo</h5>');
cmd.exec('selectAll');
cmd.exec('heading', { level: 6 });
expect(wwe.getHTML()).toBe('<h6>foo</h6>');
});
});
describe('hr command', () => {
it('should add hr element with empty paragraphs in empty document', () => {
cmd.exec('hr');
expect(wwe.getHTML()).toBe(oneLineTrim`
<p><br></p>
<div><hr></div>
<p><br></p>
`);
});
it('should add hr element with after empty paragraph', () => {
setTextToEditor('foo');
wwe.setSelection(2, 2);
cmd.exec('hr');
expect(wwe.getHTML()).toBe(oneLineTrim`
<p>foo</p>
<div><hr></div>
<p><br></p>
`);
});
it('should add only hr element', () => {
setTextToEditor('foo\nbar');
wwe.setSelection(2, 2);
cmd.exec('hr');
expect(wwe.getHTML()).toBe(oneLineTrim`
<p>foo</p>
<div><hr></div>
<p>bar</p>
`);
});
it('should not add hr element when there is selection', () => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('hr');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
});
describe('blockQuote command', () => {
it('should add blockquote element including empty paragraph', () => {
cmd.exec('blockQuote');
expect(wwe.getHTML()).toBe('<blockquote><p><br></p></blockquote>');
});
it('should change blockquote element to selection', () => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('blockQuote');
expect(wwe.getHTML()).toBe('<blockquote><p>foo</p></blockquote>');
});
it('should wrap with blockquote element', () => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('blockQuote');
cmd.exec('blockQuote');
const expected = oneLineTrim`
<blockquote>
<blockquote><p>foo</p></blockquote>
</blockquote>
`;
expect(wwe.getHTML()).toBe(expected);
});
});
describe('codeBlock command', () => {
it('should add pre element including code element', () => {
cmd.exec('codeBlock');
expect(wwe.getHTML()).toBe(oneLineTrim`
<div data-language="text" class="${CODE_BLOCK_CLS}">
<pre>
<code><br></code>
</pre>
</div>
`);
});
it('should change pre element to selection', () => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('codeBlock');
expect(wwe.getHTML()).toBe(oneLineTrim`
<div data-language="text" class="${CODE_BLOCK_CLS}">
<pre>
<code>foo</code>
</pre>
</div>
`);
});
});
describe('bulletList command', () => {
it('should add ul element having empty list item', () => {
cmd.exec('bulletList');
const expected = oneLineTrim`
<ul>
<li><p><br></p></li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should change to bullet list item in selection', () => {
setTextToEditor('foo\nbar\nbaz');
cmd.exec('selectAll');
cmd.exec('bulletList');
const expected = oneLineTrim`
<ul>
<li><p>foo</p></li>
<li><p>bar</p></li>
<li><p>baz</p></li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
});
describe('orderedList command', () => {
it('should add ol element having empty list item', () => {
cmd.exec('orderedList');
const expected = oneLineTrim`
<ol>
<li><p><br></p></li>
</ol>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should change to ordered list item in selection', () => {
setTextToEditor('foo\nbar\nbaz');
cmd.exec('selectAll');
cmd.exec('orderedList');
const expected = oneLineTrim`
<ol>
<li><p>foo</p></li>
<li><p>bar</p></li>
<li><p>baz</p></li>
</ol>
`;
expect(wwe.getHTML()).toBe(expected);
});
});
it('bulletList and orderedList command should change parent list to other list when in list item', () => {
setTextToEditor('foo\nbar\nbaz');
cmd.exec('selectAll');
cmd.exec('bulletList');
wwe.setSelection(3, 3); // in 'foo'
cmd.exec('orderedList');
let expected = oneLineTrim`
<ol>
<li><p>foo</p></li>
<li><p>bar</p></li>
<li><p>baz</p></li>
</ol>
`;
expect(wwe.getHTML()).toBe(expected);
wwe.setSelection(11, 11); // in 'bar'
cmd.exec('bulletList');
expected = oneLineTrim`
<ul>
<li><p>foo</p></li>
<li><p>bar</p></li>
<li><p>baz</p></li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
describe('taskList command', () => {
it('should add task to ul element ', () => {
cmd.exec('taskList');
const expected = oneLineTrim`
<ul>
<li class="task-list-item" data-task="true">
<p><br></p>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should change to task item in selection', () => {
setTextToEditor('foo\nbar\nbaz');
cmd.exec('selectAll');
cmd.exec('taskList');
const expected = oneLineTrim`
<ul>
<li class="task-list-item" data-task="true">
<p>foo</p>
</li>
<li class="task-list-item" data-task="true">
<p>bar</p>
</li>
<li class="task-list-item" data-task="true">
<p>baz</p>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should toggle task list item', () => {
setTextToEditor('foo\nbar\nbaz');
cmd.exec('selectAll');
cmd.exec('taskList');
wwe.setSelection(3, 3); // from 'foo'
cmd.exec('bulletList');
let expected = oneLineTrim`
<ul>
<li>
<p>foo</p>
</li>
<li class="task-list-item" data-task="true">
<p>bar</p>
</li>
<li class="task-list-item" data-task="true">
<p>baz</p>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
wwe.setSelection(3, 12); // from 'foo' to 'bar'
cmd.exec('taskList');
expected = oneLineTrim`
<ul>
<li class="task-list-item" data-task="true">
<p>foo</p>
</li>
<li>
<p>bar</p>
</li>
<li class="task-list-item" data-task="true">
<p>baz</p>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
});
describe('bold command', () => {
beforeEach(() => setTextToEditor('foo'));
it('should add strong element to selection', () => {
cmd.exec('selectAll');
cmd.exec('bold');
expect(wwe.getHTML()).toBe('<p><strong>foo</strong></p>');
});
it('should toggle and remove strong element', () => {
cmd.exec('selectAll');
cmd.exec('bold');
cmd.exec('selectAll');
cmd.exec('bold');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
});
describe('italic command', () => {
beforeEach(() => setTextToEditor('foo'));
it('should add emphasis element to selection', () => {
cmd.exec('selectAll');
cmd.exec('italic');
expect(wwe.getHTML()).toBe('<p><em>foo</em></p>');
});
it('should toggle and remove emphasis element', () => {
cmd.exec('selectAll');
cmd.exec('bold');
cmd.exec('selectAll');
cmd.exec('bold');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
});
describe('strike command', () => {
beforeEach(() => setTextToEditor('foo'));
it('should add del element to selection', () => {
cmd.exec('selectAll');
cmd.exec('strike');
expect(wwe.getHTML()).toBe('<p><del>foo</del></p>');
});
it('should toggle and remove del element', () => {
cmd.exec('selectAll');
cmd.exec('strike');
cmd.exec('selectAll');
cmd.exec('strike');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
});
describe('code command', () => {
beforeEach(() => setTextToEditor('foo'));
it('should add code element to selection', () => {
cmd.exec('selectAll');
cmd.exec('code');
expect(wwe.getHTML()).toBe('<p><code>foo</code></p>');
});
it('should toggle and remove code element', () => {
cmd.exec('selectAll');
cmd.exec('code');
cmd.exec('selectAll');
cmd.exec('code');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
});
describe('addImage command', () => {
it('should add image element', () => {
cmd.exec('addImage', {
imageUrl: '#',
});
expect(wwe.getHTML()).toBe('<p><img src="#"><br></p>');
});
it('should add image element with enabled attirbute', () => {
cmd.exec('addImage', {
imageUrl: '#',
altText: 'foo',
foo: 'test',
});
expect(wwe.getHTML()).toBe('<p><img src="#" alt="foo"><br></p>');
});
it('should not add image element when not having imageUrl attribute', () => {
cmd.exec('addImage', {
altText: 'foo',
});
expect(wwe.getHTML()).toBe('<p><br></p>');
});
it('should not decode url which is already encoded', () => {
cmd.exec('addImage', {
imageUrl: 'https://firebasestorage.googleapis.com/images%2Fimage.png?alt=media',
altText: 'foo',
});
expect(wwe.getHTML()).toBe(
'<p><img src="https://firebasestorage.googleapis.com/images%2Fimage.png?alt=media" alt="foo"><br></p>'
);
});
});
describe('addLink command', () => {
it('should add link element', () => {
cmd.exec('addLink', {
linkUrl: '#',
linkText: 'foo',
});
expect(wwe.getHTML()).toBe('<p><a href="#">foo</a></p>');
});
it('should not add link element when no selection and attributes are missing', () => {
cmd.exec('addLink', {
linkText: 'foo',
});
expect(wwe.getHTML()).toBe('<p><br></p>');
cmd.exec('addLink', {
linkUrl: '#',
});
expect(wwe.getHTML()).toBe('<p><br></p>');
});
it('should change link url in selection', () => {
cmd.exec('addLink', {
linkUrl: '#',
linkText: 'foo bar baz',
});
wwe.setSelection(5, 8);
cmd.exec('addLink', {
linkUrl: 'http://test.com',
linkText: 'bar',
});
const expected = oneLineTrim`
<p>
<a href="#">foo </a>
<a href="http://test.com">bar</a>
<a href="#"> baz</a>
</p>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should not decode url which is already encoded', () => {
cmd.exec('addLink', {
linkUrl: 'https://firebasestorage.googleapis.com/links%2Fimage.png?alt=media',
linkText: 'foo',
});
expect(wwe.getHTML()).toBe(
'<p><a href="https://firebasestorage.googleapis.com/links%2Fimage.png?alt=media">foo</a></p>'
);
});
});
describe(`addLink command with 'linkAttributes' option`, () => {
beforeEach(() => {
const linkAttributes = {
target: '_blank',
rel: 'noopener noreferrer',
};
const toDOMAdaptor = new WwToDOMAdaptor({}, {});
em = new EventEmitter();
wwe = new WysiwygEditor(em, { toDOMAdaptor, linkAttributes });
cmd = new CommandManager(em, {}, wwe.commands, () => 'wysiwyg');
});
it('should add link element with link attributes', () => {
cmd.exec('addLink', {
linkUrl: '#',
linkText: 'foo',
});
expect(wwe.getHTML()).toBe(
'<p><a href="#" target="_blank" rel="noopener noreferrer">foo</a></p>'
);
});
});
describe('toggleLink command', () => {
beforeEach(() => setTextToEditor('foo'));
it('should add link element to selection', () => {
cmd.exec('selectAll');
cmd.exec('toggleLink', {
linkUrl: 'linkUrl',
});
expect(wwe.getHTML()).toBe('<p><a href="linkUrl">foo</a></p>');
});
it('should toggle link element to selection', () => {
cmd.exec('selectAll');
cmd.exec('toggleLink', {
linkUrl: 'linkUrl',
});
cmd.exec('selectAll');
cmd.exec('toggleLink');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
});
describe('history command', () => {
beforeEach(() => {
setTextToEditor('foo');
cmd.exec('selectAll');
cmd.exec('bold');
cmd.exec('italic');
});
it('undo go back to before previous action', () => {
cmd.exec('undo');
expect(wwe.getHTML()).toBe('<p><strong>foo</strong></p>');
cmd.exec('undo');
expect(wwe.getHTML()).toBe('<p>foo</p>');
});
it('redo cancel undo action', () => {
cmd.exec('undo');
cmd.exec('undo');
cmd.exec('redo');
expect(wwe.getHTML()).toBe('<p><strong>foo</strong></p>');
});
});
describe('indent command', () => {
let html;
beforeEach(() => {
html = oneLineTrim`
<ul>
<li>
<p>foo</p>
<ol>
<li><p>bar</p></li>
<li><p>baz</p></li>
<li><p>qux</p></li>
</ol>
</li>
</ul>
`;
setContent(html);
});
// @TODO move to 'tab' key event test
// it('should add spaces for tab when it is not in list', () => {
// setContent('<p>foo</p>');
// wwe.setSelection(1, 1);
// cmd.exec( 'indent');
// expect(wwe.getHTML()).toBe('<p> foo</p>');
// wwe.setSelection(1, 8);
// cmd.exec( 'indent');
// expect(wwe.getHTML()).toBe('<p> </p>');
// });
it('should indent to list items at cursor position', () => {
wwe.setSelection(18, 18);
cmd.exec('indent');
const expected = oneLineTrim`
<ul>
<li>
<p>foo</p>
<ol>
<li>
<p>bar</p>
<ol>
<li><p>baz</p></li>
</ol>
</li>
<li><p>qux</p></li>
</ol>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should indent to list items as selection', () => {
wwe.setSelection(18, 26);
cmd.exec('indent');
const expected = oneLineTrim`
<ul>
<li>
<p>foo</p>
<ol>
<li>
<p>bar</p>
<ol>
<li><p>baz</p></li>
<li><p>qux</p></li>
</ol>
</li>
</ol>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
});
describe('outdent command', () => {
let html;
beforeEach(() => {
html = oneLineTrim`
<ul>
<li>
<p>foo</p>
<ol>
<li>
<p>bar</p>
<ul>
<li><p>baz</p></li>
</ul>
</li>
</ol>
</li>
</ul>
`;
setContent(html);
});
// @TODO move to 'shift + tab' key event test
// it('should remove spaces for tab when it is not in list', () => {
// setContent('<p> foo</p>');
// wwe.setSelection(4, 4);
// cmd.exec( 'outdent');
// expect(wwe.getHTML()).toBe('<p>foo</p>');
// setContent('<p>foo bar</p>');
// wwe.setSelection(6, 6);
// cmd.exec( 'outdent');
// expect(wwe.getHTML()).toBe('<p>foo bar</p>');
// wwe.setSelection(6, 8);
// cmd.exec( 'outdent');
// expect(wwe.getHTML()).toBe('<p>foobar</p>');
// });
it('should outdent to list items at cursor position', () => {
wwe.setSelection(19, 19);
cmd.exec('outdent');
const expected = oneLineTrim`
<ul>
<li>
<p>foo</p>
<ol>
<li><p>bar</p></li>
<li><p>baz</p></li>
</ol>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should outdent to list items as selection', () => {
wwe.setSelection(10, 20);
cmd.exec('outdent');
const expected = oneLineTrim`
<ul>
<li><p>foo</p></li>
<li>
<p>bar</p>
<ul>
<li><p>baz</p></li>
</ul>
</li>
</ul>
`;
expect(wwe.getHTML()).toBe(expected);
});
it('should change list item of 1 depth into paragraph ', () => {
wwe.setSelection(3, 5);
cmd.exec('outdent');
const expected = oneLineTrim`
<p>foo</p>
<ol>
<li>
<p>bar</p>
<ul>
<li><p>baz</p></li>
</ul>
</li>
</ol>
`;
expect(wwe.getHTML()).toBe(expected);
});
});
}); | the_stack |
import {log, assert} from '@luma.gl/api';
import GL from '@luma.gl/constants';
import {assertWebGL2Context} from '@luma.gl/webgl';
import {withParameters} from '@luma.gl/webgl';
import {flipRows, scalePixels} from '../webgl-utils/typed-array-utils';
import {getTypedArrayFromGLType, getGLTypeFromTypedArray} from '../webgl-utils/typed-array-utils';
import {glFormatToComponents, glTypeToBytes} from '../webgl-utils/format-utils';
import {toFramebuffer} from '../webgl-utils/texture-utils';
import Buffer from './buffer';
// import Texture from '../adapter/resources/webgl-texture';
import Texture from './texture';
import Framebuffer from './framebuffer';
/**
* Copies data from a type or a Texture object into ArrayBuffer object.
* App can provide targetPixelArray or have it auto allocated by this method
* newly allocated by this method unless provided by app.
* @note Slow requires roundtrip to GPU
*
* @param source
* @param options
* @returns pixel array,
*/
export function readPixelsToArray(
source: Framebuffer | Texture,
options?: {
sourceX?: number;
sourceY?: number;
sourceFormat?: number;
sourceAttachment?: number;
target?: Uint8Array | Uint16Array | Float32Array;
// following parameters are auto deduced if not provided
sourceWidth?: number;
sourceHeight?: number;
sourceType?: number;
}
): Uint8Array | Uint16Array | Float32Array {
const {sourceX = 0, sourceY = 0, sourceFormat = GL.RGBA} = options || {};
let {
sourceAttachment = GL.COLOR_ATTACHMENT0, // TODO - support gl.readBuffer
target = null,
// following parameters are auto deduced if not provided
sourceWidth,
sourceHeight,
sourceType
} = options || {};
const {framebuffer, deleteFramebuffer} = getFramebuffer(source);
assert(framebuffer);
const {gl, handle, attachments} = framebuffer;
sourceWidth = sourceWidth || framebuffer.width;
sourceHeight = sourceHeight || framebuffer.height;
// TODO - Set and unset gl.readBuffer
if (sourceAttachment === GL.COLOR_ATTACHMENT0 && handle === null) {
sourceAttachment = GL.FRONT;
}
const attachment = sourceAttachment - GL.COLOR_ATTACHMENT0;
// assert(attachments[sourceAttachment]);
// Deduce the type from color attachment if not provided.
sourceType = sourceType || framebuffer.colorAttachments[attachment].type;
// Deduce type and allocated pixelArray if needed
target = getPixelArray(target, sourceType, sourceFormat, sourceWidth, sourceHeight);
// Pixel array available, if necessary, deduce type from it.
sourceType = sourceType || getGLTypeFromTypedArray(target);
const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, handle);
gl.readPixels(sourceX, sourceY, sourceWidth, sourceHeight, sourceFormat, sourceType, target);
// @ts-expect-error
gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);
if (deleteFramebuffer) {
framebuffer.delete();
}
return target;
}
/**
* Copies data from a Framebuffer or a Texture object into a Buffer object.
* NOTE: doesn't wait for copy to be complete, it programs GPU to perform a DMA transffer.
* @param source
* @param options
*/
export function readPixelsToBuffer(
source: Framebuffer | Texture,
options?: {
sourceX?: number;
sourceY?: number;
sourceFormat?: number;
target?: Buffer; // A new Buffer object is created when not provided.
targetByteOffset?: number; // byte offset in buffer object
// following parameters are auto deduced if not provided
sourceWidth?: number;
sourceHeight?: number;
sourceType?: number;
}
): Buffer {
const {sourceX = 0, sourceY = 0, sourceFormat = GL.RGBA,
targetByteOffset = 0
} = options || {};
// following parameters are auto deduced if not provided
let {
target,
sourceWidth,
sourceHeight,
sourceType,
} = options || {}
const {framebuffer, deleteFramebuffer} = getFramebuffer(source);
assert(framebuffer);
sourceWidth = sourceWidth || framebuffer.width;
sourceHeight = sourceHeight || framebuffer.height;
// Asynchronous read (PIXEL_PACK_BUFFER) is WebGL2 only feature
const gl2 = assertWebGL2Context(framebuffer.gl);
// deduce type if not available.
sourceType = sourceType || (target ? target.type : GL.UNSIGNED_BYTE);
if (!target) {
// Create new buffer with enough size
const components = glFormatToComponents(sourceFormat);
const byteCount = glTypeToBytes(sourceType);
const byteLength = targetByteOffset + sourceWidth * sourceHeight * components * byteCount;
target = new Buffer(gl2, {byteLength, accessor: {type: sourceType, size: components}});
}
// @ts-expect-error
target.bind({target: GL.PIXEL_PACK_BUFFER});
withParameters(gl2, {framebuffer}, () => {
gl2.readPixels(
sourceX,
sourceY,
sourceWidth,
sourceHeight,
sourceFormat,
sourceType,
targetByteOffset
);
});
target.unbind({target: GL.PIXEL_PACK_BUFFER});
if (deleteFramebuffer) {
framebuffer.delete();
}
return target;
}
// Reads pixels from a Framebuffer or Texture object to a dataUrl
export function copyToDataUrl(
source,
options?: {
sourceAttachment?: number; // TODO - support gl.readBuffer
targetMaxHeight?: number;
}
): string;
// Reads pixels from a Framebuffer or Texture object to a dataUrl
export function copyToDataUrl(
source,
{
sourceAttachment = GL.COLOR_ATTACHMENT0, // TODO - support gl.readBuffer
targetMaxHeight = Number.MAX_SAFE_INTEGER
} = {}
) {
let data = readPixelsToArray(source, {sourceAttachment});
// Scale down
let {width, height} = source;
while (height > targetMaxHeight) {
({data, width, height} = scalePixels({data, width, height}));
}
// Flip to top down coordinate system
flipRows({data, width, height});
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
// Copy the pixels to a 2D canvas
const imageData = context.createImageData(width, height);
imageData.data.set(data);
context.putImageData(imageData, 0, 0);
return canvas.toDataURL();
}
// Reads pixels from a Framebuffer or Texture object into an HTML Image
// Reads pixels from a Framebuffer or Texture object into an HTML Image
export function copyToImage(
source: Framebuffer | Texture,
options?: {
sourceAttachment?: number; // TODO - support gl.readBuffer
targetImage?: typeof Image;
}
): typeof Image {
const dataUrl = copyToDataUrl(source, {sourceAttachment: options?.sourceAttachment || GL.COLOR_ATTACHMENT0});
const targetImage = options?.targetImage || new Image();
// @ts-expect-error
targetImage.src = dataUrl;
// @ts-expect-error
return targetImage;
}
/**
* Copy a rectangle from a Framebuffer or Texture object into a texture (at an offset)
*/
// eslint-disable-next-line complexity, max-statements
export function copyToTexture(
source: Framebuffer | Texture,
target: Texture | GL,
options?: {
sourceX?: number;
sourceY?: number;
targetX?: number;
targetY?: number;
targetZ?: number;
targetMipmaplevel?: number;
targetInternalFormat?: number;
width?: number; // defaults to target width
height?: number; // defaults to target height
}
): Texture {
const {
sourceX = 0,
sourceY = 0,
// attachment = GL.COLOR_ATTACHMENT0, // TODO - support gl.readBuffer
targetMipmaplevel = 0,
targetInternalFormat = GL.RGBA
} = options || {};
let {
targetX,
targetY,
targetZ,
width, // defaults to target width
height // defaults to target height
} = options || {};
const {framebuffer, deleteFramebuffer} = getFramebuffer(source);
assert(framebuffer);
const {gl, handle} = framebuffer;
const isSubCopy =
typeof targetX !== 'undefined' ||
typeof targetY !== 'undefined' ||
typeof targetZ !== 'undefined';
targetX = targetX || 0;
targetY = targetY || 0;
targetZ = targetZ || 0;
const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, handle);
// TODO - support gl.readBuffer (WebGL2 only)
// const prevBuffer = gl.readBuffer(attachment);
assert(target);
let texture = null;
let textureTarget: GL;
if (target instanceof Texture) {
texture = target;
width = Number.isFinite(width) ? width : texture.width;
height = Number.isFinite(height) ? height : texture.height;
texture.bind(0);
textureTarget = texture.target;
} else {
textureTarget = target;
}
if (!isSubCopy) {
gl.copyTexImage2D(
textureTarget,
targetMipmaplevel,
targetInternalFormat,
sourceX,
sourceY,
width,
height,
0 /* border must be 0 */
);
} else {
switch (textureTarget) {
case GL.TEXTURE_2D:
case GL.TEXTURE_CUBE_MAP:
gl.copyTexSubImage2D(
textureTarget,
targetMipmaplevel,
targetX,
targetY,
sourceX,
sourceY,
width,
height
);
break;
case GL.TEXTURE_2D_ARRAY:
case GL.TEXTURE_3D:
const gl2 = assertWebGL2Context(gl);
gl2.copyTexSubImage3D(
textureTarget,
targetMipmaplevel,
targetX,
targetY,
targetZ,
sourceX,
sourceY,
width,
height
);
break;
default:
}
}
if (texture) {
texture.unbind();
}
// @ts-expect-error
gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);
if (deleteFramebuffer) {
framebuffer.delete();
}
return texture;
}
/**
* Copies a rectangle of pixels between Framebuffer or Texture objects
* @note NOTE: WEBLG2 only
* @param source
* @param target
* @param options
*/
// eslint-disable-next-line max-statements, complexity
export function blit(
source,
target,
options: {
sourceAttachment?: number;
sourceX0?: number;
sourceY0?: number;
sourceX1?: number;
sourceY1?: number;
targetX0?: number;
targetY0?: number;
targetX1?: number;
targetY1?: number;
color?: boolean;
depth?: boolean;
stencil?: boolean;
mask?: number;
filter?: number;
}
): void {
const {
sourceX0 = 0,
sourceY0 = 0,
targetX0 = 0,
targetY0 = 0,
color = true,
depth = false,
stencil = false,
filter = GL.NEAREST
} = options;
let {
sourceX1,
sourceY1,
targetX1,
targetY1,
sourceAttachment = GL.COLOR_ATTACHMENT0,
mask = 0
} = options;
const {framebuffer: srcFramebuffer, deleteFramebuffer: deleteSrcFramebuffer} =
getFramebuffer(source);
const {framebuffer: dstFramebuffer, deleteFramebuffer: deleteDstFramebuffer} =
getFramebuffer(target);
assert(srcFramebuffer);
assert(dstFramebuffer);
const {gl, handle, width, height, readBuffer} = dstFramebuffer;
const gl2 = assertWebGL2Context(gl);
if (!srcFramebuffer.handle && sourceAttachment === GL.COLOR_ATTACHMENT0) {
sourceAttachment = GL.FRONT;
}
if (color) {
mask |= GL.COLOR_BUFFER_BIT;
}
if (depth) {
mask |= GL.DEPTH_BUFFER_BIT;
}
if (stencil) {
mask |= GL.STENCIL_BUFFER_BIT;
}
if (deleteSrcFramebuffer || deleteDstFramebuffer) {
// Either source or destiantion was a texture object, which is wrapped in a Framebuffer objecgt as color attachment.
// Overwrite the mask to `COLOR_BUFFER_BIT`
if (mask & (GL.DEPTH_BUFFER_BIT | GL.STENCIL_BUFFER_BIT)) {
mask = GL.COLOR_BUFFER_BIT;
log.warn('Blitting from or into a Texture object, forcing mask to GL.COLOR_BUFFER_BIT')();
}
}
assert(mask);
sourceX1 = sourceX1 === undefined ? srcFramebuffer.width : sourceX1;
sourceY1 = sourceY1 === undefined ? srcFramebuffer.height : sourceY1;
targetX1 = targetX1 === undefined ? width : targetX1;
targetY1 = targetY1 === undefined ? height : targetY1;
const prevDrawHandle = gl.bindFramebuffer(GL.DRAW_FRAMEBUFFER, handle);
const prevReadHandle = gl.bindFramebuffer(GL.READ_FRAMEBUFFER, srcFramebuffer.handle);
gl2.readBuffer(sourceAttachment);
gl2.blitFramebuffer(
sourceX0,
sourceY0,
sourceX1,
sourceY1,
targetX0,
targetY0,
targetX1,
targetY1,
mask,
filter
);
gl2.readBuffer(readBuffer);
// @ts-expect-error
gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, prevReadHandle || null);
// @ts-expect-error
gl2.bindFramebuffer(GL.DRAW_FRAMEBUFFER, prevDrawHandle || null);
if (deleteSrcFramebuffer) {
srcFramebuffer.delete();
}
if (deleteDstFramebuffer) {
dstFramebuffer.delete();
}
// return dstFramebuffer;
}
// Helper methods
function getFramebuffer(source): {framebuffer: Framebuffer, deleteFramebuffer: boolean} {
if (!(source instanceof Framebuffer)) {
return {framebuffer: toFramebuffer(source), deleteFramebuffer: true};
}
return {framebuffer: source, deleteFramebuffer: false};
}
function getPixelArray(pixelArray, type, format, width: number, height: number): Uint8Array | Uint16Array | Float32Array {
if (pixelArray) {
return pixelArray;
}
// Allocate pixel array if not already available, using supplied type
type = type || GL.UNSIGNED_BYTE;
const ArrayType = getTypedArrayFromGLType(type, {clamped: false});
const components = glFormatToComponents(format);
// TODO - check for composite type (components = 1).
return new ArrayType(width * height * components) as Uint8Array | Uint16Array | Float32Array;
} | the_stack |
export const enum Trs80Model {
UNKNOWN_MODEL = "UNKNOWN_MODEL",
MODEL_I = "MODEL_I",
MODEL_III = "MODEL_III",
MODEL_4 = "MODEL_4",
MODEL_4P = "MODEL_4P",
}
export const encodeTrs80Model: { [key: string]: number } = {
UNKNOWN_MODEL: 0,
MODEL_I: 1,
MODEL_III: 2,
MODEL_4: 3,
MODEL_4P: 4,
};
export const decodeTrs80Model: { [key: number]: Trs80Model } = {
0: Trs80Model.UNKNOWN_MODEL,
1: Trs80Model.MODEL_I,
2: Trs80Model.MODEL_III,
3: Trs80Model.MODEL_4,
4: Trs80Model.MODEL_4P,
};
export const enum MediaType {
UNKNOWN = "UNKNOWN",
DISK = "DISK",
CASSETTE = "CASSETTE",
COMMAND = "COMMAND",
BASIC = "BASIC",
}
export const encodeMediaType: { [key: string]: number } = {
UNKNOWN: 0,
DISK: 1,
CASSETTE: 2,
COMMAND: 3,
BASIC: 4,
};
export const decodeMediaType: { [key: number]: MediaType } = {
0: MediaType.UNKNOWN,
1: MediaType.DISK,
2: MediaType.CASSETTE,
3: MediaType.COMMAND,
4: MediaType.BASIC,
};
export interface ApiResponseApps {
success?: boolean;
message?: string;
app?: App[];
}
export function encodeApiResponseApps(message: ApiResponseApps): Uint8Array {
let bb = popByteBuffer();
_encodeApiResponseApps(message, bb);
return toUint8Array(bb);
}
function _encodeApiResponseApps(message: ApiResponseApps, bb: ByteBuffer): void {
// optional bool success = 1;
let $success = message.success;
if ($success !== undefined) {
writeVarint32(bb, 8);
writeByte(bb, $success ? 1 : 0);
}
// optional string message = 2;
let $message = message.message;
if ($message !== undefined) {
writeVarint32(bb, 18);
writeString(bb, $message);
}
// repeated App app = 3;
let array$app = message.app;
if (array$app !== undefined) {
for (let value of array$app) {
writeVarint32(bb, 26);
let nested = popByteBuffer();
_encodeApp(value, nested);
writeVarint32(bb, nested.limit);
writeByteBuffer(bb, nested);
pushByteBuffer(nested);
}
}
}
export function decodeApiResponseApps(binary: Uint8Array): ApiResponseApps {
return _decodeApiResponseApps(wrapByteBuffer(binary));
}
function _decodeApiResponseApps(bb: ByteBuffer): ApiResponseApps {
let message: ApiResponseApps = {} as any;
end_of_message: while (!isAtEnd(bb)) {
let tag = readVarint32(bb);
switch (tag >>> 3) {
case 0:
break end_of_message;
// optional bool success = 1;
case 1: {
message.success = !!readByte(bb);
break;
}
// optional string message = 2;
case 2: {
message.message = readString(bb, readVarint32(bb));
break;
}
// repeated App app = 3;
case 3: {
let limit = pushTemporaryLength(bb);
let values = message.app || (message.app = []);
values.push(_decodeApp(bb));
bb.limit = limit;
break;
}
default:
skipUnknownField(bb, tag & 7);
}
}
return message;
}
export interface ApiResponseMediaImages {
success?: boolean;
message?: string;
mediaImage?: MediaImage[];
}
export function encodeApiResponseMediaImages(message: ApiResponseMediaImages): Uint8Array {
let bb = popByteBuffer();
_encodeApiResponseMediaImages(message, bb);
return toUint8Array(bb);
}
function _encodeApiResponseMediaImages(message: ApiResponseMediaImages, bb: ByteBuffer): void {
// optional bool success = 1;
let $success = message.success;
if ($success !== undefined) {
writeVarint32(bb, 8);
writeByte(bb, $success ? 1 : 0);
}
// optional string message = 2;
let $message = message.message;
if ($message !== undefined) {
writeVarint32(bb, 18);
writeString(bb, $message);
}
// repeated MediaImage mediaImage = 3;
let array$mediaImage = message.mediaImage;
if (array$mediaImage !== undefined) {
for (let value of array$mediaImage) {
writeVarint32(bb, 26);
let nested = popByteBuffer();
_encodeMediaImage(value, nested);
writeVarint32(bb, nested.limit);
writeByteBuffer(bb, nested);
pushByteBuffer(nested);
}
}
}
export function decodeApiResponseMediaImages(binary: Uint8Array): ApiResponseMediaImages {
return _decodeApiResponseMediaImages(wrapByteBuffer(binary));
}
function _decodeApiResponseMediaImages(bb: ByteBuffer): ApiResponseMediaImages {
let message: ApiResponseMediaImages = {} as any;
end_of_message: while (!isAtEnd(bb)) {
let tag = readVarint32(bb);
switch (tag >>> 3) {
case 0:
break end_of_message;
// optional bool success = 1;
case 1: {
message.success = !!readByte(bb);
break;
}
// optional string message = 2;
case 2: {
message.message = readString(bb, readVarint32(bb));
break;
}
// repeated MediaImage mediaImage = 3;
case 3: {
let limit = pushTemporaryLength(bb);
let values = message.mediaImage || (message.mediaImage = []);
values.push(_decodeMediaImage(bb));
bb.limit = limit;
break;
}
default:
skipUnknownField(bb, tag & 7);
}
}
return message;
}
export interface App {
id?: string;
name?: string;
version?: string;
description?: string;
release_year?: number;
screenshot_url?: string[];
author?: string;
ext_trs80?: Trs80Extension;
}
export function encodeApp(message: App): Uint8Array {
let bb = popByteBuffer();
_encodeApp(message, bb);
return toUint8Array(bb);
}
function _encodeApp(message: App, bb: ByteBuffer): void {
// optional string id = 1;
let $id = message.id;
if ($id !== undefined) {
writeVarint32(bb, 10);
writeString(bb, $id);
}
// optional string name = 2;
let $name = message.name;
if ($name !== undefined) {
writeVarint32(bb, 18);
writeString(bb, $name);
}
// optional string version = 3;
let $version = message.version;
if ($version !== undefined) {
writeVarint32(bb, 26);
writeString(bb, $version);
}
// optional string description = 4;
let $description = message.description;
if ($description !== undefined) {
writeVarint32(bb, 34);
writeString(bb, $description);
}
// optional int32 release_year = 5;
let $release_year = message.release_year;
if ($release_year !== undefined) {
writeVarint32(bb, 40);
writeVarint64(bb, intToLong($release_year));
}
// repeated string screenshot_url = 6;
let array$screenshot_url = message.screenshot_url;
if (array$screenshot_url !== undefined) {
for (let value of array$screenshot_url) {
writeVarint32(bb, 50);
writeString(bb, value);
}
}
// optional string author = 7;
let $author = message.author;
if ($author !== undefined) {
writeVarint32(bb, 58);
writeString(bb, $author);
}
// optional Trs80Extension ext_trs80 = 8;
let $ext_trs80 = message.ext_trs80;
if ($ext_trs80 !== undefined) {
writeVarint32(bb, 66);
let nested = popByteBuffer();
_encodeTrs80Extension($ext_trs80, nested);
writeVarint32(bb, nested.limit);
writeByteBuffer(bb, nested);
pushByteBuffer(nested);
}
}
export function decodeApp(binary: Uint8Array): App {
return _decodeApp(wrapByteBuffer(binary));
}
function _decodeApp(bb: ByteBuffer): App {
let message: App = {} as any;
end_of_message: while (!isAtEnd(bb)) {
let tag = readVarint32(bb);
switch (tag >>> 3) {
case 0:
break end_of_message;
// optional string id = 1;
case 1: {
message.id = readString(bb, readVarint32(bb));
break;
}
// optional string name = 2;
case 2: {
message.name = readString(bb, readVarint32(bb));
break;
}
// optional string version = 3;
case 3: {
message.version = readString(bb, readVarint32(bb));
break;
}
// optional string description = 4;
case 4: {
message.description = readString(bb, readVarint32(bb));
break;
}
// optional int32 release_year = 5;
case 5: {
message.release_year = readVarint32(bb);
break;
}
// repeated string screenshot_url = 6;
case 6: {
let values = message.screenshot_url || (message.screenshot_url = []);
values.push(readString(bb, readVarint32(bb)));
break;
}
// optional string author = 7;
case 7: {
message.author = readString(bb, readVarint32(bb));
break;
}
// optional Trs80Extension ext_trs80 = 8;
case 8: {
let limit = pushTemporaryLength(bb);
message.ext_trs80 = _decodeTrs80Extension(bb);
bb.limit = limit;
break;
}
default:
skipUnknownField(bb, tag & 7);
}
}
return message;
}
export interface Trs80Extension {
model?: Trs80Model;
}
export function encodeTrs80Extension(message: Trs80Extension): Uint8Array {
let bb = popByteBuffer();
_encodeTrs80Extension(message, bb);
return toUint8Array(bb);
}
function _encodeTrs80Extension(message: Trs80Extension, bb: ByteBuffer): void {
// optional Trs80Model model = 1;
let $model = message.model;
if ($model !== undefined) {
writeVarint32(bb, 8);
writeVarint32(bb, encodeTrs80Model[$model]);
}
}
export function decodeTrs80Extension(binary: Uint8Array): Trs80Extension {
return _decodeTrs80Extension(wrapByteBuffer(binary));
}
function _decodeTrs80Extension(bb: ByteBuffer): Trs80Extension {
let message: Trs80Extension = {} as any;
end_of_message: while (!isAtEnd(bb)) {
let tag = readVarint32(bb);
switch (tag >>> 3) {
case 0:
break end_of_message;
// optional Trs80Model model = 1;
case 1: {
message.model = decodeTrs80Model[readVarint32(bb)];
break;
}
default:
skipUnknownField(bb, tag & 7);
}
}
return message;
}
export interface MediaImage {
type?: MediaType;
filename?: string;
data?: Uint8Array;
uploadTime?: Long;
description?: string;
}
export function encodeMediaImage(message: MediaImage): Uint8Array {
let bb = popByteBuffer();
_encodeMediaImage(message, bb);
return toUint8Array(bb);
}
function _encodeMediaImage(message: MediaImage, bb: ByteBuffer): void {
// optional MediaType type = 1;
let $type = message.type;
if ($type !== undefined) {
writeVarint32(bb, 8);
writeVarint32(bb, encodeMediaType[$type]);
}
// optional string filename = 2;
let $filename = message.filename;
if ($filename !== undefined) {
writeVarint32(bb, 18);
writeString(bb, $filename);
}
// optional bytes data = 3;
let $data = message.data;
if ($data !== undefined) {
writeVarint32(bb, 26);
writeVarint32(bb, $data.length), writeBytes(bb, $data);
}
// optional int64 uploadTime = 4;
let $uploadTime = message.uploadTime;
if ($uploadTime !== undefined) {
writeVarint32(bb, 32);
writeVarint64(bb, $uploadTime);
}
// optional string description = 5;
let $description = message.description;
if ($description !== undefined) {
writeVarint32(bb, 42);
writeString(bb, $description);
}
}
export function decodeMediaImage(binary: Uint8Array): MediaImage {
return _decodeMediaImage(wrapByteBuffer(binary));
}
function _decodeMediaImage(bb: ByteBuffer): MediaImage {
let message: MediaImage = {} as any;
end_of_message: while (!isAtEnd(bb)) {
let tag = readVarint32(bb);
switch (tag >>> 3) {
case 0:
break end_of_message;
// optional MediaType type = 1;
case 1: {
message.type = decodeMediaType[readVarint32(bb)];
break;
}
// optional string filename = 2;
case 2: {
message.filename = readString(bb, readVarint32(bb));
break;
}
// optional bytes data = 3;
case 3: {
message.data = readBytes(bb, readVarint32(bb));
break;
}
// optional int64 uploadTime = 4;
case 4: {
message.uploadTime = readVarint64(bb, /* unsigned */ false);
break;
}
// optional string description = 5;
case 5: {
message.description = readString(bb, readVarint32(bb));
break;
}
default:
skipUnknownField(bb, tag & 7);
}
}
return message;
}
export interface Long {
low: number;
high: number;
unsigned: boolean;
}
interface ByteBuffer {
bytes: Uint8Array;
offset: number;
limit: number;
}
function pushTemporaryLength(bb: ByteBuffer): number {
let length = readVarint32(bb);
let limit = bb.limit;
bb.limit = bb.offset + length;
return limit;
}
function skipUnknownField(bb: ByteBuffer, type: number): void {
switch (type) {
case 0: while (readByte(bb) & 0x80) { } break;
case 2: skip(bb, readVarint32(bb)); break;
case 5: skip(bb, 4); break;
case 1: skip(bb, 8); break;
default: throw new Error("Unimplemented type: " + type);
}
}
function stringToLong(value: string): Long {
return {
low: value.charCodeAt(0) | (value.charCodeAt(1) << 16),
high: value.charCodeAt(2) | (value.charCodeAt(3) << 16),
unsigned: false,
};
}
function longToString(value: Long): string {
let low = value.low;
let high = value.high;
return String.fromCharCode(
low & 0xFFFF,
low >>> 16,
high & 0xFFFF,
high >>> 16);
}
// The code below was modified from https://github.com/protobufjs/bytebuffer.js
// which is under the Apache License 2.0.
let f32 = new Float32Array(1);
let f32_u8 = new Uint8Array(f32.buffer);
let f64 = new Float64Array(1);
let f64_u8 = new Uint8Array(f64.buffer);
function intToLong(value: number): Long {
value |= 0;
return {
low: value,
high: value >> 31,
unsigned: value >= 0,
};
}
let bbStack: ByteBuffer[] = [];
function popByteBuffer(): ByteBuffer {
const bb = bbStack.pop();
if (!bb) return { bytes: new Uint8Array(64), offset: 0, limit: 0 };
bb.offset = bb.limit = 0;
return bb;
}
function pushByteBuffer(bb: ByteBuffer): void {
bbStack.push(bb);
}
function wrapByteBuffer(bytes: Uint8Array): ByteBuffer {
return { bytes, offset: 0, limit: bytes.length };
}
function toUint8Array(bb: ByteBuffer): Uint8Array {
let bytes = bb.bytes;
let limit = bb.limit;
return bytes.length === limit ? bytes : bytes.subarray(0, limit);
}
function skip(bb: ByteBuffer, offset: number): void {
if (bb.offset + offset > bb.limit) {
throw new Error('Skip past limit');
}
bb.offset += offset;
}
function isAtEnd(bb: ByteBuffer): boolean {
return bb.offset >= bb.limit;
}
function grow(bb: ByteBuffer, count: number): number {
let bytes = bb.bytes;
let offset = bb.offset;
let limit = bb.limit;
let finalOffset = offset + count;
if (finalOffset > bytes.length) {
let newBytes = new Uint8Array(finalOffset * 2);
newBytes.set(bytes);
bb.bytes = newBytes;
}
bb.offset = finalOffset;
if (finalOffset > limit) {
bb.limit = finalOffset;
}
return offset;
}
function advance(bb: ByteBuffer, count: number): number {
let offset = bb.offset;
if (offset + count > bb.limit) {
throw new Error('Read past limit');
}
bb.offset += count;
return offset;
}
function readBytes(bb: ByteBuffer, count: number): Uint8Array {
let offset = advance(bb, count);
return bb.bytes.subarray(offset, offset + count);
}
function writeBytes(bb: ByteBuffer, buffer: Uint8Array): void {
let offset = grow(bb, buffer.length);
bb.bytes.set(buffer, offset);
}
function readString(bb: ByteBuffer, count: number): string {
// Sadly a hand-coded UTF8 decoder is much faster than subarray+TextDecoder in V8
let offset = advance(bb, count);
let fromCharCode = String.fromCharCode;
let bytes = bb.bytes;
let invalid = '\uFFFD';
let text = '';
for (let i = 0; i < count; i++) {
let c1 = bytes[i + offset], c2: number, c3: number, c4: number, c: number;
// 1 byte
if ((c1 & 0x80) === 0) {
text += fromCharCode(c1);
}
// 2 bytes
else if ((c1 & 0xE0) === 0xC0) {
if (i + 1 >= count) text += invalid;
else {
c2 = bytes[i + offset + 1];
if ((c2 & 0xC0) !== 0x80) text += invalid;
else {
c = ((c1 & 0x1F) << 6) | (c2 & 0x3F);
if (c < 0x80) text += invalid;
else {
text += fromCharCode(c);
i++;
}
}
}
}
// 3 bytes
else if ((c1 & 0xF0) == 0xE0) {
if (i + 2 >= count) text += invalid;
else {
c2 = bytes[i + offset + 1];
c3 = bytes[i + offset + 2];
if (((c2 | (c3 << 8)) & 0xC0C0) !== 0x8080) text += invalid;
else {
c = ((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F);
if (c < 0x0800 || (c >= 0xD800 && c <= 0xDFFF)) text += invalid;
else {
text += fromCharCode(c);
i += 2;
}
}
}
}
// 4 bytes
else if ((c1 & 0xF8) == 0xF0) {
if (i + 3 >= count) text += invalid;
else {
c2 = bytes[i + offset + 1];
c3 = bytes[i + offset + 2];
c4 = bytes[i + offset + 3];
if (((c2 | (c3 << 8) | (c4 << 16)) & 0xC0C0C0) !== 0x808080) text += invalid;
else {
c = ((c1 & 0x07) << 0x12) | ((c2 & 0x3F) << 0x0C) | ((c3 & 0x3F) << 0x06) | (c4 & 0x3F);
if (c < 0x10000 || c > 0x10FFFF) text += invalid;
else {
c -= 0x10000;
text += fromCharCode((c >> 10) + 0xD800, (c & 0x3FF) + 0xDC00);
i += 3;
}
}
}
}
else text += invalid;
}
return text;
}
function writeString(bb: ByteBuffer, text: string): void {
// Sadly a hand-coded UTF8 encoder is much faster than TextEncoder+set in V8
let n = text.length;
let byteCount = 0;
// Write the byte count first
for (let i = 0; i < n; i++) {
let c = text.charCodeAt(i);
if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) {
c = (c << 10) + text.charCodeAt(++i) - 0x35FDC00;
}
byteCount += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
writeVarint32(bb, byteCount);
let offset = grow(bb, byteCount);
let bytes = bb.bytes;
// Then write the bytes
for (let i = 0; i < n; i++) {
let c = text.charCodeAt(i);
if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) {
c = (c << 10) + text.charCodeAt(++i) - 0x35FDC00;
}
if (c < 0x80) {
bytes[offset++] = c;
} else {
if (c < 0x800) {
bytes[offset++] = ((c >> 6) & 0x1F) | 0xC0;
} else {
if (c < 0x10000) {
bytes[offset++] = ((c >> 12) & 0x0F) | 0xE0;
} else {
bytes[offset++] = ((c >> 18) & 0x07) | 0xF0;
bytes[offset++] = ((c >> 12) & 0x3F) | 0x80;
}
bytes[offset++] = ((c >> 6) & 0x3F) | 0x80;
}
bytes[offset++] = (c & 0x3F) | 0x80;
}
}
}
function writeByteBuffer(bb: ByteBuffer, buffer: ByteBuffer): void {
let offset = grow(bb, buffer.limit);
let from = bb.bytes;
let to = buffer.bytes;
// This for loop is much faster than subarray+set on V8
for (let i = 0, n = buffer.limit; i < n; i++) {
from[i + offset] = to[i];
}
}
function readByte(bb: ByteBuffer): number {
return bb.bytes[advance(bb, 1)];
}
function writeByte(bb: ByteBuffer, value: number): void {
let offset = grow(bb, 1);
bb.bytes[offset] = value;
}
function readFloat(bb: ByteBuffer): number {
let offset = advance(bb, 4);
let bytes = bb.bytes;
// Manual copying is much faster than subarray+set in V8
f32_u8[0] = bytes[offset++];
f32_u8[1] = bytes[offset++];
f32_u8[2] = bytes[offset++];
f32_u8[3] = bytes[offset++];
return f32[0];
}
function writeFloat(bb: ByteBuffer, value: number): void {
let offset = grow(bb, 4);
let bytes = bb.bytes;
f32[0] = value;
// Manual copying is much faster than subarray+set in V8
bytes[offset++] = f32_u8[0];
bytes[offset++] = f32_u8[1];
bytes[offset++] = f32_u8[2];
bytes[offset++] = f32_u8[3];
}
function readDouble(bb: ByteBuffer): number {
let offset = advance(bb, 8);
let bytes = bb.bytes;
// Manual copying is much faster than subarray+set in V8
f64_u8[0] = bytes[offset++];
f64_u8[1] = bytes[offset++];
f64_u8[2] = bytes[offset++];
f64_u8[3] = bytes[offset++];
f64_u8[4] = bytes[offset++];
f64_u8[5] = bytes[offset++];
f64_u8[6] = bytes[offset++];
f64_u8[7] = bytes[offset++];
return f64[0];
}
function writeDouble(bb: ByteBuffer, value: number): void {
let offset = grow(bb, 8);
let bytes = bb.bytes;
f64[0] = value;
// Manual copying is much faster than subarray+set in V8
bytes[offset++] = f64_u8[0];
bytes[offset++] = f64_u8[1];
bytes[offset++] = f64_u8[2];
bytes[offset++] = f64_u8[3];
bytes[offset++] = f64_u8[4];
bytes[offset++] = f64_u8[5];
bytes[offset++] = f64_u8[6];
bytes[offset++] = f64_u8[7];
}
function readInt32(bb: ByteBuffer): number {
let offset = advance(bb, 4);
let bytes = bb.bytes;
return (
bytes[offset] |
(bytes[offset + 1] << 8) |
(bytes[offset + 2] << 16) |
(bytes[offset + 3] << 24)
);
}
function writeInt32(bb: ByteBuffer, value: number): void {
let offset = grow(bb, 4);
let bytes = bb.bytes;
bytes[offset] = value;
bytes[offset + 1] = value >> 8;
bytes[offset + 2] = value >> 16;
bytes[offset + 3] = value >> 24;
}
function readInt64(bb: ByteBuffer, unsigned: boolean): Long {
return {
low: readInt32(bb),
high: readInt32(bb),
unsigned,
};
}
function writeInt64(bb: ByteBuffer, value: Long): void {
writeInt32(bb, value.low);
writeInt32(bb, value.high);
}
function readVarint32(bb: ByteBuffer): number {
let c = 0;
let value = 0;
let b: number;
do {
b = readByte(bb);
if (c < 32) value |= (b & 0x7F) << c;
c += 7;
} while (b & 0x80);
return value;
}
function writeVarint32(bb: ByteBuffer, value: number): void {
value >>>= 0;
while (value >= 0x80) {
writeByte(bb, (value & 0x7f) | 0x80);
value >>>= 7;
}
writeByte(bb, value);
}
function readVarint64(bb: ByteBuffer, unsigned: boolean): Long {
let part0 = 0;
let part1 = 0;
let part2 = 0;
let b: number;
b = readByte(bb); part0 = (b & 0x7F); if (b & 0x80) {
b = readByte(bb); part0 |= (b & 0x7F) << 7; if (b & 0x80) {
b = readByte(bb); part0 |= (b & 0x7F) << 14; if (b & 0x80) {
b = readByte(bb); part0 |= (b & 0x7F) << 21; if (b & 0x80) {
b = readByte(bb); part1 = (b & 0x7F); if (b & 0x80) {
b = readByte(bb); part1 |= (b & 0x7F) << 7; if (b & 0x80) {
b = readByte(bb); part1 |= (b & 0x7F) << 14; if (b & 0x80) {
b = readByte(bb); part1 |= (b & 0x7F) << 21; if (b & 0x80) {
b = readByte(bb); part2 = (b & 0x7F); if (b & 0x80) {
b = readByte(bb); part2 |= (b & 0x7F) << 7;
}
}
}
}
}
}
}
}
}
return {
low: part0 | (part1 << 28),
high: (part1 >>> 4) | (part2 << 24),
unsigned,
};
}
function writeVarint64(bb: ByteBuffer, value: Long): void {
let part0 = value.low >>> 0;
let part1 = ((value.low >>> 28) | (value.high << 4)) >>> 0;
let part2 = value.high >>> 24;
// ref: src/google/protobuf/io/coded_stream.cc
let size =
part2 === 0 ?
part1 === 0 ?
part0 < 1 << 14 ?
part0 < 1 << 7 ? 1 : 2 :
part0 < 1 << 21 ? 3 : 4 :
part1 < 1 << 14 ?
part1 < 1 << 7 ? 5 : 6 :
part1 < 1 << 21 ? 7 : 8 :
part2 < 1 << 7 ? 9 : 10;
let offset = grow(bb, size);
let bytes = bb.bytes;
switch (size) {
case 10: bytes[offset + 9] = (part2 >>> 7) & 0x01;
case 9: bytes[offset + 8] = size !== 9 ? part2 | 0x80 : part2 & 0x7F;
case 8: bytes[offset + 7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
case 7: bytes[offset + 6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
case 6: bytes[offset + 5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
case 5: bytes[offset + 4] = size !== 5 ? part1 | 0x80 : part1 & 0x7F;
case 4: bytes[offset + 3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
case 3: bytes[offset + 2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
case 2: bytes[offset + 1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
case 1: bytes[offset] = size !== 1 ? part0 | 0x80 : part0 & 0x7F;
}
}
function readVarint32ZigZag(bb: ByteBuffer): number {
let value = readVarint32(bb);
// ref: src/google/protobuf/wire_format_lite.h
return (value >>> 1) ^ -(value & 1);
}
function writeVarint32ZigZag(bb: ByteBuffer, value: number): void {
// ref: src/google/protobuf/wire_format_lite.h
writeVarint32(bb, (value << 1) ^ (value >> 31));
}
function readVarint64ZigZag(bb: ByteBuffer): Long {
let value = readVarint64(bb, /* unsigned */ false);
let low = value.low;
let high = value.high;
let flip = -(low & 1);
// ref: src/google/protobuf/wire_format_lite.h
return {
low: ((low >>> 1) | (high << 31)) ^ flip,
high: (high >>> 1) ^ flip,
unsigned: false,
};
}
function writeVarint64ZigZag(bb: ByteBuffer, value: Long): void {
let low = value.low;
let high = value.high;
let flip = high >> 31;
// ref: src/google/protobuf/wire_format_lite.h
writeVarint64(bb, {
low: (low << 1) ^ flip,
high: ((high << 1) | (low >>> 31)) ^ flip,
unsigned: false,
});
} | the_stack |
declare module 'vscode' {
/**
* Configuration for a debug session.
*/
export interface DebugConfiguration {
/**
* The type of the debug session.
*/
type: string;
/**
* The name of the debug session.
*/
name: string;
/**
* The request type of the debug session.
*/
request: string;
/**
* Additional debug type specific properties.
*/
[key: string]: any;
}
/**
* A debug session.
*/
export interface DebugSession {
/**
* The unique ID of this debug session.
*/
readonly id: string;
/**
* The debug session's type from the [debug configuration](#DebugConfiguration).
*/
readonly type: string;
/**
* The parent session of this debug session, if it was created as a child.
* @see DebugSessionOptions.parentSession
*/
readonly parentSession?: DebugSession;
/**
* The debug session's name from the [debug configuration](#DebugConfiguration).
*/
readonly name: string;
/**
* The workspace folder of this session or `undefined` for a folderless setup.
*/
readonly workspaceFolder: WorkspaceFolder | undefined;
/**
* The "resolved" [debug configuration](#DebugConfiguration) of this session.
* "Resolved" means that
* - all variables have been substituted and
* - platform specific attribute sections have been "flattened" for the matching platform and removed for non-matching platforms.
*/
readonly configuration: DebugConfiguration;
/**
* Send a custom request to the debug adapter.
*/
customRequest(command: string, args?: any): Thenable<any>;
/**
* Maps a VS Code breakpoint to the corresponding Debug Adapter Protocol (DAP) breakpoint that is managed by the debug adapter of the debug session.
* If no DAP breakpoint exists (either because the VS Code breakpoint was not yet registered or because the debug adapter is not interested in the breakpoint), the value `undefined` is returned.
*
* @param breakpoint A VS Code [breakpoint](#Breakpoint).
* @return A promise that resolves to the Debug Adapter Protocol breakpoint or `undefined`.
*/
getDebugProtocolBreakpoint(breakpoint: Breakpoint): Thenable<DebugProtocolBreakpoint | undefined>;
}
/**
* A custom Debug Adapter Protocol event received from a [debug session](#DebugSession).
*/
export interface DebugSessionCustomEvent {
/**
* The [debug session](#DebugSession) for which the custom event was received.
*/
readonly session: DebugSession;
/**
* Type of event.
*/
readonly event: string;
/**
* Event specific information.
*/
readonly body?: any;
}
/**
* A debug configuration provider allows to add the initial debug configurations to a newly created launch.json
* and to resolve a launch configuration before it is used to start a new debug session.
* A debug configuration provider is registered via #debug.registerDebugConfigurationProvider.
*/
export interface DebugConfigurationProvider {
/**
* Provides initial [debug configuration](#DebugConfiguration). If more than one debug configuration provider is
* registered for the same type, debug configurations are concatenated in arbitrary order.
*
* @param folder The workspace folder for which the configurations are used or `undefined` for a folderless setup.
* @param token A cancellation token.
* @return An array of [debug configurations](#DebugConfiguration).
*/
provideDebugConfigurations?(
folder: WorkspaceFolder | undefined,
token?: CancellationToken
): ProviderResult<DebugConfiguration[]>;
/**
* Resolves a [debug configuration](#DebugConfiguration) by filling in missing values or by adding/changing/removing attributes.
* If more than one debug configuration provider is registered for the same type, the resolveDebugConfiguration calls are chained
* in arbitrary order and the initial debug configuration is piped through the chain.
* Returning the value 'undefined' prevents the debug session from starting.
* Returning the value 'null' prevents the debug session from starting and opens the underlying debug configuration instead.
*
* @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup.
* @param debugConfiguration The [debug configuration](#DebugConfiguration) to resolve.
* @param token A cancellation token.
* @return The resolved debug configuration or undefined or null.
*/
resolveDebugConfiguration?(
folder: WorkspaceFolder | undefined,
debugConfiguration: DebugConfiguration,
token?: CancellationToken
): ProviderResult<DebugConfiguration>;
/**
* This hook is directly called after 'resolveDebugConfiguration' but with all variables substituted.
* It can be used to resolve or verify a [debug configuration](#DebugConfiguration) by filling in missing values or by adding/changing/removing attributes.
* If more than one debug configuration provider is registered for the same type, the 'resolveDebugConfigurationWithSubstitutedVariables' calls are chained
* in arbitrary order and the initial debug configuration is piped through the chain.
* Returning the value 'undefined' prevents the debug session from starting.
* Returning the value 'null' prevents the debug session from starting and opens the underlying debug configuration instead.
*
* @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup.
* @param debugConfiguration The [debug configuration](#DebugConfiguration) to resolve.
* @param token A cancellation token.
* @return The resolved debug configuration or undefined or null.
*/
resolveDebugConfigurationWithSubstitutedVariables?(
folder: WorkspaceFolder | undefined,
debugConfiguration: DebugConfiguration,
token?: CancellationToken
): ProviderResult<DebugConfiguration>;
}
/**
* Represents a debug adapter executable and optional arguments and runtime options passed to it.
*/
export class DebugAdapterExecutable {
/**
* Creates a description for a debug adapter based on an executable program.
*
* @param command The command or executable path that implements the debug adapter.
* @param args Optional arguments to be passed to the command or executable.
* @param options Optional options to be used when starting the command or executable.
*/
constructor(
command: string,
args?: string[],
options?: DebugAdapterExecutableOptions
);
/**
* The command or path of the debug adapter executable.
* A command must be either an absolute path of an executable or the name of an command to be looked up via the PATH environment variable.
* The special value 'node' will be mapped to VS Code's built-in Node.js runtime.
*/
readonly command: string;
/**
* The arguments passed to the debug adapter executable. Defaults to an empty array.
*/
readonly args: string[];
/**
* Optional options to be used when the debug adapter is started.
* Defaults to undefined.
*/
readonly options?: DebugAdapterExecutableOptions;
}
/**
* Options for a debug adapter executable.
*/
export interface DebugAdapterExecutableOptions {
/**
* The additional environment of the executed program or shell. If omitted
* the parent process' environment is used. If provided it is merged with
* the parent process' environment.
*/
env?: { [key: string]: string };
/**
* The current working directory for the executed debug adapter.
*/
cwd?: string;
}
/**
* Represents a debug adapter running as a socket based server.
*/
export class DebugAdapterServer {
/**
* The port.
*/
readonly port: number;
/**
* The host.
*/
readonly host?: string;
/**
* Create a description for a debug adapter running as a socket based server.
*/
constructor(port: number, host?: string);
}
/**
* Represents a debug adapter running as a Named Pipe (on Windows)/UNIX Domain Socket (on non-Windows) based server.
*/
export class DebugAdapterNamedPipeServer {
/**
* The path to the NamedPipe/UNIX Domain Socket.
*/
readonly path: string;
/**
* Create a description for a debug adapter running as a socket based server.
*/
constructor(path: string);
}
/**
* A debug adapter that implements the Debug Adapter Protocol can be registered with VS Code if it implements the DebugAdapter interface.
*/
export interface DebugAdapter extends Disposable {
/**
* An event which fires after the debug adapter has sent a Debug Adapter Protocol message to VS Code.
* Messages can be requests, responses, or events.
*/
readonly onDidSendMessage: Event<DebugProtocolMessage>;
/**
* Handle a Debug Adapter Protocol message.
* Messages can be requests, responses, or events.
* Results or errors are returned via onSendMessage events.
* @param message A Debug Adapter Protocol message
*/
handleMessage(message: DebugProtocolMessage): void;
}
/**
* A DebugProtocolMessage is an opaque stand-in type for the [ProtocolMessage](https://microsoft.github.io/debug-adapter-protocol/specification#Base_Protocol_ProtocolMessage) type defined in the Debug Adapter Protocol.
*/
export interface DebugProtocolMessage {
// Properties: see details [here](https://microsoft.github.io/debug-adapter-protocol/specification#Base_Protocol_ProtocolMessage).
}
/**
* A debug adapter descriptor for an inline implementation.
*/
export class DebugAdapterInlineImplementation {
/**
* Create a descriptor for an inline implementation of a debug adapter.
*/
constructor(implementation: DebugAdapter);
}
export type DebugAdapterDescriptor =
| DebugAdapterExecutable
| DebugAdapterServer
| DebugAdapterNamedPipeServer
| DebugAdapterInlineImplementation;
export interface DebugAdapterDescriptorFactory {
/**
* 'createDebugAdapterDescriptor' is called at the start of a debug session to provide details about the debug adapter to use.
* These details must be returned as objects of type [DebugAdapterDescriptor](#DebugAdapterDescriptor).
* Currently two types of debug adapters are supported:
* - a debug adapter executable is specified as a command path and arguments (see [DebugAdapterExecutable](#DebugAdapterExecutable)),
* - a debug adapter server reachable via a communication port (see [DebugAdapterServer](#DebugAdapterServer)).
* If the method is not implemented the default behavior is this:
* createDebugAdapter(session: DebugSession, executable: DebugAdapterExecutable) {
* if (typeof session.configuration.debugServer === 'number') {
* return new DebugAdapterServer(session.configuration.debugServer);
* }
* return executable;
* }
* @param session The [debug session](#DebugSession) for which the debug adapter will be used.
* @param executable The debug adapter's executable information as specified in the package.json (or undefined if no such information exists).
* @return a [debug adapter descriptor](#DebugAdapterDescriptor) or undefined.
*/
createDebugAdapterDescriptor(
session: DebugSession,
executable: DebugAdapterExecutable | undefined
): ProviderResult<DebugAdapterDescriptor>;
}
/**
* A Debug Adapter Tracker is a means to track the communication between VS Code and a Debug Adapter.
*/
export interface DebugAdapterTracker {
/**
* A session with the debug adapter is about to be started.
*/
onWillStartSession?(): void;
/**
* The debug adapter is about to receive a Debug Adapter Protocol message from VS Code.
*/
onWillReceiveMessage?(message: any): void;
/**
* The debug adapter has sent a Debug Adapter Protocol message to VS Code.
*/
onDidSendMessage?(message: any): void;
/**
* The debug adapter session is about to be stopped.
*/
onWillStopSession?(): void;
/**
* An error with the debug adapter has occurred.
*/
onError?(error: Error): void;
/**
* The debug adapter has exited with the given exit code or signal.
*/
onExit?(code: number | undefined, signal: string | undefined): void;
}
export interface DebugAdapterTrackerFactory {
/**
* The method 'createDebugAdapterTracker' is called at the start of a debug session in order
* to return a "tracker" object that provides read-access to the communication between VS Code and a debug adapter.
*
* @param session The [debug session](#DebugSession) for which the debug adapter tracker will be used.
* @return A [debug adapter tracker](#DebugAdapterTracker) or undefined.
*/
createDebugAdapterTracker(
session: DebugSession
): ProviderResult<DebugAdapterTracker>;
}
/**
* Represents the debug console.
*/
export interface DebugConsole {
/**
* Append the given value to the debug console.
*
* @param value A string, falsy values will not be printed.
*/
append(value: string): void;
/**
* Append the given value and a line feed character
* to the debug console.
*
* @param value A string, falsy values will be printed.
*/
appendLine(value: string): void;
}
/**
* An event describing the changes to the set of [breakpoints](#Breakpoint).
*/
export interface BreakpointsChangeEvent {
/**
* Added breakpoints.
*/
readonly added: ReadonlyArray<Breakpoint>;
/**
* Removed breakpoints.
*/
readonly removed: ReadonlyArray<Breakpoint>;
/**
* Changed breakpoints.
*/
readonly changed: ReadonlyArray<Breakpoint>;
}
/**
* The base class of all breakpoint types.
*/
export class Breakpoint {
/**
* The unique ID of the breakpoint.
*/
readonly id: string;
/**
* Is breakpoint enabled.
*/
readonly enabled: boolean;
/**
* An optional expression for conditional breakpoints.
*/
readonly condition?: string;
/**
* An optional expression that controls how many hits of the breakpoint are ignored.
*/
readonly hitCondition?: string;
/**
* An optional message that gets logged when this breakpoint is hit. Embedded expressions within {} are interpolated by the debug adapter.
*/
readonly logMessage?: string;
protected constructor(
enabled?: boolean,
condition?: string,
hitCondition?: string,
logMessage?: string
);
}
/**
* A breakpoint specified by a source location.
*/
export class SourceBreakpoint extends Breakpoint {
/**
* The source and line position of this breakpoint.
*/
readonly location: Location;
/**
* Create a new breakpoint for a source location.
*/
constructor(
location: Location,
enabled?: boolean,
condition?: string,
hitCondition?: string,
logMessage?: string
);
}
/**
* A breakpoint specified by a function name.
*/
export class FunctionBreakpoint extends Breakpoint {
/**
* The name of the function to which this breakpoint is attached.
*/
readonly functionName: string;
/**
* Create a new function breakpoint.
*/
constructor(
functionName: string,
enabled?: boolean,
condition?: string,
hitCondition?: string,
logMessage?: string
);
}
/**
* Debug console mode used by debug session, see [options](#DebugSessionOptions).
*/
export enum DebugConsoleMode {
/**
* Debug session should have a separate debug console.
*/
Separate = 0,
/**
* Debug session should share debug console with its parent session.
* This value has no effect for sessions which do not have a parent session.
*/
MergeWithParent = 1,
}
/**
* Options for [starting a debug session](#debug.startDebugging).
*/
export interface DebugSessionOptions {
/**
* When specified the newly created debug session is registered as a "child" session of this
* "parent" debug session.
*/
parentSession?: DebugSession;
/**
* Controls whether lifecycle requests like 'restart' are sent to the newly created session or its parent session.
* By default (if the property is false or missing), lifecycle requests are sent to the new session.
* This property is ignored if the session has no parent session.
*/
lifecycleManagedByParent?: boolean;
/**
* Controls whether this session should have a separate debug console or share it
* with the parent session. Has no effect for sessions which do not have a parent session.
* Defaults to Separate.
*/
consoleMode?: DebugConsoleMode;
/**
* Controls whether this session should run without debugging, thus ignoring breakpoints.
* When this property is not specified, the value from the parent session (if there is one) is used.
*/
noDebug?: boolean;
/**
* Controls if the debug session's parent session is shown in the CALL STACK view even if it has only a single child.
* By default, the debug session will never hide its parent.
* If compact is true, debug sessions with a single child are hidden in the CALL STACK view to make the tree more compact.
*/
compact?: boolean;
}
/**
* A DebugConfigurationProviderTriggerKind specifies when the `provideDebugConfigurations` method of a `DebugConfigurationProvider` is triggered.
* Currently there are two situations: to provide the initial debug configurations for a newly created launch.json or
* to provide dynamically generated debug configurations when the user asks for them through the UI (e.g. via the "Select and Start Debugging" command).
* A trigger kind is used when registering a `DebugConfigurationProvider` with #debug.registerDebugConfigurationProvider.
*/
export enum DebugConfigurationProviderTriggerKind {
/**
* `DebugConfigurationProvider.provideDebugConfigurations` is called to provide the initial debug configurations for a newly created launch.json.
*/
Initial = 1,
/**
* `DebugConfigurationProvider.provideDebugConfigurations` is called to provide dynamically generated debug configurations when the user asks for them through the UI (e.g. via the "Select and Start Debugging" command).
*/
Dynamic = 2
}
/**
* A DebugProtocolSource is an opaque stand-in type for the [Source](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source) type defined in the Debug Adapter Protocol.
*/
export interface DebugProtocolSource {
// Properties: see details [here](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source).
}
/**
* A DebugProtocolBreakpoint is an opaque stand-in type for the [Breakpoint](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Breakpoint) type defined in the Debug Adapter Protocol.
*/
export interface DebugProtocolBreakpoint {
// Properties: see details [here](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Breakpoint).
}
/**
* Namespace for debug functionality.
*/
export namespace debug {
/**
* The currently active [debug session](#DebugSession) or `undefined`. The active debug session is the one
* represented by the debug action floating window or the one currently shown in the drop down menu of the debug action floating window.
* If no debug session is active, the value is `undefined`.
*/
export let activeDebugSession: DebugSession | undefined;
/**
* The currently active [debug console](#DebugConsole).
* If no debug session is active, output sent to the debug console is not shown.
*/
export let activeDebugConsole: DebugConsole;
/**
* List of breakpoints.
*/
export let breakpoints: Breakpoint[];
/**
* An [event](#Event) which fires when the [active debug session](#debug.activeDebugSession)
* has changed. *Note* that the event also fires when the active debug session changes
* to `undefined`.
*/
export const onDidChangeActiveDebugSession: Event<DebugSession | undefined>;
/**
* An [event](#Event) which fires when a new [debug session](#DebugSession) has been started.
*/
export const onDidStartDebugSession: Event<DebugSession>;
/**
* An [event](#Event) which fires when a custom DAP event is received from the [debug session](#DebugSession).
*/
export const onDidReceiveDebugSessionCustomEvent: Event<DebugSessionCustomEvent>;
/**
* An [event](#Event) which fires when a [debug session](#DebugSession) has terminated.
*/
export const onDidTerminateDebugSession: Event<DebugSession>;
/**
* An [event](#Event) that is emitted when the set of breakpoints is added, removed, or changed.
*/
export const onDidChangeBreakpoints: Event<BreakpointsChangeEvent>;
/**
* Register a [debug configuration provider](#DebugConfigurationProvider) for a specific debug type.
* The optional [triggerKind](#DebugConfigurationProviderTriggerKind) can be used to specify when the `provideDebugConfigurations` method of the provider is triggered.
* Currently two trigger kinds are possible: with the value `Initial` (or if no trigger kind argument is given) the `provideDebugConfigurations` method is used to provide the initial debug configurations to be copied into a newly created launch.json.
* With the trigger kind `Dynamic` the `provideDebugConfigurations` method is used to dynamically determine debug configurations to be presented to the user (in addition to the static configurations from the launch.json).
* Please note that the `triggerKind` argument only applies to the `provideDebugConfigurations` method: so the `resolveDebugConfiguration` methods are not affected at all.
* Registering a single provider with resolve methods for different trigger kinds, results in the same resolve methods called multiple times.
* More than one provider can be registered for the same type.
*
* @param type The debug type for which the provider is registered.
* @param provider The [debug configuration provider](#DebugConfigurationProvider) to register.
* @param triggerKind The [trigger](#DebugConfigurationProviderTrigger) for which the 'provideDebugConfiguration' method of the provider is registered. If `triggerKind` is missing, the value `DebugConfigurationProviderTriggerKind.Initial` is assumed.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDebugConfigurationProvider(
debugType: string,
provider: DebugConfigurationProvider,
triggerKind?: DebugConfigurationProviderTriggerKind
): Disposable;
/**
* Register a [debug adapter descriptor factory](#DebugAdapterDescriptorFactory) for a specific debug type.
* An extension is only allowed to register a DebugAdapterDescriptorFactory for the debug type(s) defined by the extension. Otherwise an error is thrown.
* Registering more than one DebugAdapterDescriptorFactory for a debug type results in an error.
*
* @param debugType The debug type for which the factory is registered.
* @param factory The [debug adapter descriptor factory](#DebugAdapterDescriptorFactory) to register.
* @return A [disposable](#Disposable) that unregisters this factory when being disposed.
*/
export function registerDebugAdapterDescriptorFactory(
debugType: string,
factory: DebugAdapterDescriptorFactory
): Disposable;
/**
* Register a debug adapter tracker factory for the given debug type.
*
* @param debugType The debug type for which the factory is registered or '*' for matching all debug types.
* @param factory The [debug adapter tracker factory](#DebugAdapterTrackerFactory) to register.
* @return A [disposable](#Disposable) that unregisters this factory when being disposed.
*/
export function registerDebugAdapterTrackerFactory(
debugType: string,
factory: DebugAdapterTrackerFactory
): Disposable;
/**
* Start debugging by using either a named launch or named compound configuration,
* or by directly passing a [DebugConfiguration](#DebugConfiguration).
* The named configurations are looked up in '.vscode/launch.json' found in the given folder.
* Before debugging starts, all unsaved files are saved and the launch configurations are brought up-to-date.
* Folder specific variables used in the configuration (e.g. '${workspaceFolder}') are resolved against the given folder.
* @param folder The [workspace folder](#WorkspaceFolder) for looking up named configurations and resolving variables or `undefined` for a non-folder setup.
* @param nameOrConfiguration Either the name of a debug or compound configuration or a [DebugConfiguration](#DebugConfiguration) object.
* @param parent If specified the newly created debug session is registered as a "child" session of a "parent" debug session.
* @return A thenable that resolves when debugging could be successfully started.
*/
export function startDebugging(
folder: WorkspaceFolder | undefined,
nameOrConfiguration: string | DebugConfiguration,
parentSessionOrOptions?: DebugSession | DebugSessionOptions
): Thenable<boolean>;
/**
* Stop the given debug session or stop all debug sessions if session is omitted.
* @param session The [debug session](#DebugSession) to stop; if omitted all sessions are stopped.
*/
export function stopDebugging(session?: DebugSession): Thenable<void>;
/**
* Add breakpoints.
* @param breakpoints The breakpoints to add.
*/
export function addBreakpoints(breakpoints: Breakpoint[]): void;
/**
* Remove breakpoints.
* @param breakpoints The breakpoints to remove.
*/
export function removeBreakpoints(breakpoints: Breakpoint[]): void;
/**
* Converts a "Source" descriptor object received via the Debug Adapter Protocol into a Uri that can be used to load its contents.
* If the source descriptor is based on a path, a file Uri is returned.
* If the source descriptor uses a reference number, a specific debug Uri (scheme 'debug') is constructed that requires a corresponding VS Code ContentProvider and a running debug session
*
* If the "Source" descriptor has insufficient information for creating the Uri, an error is thrown.
*
* @param source An object conforming to the [Source](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source) type defined in the Debug Adapter Protocol.
* @param session An optional debug session that will be used when the source descriptor uses a reference number to load the contents from an active debug session.
* @return A uri that can be used to load the contents of the source.
*/
export function asDebugSourceUri(source: DebugProtocolSource, session?: DebugSession): Uri;
}
} | the_stack |
import { ProgressBar } from '../../progressbar';
import { ProgressAnimation } from '../utils/progress-animation';
import { PathOption, getElement, Size, measureText } from '@syncfusion/ej2-svg-base';
import { ITextRenderEventArgs } from '../model/progress-interface';
import { stringToNumber, getPathArc } from '../utils/helper';
import { Segment } from './segment-progress';
import { TextOption } from '../utils/helper';
import { ModeType } from '../utils';
/**
* Progressbar of type circular
*/
export class Circular {
private progress: ProgressBar;
private delay: number;
private segment: Segment = new Segment();
private animation: ProgressAnimation = new ProgressAnimation();
private isRange: boolean;
private centerX: number;
private centerY: number;
private maxThickness: number;
private availableSize: number;
private trackEndAngle: number;
constructor(progress: ProgressBar) {
this.progress = progress;
}
/** To render the circular track */
public renderCircularTrack(): void {
const progress: ProgressBar = this.progress;
const circularTrackGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + '_CircularTrackGroup' });
let radius: number;
let endAngle: number;
const startAngle: number = progress.startAngle;
progress.totalAngle = (progress.endAngle - progress.startAngle) % 360;
progress.totalAngle = (progress.totalAngle <= 0 ? (360 + progress.totalAngle) : progress.totalAngle);
progress.totalAngle -= (progress.totalAngle === 360) ? 0.01 : 0;
this.trackEndAngle = endAngle = (progress.startAngle + (
(progress.enableRtl) ? -progress.totalAngle : +progress.totalAngle)) % 360;
this.centerX = progress.progressRect.x + (progress.progressRect.width / 2);
this.centerY = progress.progressRect.y + (progress.progressRect.height / 2);
this.maxThickness = Math.max(progress.trackThickness, progress.progressThickness) ||
Math.max(progress.themeStyle.circularProgressThickness, progress.themeStyle.circularTrackThickness);
this.availableSize = (Math.min(progress.progressRect.height, progress.progressRect.width) / 2) - this.maxThickness / 2;
radius = stringToNumber(progress.radius, this.availableSize);
radius = (radius === null) ? 0 : radius;
const stroke: string = (progress.argsData.trackColor || progress.themeStyle.circularTrackColor);
const fill: string = (progress.enablePieProgress) ? (progress.argsData.trackColor || progress.themeStyle.circularTrackColor) : 'none';
const strokeWidth: number = (progress.enablePieProgress) ? 0 :
(progress.trackThickness || progress.themeStyle.circularTrackThickness);
const circularPath: string = getPathArc(
this.centerX, this.centerY, radius, startAngle, endAngle, progress.enableRtl, progress.enablePieProgress);
this.isRange = (this.progress.rangeColors[0].color !== '' || this.progress.rangeColors[0].start !== null ||
this.progress.rangeColors[0].end !== null);
const option: PathOption = new PathOption(
progress.element.id + '_Circulartrack', fill, strokeWidth, stroke, progress.themeStyle.trackOpacity, '0', circularPath
);
const circularTrack: Element = progress.renderer.drawPath(option);
progress.trackWidth = (<SVGPathElement>circularTrack).getTotalLength();
if (progress.segmentCount > 1 && !progress.enableProgressSegments && !progress.enablePieProgress && !this.isRange) {
progress.segmentSize = progress.calculateSegmentSize(progress.trackWidth, strokeWidth);
circularTrack.setAttribute('stroke-dasharray', progress.segmentSize);
}
if (progress.cornerRadius === 'Round' && !progress.enablePieProgress && !this.isRange) {
circularTrack.setAttribute('stroke-linecap', 'round');
}
circularTrackGroup.appendChild(circularTrack);
progress.svgObject.appendChild(circularTrackGroup);
}
/** To render the circular progress */
public renderCircularProgress(previousEnd?: number, previousTotalEnd?: number, refresh?: boolean): void {
const progress: ProgressBar = this.progress;
const startAngle: number = progress.startAngle;
let endAngle: number; let totalAngle: number;
let radius: number; let previousPath: string;
let progressTotalAngle: number;
let progressEnd: number; let circularProgress: Element;
let linearClipPath: Element;
let circularProgressGroup: Element;
let segmentWidth: number;
if (!refresh) {
circularProgressGroup = progress.renderer.createGroup({ 'id': progress.element.id + '_CircularProgressGroup' });
} else {
circularProgressGroup = getElement(progress.element.id + '_CircularProgressGroup');
}
radius = stringToNumber(progress.innerRadius, this.availableSize);
radius = (radius === null) ? 0 : radius;
progress.previousTotalEnd = progressEnd = progress.calculateProgressRange(progress.argsData.value);
const progressEndAngle: number = (progress.startAngle + ((progress.enableRtl) ? -progressEnd : progressEnd)) % 360;
progress.previousEndAngle = endAngle = ((progress.isIndeterminate && !progress.enableProgressSegments) ? (progress.startAngle + (
(progress.enableRtl) ? -progress.totalAngle : progress.totalAngle)) % 360 : progressEndAngle
);
progressTotalAngle = (progressEnd - progress.startAngle) % 360;
progressTotalAngle = (progressTotalAngle <= 0 ? (360 + progressTotalAngle) : progressTotalAngle);
progressTotalAngle -= (progressTotalAngle === 360) ? 0.01 : 0;
const circularPath: string = getPathArc(
this.centerX, this.centerY, radius, startAngle, endAngle, progress.enableRtl, progress.enablePieProgress);
const stroke: string = this.checkingCircularProgressColor();
const fill: string = (progress.enablePieProgress) ? stroke : 'none';
const thickness: number = (progress.progressThickness || progress.themeStyle.circularProgressThickness);
const strokeWidth: number = (progress.enablePieProgress) ? 0 : thickness;
const option: PathOption = new PathOption(
progress.element.id + '_Circularprogress', fill, strokeWidth, stroke, progress.themeStyle.progressOpacity, '0', circularPath
);
progress.progressWidth = (<SVGPathElement>progress.renderer.drawPath(option)).getTotalLength();
progress.segmentSize = this.validateSegmentSize(progress, thickness);
if (progress.secondaryProgress !== null && !progress.isIndeterminate) {
this.renderCircularBuffer(progress, radius, progressTotalAngle);
}
if (progress.argsData.value !== null) {
if (progress.segmentColor.length !== 0 && !progress.isIndeterminate && !progress.enablePieProgress) {
totalAngle = (!progress.enableProgressSegments) ? progress.totalAngle : progressTotalAngle;
segmentWidth = (!progress.enableProgressSegments) ? progress.trackWidth : progress.progressWidth;
circularProgress = this.segment.createCircularSegment(
progress, '_CircularProgressSegment', this.centerX, this.centerY, radius, progress.argsData.value,
progress.themeStyle.progressOpacity, thickness, totalAngle, segmentWidth
);
} else if (this.isRange && !progress.isIndeterminate) {
circularProgress = this.segment.createCircularRange(this.centerX, this.centerY, radius, progress);
} else {
if (!refresh) {
circularProgress = progress.renderer.drawPath(option);
} else {
circularProgress = getElement(progress.element.id + '_Circularprogress');
previousPath = circularProgress.getAttribute('d');
circularProgress.setAttribute('stroke', stroke);
circularProgress.setAttribute('d', circularPath);
}
if (progress.segmentCount > 1 && !progress.enablePieProgress) {
circularProgress.setAttribute('stroke-dasharray', progress.segmentSize);
}
if (progress.cornerRadius === 'Round' && startAngle !== endAngle) {
circularProgress.setAttribute('stroke-linecap', 'round');
}
}
circularProgressGroup.appendChild(circularProgress);
if (progress.isActive && !progress.isIndeterminate && !progress.enablePieProgress) {
this.renderActiveState(
circularProgressGroup, radius, strokeWidth, circularPath, progressEndAngle, progressEnd, refresh
);
}
if (progress.animation.enable || progress.isIndeterminate) {
this.delay = (progress.secondaryProgress !== null) ? 300 : progress.animation.delay;
linearClipPath = progress.createClipPath(progress.clipPath, null, refresh ? previousPath : '', refresh);
circularProgressGroup.appendChild(progress.clipPath);
if (progress.animation.enable && !progress.isIndeterminate && !progress.isActive) {
circularProgress.setAttribute('style', 'clip-path:url(#' + progress.element.id + '_clippath)');
this.animation.doCircularAnimation(
this.centerX, this.centerY, radius, progressEndAngle, progressEnd, linearClipPath, progress,
thickness, this.delay, refresh ? previousEnd : null, refresh ? previousTotalEnd : null
);
}
if (progress.isIndeterminate) {
if (progress.enableProgressSegments) {
linearClipPath.setAttribute('d', getPathArc(
this.centerX, this.centerY, radius + (thickness / 2), progress.startAngle,
this.trackEndAngle, progress.enableRtl, true)
);
}
circularProgress.setAttribute('style', 'clip-path:url(#' + progress.element.id + '_clippath)');
this.animation.doCircularIndeterminate(
(!progress.enableProgressSegments) ? linearClipPath : circularProgress, progress, startAngle,
progressEndAngle, this.centerX, this.centerY, radius, thickness, linearClipPath
);
}
}
progress.svgObject.appendChild(circularProgressGroup);
}
}
/** To render the circular buffer */
private renderCircularBuffer(progress: ProgressBar, radius: number, progressTotalAngle: number): void {
let bufferClipPath: Element;
let circularBuffer: Element;
let segmentWidth: number;
let totalAngle: number;
const circularBufferGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + '_ CircularBufferGroup' });
const bufferEnd: number = progress.calculateProgressRange(progress.secondaryProgress);
const endAngle: number = (progress.startAngle + ((progress.enableRtl) ? -bufferEnd : bufferEnd)) % 360;
const circularPath: string = getPathArc(
this.centerX, this.centerY, radius, progress.startAngle, endAngle, progress.enableRtl, progress.enablePieProgress
);
const stroke: string = this.checkingCircularProgressColor();
const fill: string = (progress.enablePieProgress) ? stroke : 'none';
const strokeWidth: number = (progress.enablePieProgress) ? 0 :
(progress.progressThickness || progress.themeStyle.circularProgressThickness);
const option: PathOption = new PathOption(
progress.element.id + '_Circularbuffer', fill, strokeWidth, stroke,
progress.themeStyle.bufferOpacity, '0', circularPath
);
if (progress.segmentColor.length !== 0 && !progress.isIndeterminate && !progress.enablePieProgress && !this.isRange) {
totalAngle = (!progress.enableProgressSegments) ? progress.totalAngle : progressTotalAngle;
segmentWidth = (!progress.enableProgressSegments) ? progress.trackWidth : progress.progressWidth;
circularBuffer = this.segment.createCircularSegment(
progress, '_CircularBufferSegment', this.centerX, this.centerY, radius,
progress.secondaryProgress, progress.themeStyle.bufferOpacity, strokeWidth, totalAngle, segmentWidth
);
} else {
circularBuffer = progress.renderer.drawPath(option);
if (progress.segmentCount > 1 && !progress.enablePieProgress && !this.isRange) {
circularBuffer.setAttribute('stroke-dasharray', progress.segmentSize);
}
if (progress.cornerRadius === 'Round' && !this.isRange) {
circularBuffer.setAttribute('stroke-linecap', 'round');
}
}
circularBufferGroup.appendChild(circularBuffer);
if (progress.animation.enable && !progress.isActive) {
bufferClipPath = progress.createClipPath(progress.bufferClipPath, null, '', false);
circularBufferGroup.appendChild(progress.bufferClipPath);
circularBuffer.setAttribute('style', 'clip-path:url(#' + progress.element.id + '_clippathBuffer)');
this.animation.doCircularAnimation(
this.centerX, this.centerY, radius, endAngle, bufferEnd, bufferClipPath, progress,
(progress.progressThickness || progress.themeStyle.circularProgressThickness), progress.animation.delay
);
}
progress.svgObject.appendChild(circularBufferGroup);
}
/** To render the circular Label */
public renderCircularLabel(isProgressRefresh: boolean = false): void {
let end: number;
let circularLabel: Element;
let centerY: number;
let textSize: Size;
let option: TextOption;
const percentage: number = 100;
const progress: ProgressBar = this.progress;
const labelText: string = progress.labelStyle.text;
const circularLabelGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + '_CircularLabelGroup' });
if (document.getElementById(circularLabelGroup.id)) {
document.getElementById(circularLabelGroup.id).remove();
}
const labelValue: number = ((progress.value - progress.minimum) / (progress.maximum - progress.minimum)) * percentage;
const circularValue: number = (progress.value < progress.minimum || progress.value > progress.maximum) ? 0 : Math.round(labelValue);
const argsData: ITextRenderEventArgs = {
cancel: false, text: labelText ? labelText : String(circularValue) + '%', color: progress.labelStyle.color
};
progress.trigger('textRender', argsData);
if (!argsData.cancel) {
textSize = measureText(argsData.text, progress.labelStyle);
centerY = this.centerY + (textSize.height / 2);
option = new TextOption(
progress.element.id + '_circularLabel', progress.labelStyle.size || progress.themeStyle.circularFontSize,
progress.labelStyle.fontStyle || progress.themeStyle.circularFontStyle,
progress.labelStyle.fontFamily || progress.themeStyle.circularFontFamily, progress.labelStyle.fontWeight,
'middle', argsData.color || progress.themeStyle.fontColor, this.centerX, centerY, progress.progressRect.width,
progress.progressRect.height
);
circularLabel = progress.renderer.createText(option, argsData.text);
circularLabelGroup.appendChild(circularLabel);
if (progress.animation.enable && !progress.isIndeterminate) {
end = ((progress.value - progress.minimum) / (progress.maximum - progress.minimum)) * progress.totalAngle;
end = (progress.value < progress.minimum || progress.value > progress.maximum) ? 0 : end;
this.animation.doLabelAnimation(circularLabel, isProgressRefresh ? progress.previousWidth : progress.startAngle, end, progress, this.delay);
}
progress.svgObject.appendChild(circularLabelGroup);
progress.previousWidth = end;
}
}
/** To render a progressbar active state */
private renderActiveState(
progressGroup: Element, radius: number, strokeWidth: number, circularPath: string,
endAngle: number, totalEnd: number, refresh: boolean
): void {
let circularActive: Element;
let option: PathOption;
const progress: ProgressBar = this.progress;
const thickness: number = strokeWidth + 1;
if (!refresh) {
option = new PathOption(
progress.element.id + '_CircularActiveProgress', 'none', thickness, '#ffffff', 0.5, '0', circularPath
);
circularActive = progress.renderer.drawPath(option);
} else {
circularActive = getElement(progress.element.id + '_CircularActiveProgress');
circularActive.setAttribute('d', circularPath);
}
if (progress.segmentCount > 1) {
circularActive.setAttribute('stroke-dasharray', progress.segmentSize);
}
if (progress.cornerRadius === 'Round') {
circularActive.setAttribute('stroke-linecap', 'round');
}
const activeClip: Element = progress.createClipPath(progress.clipPath, null, '', refresh);
circularActive.setAttribute('style', 'clip-path:url(#' + progress.element.id + '_clippath)');
progressGroup.appendChild(circularActive);
progressGroup.appendChild(progress.clipPath);
this.animation.doCircularAnimation(
this.centerX, this.centerY, radius, endAngle, totalEnd, activeClip, progress,
thickness, 0, null, null, circularActive
);
}
/** Checking the segment size */
private validateSegmentSize(progress: ProgressBar, thickness: number): string {
let validSegment: string;
let progressSegment: number;
const rDiff: number = parseInt(progress.radius, 10) - parseInt(progress.innerRadius, 10);
if (rDiff !== 0 && !progress.enableProgressSegments) {
progressSegment = progress.trackWidth + (
(rDiff < 0) ? (progress.trackWidth * Math.abs(rDiff)) / parseInt(progress.radius, 10) :
-(progress.trackWidth * Math.abs(rDiff)) / parseInt(progress.radius, 10)
);
validSegment = progress.calculateSegmentSize(progressSegment, thickness);
} else if (progress.enableProgressSegments) {
validSegment = progress.calculateSegmentSize(progress.progressWidth, thickness);
} else {
validSegment = progress.segmentSize;
}
return validSegment;
}
/** checking progress color */
private checkingCircularProgressColor(): string {
let circularColor: string;
const progress: ProgressBar = this.progress;
const role: ModeType = progress.role;
switch (role) {
case 'Success':
circularColor = progress.themeStyle.success;
break;
case 'Info':
circularColor = progress.themeStyle.info;
break;
case 'Warning':
circularColor = progress.themeStyle.warning;
break;
case 'Danger':
circularColor = progress.themeStyle.danger;
break;
default:
circularColor = (progress.argsData.progressColor || progress.themeStyle.circularProgressColor);
}
return circularColor;
}
} | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// 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 Moment from 'moment';
import * as vscode from 'vscode';
/**
* Default host address.
*/
export const DEFAULT_HOST = '127.0.0.1';
/**
* The default directory where remote files should be stored.
*/
export const DEFAULT_HOST_DIR = './';
/**
* Default maximum size of a remote JSON message.
*/
export const DEFAULT_MAX_MESSAGE_SIZE = 16777215;
/**
* The default algorithm for crypting data by password.
*/
export const DEFAULT_PASSWORD_ALGORITHM = 'aes-256-ctr';
/**
* Default TCP port of a host.
*/
export const DEFAULT_PORT = 23979;
/**
* Name of the event to cancel a deployment.
*/
export const EVENT_CANCEL_DEPLOY = 'deploy.cancel';
/**
* Name of the event to cancel a pull.
*/
export const EVENT_CANCEL_PULL = 'pull.cancel';
/**
* Name of the event that is raised when
* configuration has been reloaded.
*/
export const EVENT_CONFIG_RELOADED = 'deploy.config.reloaded';
/**
* Name of the event that deploys files.
*/
export const EVENT_DEPLOYFILES = 'deploy.deployFiles';
/**
* Name of the event for the 'complete' for the
* event that deploys files.
*/
export const EVENT_DEPLOYFILES_COMPLETE = 'deploy.deployFiles.complete';
/**
* Name of the event for the 'error' for the
* event that deploys files.
*/
export const EVENT_DEPLOYFILES_ERROR = 'deploy.deployFiles.error';
/**
* Name of the event for the 'success' for the
* event that deploys files.
*/
export const EVENT_DEPLOYFILES_SUCCESS = 'deploy.deployFiles.success';
/**
* Name of the event that is raised when 'deploy on change'
* feature should be disabled.
*/
export const EVENT_DEPLOYONCHANGE_DISABLE = 'deploy.deployOnChange.disable';
/**
* Name of the event that is raised when 'deploy on change'
* feature should be enabled.
*/
export const EVENT_DEPLOYONCHANGE_ENABLE = 'deploy.deployOnChange.enable';
/**
* Name of the event that is raised when 'deploy on change'
* feature should be toggled.
*/
export const EVENT_DEPLOYONCHANGE_TOGGLE = 'deploy.deployOnChange.toggle';
/**
* Name of the event that is raised when 'deploy on save'
* feature should be disabled.
*/
export const EVENT_DEPLOYONSAVE_DISABLE = 'deploy.deployOnSave.disable';
/**
* Name of the event that is raised when 'deploy on save'
* feature should be enabled.
*/
export const EVENT_DEPLOYONSAVE_ENABLE = 'deploy.deployOnSave.enable';
/**
* Name of the event that is raised when 'deploy on save'
* feature should be toggled.
*/
export const EVENT_DEPLOYONSAVE_TOGGLE = 'deploy.deployOnSave.toggle';
/**
* Name of the event that is raised when 'sync when open'
* feature should be disabled.
*/
export const EVENT_SYNCWHENOPEN_DISABLE = 'deploy.syncWhenOpen.disable';
/**
* Name of the event that is raised when 'sync when open'
* feature should be enabled.
*/
export const EVENT_SYNCWHENOPEN_ENABLE = 'deploy.syncWhenOpen.enable';
/**
* Name of the event that is raised when 'sync when open'
* feature should be toggled.
*/
export const EVENT_SYNCWHENOPEN_TOGGLE = 'deploy.syncWhenOpen.toggle';
/**
* Name of the event that is raised when workspace (folder) changed.
*/
export const EVENT_WORKSPACE_CHANGED = 'deploy.workspace.changed';
/**
* An object that can handle access keys.
*/
export interface AccessKeyObject {
/**
* Prompt for an access key if not defined.
*/
promptForKey?: boolean;
}
/**
* An object that can handle access tokens.
*/
export interface AccessTokenObject {
/**
* Prompt for an access token if not defined.
*/
promptForToken?: boolean;
}
/**
* A deploy operation for compiling files that is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployedCompileOperation extends AfterDeployedOperation, DeployCompileOperation {
}
/**
* A deploy operation for doing a HTTP request that is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployedHttpOperation extends AfterDeployedOperation, DeployHttpOperation {
}
/**
* An operation that is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployedOperation extends DeployOperation {
}
/**
* An operation that opens something like an URI and is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployedOpenOperation extends AfterDeployedOperation, DeployOpenOperation {
}
/**
* An operation that uses a script and is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployScriptOperation extends AfterDeployedOperation, DeployScriptOperation {
}
/**
* An operation that executes SQL and is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeploySqlOperation extends AfterDeployedOperation, DeploySqlOperation {
}
/**
* An operation that executes a Visual Studio Code command and is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployedVSCommandOperation extends AfterDeployedOperation, DeployVSCommandOperation {
}
/**
* An execution context for a Visual Studio Code command (after deployed).
*/
export interface AfterDeployedVSCommandOperationContext extends DeployVSCommandOperationContext {
}
/**
* An operation that waits a number of milliseconds and is invoked AFTER
* ALL files have been deployed.
*/
export interface AfterDeployedWaitOperation extends AfterDeployedOperation, DeployWaitOperation {
}
/**
* An operation that starts Web Deploy (msdeploy)
* and is invoked AFTER ALL files have been deployed.
*/
export interface AfterDeployedWebDeployOperation extends AfterDeployedOperation, DeployWebDeployOperation {
}
/**
* An object that can apply to (its) properties by using
* generated values by placeholders.
*/
export interface Applyable {
/**
* A list of property names and their values
* that should be applied to that object.
*/
applyValuesTo?: { [prop: string]: any };
}
/**
* Describes an event handler that is raised BEFORE a file starts to be deployed.
*
* @param {any} sender The sending object.
* @param {BeforeDeployFileEventArguments} e The Arguments of the event.
*/
export type BeforeDeployFileEventHandler = (sender: any, e: BeforeDeployFileEventArguments) => void;
/**
* Arguments for a "before deploy file" event.
*/
export interface BeforeDeployFileEventArguments extends DeployFileEventArguments {
/**
* A string that represents the destination.
*/
destination: string;
}
/**
* An operation that is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployOperation extends DeployOperation {
}
/**
* A deploy operation for compiling files that is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployCompileOperation extends BeforeDeployOperation, DeployCompileOperation {
}
/**
* A deploy operation for doing a HTTP request that is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployHttpOperation extends BeforeDeployOperation, DeployHttpOperation {
}
/**
* An operation that opens something like an URI and is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployOpenOperation extends BeforeDeployOperation, DeployOpenOperation {
}
/**
* An operation that uses a script and is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployScriptOperation extends BeforeDeployOperation, DeployScriptOperation {
}
/**
* An operation that executes SQL and is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeploySqlOperation extends BeforeDeployOperation, DeploySqlOperation {
}
/**
* An operation that executes a Visual Studio Code command and is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployVSCommandOperation extends BeforeDeployOperation, DeployVSCommandOperation {
}
/**
* An execution context for a Visual Studio Code command (before deploy).
*/
export interface BeforeDeployVSCommandOperationContext extends DeployVSCommandOperationContext {
}
/**
* An operation that waits a number of milliseconds and is invoked BEFORE
* files will be deployed.
*/
export interface BeforeDeployWaitOperation extends BeforeDeployOperation, DeployWaitOperation {
}
/**
* An operation that starts Web Deploy (msdeploy)
* and is invoked BEFORE files will be deployed.
*/
export interface BeforeDeployWebDeployOperation extends BeforeDeployOperation, DeployWebDeployOperation {
}
/**
* An object that can load (parts) of its data from a source.
*/
export interface CanLoadFrom {
/**
* The source from where to load the data from.
*/
loadFrom?: string;
}
/**
* A value with a name that is generated by code.
*/
export interface CodeValueWithName extends ValueWithName {
/** @inheritdoc */
type: "code";
/**
* Gets the code to execute.
*/
code: string;
}
/**
* A command.
*/
export interface Command {
/**
* The ID of the command.
*/
command: string;
}
/**
* An item that uses JavaScript code if it is available or not.
*/
export interface ConditionalItem {
/**
* One or more (JavaScript) conditions that check if that item is available or not.
*/
if?: string | string[];
}
/**
* Filters "conditional" items.
*/
export interface ConditionalItemFilter {
/**
* Filters "conditional" items.
*
* @param {T|T[]} items The items to filter.
*
* @return {T[]} The filtered items.
*/
filterConditionalItems<T extends ConditionalItem>(items: T | T[]): T[];
}
/**
* Describes a function that transforms data into new format.
*
* @param {DataTransformerContext} ctx The transformer context.
*
* @return {DataTransformerResult} The result.
*/
export type DataTransformer = (ctx: DataTransformerContext) => DataTransformerResult;
/**
* The context of data transformer.
*/
export interface DataTransformerContext extends ScriptArguments {
/**
* An optional context / object value defined by the "sender".
*/
context?: any;
/**
* The data to transform.
*/
data: Buffer;
/**
* The mode.
*/
mode: DataTransformerMode;
/**
* The optional options for transformation.
*/
options?: any;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
readonly replaceWithValues: (val: any) => string;
}
/**
* The transformer mode.
*/
export enum DataTransformerMode {
/**
* Restore transformed data.
*/
Restore,
/**
* Transform UNtransformed data.
*/
Transform,
}
/**
* Describes a "data transformer" module.
*/
export interface DataTransformModule {
/**
* Restores transformed / encoded / crypted data.
*/
restoreData?: DataTransformer;
/**
* Transforms data into new format.
*/
transformData?: DataTransformer;
}
/**
* Possible results of a data transformer.
*/
export type DataTransformerResult = Promise<Buffer> | Buffer;
/**
* A quick pick that is based on an action.
*/
export interface DeployActionQuickPick extends DeployQuickPickItem {
/**
* The action to invoke.
*
* @param {any} The sending object.
*
* @return {any} The result.
*/
action?: (sender: any) => any;
}
/**
* A deploy operation for compiling files.
*/
export interface DeployCompileOperation extends DeployOperation {
/**
* The compiler to use.
*/
compiler: string;
/**
* The options for the compiler.
*/
options?: any;
/**
* Use files that will be deployed / have been deployed as source or not.
*/
useFilesOfDeployment?: boolean;
}
/**
* Configuration settings.
*/
export interface DeployConfiguration extends vscode.WorkspaceConfiguration {
/**
* Indicates if package list is shown, even if there is only one entry.
*/
alwaysShowPackageList?: boolean;
/**
* Indicates if target list is shown, even if there is only one entry.
*/
alwaysShowTargetList?: boolean;
/**
* Always synchronize a local file with a newer one when using 'sync when open' in a package.
*/
alwaysSyncIfNewer?: boolean;
/**
* Select the workspace by active text editor automatically or not.
*/
autoSelectWorkspace?: boolean;
/**
* Settings for a "quick deploy button".
*/
button?: {
/**
* Inidciates if button is enabled / visible or not.
*/
enabled?: boolean;
/**
* A list of one or more packages to deploy.
*/
packages?: string | string[];
/**
* A custom text for the button.
*/
text?: string;
},
/**
* Clear output on startup or not.
*/
clearOutputOnStartup?: boolean;
/**
* A list of one or more script based commands to register.
*/
commands?: ScriptCommand | ScriptCommand[];
/**
* Activates or deactivates "deploy on change" feature.
*/
deployOnChange?: boolean;
/**
* Activates or deactivates "deploy on save" feature.
*/
deployOnSave?: boolean;
/**
* Disables the display of popups that reports for a new version of that extension.
*/
disableNewVersionPopups?: boolean;
/**
* Display loaded plugins in output window or not.
*/
displayLoadedPlugins?: boolean;
/**
* Display network information in output window or not.
*/
displayNetworkInfo?: boolean;
/**
* Settings for the process's environment.
*/
env?: {
/**
* Automatically import environment variables as placesholders / values.
*/
importVarsAsPlaceholders?: boolean;
/**
* A list of variables that should NOT use placeholders / values.
*/
noPlaceholdersForTheseVars?: string | string[] | boolean;
/**
* One or more variable for the process to define.
*/
vars?: { [name: string]: any };
};
/**
* One or more global events.
*/
events?: Event | Event[];
/**
* Indicates if a "fast" file check should be
* used for the list of ignored files (s. 'ignores').
*/
fastCheckForIgnores?: boolean;
/**
* Default value that indicates if a "fast" file check
* should be used for "deploy on change" feature or not.
*/
fastCheckOnChange?: boolean;
/**
* Default value that indicates if a "fast" file check
* should be used for "deploy on save" feature or not.
*/
fastCheckOnSave?: boolean;
/**
* Default value that indicates if a "fast" file check
* should be used for "sync when open" feature or not.
*/
fastCheckOnSync?: boolean;
/**
* Defines an object that contains global values and objects, categorized by its properties.
*/
globals?: GlobalVariables;
/**
* The time in seconds the result item in the status bar should disapear.
*/
hideDeployResultInStatusBarAfter?: number;
/**
* Deploy host settings.
*/
host?: {
/**
* Run on startup or not.
*/
autoStart?: boolean;
/**
* The root directory where files should be stored.
*/
dir?: string;
/**
* Maximum size of a JSON message.
*/
maxMessageSize?: number;
/**
* The path to a module that UNtransforms received message data.
*
* s. 'TranformerModule' interface
*/
messageTransformer?: string;
/**
* The optional options for the "message data" transformer script.
*/
messageTransformerOptions?: any;
/**
* An optional password to use.
*/
password?: string;
/**
* The algorithm for the password to use.
*/
passwordAlgorithm?: string;
/**
* The TCP port on that the host should listen.
*/
port?: number;
/**
* Show popup if host has been started or stopped successfully.
*/
showPopupOnSuccess?: boolean;
/**
* The path to a module that UNtransforms received file data.
*
* s. 'TranformerModule' interface
*/
transformer?: string;
/**
* The optional options for the "file data" transformer script.
*/
transformerOptions?: any;
/**
* The path to the script that validates received files.
*
* s. 'ValidatorModule' interface
*/
validator?: string;
/**
* The optional options for the "validator" script.
*/
validatorOptions?: any;
};
/**
* One or more pattern of files that should be ignored
* even if a deployment is started for them.
*/
ignore?: string | string[];
/**
* A list of imports.
*/
imports?: ImportType | ImportType[];
/**
* The ID of the language to use (e.g. 'en', 'de')
*/
language?: string;
/**
* List of additional files of plugin modules to load.
*/
modules?: string | string[];
/**
* A custom machine name.
*/
name?: string;
/**
* A list files to open on startup.
*/
open?: OpenFileFilter | OpenFileFilter[];
/**
* Open the output window before deploying starts or not.
*/
openOutputOnDeploy?: boolean;
/**
* Open the output window on startup or not.
*/
openOutputOnStartup?: boolean;
/**
* List of packages.
*/
packages?: DeployPackage[];
/**
* Run build task on startup or define the wait time, in milliseconds, after
* the build task should be run after startup.
*/
runBuildTaskOnStartup?: boolean | number;
/**
* Run Git pull on startup or define the wait time, in milliseconds, after
* Git pull should be run after startup.
*/
runGitPullOnStartup?: boolean | number;
/**
* Show an item in the status bar after deployment or not.
*/
showDeployResultInStatusBar?: boolean;
/**
* Indicates if an info popup / notification should be displayed after a successful deployment or not.
*/
showPopupOnSuccess?: boolean;
/**
* Show a warning message if a (single) file has been ignored.
*/
showWarningIfIgnored?: boolean;
/**
* Indicates if a warning popup / notification should be displayed if targets do not exist.
*/
showWarningsForNonExistingTargets?: boolean;
/**
* Starts the REST API or not.
* s. https://github.com/mkloubert/vs-rest-api
*/
startApi?: boolean;
/**
* Starts the cron jobs or not.
* s. https://github.com/mkloubert/vs-cron
*/
startCronJobs?: boolean;
/**
* A list of one or more Visual Studio Code commands that should be run on startup.
*/
startupCommands?: (string | StartupCommand)[] | StartupCommand | string;
/**
* Activates or deactivates "sync when open" feature.
*/
syncWhenOpen?: boolean;
/**
* List of targets.
*/
targets?: DeployTarget[];
/**
* A list of template sources.
*/
templates?: {
/**
* Allow unparsed (HTML) documents or not.
*/
allowUnparsedDocuments?: boolean;
/**
* Path or URL to a HTML footer that should be inserted at the beginning
* inside the BODY tag of each (default) HTML document.
*/
footer?: string;
/**
* Path or URL to a HTML header that should be inserted at the beginning
* inside the BODY tag of each (default) HTML document.
*/
header?: string;
/**
* Show default sources or not.
*/
showDefaults?: boolean;
/**
* List of one or more sources.
*/
sources?: string | string[] | TemplateSource | TemplateSource[];
};
/**
* The time (in milliseconds) to wait before activating 'deploy on change' feature.
*/
timeToWaitBeforeActivateDeployOnChange?: number;
/**
* Also check directory patterns, like in '.gitignore' files, in all packages by default or not.
*/
useGitIgnoreStylePatterns?: boolean;
/**
* Use 'targets' property of a package instead, if its 'deployOnSave' property is
* set to (true).
*/
useTargetListForDeployOnSave?: boolean;
/**
* Use workspace start time for 'sync when open' for all packages by default or not.
*/
useWorkspaceStartTimeForSyncWhenOpen?: boolean;
/**
* A list of one or more values that can be accessed
* via placeholders in strings, e.g.
*/
values?: ValueWithName | ValueWithName[];
}
/**
* A deploy context.
*/
export interface DeployContext extends ConditionalItemFilter, vscode.Disposable, FileDeployer {
/**
* Returns the current config.
*
* @return {DeployConfiguration} The current config.
*/
config: () => DeployConfiguration;
/**
* Emits an event of the context.
*
* @param {string | symbol} event The event.
* @param {any[]} args The arguments.
*/
emit: (event: string | symbol, ...args: any[]) => boolean;
/**
* Emits a global event.
*
* @param {string | symbol} event The event.
* @param {any[]} args The arguments.
*/
emitGlobal: (event: string | symbol, ...args: any[]) => boolean;
/**
* Shows an error message.
*
* @param {any} msg The message to show.
*
* @chainable
*/
error: (msg: any) => DeployContext;
/**
* Gets the list of global vars.
*/
globals: () => GlobalVariables;
/**
* Shows an info message.
*
* @param {any} msg The message to show.
*
* @chainable
*/
info: (msg: any) => DeployContext;
/**
* Returns if the underlying extension is currently active or not.
*/
isActive: () => boolean;
/**
* Returns if cancellation has been requested or not.
*
* @return {boolean} Cancellation has been requested or not.
*/
isCancelling: () => boolean;
/**
* Logs a message.
*
* @param {any} msg The message to log.
*
* @chainable
*/
log: (msg: any) => DeployContext;
/**
* Registers a callback for an event that is invoked once.
*
* @param {string | symbol} event The event.
* @param {() => void} callback The callback to register.
*
* @chainable
*/
once: (event: string | symbol,
handler: EventHandler) => DeployContext;
/**
* Opens a HTML document in a new tab.
*
* @param {string} html The HTML document (source code).
* @param {string} [title] The custom title for the tab.
* @param {any} [id] The custom ID for the document in the storage.
*
* @returns {Promise<any>} The promise.
*/
openHtml: (html: string, title?: string, id?: any) => Promise<any>;
/**
* Gets the global output channel.
*/
outputChannel: () => vscode.OutputChannel;
/**
* Returns the package file of that extension.
*
* @return {PackageFile} The data of the package file.
*/
packageFile: () => PackageFile;
/**
* Returns the list of packages.
*
* @return {DeployPackage[]} The packages.
*/
packages: () => DeployPackage[];
/**
* Returns the list of (other) plugins.
*
* @return {DeployPlugin[]} The list of (other) plugins.
*/
plugins: () => DeployPlugin[];
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
replaceWithValues: (val: any) => string;
/**
* Loads a module from the extension context / directory.
*
* @param {string} id The ID / path of the module.
*
* @return {any} The module.
*/
require: (id: string) => any;
/**
* Shows a warning message.
*
* @param {any} [msg] The message to show.
*
* @chainable
*/
warn: (msg: any) => DeployContext;
/**
* Returns the root directory of the current workspace.
*
* @return {string} The root directory of the current workspace.
*/
workspace: () => string;
/**
* Writes a messages to the output channel.
*
* @param {any} msg The message to write.
*
* @chainable
*/
write: (msg: any) => DeployContext;
/**
* Writes a messages to the output channel and adds a new line.
*
* @param {any} msg The message to write.
*
* @chainable
*/
writeLine: (msg: any) => DeployContext;
/**
* Returns the cache of the targets.
*
* @return {ObjectCache<DeployTarget>} The cache.
*/
targetCache: () => ObjectCache<DeployTarget>;
/**
* Returns the list of targets.
*
* @return {DeployTarget[]} The targets.
*/
targets: () => DeployTarget[];
/**
* Returns the list of values.
*/
values: () => ObjectWithNameAndValue[];
}
/**
* List of deploy directions.
*/
export enum DeployDirection {
/**
* Deploy (from workspace to target)
*/
Deploy = 1,
/**
* Pull (From target to workspace)
*/
Pull = 2,
/**
* Download from target
*/
Download = 3,
/**
* Get information about a file.
*/
FileInfo = 4,
}
/**
* Arguments for a deploy event.
*/
export interface DeployEventArguments {
}
/**
* Arguments for a "before deploy file" event.
*/
export interface DeployFileEventArguments extends DeployEventArguments {
/**
* File file.
*/
file: string;
/**
* The file.
*/
target: DeployTarget;
}
/**
* Additional options for a 'DeployFileCallback'.
*/
export interface DeployFileOptions {
/**
* The custom root directory to use.
*/
baseDirectory?: string;
/**
* The custom deploy context.
*/
context?: DeployContext;
/**
* The "before deploy" callback.
*/
onBeforeDeploy?: BeforeDeployFileEventHandler;
/**
* The "completed" callback.
*/
onCompleted?: FileDeployCompletedEventHandler;
}
/**
* A quick pick item for deploying a file.
*/
export interface DeployFileQuickPickItem extends DeployTargetQuickPickItem {
/**
* The path of the source file to deploy.
*/
file: string;
}
/**
* Arguments for a 'deploy files' event result.
*/
export interface DeployFilesEventArguments {
/**
* The error (if occurred).
*/
error?: any;
/**
* The files that have been (try to be) deployed.
*/
files?: string[];
/**
* The targets.
*/
targets?: DeployTarget[];
/**
* The symbol that indentifies the operation.
*/
symbol?: symbol;
}
/**
* An operation that does a HTTP request.
*/
export interface DeployHttpOperation extends DeployOperation {
/**
* The body or the path to a script that returns the body to send.
*/
body?: string;
/**
* The request headers.
*/
headers?: any;
/**
* Indicates if 'body' is Base64 encoded or not.
*/
isBodyBase64?: boolean;
/**
* Indicates if 'body' contains the path to a script instead the content to send.
*/
isBodyScript?: boolean;
/**
* The HTTP request method.
*/
method?: string;
/**
* A list of headers that should NOT use placeholders / values.
*/
noPlaceholdersForTheseHeaders?: string | string[] | boolean;
/**
* The options for the script that returns the body to send.
*/
options?: any;
/**
* The password for basic auth.
*/
password?: string;
/**
* The URL.
*/
url?: string;
/**
* The username for basic auth.
*/
username?: string;
}
/**
* 'Deploy on change' file filter.
*/
export interface DeployOnChangeFileFilter extends FileFilter {
/**
* Use target lists or not.
*/
useTargetList?: boolean;
}
/**
* An operation that opens something like an URI.
*/
export interface DeployOpenOperation extends DeployOperation, ProcessObject {
/**
* List of arguments to send to the target.
*/
arguments?: string | string[];
/**
* Run in integrated terminal or not.
*/
runInTerminal?: boolean;
/**
* The application / target to open.
*/
target?: string;
/**
* Use placeholders in arguments or not.
*/
usePlaceholdersInArguments?: boolean;
/**
* Wait until target has been executed or not.
*/
wait?: boolean;
}
/**
* A deploy operation.
*/
export interface DeployOperation {
/**
* The description for the operation.
*/
description?: string;
/**
* The name of the operation.
*/
name?: string;
/**
* The type.
*/
type?: string;
}
/**
* List of deploy operation kinds.
*/
export enum DeployOperationKind {
/**
* Before deployment starts.
*/
Before = 0,
/**
* After successful deployment.
*/
After = 1,
}
/**
* A package.
*/
export interface DeployPackage extends Applyable, CanLoadFrom, ConditionalItem, Hideable, Inheritable, MachineItem, PlatformItem, Sortable {
/**
* Always synchronize a local file with a newer one when using 'sync when open' in that package.
*/
alwaysSyncIfNewer?: boolean;
/**
* Settings for a "package button".
*/
button?: DeployPackageButton | boolean,
/**
* Deploys files on change.
*/
deployOnChange?: true | DeployOnChangeFileFilter;
/**
* Deploy files of the package on save or not.
*/
deployOnSave?: true | string | string[];
/**
* The description.
*/
description?: string;
/**
* Additional information that should be shown in the GUI, e.g.
*/
detail?: string;
/**
* Files to exclude.
*/
exclude?: string[];
/**
* Indicates if a "fast" file check
* should be used for "deploy on change" feature or not.
*/
fastCheckOnChange?: boolean;
/**
* Indicates if a "fast" file check
* should be used for "deploy on save" feature or not.
*/
fastCheckOnSave?: boolean;
/**
* Indicates if a "fast" file check
* should be used for "sync when open" feature or not.
*/
fastCheckOnSync?: boolean;
/**
* Files to include.
*/
files?: string[];
/**
* The name.
*/
name?: string;
/**
* Exclude 'node_modules' directory by default or not.
*/
noNodeModules?: boolean;
/**
* Show this package for deploying or not.
*/
showForDeploy?: boolean;
/**
* Show this package for pulling or not.
*/
showForPull?: boolean;
/**
* Synchronizes local files with remote ones when opening it.
*/
syncWhenOpen?: boolean | string | SyncWhenOpenFileFilter;
/**
* One or more explicit targets to deploy to.
*/
targets?: string | string[];
/**
* Use 'targets' property of this package instead,
* if its 'deployOnSave' property is set to (true).
*/
useTargetListForDeployOnSave?: boolean;
/**
* Use workspace start time for 'sync when open' for that package or not.
*/
useWorkspaceStartTimeForSyncWhenOpen?: boolean;
}
/**
* A button for a package.
*/
export interface DeployPackageButton {
/**
* The custom ID for the underlying command.
*/
command?: string;
/**
* Enable button or not.
*/
enabled?: boolean;
/**
* Put button on the right side or not.
*/
isRight?: boolean;
/**
* The priority.
*/
priority?: number;
/**
* One or more explicit targets to deploy to.
*/
targets?: string | string[];
/**
* A custom text for the button.
*/
text?: string;
/**
* A custom tooltip for the button.
*/
tooltip?: string;
}
/**
* A quick pick for a package.
*/
export interface DeployPackageQuickPickItem extends DeployQuickPickItem {
/**
* The package.
*/
package: DeployPackage;
}
/**
* A plugin.
*/
export interface DeployPlugin {
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* Gets the filename of the plugin.
*/
__file?: string;
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* Gets the full path of the plugin's file.
*/
__filePath?: string;
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* Gets the index of the plugin.
*/
__index?: number;
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* Gets the type of the plugin.
*/
__type?: string;
/**
* Indicates if plugin is able to get information about remote files or not.
*/
canGetFileInfo?: boolean;
/**
* Indicates if plugin can pull files or not.
*/
canPull?: boolean;
/**
* Compares a local file with a remote one.
*
* @param {string} file The file to compare.
* @param {DeployTarget} target The source from where to download the file from.
* @param {DeployFileOptions} [opts] Additional options.
*
* @return {PromiseLike<FileCompareResult>|FileCompareResult} The result.
*/
compareFiles?: (file: string, target: DeployTarget, opts?: DeployFileOptions) => PromiseLike<FileCompareResult> | FileCompareResult;
/**
* Compares local files with a remote ones.
*
* @param {string[]} files The files to compare.
* @param {DeployTarget} target The source from where to download the file from.
* @param {DeployFileOptions} [opts] Additional options.
*
* @return {PromiseLike<FileCompareResult[]>|FileCompareResult[]} The result.
*/
compareWorkspace?: (files: string[], target: DeployTarget, opts?: DeployFileOptions) => PromiseLike<FileCompareResult[]> | FileCompareResult[];
/**
* Deploys a file.
*
* @param {string} file The path of the local file.
* @param {DeployTarget} target The target.
* @param {DeployFileOptions} [opts] Additional options.
*/
deployFile?: (file: string, target: DeployTarget, opts?: DeployFileOptions) => void;
/**
* Deploys files of a workspace.
*
* @param {string[]} files The files to deploy.
* @param {DeployTarget} target The target.
* @param {DeployWorkspaceOptions} [opts] Additional options.
*/
deployWorkspace?: (files: string[], target: DeployTarget, opts?: DeployWorkspaceOptions) => void;
/**
* Disposes / cleanup the plugin.
*/
dispose?: () => void;
/**
* Downloads a file from target.
*
* @param {string} file The file to download.
* @param {DeployTarget} target The source from where to download the file from.
* @param {DeployFileOptions} [opts] Additional options.
*
* @return {Promise<Buffer>} The promise.
*/
downloadFile?: (file: string, target: DeployTarget, opts?: DeployFileOptions) => Promise<Buffer> | Buffer;
/**
* Gets information about a file from target.
*
* @param {string} file The file to download.
* @param {DeployTarget} target The source from where to download the file from.
* @param {DeployFileOptions} [opts] Additional options.
*
* @return {PromiseLike<FileInfo>|FileInfo} The result.
*/
getFileInfo?: (file: string, target: DeployTarget, opts?: DeployFileOptions) => PromiseLike<FileInfo> | FileInfo;
/**
* Return information of the plugin.
*
* @return {DeployPluginInfo} The plugin info.
*/
info?: () => DeployPluginInfo;
/**
* Pulls a file.
*
* @param {string} file The path of the local file.
* @param {DeployTarget} target The target that contains the file to pull.
* @param {DeployFileOptions} [opts] Additional options.
*/
pullFile?: (file: string, target: DeployTarget, opts?: DeployFileOptions) => void;
/**
* Pulls files of to the workspace.
*
* @param {string[]} files The files to pull.
* @param {DeployTarget} target The target that contains the files to pull.
* @param {DeployWorkspaceOptions} [opts] Additional options.
*/
pullWorkspace?: (files: string[], target: DeployTarget, opts?: DeployWorkspaceOptions) => void;
}
/**
* Information about a plugin.
*/
export interface DeployPluginInfo {
/**
* The description of the plugin.
*/
description?: string;
}
/**
* A plugin module.
*/
export interface DeployPluginModule {
/**
* Creates a new instance.
*
* @param {DeployContext} ctx The context.
*
* @return {DeployPlugin} The new instance.
*/
createPlugin?: (ctx: DeployContext) => DeployPlugin;
}
/**
* Stores a deploy plugin with its deploy context.
*/
export interface DeployPluginWithContext {
/**
* The deploy context.
*/
context: DeployContext;
/**
* The plugin.
*/
plugin: DeployPlugin;
}
/**
* A quick pick item.
*/
export interface DeployQuickPickItem extends vscode.QuickPickItem {
}
/**
* A deploy operation that uses a script.
*/
export interface DeployScriptOperation extends DeployOperation {
/**
* Addtional data for the script.
*/
options?: any;
/**
* The path to the script.
*/
script: string;
}
/**
* The arguments for a script of a deploy operation.
*/
export interface DeployScriptOperationArguments extends ScriptArguments, FileDeployer {
/**
* The files that should be deployed.
*/
files: string[];
/**
* A state value for the ALL scripts that exists while the
* current session.
*/
globalState?: Object;
/**
* The kind of operation.
*/
kind: DeployOperationKind;
/**
* Opens a HTML document in a new tab.
*
* @param {string} html The HTML document (source code).
* @param {string} [title] The custom title for the tab.
* @param {any} [id] The custom ID for the document in the storage.
*
* @returns {Promise<any>} The promise.
*/
openHtml: (html: string, title?: string, id?: any) => Promise<any>;
/**
* The addtional options.
*/
options?: any;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
replaceWithValues: (val: any) => string;
/**
* A state value for the current script that exists while the
* current session.
*/
state?: any;
/**
* The underlying target configuration.
*/
target: DeployTarget;
}
/**
* A function for a script based deploy operation.
*
* @param {DeployScriptOperationArguments} args The arguments for the execution.
*
* @return {void|Promise<any>} The result.
*/
export type DeployScriptOperationExecutor = (args: DeployScriptOperationArguments) => void | Promise<any>;
/**
* A module for a script operation.
*/
export interface DeployScriptOperationModule {
/**
* Executes the logic of the script.
*/
execute?: DeployScriptOperationExecutor;
}
/**
* An operation that executes SQL.
*/
export interface DeploySqlOperation extends DeployOperation, PasswordObject {
/**
* The engine.
*/
engine?: string;
/**
* The connection options.
*/
options?: any;
/**
* The list of queries to execute.
*/
queries: string | string[];
}
/**
* A target.
*/
export interface DeployTarget extends Applyable, CanLoadFrom, ConditionalItem, Hideable, Inheritable, MachineItem, PlatformItem, Sortable {
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* Gets the ID of that target.
*/
__id?: any;
/**
* List of operations that should be invoked BEFORE
* target is being deployed.
*/
beforeDeploy?: BeforeDeployOpenOperation | BeforeDeployOpenOperation[];
/**
* Check for newer files before a deployment starts or not.
*/
checkBeforeDeploy?: boolean;
/**
* List of operations that should be invoked AFTER
* ALL files have been deployed.
*/
deployed?: AfterDeployedOperation | AfterDeployedOperation[];
/**
* The description.
*/
description?: string;
/**
* Additional information that should be shown in the GUI, e.g.
*/
detail?: string;
/**
* Start a diff before deploy file(s).
*/
diffBeforeDeploy?: boolean;
/**
* A list of one or more package names that indicates
* if that target is hidden from GUI if one of the package(s) has been selected.
*/
hideIf?: string | string[];
/**
* One or more folder mapping.
*/
mappings?: DeployTargetMapping | DeployTargetMapping[];
/**
* The name.
*/
name?: string;
/**
* A list of one or more package names that indicates
* if that target is only shown in GUI if one of the package(s) has been selected.
*/
showIf?: string | string[];
/**
* The type.
*/
type?: string;
}
/**
* A list of targets.
*/
export type DeployTargetList = string | string[] | DeployTarget | DeployTarget[];
/**
* A wrapper for a deploy target and matching plugins.
*/
export interface DeployTargetWithPlugins {
/**
* The list of matching plugings.
*/
plugins: DeployPlugin[];
/**
* The underlying target.
*/
target: DeployTarget;
}
/**
* A folder mapping.
*/
export interface DeployTargetMapping {
/**
* Indicates if 'source' contains a regular expression
* instead of a static string.
*/
isRegEx?: boolean;
/**
* The source directory.
*/
source: string;
/**
* The target directory.
*/
target: string;
}
/**
* A quick pick item for selecting a target.
*/
export interface DeployTargetQuickPickItem extends DeployQuickPickItem {
/**
* The target.
*/
target: DeployTarget;
}
/**
* An operation that executes a Visual Studio Code command.
*/
export interface DeployVSCommandOperation extends DeployOperation {
/**
* The arguments for the command.
*/
arguments?: any[];
/**
* The command to execute.
*/
command: string;
/**
* Options for the operation context object (@see DeployVSCommandOperationContext).
*/
contextOptions?: any;
/**
* Submit an operation context object (@see DeployVSCommandOperationContext) as first argument or not.
*/
submitContext?: boolean;
}
/**
* An execution context for a Visual Studio Code command.
*/
export interface DeployVSCommandOperationContext {
/**
* The ID of the command.
*/
command: string;
/**
* The globals defined in the settings.
*/
globals: GlobalVariables;
/**
* The files to deploy.
*/
files: string[];
/**
* The kind of operation.
*/
kind: DeployOperationKind;
/**
* The operation
*/
operation: DeployVSCommandOperation;
/**
* Options for the execution (@see DeployVSCommandOperation.contextOptions).
*/
options?: any;
/**
* Loads a module from the script context.
*/
require: (id: string) => any;
}
/**
* An operation that waits a number of milliseconds.
*/
export interface DeployWaitOperation extends DeployOperation {
/**
* The time in milliseconds to wait.
*/
time?: number;
}
/**
* An operation that starts Web Deploy (msdeploy).
*/
export interface DeployWebDeployOperation extends DeployOperation, ProcessObject {
// s. https://technet.microsoft.com/en-us/library/d860fa74-738a-4f09-87f6-66c6705145f9
allowUntrusted?: boolean;
appHostConfigDir?: string;
args?: string[];
declareParam?: string;
declareParamFile?: string;
dest?: string;
disableAppStore?: boolean;
disableLink?: string;
disableRule?: string;
disableSkipDirective?: string;
enableLink?: string;
enableRule?: string;
enableSkipDirective?: string;
postSync?: string;
preSync?: string;
removeParam?: string;
replace?: string;
retryAttempts?: number;
retryInterval?: number;
setParam?: string;
setParamFile?: string;
showSecure?: boolean;
skip?: string;
source: string;
unicode?: boolean;
useCheckSum?: boolean;
verb: string;
verbose?: boolean;
webServerDir?: string;
whatif?: boolean;
xml?: boolean;
xpath?: string;
/**
* The working directory.
*/
dir?: string;
/**
* The optional path to the executable.
*/
exec?: string;
/**
* Run in integrated terminal or not.
*/
runInTerminal?: boolean;
/**
* Wait for execution finished or not.
*/
wait?: boolean;
}
/**
* Additional options for a 'deploy workspace' operation.
*/
export interface DeployWorkspaceOptions {
/**
* The custom root directory to use.
*/
baseDirectory?: string;
/**
* The custom deploy context.
*/
context?: DeployContext;
/**
* The "before deploy" file callback.
*/
onBeforeDeployFile?: BeforeDeployFileEventHandler;
/**
* The "completed" callback for the whole operation.
*/
onCompleted?: WorkspaceDeployedEventHandler;
/**
* The "completed" callback for the a single file.
*/
onFileCompleted?: FileDeployCompletedEventHandler;
}
/**
* A document.
*/
export interface Document {
/**
* The body / content of the document.
*/
body: Buffer;
/**
* The encoding.
*/
encoding?: string;
/**
* The ID.
*/
id?: any;
/**
* The MIME type.
*/
mime?: string;
/**
* The title.
*/
title?: string;
}
/**
* A value with a name that accesses an environment variable with the same name.
*/
export interface EnvValueWithName extends ValueWithName {
/**
* The optional alias of the variable.
*/
alias?: string;
/** @inheritdoc */
type: "env" | "environment";
}
/**
* An event entry.
*/
export interface Event extends ConditionalItem, MachineItem, PlatformItem, Sortable {
/**
* A description for that event.
*/
description?: string;
/**
* The name of the event.
*/
name: string;
/**
* Execute once or not.
*/
once?: boolean;
/**
* Options / data for the execution.
*/
options?: any;
/**
* The path to the script.
*/
script: string;
/**
* The initial value for the state.
*/
state?: any;
}
/**
* Arguments for an event.
*/
export interface EventArguments {
}
/**
* An event handler.
*
* @param {any} sender The sending object.
* @param {EventArguments} e The arguments for the event.
*/
export type EventHandler = (sender: any, e: EventArguments) => void;
/**
* An event module.
*/
export interface EventModule {
/**
* Raises the event.
*/
raiseEvent: EventModuleExecutor;
}
/**
* Describes a function for executing the logic of an event.
*
* @param {EventModuleExecutorArguments} args The arguments for the execution.
*
* @return {EventModuleExecutorResult} The result.
*/
export type EventModuleExecutor = (args: EventModuleExecutorArguments) => EventModuleExecutorResult;
/**
* A possible result of an event execution.
*/
export type EventModuleExecutorResult = Promise<number> | number | void;
/**
* Arguments for an event execution.
*/
export interface EventModuleExecutorArguments extends ScriptArguments {
/**
* The arguments of the underlying listener.
*/
readonly arguments: IArguments;
/**
* Gets an object that can share data between all other events.
*/
readonly globalState: Object;
/**
* Gets the name of the underlying event.
*/
readonly name: string;
/**
* Opens a HTML document in a new tab.
*
* @param {string} html The HTML document (source code).
* @param {string} [title] The custom title for the tab.
* @param {any} [id] The custom ID for the document in the storage.
*
* @returns {Promise<any>} The promise.
*/
readonly openHtml: (html: string, title?: string, id?: any) => Promise<any>;
/**
* Data / options for the execution.
*/
readonly options?: any;
/**
* Removes the underlying event.
*
* @return {boolean} Event has been removed or not.
*/
readonly remove: () => boolean;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
readonly replaceWithValues: (val: any) => string;
/**
* Gets or sets a state for that event.
*/
state: any;
}
/**
* Result of a file comparison.
*/
export interface FileCompareResult {
/**
* Information about the "left" file.
*/
left: FileInfo;
/**
* Information about the "right" file.
*/
right: FileInfo;
}
/**
* Arguments for a "file deployed completed" event.
*/
export interface FileDeployCompletedEventArguments extends DeployEventArguments {
/**
* Gets if the operation has been canceled or not.
*/
canceled?: boolean;
/**
* The error (if occurred).
*/
error?: any;
/**
* The file.
*/
file: string;
/**
* The target.
*/
target: DeployTarget;
}
/**
* Describes an event handler that is raised AFTER a file deployment has been completed.
*
* @param {any} sender The sending object.
* @param {FileDeployedCompletedEventArguments} e The Arguments of the event.
*/
export type FileDeployCompletedEventHandler = (sender: any, e: FileDeployCompletedEventArguments) => void;
/**
* An object that can deploy files.
*/
export interface FileDeployer {
/**
* Deploys files.
*
* @param {string | string[]} files The files to deploy.
* @param {DeployTargetList} targets The targets to deploy to.
*/
deployFiles(files: string | string[], targets: DeployTargetList): Promise<DeployFilesEventArguments>;
}
/**
* A file filter.
*/
export interface FileFilter {
/**
* Files to exclude.
*/
exclude?: string | string[];
/**
* Files to include.
*/
files?: string | string[];
/**
* Also check directory patterns, like in '.gitignore' files, in that filter or not.
*/
useGitIgnoreStylePatterns?: boolean;
}
/**
* Information about a file.
*/
export interface FileInfo {
/**
* Files exists or not.
*/
exists: boolean;
/**
* Is remote file or not.
*/
isRemote: boolean;
/**
* The time the file has been modified.
*/
modifyTime?: Moment.Moment;
/**
* The "real" name.
*/
name?: string;
/**
* The path.
*/
path?: string;
/**
* The size.
*/
size?: number;
}
/**
* A value with a name that loads its value from file.
*/
export interface FileValueWithName extends ValueWithName {
/**
* Returns as binary / buffer or not.
*/
asBinary?: boolean;
/**
* The text encoding to use.
*/
encoding?: string;
/**
* The file to load.
*/
file: string;
/** @inheritdoc */
type: "file";
/**
* Also use placeholders for the (string) content or not.
*/
usePlaceholders?: boolean;
}
/**
* Global variables.
*/
export type GlobalVariables = Object;
/**
* Describes an object that can be hidden (in the GUI e.g.).
*/
export interface Hideable {
/**
* Is hidden or not.
*/
isHidden?: boolean;
}
/**
* An import entry.
*/
export interface Import extends ConditionalItem, MachineItem, PlatformItem, Sortable {
/**
* An optional description for the entry.
*/
description?: string;
/**
* Gets the source.
*/
from: string;
/**
* Merge with parent object or not.
*/
merge?: boolean;
}
/**
* Import types.
*/
export type ImportType = string | Import;
/**
* An object with a name that can inherit from other objects.
*/
export interface Inheritable {
/**
* One or more names of objects from where to inherit from.
*/
inheritFrom?: string | string[];
/**
* The name of the object.
*/
name?: string;
}
/**
* An item for a specific machine.
*/
export interface MachineItem {
/**
* A list of one or more (host)names that item is (visible) for.
*/
isFor?: string | string[];
}
/**
* A cache for objects.
*/
export interface ObjectCache<T> {
/**
* Returns a value from the cache.
*
* @param {T} obj The underlying object.
* @param {string} name The name of the value.
* @param {TValue} [defaultValue] The default value.
*
* @returns {TValue|TDefault} The value.
*/
get<TValue = any, TDefault = TValue>(obj: T, name: string, defaultValue?: TDefault): TValue | TDefault;
/**
* Checks if the cache contains a value.
*
* @param {T} obj The underlying object.
* @param {string} name The name of the value.
*
* @return {boolean} Contains value or not.
*/
has(obj: T, name: string): boolean;
/**
* Sets a value for an object.
*
* @param {T} obj The underlying object.
* @param {string} name The name of the value.
* @param {TValue} value The value to set.
*
* @returns {this}
*/
set<TValue>(obj: T, name: string, value: TValue): this;
}
/**
* An object with a name (property).
*/
export interface ObjectWithName {
/**
* Gets the name.
*/
name: string;
}
/**
* An object with name and value (properties).
*/
export interface ObjectWithNameAndValue extends ObjectWithName, ObjectWithValue {
}
/**
* An object with a value (property).
*/
export interface ObjectWithValue {
/**
* Gets the (current) value.
*/
value: any;
}
/**
* Files to open at startup.
*/
export interface OpenFileFilter extends ConditionalItem, FileFilter, MachineItem {
/**
* Close other opened files or not.
*/
closeOthers?: boolean;
}
/**
* An object that can handle passwords.
*/
export interface PasswordObject {
/**
* Prompt for a password if not defined.
*/
promptForPassword?: boolean;
}
/**
* Describes the structure of the package file of that extenstion.
*/
export interface PackageFile {
/**
* The display name.
*/
displayName: string;
/**
* The (internal) name.
*/
name: string;
/**
* The version string.
*/
version: string;
}
/**
* An item / object that can be filtered by platform.
*/
export interface PlatformItem {
/**
* One or more platform the item is for.
*/
platforms?: string | string[];
}
/**
* Describes a button of a popup.
*/
export interface PopupButton extends vscode.MessageItem {
/**
* Gets the action of that button.
*/
action?: PopupButtonAction;
/**
* Contains an additional object that should be linked with that instance.
*/
tag?: any;
}
/**
* A popup button action.
*/
export type PopupButtonAction = () => void;
/**
* An object that creates or handles a process
* of an operating system.
*/
export interface ProcessObject {
/**
* A list of optional environment variables to use.
*/
envVars?: { [name: string]: any };
/**
* A list of variables that should NOT use placeholders / values.
*/
noPlaceholdersForTheseVars?: string | string[] | boolean;
/**
* Also use environment variables of the process of
* current workspace or not.
*/
useEnvVarsOfWorkspace?: boolean;
}
/**
* Arguments that be used script or something like that.
*/
export interface ScriptArguments {
/**
* Emits a global event.
*
* @param {string | symbol} event The event.
* @param {any[]} args The arguments.
*/
emitGlobal: (event: string | symbol, ...args: any[]) => boolean;
/**
* The global variables from the settings.
*/
globals: GlobalVariables;
/**
* Loads a module from the script context.
*
* @param {string} id The ID / path to the module.
*
* @return {any} The loaded module.
*/
require: (id: string) => any;
}
/**
* A startup command.
*/
export interface ScriptCommand extends Command {
/**
* Settings for optional button in the status bar.
*/
button?: {
/**
* The custom (text) color for the button.
*/
color?: string;
/**
* Set button on the right side or not.
*/
isRight?: boolean;
/**
* The custom priority.
*/
priority?: number;
/**
* Show button on startup or not.
*/
show?: boolean;
/**
* The caption for the button.
*/
text?: string;
/**
* The tooltip for the button.
*/
tooltip?: string;
},
/**
* The initial value for 'commandState' property.
* s. https://mkloubert.github.io/vs-deploy/interfaces/_contracts_.scriptcommandexecutorarguments.html#commandstate
*/
commandState?: any;
/**
* Optional data for the execution.
*/
options?: any;
/**
* The path to the script that is run when command is executed.
*/
script: string;
}
/**
* Describes the function that execute a command.
*
* @param {ScriptCommandExecutorArguments} args The arguments for the execution.
*
* @returns {ScriptCommandExecutorResult} The result.
*/
export type ScriptCommandExecutor = (args: ScriptCommandExecutorArguments) => ScriptCommandExecutorResult;
/**
* Possible results of a script command.
*/
export type ScriptCommandExecutorResult = any;
/**
* Arguments for a command execution.
*/
export interface ScriptCommandExecutorArguments extends ScriptArguments, FileDeployer {
/**
* Arguments from the callback.
*/
arguments: IArguments;
/**
* The underlying button.
*/
button?: vscode.StatusBarItem;
/**
* The ID of the underlying command.
*/
command: string;
/**
* Defines data that should be keeped while the current session
* and is available for ONLY for current command.
*/
commandState?: any;
/**
* Defines data that should be keeped while the current session
* and is available for ALL commands defined by that extension.
*/
globalState?: any;
/**
* Opens a HTML document in a new tab.
*
* @param {string} html The HTML document (source code).
* @param {string} [title] The custom title for the tab.
* @param {any} [id] The custom ID for the document in the storage.
*
* @returns {Promise<any>} The promise.
*/
openHtml: (html: string, title?: string, id?: any) => Promise<any>;
/**
* The options.
*/
options?: any;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
replaceWithValues: (val: any) => string;
}
/**
* A module of a script based command.
*/
export interface ScriptCommandModule {
/**
* Executes the command.
*/
execute?: ScriptCommandExecutor;
}
/**
* A module of a script value.
*/
export interface ScriptValueModule {
/**
* Gets the value.
*/
getValue: ScriptValueProvider;
}
/**
* A function that provides a script value.
*
* @param {ScriptValueProviderArguments} args The arguments for the underlying script.
*
* @return {any} The value.
*/
export type ScriptValueProvider = (args: ScriptValueProviderArguments) => any;
/**
* Arguments for the function of a script value.
*/
export interface ScriptValueProviderArguments extends ScriptArguments {
/**
* Gets the object that can share data between all values.
*/
readonly globalState: Object;
/**
* Gets the name of that value.
*/
readonly name: string;
/**
* Gets the data for the underlying script.
*/
readonly options: any;
/**
* Gets the object that can access the other values.
*/
readonly others: { [key: string]: any };
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
replaceWithValues: (val: any) => string;
/**
* Loads a module from the script context.
*
* @param {string} id The ID / path to the module.
*
* @return {any} The loaded module.
*/
require: (id: string) => any;
/**
* Gets or sets a state for that script.
*/
state: any;
}
/**
* A (static) value with a name.
*/
export interface ScriptValueWithName extends ValueWithName {
/**
* Data for the underlying script.
*/
options?: any;
/**
* The path to the script.
*/
script: string;
/** @inheritdoc */
type: "script";
}
/**
* Describes an object that is sortable.
*/
export interface Sortable {
/**
* The sort order.
*/
sortOrder?: number | Object;
}
/**
* A startup command.
*/
export interface StartupCommand extends Command {
/**
* Arguments for the execution.
*/
arguments?: any[];
}
/**
* A (static) value with a name.
*/
export interface StaticValueWithName extends ValueWithName {
/** @inheritdoc */
type?: "" | "static";
/**
* Gets the value.
*/
value: any;
}
/**
* 'Sync when open' file filter.
*/
export interface SyncWhenOpenFileFilter extends FileFilter {
/**
* The target from where to sync.
*/
target?: string;
}
/**
* A template category.
*/
export interface TemplateCategory extends TemplateItem {
/**
* One or more child.
*/
children?: TemplateItemList;
/** @inheritdoc */
type: "category" | "cat" | "c";
}
/**
* A template file.
*/
export interface TemplateFile extends TemplateItem {
/**
* A description for the item.
*/
description?: string;
/**
* Gets if the file in an (HTML) document or not.
*/
isDocument?: boolean;
/**
* The source of the file.
*/
source: string;
/** @inheritdoc */
type?: "" | "f" | "file"
}
/**
* A template item.
*/
export interface TemplateItem {
/**
* The name of the custom icon.
*/
icon?: string;
/**
* The minimum version of that extension
* that is required to display the item.
*/
requires?: string;
/**
* A custom sort order.
*/
sortOrder?: number;
/**
* The type.
*/
type?: string;
}
/**
* An object with a list of template items.
*/
export type TemplateItemList = {
/**
* Gets an item by its name.
*/
[name: string]: TemplateItem;
}
/**
* A template repository.
*/
export interface TemplateRepository extends TemplateItem {
/**
* A description for the item.
*/
description?: string;
/**
* The source of the repository.
*/
source: string;
/** @inheritdoc */
type?: "r" | "repo" | "repository"
}
/**
* A template link.
*/
export interface TemplateLink {
/**
* A description for the item.
*/
description?: string;
/**
* The path or URL to the source.
*/
source: string;
/** @inheritdoc */
type?: "l" | "link" | "u" | "url";
}
/**
* A template source.
*/
export interface TemplateSource {
/**
* Options for the source.
*/
options?: any;
/**
* The source.
*/
source: string;
}
/**
* An object that can transform (its) data.
*/
export interface Transformable {
/**
* The path to a (script) module that transforms data.
*
* s. 'TranformerModule' interface
*/
transformer?: string;
/**
* The optional options for the transformer script.
*/
transformerOptions?: any;
}
/**
* A target that supports data transformation.
*/
export interface TransformableDeployTarget extends DeployTarget, Transformable {
}
/**
* A function that validates a value.
*
* @param {ValidatorArguments<T>} args The arguments.
*
* @return {Promise<boolean>} The promise.
*/
export type Validator<T> = (args: ValidatorArguments<T>) => Promise<boolean>;
/**
* Arguments for a "validator" function.
*/
export interface ValidatorArguments<T> extends ScriptArguments {
/**
* Additional context data, defined by "caller".
*/
context?: any;
/**
* The options for validation.
*/
options?: any;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
replaceWithValues: (val: any) => string;
/**
* The value to check.
*/
value: T;
}
/**
* A validator module.
*/
export interface ValidatorModule<T> {
/**
* Validates a value.
*/
validate?: Validator<T>;
}
/**
* Describes a function that provides a value.
*
* @return {TValue} The value.
*/
export type ValueProvider<TValue> = () => TValue;
/**
* A value with a name.
*/
export interface ValueWithName extends MachineItem, PlatformItem {
/**
* An optional description for the value.
*/
description?: string;
/**
* The name of the value.
*/
name: string;
/**
* The type of the value.
*/
type?: string;
}
/**
* Event handler for a completed "deploy workspace" operation.
*
* @param {any} sender The sending object.
* @param {WorkspaceDeployedEventArguments} e Arguments of the event.
*/
export type WorkspaceDeployedEventHandler = (sender: any, e: WorkspaceDeployedEventArguments) => void;
/**
* Arguments for an a completed "deploy workspace" event.
*/
export interface WorkspaceDeployedEventArguments {
/**
* Gets if the operation has been canceled or not.
*/
canceled?: boolean;
/**
* The error (if occurred).
*/
error?: any;
/**
* The target.
*/
target: DeployTarget;
} | the_stack |
import React, { useState } from "react";
import { queryKeys, usePaxMonStatusQuery } from "../../api/paxmon";
import { Station, TripServiceInfo } from "../../api/protocol/motis";
import {
LoadLevel,
MeasureType,
MeasureWrapper,
} from "../../api/protocol/motis/paxforecast";
import TripPicker from "../TripPicker";
import StationPicker from "../StationPicker";
import TripServiceInfoView from "../TripServiceInfoView";
import TimeInput from "./TimeInput";
import { useMutation, useQueryClient } from "react-query";
import { useAtom } from "jotai";
import { universeAtom } from "../../data/simulation";
import { sendPaxForecastApplyMeasuresRequest } from "../../api/paxforecast";
const loadLevels: Array<{ level: LoadLevel; label: string }> = [
{ level: "Unknown", label: "unbekannt" },
{ level: "Low", label: "gering" },
{ level: "NoSeats", label: "keine Sitzplätze mehr" },
{ level: "Full", label: "voll" },
];
const measureTypes: Array<{ type: MeasureType; label: string }> = [
{ type: "TripLoadInfoMeasure", label: "Auslastungsinformation" },
{ type: "TripRecommendationMeasure", label: "Alternativenempfehlung" },
];
const labelClass = "font-semibold";
function MeasureInput(): JSX.Element {
const queryClient = useQueryClient();
const [universe] = useAtom(universeAtom);
const [recipientTrips, setRecipientTrips] = useState<TripServiceInfo[]>([]);
const [recipientStations, setRecipientStations] = useState<Station[]>([]);
const { data: status } = usePaxMonStatusQuery();
const [time, setTime] = useState(() =>
status ? new Date(status.system_time * 1000) : new Date()
);
const [measureType, setMeasureType] = useState<MeasureType>(
"TripLoadInfoMeasure"
);
const [loadInfoTrip, setLoadInfoTrip] = useState<TripServiceInfo>();
const [loadInfoLevel, setLoadInfoLevel] = useState<LoadLevel>("Unknown");
const [tripRecDestination, setTripRecDestination] = useState<Station>();
const [tripRecInterchange, setTripRecInterchange] = useState<Station>();
const [tripRecTrip, setTripRecTrip] = useState<TripServiceInfo>();
const applyEnabled = universe != 0;
const applyMeasuresMutation = useMutation(
(measures: MeasureWrapper[]) =>
sendPaxForecastApplyMeasuresRequest({
universe,
measures,
replace_existing: true,
preparation_time: 0,
}),
{
onSuccess: async () => {
console.log("measures applied");
await queryClient.invalidateQueries(queryKeys.trip());
},
}
);
const addTrip = (trip: TripServiceInfo | undefined) => {
if (trip) {
const id = JSON.stringify(trip.trip);
if (!recipientTrips.some((t) => JSON.stringify(t.trip) === id)) {
setRecipientTrips([...recipientTrips, trip]);
}
}
};
const removeTrip = (idx: number) => {
const newTrips = [...recipientTrips];
newTrips.splice(idx, 1);
setRecipientTrips(newTrips);
};
const addStation = (station: Station | undefined) => {
if (station && !recipientStations.some((s) => s.id == station.id)) {
setRecipientStations([...recipientStations, station]);
}
};
const removeStation = (idx: number) => {
const newStations = [...recipientStations];
newStations.splice(idx, 1);
setRecipientStations(newStations);
};
const buildMeasure: () => MeasureWrapper = () => {
const recipients = {
trips: recipientTrips.map((tsi) => tsi.trip),
stations: recipientStations.map((s) => s.id),
};
const unixTime = Math.round(time.getTime() / 1000);
if (recipients.trips.length == 0 && recipients.stations.length == 0) {
throw new Error("Kein Ort für die Ansage ausgewählt");
}
switch (measureType) {
case "TripLoadInfoMeasure":
if (!loadInfoTrip) {
throw new Error("Kein Trip ausgewählt");
}
return {
measure_type: "TripLoadInfoMeasure",
measure: {
recipients,
time: unixTime,
trip: loadInfoTrip.trip,
level: loadInfoLevel,
},
};
case "TripRecommendationMeasure":
if (!tripRecDestination || !tripRecInterchange || !tripRecTrip) {
throw new Error("Nicht alle benötigten Felder ausgefüllt");
}
return {
measure_type: "TripRecommendationMeasure",
measure: {
recipients,
time: unixTime,
planned_trips: [],
planned_destinations: [tripRecDestination.id],
planned_long_distance_destinations: [],
recommended_trip: tripRecTrip.trip,
interchange_station: tripRecInterchange.id,
},
};
}
};
const measureDetails: () => JSX.Element = () => {
switch (measureType) {
case "TripLoadInfoMeasure":
return (
<>
{/*<div className="font-semibold mt-2">Auslastungsinformation</div>*/}
<div>
<div className={labelClass}>Trip</div>
<div>
<TripPicker
onTripPicked={setLoadInfoTrip}
clearOnPick={false}
longDistanceOnly={false}
/>
</div>
</div>
<div>
<div className={labelClass}>Auslastungsstufe</div>
<div className="flex flex-col">
{loadLevels.map(({ level, label }) => (
<label key={level} className="inline-flex items-center gap-1">
<input
type="radio"
name="load-level"
value={level}
checked={loadInfoLevel == level}
onChange={() => setLoadInfoLevel(level)}
/>
{label}
</label>
))}
</div>
</div>
</>
);
case "TripRecommendationMeasure":
return (
<>
{/*<div className="font-semibold mt-2">Alternativenempfehlung</div>*/}
<div>
<div className={labelClass}>Reisende Richtung</div>
<StationPicker
onStationPicked={setTripRecDestination}
clearOnPick={false}
/>
</div>
<div>
<div className={labelClass}>Umsteigen an Station</div>
<StationPicker
onStationPicked={setTripRecInterchange}
clearOnPick={false}
/>
</div>
<div>
<div className={labelClass}>in Trip</div>
<TripPicker
onTripPicked={setTripRecTrip}
clearOnPick={false}
longDistanceOnly={false}
/>
</div>
</>
);
}
};
return (
<form
onSubmit={(e) => {
e.preventDefault();
try {
const measure = buildMeasure();
console.log(JSON.stringify(measure, null, 2));
applyMeasuresMutation.mutate([measure]);
} catch (ex) {
alert(ex);
}
}}
>
<div className="flex flex-col gap-4">
<div>
<div className={labelClass}>Ansage in Zug</div>
<ul className="leading-loose">
{recipientTrips.map((tsi, idx) => (
<li key={JSON.stringify(tsi.trip)}>
<TripServiceInfoView tsi={tsi} format="Short" />
<button
type="button"
className="ml-3 px-2 py-1 bg-db-red-500 hover:bg-db-red-600 text-white text-xs rounded"
onClick={() => removeTrip(idx)}
>
Entfernen
</button>
</li>
))}
</ul>
<TripPicker
onTripPicked={addTrip}
clearOnPick={true}
longDistanceOnly={false}
/>
</div>
<div>
<div className={labelClass}>Ansage an Station</div>
<ul className="leading-loose">
{recipientStations.map((station, idx) => (
<li key={station.id}>
<span>{station.name}</span>
<button
type="button"
className="ml-3 px-2 py-1 bg-db-red-500 hover:bg-db-red-600 text-white text-xs rounded"
onClick={() => removeStation(idx)}
>
Entfernen
</button>
</li>
))}
</ul>
<StationPicker onStationPicked={addStation} clearOnPick={true} />
</div>
<div>
<div className={labelClass}>Zeitpunkt der Ansage</div>
<div>
<TimeInput
value={time}
onChange={setTime}
className="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
/>
</div>
</div>
<div>
<div className={labelClass}>Maßnahmentyp</div>
<div className="flex flex-col">
{measureTypes.map(({ type, label }) => (
<label key={type} className="inline-flex items-center gap-1">
<input
type="radio"
name="measure-type"
value={type}
checked={measureType == type}
onChange={() => setMeasureType(type)}
/>
{label}
</label>
))}
</div>
</div>
{measureDetails()}
<button
className={`w-full p-3 rounded ${
applyMeasuresMutation.isLoading
? "bg-db-red-300 text-db-red-100 cursor-wait"
: applyEnabled
? "bg-db-red-500 hover:bg-db-red-600 text-white"
: "bg-db-red-300 text-db-red-100 cursor-not-allowed"
}`}
disabled={!applyEnabled}
>
Maßnahme simulieren
</button>
{applyMeasuresMutation.isError && (
<div>
<div className={labelClass}>
Fehler bei der Maßnahmensimulation:
</div>
<div>
{applyMeasuresMutation.error instanceof Error
? applyMeasuresMutation.error.message
: "Unbekannter Fehler"}
</div>
</div>
)}
{applyEnabled ? null : (
<div>
Maßnahmen können nicht im Hauptuniversum (#0) simuliert werden.
Bitte zuerst ein neues Paralleluniversum anlegen (Kopieren-Button in
der Kopfzeile) bzw. auswählen.
</div>
)}
</div>
</form>
);
}
export default MeasureInput; | the_stack |
import { ethers, upgrades, waffle } from "hardhat";
import { Signer, BigNumber, constants, Wallet } from "ethers";
import chai from "chai";
import { MockProvider, solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import {
MockERC20,
MockERC20__factory,
PancakeFactory,
PancakeFactory__factory,
PancakeRouterV2__factory,
PancakeMasterChef,
PancakeMasterChef__factory,
PancakeRouterV2,
PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading,
PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading__factory,
PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly,
PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly__factory,
PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm,
PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm__factory,
PancakeswapV2RestrictedSingleAssetStrategyLiquidate,
PancakeswapV2RestrictedSingleAssetStrategyLiquidate__factory,
MockVaultForRestrictedCakeMaxiAddBaseWithFarm,
MockVaultForRestrictedCakeMaxiAddBaseWithFarm__factory,
WETH,
WETH__factory,
WNativeRelayer__factory,
WNativeRelayer,
CakeMaxiWorker02__factory,
CakeMaxiWorker02,
CakeToken,
SyrupBar,
CakeToken__factory,
SyrupBar__factory,
MockBeneficialVault,
MockBeneficialVault__factory,
Vault,
Vault__factory,
SimpleVaultConfig,
SimpleVaultConfig__factory,
DebtToken__factory,
DebtToken,
FairLaunch,
FairLaunch__factory,
AlpacaToken__factory,
AlpacaToken,
CakeMaxiWorker,
CakeMaxiWorker__factory,
PancakePair__factory,
} from "../../../../../typechain";
import * as Assert from "../../../../helpers/assert";
chai.use(solidity);
const { expect } = chai;
describe("CakeMaxiWorker02", () => {
const FOREVER = "2000000000";
const CAKE_REWARD_PER_BLOCK = ethers.utils.parseEther("0.1");
const ALPACA_BONUS_LOCK_UP_BPS = 7000;
const ALPACA_REWARD_PER_BLOCK = ethers.utils.parseEther("5000");
const REINVEST_BOUNTY_BPS = "100"; // 1% reinvest bounty
const RESERVE_POOL_BPS = "0"; // 0% reserve pool
const KILL_PRIZE_BPS = "1000"; // 10% Kill prize
const INTEREST_RATE = "3472222222222"; // 30% per year
const MIN_DEBT_SIZE = ethers.utils.parseEther("0.05");
const ZERO_BENEFICIALVAULT_BOUNTY_BPS = "0";
const BENEFICIALVAULT_BOUNTY_BPS = "1000";
const poolId = 0;
const WORK_FACTOR = "7000";
const KILL_FACTOR = "8000";
const MAX_REINVEST_BOUNTY = "2000";
const DEPLOYER = "0xC44f82b07Ab3E691F826951a6E335E1bC1bB0B51";
const ZERO_REINVEST_THRESHOLD = "0";
const KILL_TREASURY_BPS = "100";
/// PancakeswapV2-related instance(s)
let factoryV2: PancakeFactory;
let routerV2: PancakeRouterV2;
let masterChef: PancakeMasterChef;
/// cake maxi worker instance(s)
let cakeMaxiWorkerNative: CakeMaxiWorker02;
let cakeMaxiWorkerNonNative: CakeMaxiWorker02;
let integratedCakeMaxiWorker: CakeMaxiWorker02;
let integratedCakeMaxiWorker01: CakeMaxiWorker;
/// Token-related instance(s)
let wbnb: WETH;
let baseToken: MockERC20;
let alpaca: AlpacaToken;
let cake: CakeToken;
let syrup: SyrupBar;
/// Strategy instance(s)
let stratAdd: PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly;
let stratLiq: PancakeswapV2RestrictedSingleAssetStrategyLiquidate;
let stratAddWithFarm: PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm;
let stratMinimize: PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading;
let stratEvil: PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
let eve: Signer;
let deployerAddress: string;
let aliceAddress: string;
let bobAddress: string;
let eveAddress: string;
// Vault
let mockedVault: MockVaultForRestrictedCakeMaxiAddBaseWithFarm;
let mockedBeneficialVault: MockBeneficialVault;
let integratedVault: Vault;
let simpleVaultConfig: SimpleVaultConfig;
let debtToken: DebtToken;
let fairLaunch: FairLaunch;
// Contract Signer
let baseTokenAsAlice: MockERC20;
let baseTokenAsBob: MockERC20;
let cakeAsAlice: MockERC20;
let wbnbTokenAsAlice: WETH;
let wbnbTokenAsBob: WETH;
let routerV2AsAlice: PancakeRouterV2;
let cakeMaxiWorkerNativeAsAlice: CakeMaxiWorker02;
let cakeMaxiWorkerNonNativeAsAlice: CakeMaxiWorker02;
let cakeMaxiWorkerNativeAsEve: CakeMaxiWorker02;
let cakeMaxiWorkerNonNativeAsEve: CakeMaxiWorker02;
let notOperatorCakeMaxiWorker: CakeMaxiWorker02;
let integratedVaultAsAlice: Vault;
let integratedVaultAsBob: Vault;
let integratedCakeMaxiWorkerAsEve: CakeMaxiWorker02;
let integratedCakeMaxiWorker01AsEve: CakeMaxiWorker;
let wNativeRelayer: WNativeRelayer;
async function fixture(maybeWallets?: Wallet[], maybeProvider?: MockProvider) {
[deployer, alice, bob, eve] = await ethers.getSigners();
[deployerAddress, aliceAddress, bobAddress, eveAddress] = await Promise.all([
deployer.getAddress(),
alice.getAddress(),
bob.getAddress(),
eve.getAddress(),
]);
// Setup Mocked Vault (for unit testing purposed)
const MockVault = (await ethers.getContractFactory(
"MockVaultForRestrictedCakeMaxiAddBaseWithFarm",
deployer
)) as MockVaultForRestrictedCakeMaxiAddBaseWithFarm__factory;
mockedVault = (await upgrades.deployProxy(MockVault)) as MockVaultForRestrictedCakeMaxiAddBaseWithFarm;
await mockedVault.deployed();
await mockedVault.setMockOwner(await alice.getAddress());
// Setup Pancakeswap
const PancakeFactory = (await ethers.getContractFactory("PancakeFactory", deployer)) as PancakeFactory__factory;
factoryV2 = await PancakeFactory.deploy(await deployer.getAddress());
await factoryV2.deployed();
const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory;
wbnb = await WBNB.deploy();
await wbnb.deployed();
// Setup WNativeRelayer
const WNativeRelayer = (await ethers.getContractFactory("WNativeRelayer", deployer)) as WNativeRelayer__factory;
wNativeRelayer = await WNativeRelayer.deploy(wbnb.address);
await wNativeRelayer.deployed();
const PancakeRouterV2 = (await ethers.getContractFactory("PancakeRouterV2", deployer)) as PancakeRouterV2__factory;
routerV2 = await PancakeRouterV2.deploy(factoryV2.address, wbnb.address);
await routerV2.deployed();
// Setup token stuffs
const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory;
baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20;
await baseToken.deployed();
await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100"));
await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
const AlpacaToken = (await ethers.getContractFactory("AlpacaToken", deployer)) as AlpacaToken__factory;
alpaca = await AlpacaToken.deploy(132, 137);
await alpaca.deployed();
await alpaca.mint(await deployer.getAddress(), ethers.utils.parseEther("1000"));
const CakeToken = (await ethers.getContractFactory("CakeToken", deployer)) as CakeToken__factory;
cake = await CakeToken.deploy();
await cake.deployed();
await cake["mint(address,uint256)"](await deployer.getAddress(), ethers.utils.parseEther("100"));
await cake["mint(address,uint256)"](await alice.getAddress(), ethers.utils.parseEther("10"));
await cake["mint(address,uint256)"](await bob.getAddress(), ethers.utils.parseEther("10"));
await factoryV2.createPair(baseToken.address, wbnb.address);
await factoryV2.createPair(cake.address, wbnb.address);
await factoryV2.createPair(alpaca.address, wbnb.address);
const SyrupBar = (await ethers.getContractFactory("SyrupBar", deployer)) as SyrupBar__factory;
syrup = await SyrupBar.deploy(cake.address);
await syrup.deployed();
// add beneficial vault with alpaca as an underlying token, thus beneficialVault reward is ALPACA
const MockBeneficialVault = (await ethers.getContractFactory(
"MockBeneficialVault",
deployer
)) as MockBeneficialVault__factory;
mockedBeneficialVault = (await upgrades.deployProxy(MockBeneficialVault, [alpaca.address])) as MockBeneficialVault;
await mockedBeneficialVault.deployed();
await mockedBeneficialVault.setMockOwner(await alice.getAddress());
// Setup Strategies
const PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly = (await ethers.getContractFactory(
"PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly",
deployer
)) as PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly__factory;
stratAdd = (await upgrades.deployProxy(PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly, [
routerV2.address,
])) as PancakeswapV2RestrictedSingleAssetStrategyAddBaseTokenOnly;
await stratAdd.deployed();
const PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm = (await ethers.getContractFactory(
"PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm",
deployer
)) as PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm__factory;
stratAddWithFarm = (await upgrades.deployProxy(PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm, [
routerV2.address,
mockedVault.address,
])) as PancakeswapV2RestrictedSingleAssetStrategyAddBaseWithFarm;
await stratAddWithFarm.deployed();
const PancakeswapV2RestrictedSingleAssetStrategyLiquidate = (await ethers.getContractFactory(
"PancakeswapV2RestrictedSingleAssetStrategyLiquidate",
deployer
)) as PancakeswapV2RestrictedSingleAssetStrategyLiquidate__factory;
stratLiq = (await upgrades.deployProxy(PancakeswapV2RestrictedSingleAssetStrategyLiquidate, [
routerV2.address,
])) as PancakeswapV2RestrictedSingleAssetStrategyLiquidate;
await stratLiq.deployed();
const PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading = (await ethers.getContractFactory(
"PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading",
deployer
)) as PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading__factory;
stratMinimize = (await upgrades.deployProxy(PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading, [
routerV2.address,
wNativeRelayer.address,
])) as PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading;
await stratMinimize.deployed();
const EvilStrat = (await ethers.getContractFactory(
"PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading",
deployer
)) as PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading__factory;
stratEvil = (await upgrades.deployProxy(EvilStrat, [
routerV2.address,
wNativeRelayer.address,
])) as PancakeswapV2RestrictedSingleAssetStrategyWithdrawMinimizeTrading;
await stratEvil.deployed();
/// Setup MasterChef
const PancakeMasterChef = (await ethers.getContractFactory(
"PancakeMasterChef",
deployer
)) as PancakeMasterChef__factory;
masterChef = await PancakeMasterChef.deploy(
cake.address,
syrup.address,
await deployer.getAddress(),
CAKE_REWARD_PER_BLOCK,
0
);
await masterChef.deployed();
// Transfer ownership so masterChef can mint CAKE
await cake.transferOwnership(masterChef.address);
await syrup.transferOwnership(masterChef.address);
// Setup Cake Maxi Worker
const CakeMaxiWorker02 = (await ethers.getContractFactory(
"CakeMaxiWorker02",
deployer
)) as CakeMaxiWorker02__factory;
const CakeMaxiWorker = (await ethers.getContractFactory("CakeMaxiWorker", deployer)) as CakeMaxiWorker__factory;
cakeMaxiWorkerNative = (await upgrades.deployProxy(CakeMaxiWorker02, [
await alice.getAddress(),
wbnb.address,
masterChef.address,
routerV2.address,
mockedBeneficialVault.address,
poolId,
stratAdd.address,
stratLiq.address,
REINVEST_BOUNTY_BPS,
ZERO_BENEFICIALVAULT_BOUNTY_BPS,
[wbnb.address, cake.address],
[cake.address, wbnb.address, alpaca.address],
ZERO_REINVEST_THRESHOLD,
])) as CakeMaxiWorker02;
await cakeMaxiWorkerNative.deployed();
cakeMaxiWorkerNonNative = (await upgrades.deployProxy(CakeMaxiWorker02, [
await alice.getAddress(),
baseToken.address,
masterChef.address,
routerV2.address,
mockedBeneficialVault.address,
poolId,
stratAdd.address,
stratLiq.address,
REINVEST_BOUNTY_BPS,
ZERO_BENEFICIALVAULT_BOUNTY_BPS,
[baseToken.address, wbnb.address, cake.address],
[cake.address, wbnb.address, alpaca.address],
ZERO_REINVEST_THRESHOLD,
])) as CakeMaxiWorker02;
await cakeMaxiWorkerNonNative.deployed();
// Set Up integrated Vault (for integration test purposed)
const FairLaunch = (await ethers.getContractFactory("FairLaunch", deployer)) as FairLaunch__factory;
fairLaunch = await FairLaunch.deploy(
alpaca.address,
await deployer.getAddress(),
ALPACA_REWARD_PER_BLOCK,
0,
ALPACA_BONUS_LOCK_UP_BPS,
0
);
await fairLaunch.deployed();
await alpaca.transferOwnership(fairLaunch.address);
const SimpleVaultConfig = (await ethers.getContractFactory(
"SimpleVaultConfig",
deployer
)) as SimpleVaultConfig__factory;
simpleVaultConfig = (await upgrades.deployProxy(SimpleVaultConfig, [
MIN_DEBT_SIZE,
INTEREST_RATE,
RESERVE_POOL_BPS,
KILL_PRIZE_BPS,
wbnb.address,
wNativeRelayer.address,
fairLaunch.address,
"0",
ethers.constants.AddressZero,
])) as SimpleVaultConfig;
await simpleVaultConfig.deployed();
await simpleVaultConfig.setWhitelistedLiquidators([bobAddress], true);
const DebtToken = (await ethers.getContractFactory("DebtToken", deployer)) as DebtToken__factory;
debtToken = (await upgrades.deployProxy(DebtToken, [
"debtibBTOKEN_V2",
"debtibBTOKEN_V2",
await deployer.getAddress(),
])) as DebtToken;
await debtToken.deployed();
const Vault = (await ethers.getContractFactory("Vault", deployer)) as Vault__factory;
integratedVault = (await upgrades.deployProxy(Vault, [
simpleVaultConfig.address,
wbnb.address,
"Interest Bearing BNB",
"ibBNB",
18,
debtToken.address,
])) as Vault;
await integratedVault.deployed();
await debtToken.setOkHolders([fairLaunch.address, integratedVault.address], true);
await debtToken.transferOwnership(integratedVault.address);
// Add FairLaunch pool and set fairLaunchPoolId for Vault
await fairLaunch.addPool(1, await integratedVault.debtToken(), false);
await integratedVault.setFairLaunchPoolId(0);
// Setup integrated CakeMaxiWorker02 for integration test
integratedCakeMaxiWorker = (await upgrades.deployProxy(CakeMaxiWorker02, [
integratedVault.address,
wbnb.address,
masterChef.address,
routerV2.address,
integratedVault.address,
poolId,
stratAdd.address,
stratLiq.address,
REINVEST_BOUNTY_BPS,
ZERO_BENEFICIALVAULT_BOUNTY_BPS,
[wbnb.address, cake.address],
[cake.address, wbnb.address],
ZERO_REINVEST_THRESHOLD,
])) as CakeMaxiWorker02;
// Setup CakeMaxiWorker01 (previous implementation) for integration test
integratedCakeMaxiWorker01 = (await upgrades.deployProxy(CakeMaxiWorker, [
integratedVault.address,
wbnb.address,
masterChef.address,
routerV2.address,
integratedVault.address,
poolId,
stratAdd.address,
stratLiq.address,
REINVEST_BOUNTY_BPS,
ZERO_BENEFICIALVAULT_BOUNTY_BPS,
[wbnb.address, cake.address],
[cake.address, wbnb.address],
])) as CakeMaxiWorker;
await cakeMaxiWorkerNonNative.deployed();
// Setting up dependencies for workers & strategies
await simpleVaultConfig.setWorker(
integratedCakeMaxiWorker.address,
true,
true,
WORK_FACTOR,
KILL_FACTOR,
true,
true
);
await simpleVaultConfig.setWorker(
integratedCakeMaxiWorker01.address,
true,
true,
WORK_FACTOR,
KILL_FACTOR,
true,
true
);
await wNativeRelayer.setCallerOk(
[stratMinimize.address, stratLiq.address, stratAddWithFarm.address, stratAdd.address, integratedVault.address],
true
);
await cakeMaxiWorkerNative.setStrategyOk(
[stratAdd.address, stratAddWithFarm.address, stratLiq.address, stratMinimize.address],
true
);
await cakeMaxiWorkerNative.setReinvestorOk([await eve.getAddress()], true);
await cakeMaxiWorkerNative.setTreasuryConfig(await eve.getAddress(), REINVEST_BOUNTY_BPS);
await cakeMaxiWorkerNonNative.setStrategyOk(
[stratAdd.address, stratAddWithFarm.address, stratLiq.address, stratMinimize.address],
true
);
await cakeMaxiWorkerNonNative.setReinvestorOk([await eve.getAddress()], true);
await cakeMaxiWorkerNonNative.setTreasuryConfig(await eve.getAddress(), REINVEST_BOUNTY_BPS);
await integratedCakeMaxiWorker.setStrategyOk(
[stratAdd.address, stratAddWithFarm.address, stratLiq.address, stratMinimize.address],
true
);
await integratedCakeMaxiWorker.setReinvestorOk([await eve.getAddress()], true);
await integratedCakeMaxiWorker.setTreasuryConfig(await eve.getAddress(), REINVEST_BOUNTY_BPS);
await integratedCakeMaxiWorker01.setStrategyOk(
[stratAdd.address, stratAddWithFarm.address, stratLiq.address, stratMinimize.address],
true
);
await integratedCakeMaxiWorker01.setReinvestorOk([await eve.getAddress()], true);
await stratAdd.setWorkersOk(
[
cakeMaxiWorkerNative.address,
cakeMaxiWorkerNonNative.address,
integratedCakeMaxiWorker.address,
integratedCakeMaxiWorker01.address,
],
true
);
await stratAddWithFarm.setWorkersOk(
[
cakeMaxiWorkerNative.address,
cakeMaxiWorkerNonNative.address,
integratedCakeMaxiWorker.address,
integratedCakeMaxiWorker01.address,
],
true
);
await stratLiq.setWorkersOk(
[
cakeMaxiWorkerNative.address,
cakeMaxiWorkerNonNative.address,
integratedCakeMaxiWorker.address,
integratedCakeMaxiWorker01.address,
],
true
);
await stratMinimize.setWorkersOk(
[
cakeMaxiWorkerNative.address,
cakeMaxiWorkerNonNative.address,
integratedCakeMaxiWorker.address,
integratedCakeMaxiWorker01.address,
],
true
);
await stratEvil.setWorkersOk(
[
cakeMaxiWorkerNative.address,
cakeMaxiWorkerNonNative.address,
integratedCakeMaxiWorker.address,
integratedCakeMaxiWorker01.address,
],
true
);
// Assign contract signer
baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice);
baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob);
cakeAsAlice = MockERC20__factory.connect(cake.address, alice);
wbnbTokenAsAlice = WETH__factory.connect(wbnb.address, alice);
wbnbTokenAsBob = WETH__factory.connect(wbnb.address, bob);
routerV2AsAlice = PancakeRouterV2__factory.connect(routerV2.address, alice);
cakeMaxiWorkerNativeAsAlice = CakeMaxiWorker02__factory.connect(cakeMaxiWorkerNative.address, alice);
cakeMaxiWorkerNonNativeAsAlice = CakeMaxiWorker02__factory.connect(cakeMaxiWorkerNonNative.address, alice);
cakeMaxiWorkerNativeAsEve = CakeMaxiWorker02__factory.connect(cakeMaxiWorkerNative.address, eve);
cakeMaxiWorkerNonNativeAsEve = CakeMaxiWorker02__factory.connect(cakeMaxiWorkerNonNative.address, eve);
notOperatorCakeMaxiWorker = CakeMaxiWorker02__factory.connect(cakeMaxiWorkerNative.address, bob);
integratedVaultAsAlice = Vault__factory.connect(integratedVault.address, alice);
integratedVaultAsBob = Vault__factory.connect(integratedVault.address, bob);
integratedCakeMaxiWorkerAsEve = CakeMaxiWorker02__factory.connect(integratedCakeMaxiWorker.address, eve);
integratedCakeMaxiWorker01AsEve = CakeMaxiWorker__factory.connect(integratedCakeMaxiWorker01.address, eve);
// Adding liquidity to the pool
await wbnbTokenAsAlice.deposit({
value: ethers.utils.parseEther("52"),
});
await wbnbTokenAsBob.deposit({
value: ethers.utils.parseEther("50"),
});
await wbnb.deposit({
value: ethers.utils.parseEther("50"),
});
await cakeAsAlice.approve(routerV2.address, ethers.utils.parseEther("0.1"));
await baseTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("1"));
await wbnbTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("2"));
await alpaca.approve(routerV2.address, ethers.utils.parseEther("10"));
await wbnb.approve(routerV2.address, ethers.utils.parseEther("10"));
// Add liquidity to the BTOKEN-WBNB pool on Pancakeswap
await routerV2AsAlice.addLiquidity(
baseToken.address,
wbnb.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("1"),
"0",
"0",
await alice.getAddress(),
FOREVER
);
// Add liquidity to the CAKE-WBNB pool on Pancakeswap
await routerV2AsAlice.addLiquidity(
cake.address,
wbnb.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("1"),
"0",
"0",
await alice.getAddress(),
FOREVER
);
// Add liquidity to the ALPACA-WBNB pool on Pancakeswap
await routerV2.addLiquidity(
wbnb.address,
alpaca.address,
ethers.utils.parseEther("10"),
ethers.utils.parseEther("10"),
"0",
"0",
await deployer.getAddress(),
FOREVER
);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
describe("iworker2", async () => {
it("should return the correct path", async () => {
expect(await cakeMaxiWorkerNative.getPath()).to.be.deep.eq([wbnb.address, cake.address]);
expect(await cakeMaxiWorkerNonNative.getPath()).to.be.deep.eq([baseToken.address, wbnb.address, cake.address]);
});
it("should reverse path", async () => {
expect(await cakeMaxiWorkerNative.getReversedPath()).to.be.deep.eq([cake.address, wbnb.address]);
expect(await cakeMaxiWorkerNonNative.getReversedPath()).to.be.deep.eq([
cake.address,
wbnb.address,
baseToken.address,
]);
});
it("should return reward path", async () => {
expect(await cakeMaxiWorkerNative.getRewardPath()).to.be.deep.eq([cake.address, wbnb.address, alpaca.address]);
expect(await cakeMaxiWorkerNonNative.getRewardPath()).to.be.deep.eq([cake.address, wbnb.address, alpaca.address]);
});
});
describe("#setTreasuryBountyBps", async () => {
context("when treasury bounty > max reinvest bounty", async () => {
it("should revert", async () => {
await expect(
cakeMaxiWorkerNative.setTreasuryConfig(DEPLOYER, parseInt(MAX_REINVEST_BOUNTY) + 1)
).to.revertedWith("CakeMaxiWorker02::setTreasuryConfig:: _treasuryBountyBps exceeded maxReinvestBountyBps");
expect(await cakeMaxiWorkerNative.treasuryBountyBps()).to.eq(REINVEST_BOUNTY_BPS);
});
});
context("when treasury bounty <= max reinvest bounty", async () => {
it("should successfully set a treasury bounty", async () => {
await cakeMaxiWorkerNative.setTreasuryConfig(DEPLOYER, 499);
expect(await cakeMaxiWorkerNative.treasuryBountyBps()).to.eq(499);
});
});
});
describe("#setTreasuryAccount", async () => {
it("should successfully set a treasury account", async () => {
const aliceAddr = await alice.getAddress();
await cakeMaxiWorkerNative.setTreasuryConfig(aliceAddr, REINVEST_BOUNTY_BPS);
expect(await cakeMaxiWorkerNative.treasuryAccount()).to.eq(aliceAddr);
});
});
describe("#setMaxReinvestBountyBps", async () => {
it("should successfully set a max reinvest bounty bps", async () => {
await cakeMaxiWorkerNative.setMaxReinvestBountyBps("3000");
expect(await cakeMaxiWorkerNative.maxReinvestBountyBps()).to.be.eq("3000");
});
it("should revert when new max reinvest bounty over 30%", async () => {
await expect(cakeMaxiWorkerNative.setMaxReinvestBountyBps("3001")).to.be.revertedWith(
"CakeMaxiWorker02::setMaxReinvestBountyBps:: _maxReinvestBountyBps exceeded 30%"
);
expect(await cakeMaxiWorkerNative.maxReinvestBountyBps()).to.be.eq("2000");
});
});
describe("#work()", async () => {
context("When the caller is not an operator", async () => {
it("should be reverted", async () => {
await expect(
notOperatorCakeMaxiWorker.work(
0,
await bob.getAddress(),
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.05")])]
)
)
).to.revertedWith("CakeMaxiWorker02::onlyOperator:: not operator");
});
});
context("When the caller calling a non-whitelisted strategy", async () => {
it("should be reverted", async () => {
await expect(
cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratEvil.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
)
).to.revertedWith("CakeMaxiWorker02::work:: unapproved work strategy");
});
});
context("When the operator calling a revoked strategy", async () => {
it("should be reverted", async () => {
await cakeMaxiWorkerNative.setStrategyOk([stratAdd.address], false);
await expect(
cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
)
).to.revertedWith("CakeMaxiWorker02::work:: unapproved work strategy");
});
});
context("When the treasury Account and treasury bounty bps haven't been set", async () => {
it("should not auto reinvest", async () => {
await cakeMaxiWorkerNative.setTreasuryConfig(constants.AddressZero, 0);
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1* 0.9975 * 0.1) / ( 1 + 0.1 * 0.9975) = 0.009070243237099340 FTOKEN
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice opens a new position with 0.1 WBNB. This position ID is 1.
// Her previous position must still has the same LPs as before due to reinvest is not triggered.
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
1,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
});
});
context("When the user passes addBaseToken strategy", async () => {
it("should convert an input base token to a farming token and stake to the masterchef", async () => {
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1* 0.9975 * 0.1) / ( 1 + 0.1 * 0.9975) = 0.009070243237099340 FTOKEN
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.009070243237099340 = 0.207070243237097456
// amountOut of 0.1 from alice will be
// if 1.1 WBNB = (0.1 - 0.00907024323709934) FToken ((0.1 - 0.00907024323709934) is from a reserve pool changed during swap)
// if 1.1 WBNB = 0.09092975676290066 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.09092975676290066) /(1.1 + 0.1 * 0.9975)
// = 0.0075601110540523785
// thus, the current amount accumulated with the previous one will be 0.0075601110540523785 + 0.207070243237097456 = 0.214630354291149834 CAKE
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
// after all these steps above, alice will have a balance in total of 0.214630354291149834
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.214630354291149834"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.214630354291149834"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.214630354291149834")
);
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.002").toString()
);
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
// bob start opening his position using 0.1 wbnb
// once bob call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.214630354291149834 = 0.412630354291058781
// amountOut of 0.1 will be
// if 1.2 WBNB = (0.1 - (0.00907024323709934 + 0.0075601110540523785)) FToken
// if 1.2 WBNB = 0.08336964570884828 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.08336964570884828) / (1.2+0.1*0.9975) = 0.006398247477943924
// total farming token amount will be 0.412630354291058781 + 0.006398247477943924 = 0.419028601769002705
// bob total share will be (0.006398247477943924 / 0.412630354291058781) * 0.214630354291149834 = 0.003328058900060705
// alice total balance will be (0.214630354291149834 / 0.214630354291149834) * 0.419028601769002705 = 0.419028601769002705
await wbnbTokenAsBob.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
1,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.419028601769002705"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.214630354291149834"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.412630354291058781")
);
expect(await cakeMaxiWorkerNative.shares(1)).to.eq(ethers.utils.parseEther("0.003328058900060705"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(1))).to.eq(
ethers.utils.parseEther("0.006398247477943923")
);
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.004").toString()
);
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
});
});
context("When the user passes addBaseWithFarm strategy", async () => {
it("should convert an input as a base token with some farming token and stake to the masterchef", async () => {
// Alice transfer 0.1 WBNB to StrategyAddBaseWithFarm first
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
// Alice uses AddBaseWithFarm strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.00907024323709934
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAddWithFarm.address, ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", "0"])]
)
);
// after all these steps above, alice will have a balance in total of 0.00907024323709934
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
// Alice uses AddBaseWithFarm strategy to add another 0.1 WBNB with 0.04 CAKE
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 3 blocks away from the last `work()`, the reward will be 0.3 CAKE
// thus, reward staked in the masterchef will be 0.3 - 0.003 (as a reward) + 0.009070243237099340 = 0.306070243237092023
// amountOut of 0.1 will be
// if 1.1 WBNB = (0.1 - 0.00907024323709934) FToken
// if 1.1 WBNB = 0.09092975676290066 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.09092975676290066) / (1.1 + 0.1 * 0.9975) = 0.0075601110540523785
// thus, the current amount accumulated with the previous one will be 0.0075601110540523785 + 0.306070243237092023 + 0.04 = 0.353630354291144401
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeAsAlice.approve(mockedVault.address, ethers.utils.parseEther("0.04"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
stratAddWithFarm.address,
ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], [ethers.utils.parseEther("0.04"), "0"]),
]
)
);
// after all these steps above, alice will have a balance in total of 0.353630354291144401
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.353630354291144401"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.353630354291144401"));
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
// Bob start opening his position using 0.1 wbnb with 0.05 CAKE
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 3 blocks away from the last `work()`, the reward will be 0.3 CAKE
// thus, reward staked in the masterchef will be 0.3 - 0.003 (as a reward) + 0.353630354291144401 = 0.650630354290912584
// amountOut of 0.1 will be
// if 1.2 WBNB = (0.1 - (0.0075601110540523785 + 0.00907024323709934)) FToken
// if 1.2 WBNB = 0.08336964570884828 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.08336964570884828) / (1.2 + 0.1 * 0.9975) = 0.006398247477943925
// thus, total staked balance will be = 0.650630354290912584 + 0.006398247477943925 + 0.05 = 0.707028601768856508
// bob will receive total share of ((0.05 + 0.006398247477943925) / 0.650630354290912584) * 0.353630354291144401 = 0.030653553289503376
await wbnbTokenAsBob.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeAsAlice.approve(mockedVault.address, ethers.utils.parseEther("0.05"));
await cakeMaxiWorkerNativeAsAlice.work(
1,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
stratAddWithFarm.address,
ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], [ethers.utils.parseEther("0.05"), "0"]),
]
)
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.707028601768856508"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.353630354291144401"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.650630354290912585")
);
expect(await cakeMaxiWorkerNative.shares(1)).to.eq(ethers.utils.parseEther("0.030653553289503376"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(1))).to.eq(
ethers.utils.parseEther("0.056398247477943922")
);
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
});
});
context("When the user passes liquidation strategy to close the position", async () => {
context("When alice opened and closed her position", async () => {
it("should liquidate a position based on the share of a user", async () => {
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1+ 0.1 * 0.9975) = 0.009070243237099340
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
const aliceBaseTokenBefore = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenBefore = await cake.balanceOf(await alice.getAddress());
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
// Alice call liquidate strategy to close her position
// once alice call function `work()` the `reinvest()` will be triggered
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratLiq.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.009070243237099340 = 0.108070243237093908 FTOKEN
// alice will get a base token based on 0.108070243237093908 farming token (staked balance)
// if 0.1 - 0.108070243237093908 FTOKEN = 1.1 BNB
// if 0.09092975676290066 FTOKEN = 1.1 BNB
// 0.108070243237093908 FTOKEN = (0.108070243237093908 * 0.9975 * 1.1) / (0.09092975676290066 + 0.108070243237093908 * 0.9975) = 0.596689876593748878 BNB
// thus, alice should get a baseToken amount of 0.596689876593748878
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
const aliceBaseTokenAfter = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenAfter = await cake.balanceOf(await alice.getAddress());
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0"));
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.001").toString()
);
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.eq(ethers.utils.parseEther("0.596689876593748878"));
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.eq(ethers.utils.parseEther("0"));
});
});
context("When alice closed her position after bob did", async () => {
it("should liquidate a position based on the share of a user", async () => {
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1+ 0.1 * 0.9975) = 0.009070243237099340
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
const aliceBaseTokenBefore = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenBefore = await cake.balanceOf(await alice.getAddress());
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
// Bob uses AddBaseTokenOnly strategy to add 0.1 WBNB
// once Bob call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.009070243237099340 = 0.207070243237097456
// amountOut of 0.1 from Bob will be
// if 1.1 WBNB = (0.1 - 0.00907024323709934) FToken
// if 1.1 WBNB = 0.09092975676290066 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.09092975676290066) /(1.1 + 0.1 * 0.9975)
// = 0.0075601110540523785
// thus, the current amount accumulated with the previous one will be 0.0075601110540523785 + 0.207070243237097456 = 0.214630354291149834 CAKE
// bob will receive the total share of (0.0075601110540523785 / 0.207070243237097456) * 0.009070243237099340 = 0.000331153550059932
await wbnbTokenAsBob.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
1,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.002").toString()
);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.214630354291149834"));
expect(await cakeMaxiWorkerNative.shares(1)).to.eq(ethers.utils.parseEther("0.000331153550059932"));
// Alice call liquidate strategy to close her position
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.214630354291149834 = 0.313630354290998067
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratLiq.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
// alice's share is 0.00907024323709934 farming token (staked balance)
// thus alice is going to liquidate for (0.00907024323709934 / 9401396787159272) * 0.313630354290998067 = 0.302583080403795127 CAKE
// thus the leftover balance will be 0.313630354290998067 - 0.302583080403795127 = 0.011047273887202940
// if 0.1 - 0.01663035429115172 FTOKEN = 1.2 BNB
// if 0.08336964570884828 FTOKEN = 1.2 BNB
// 0.302583080403795127 FTOKEN = (0.302583080403795127 * 0.9975 * 1.2) / (0.08336964570884828 + 0.302583080403795127 * 0.9975) = 0.940278961519668853 BNB
// thus, alice should get a baseToken amount of 0.940278961519668853
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
const aliceBaseTokenAfter = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenAfter = await cake.balanceOf(await alice.getAddress());
// only bobs' left
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.011047273887202940"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0"));
// bob's position should remain the same
expect(await cakeMaxiWorkerNative.shares(1)).to.eq(ethers.utils.parseEther("0.000331153550059932"));
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.eq(ethers.utils.parseEther("0.940278961519668853"));
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.eq(ethers.utils.parseEther("0"));
});
});
});
context("When the user passes close minimize trading strategy to close the position", async () => {
it("should send a base token to be enough for repaying the debt, the rest will be sent as a farming token", async () => {
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1+ 0.1 * 0.9975) = 0.009070243237099340
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
const aliceBaseTokenBefore = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenBefore = await cake.balanceOf(await alice.getAddress());
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
// Alice call withdraw minimize trading strategy to close her position
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.009070243237099340 = 0.108070243237093908
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("0.05"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratMinimize.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
// 0.1 - 0.00907024323709934 FTOKEN = 1.1 WBNB
// 0.09092975676290066 FTOKEN = 1.1 WBNB
// x FTOKEN = (x * 0.9975 * 1.1) / (0.09092975676290066 + x * 0.9975) = 0.05 WBNB
// x = 0.004340840518577427
// thus, the remaining farming token will be 0.108070243237093908 - 0.004340840518577427
// = 0.10372940271851648
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
const aliceBaseTokenAfter = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenAfter = await cake.balanceOf(await alice.getAddress());
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.001").toString()
);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0"));
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.eq(ethers.utils.parseEther("0.05"));
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.eq(
ethers.utils.parseEther("0.10372940271851648")
);
});
});
});
describe("#reinvest()", async () => {
context("When the caller is not a reinvestor", async () => {
it("should be reverted", async () => {
await expect(cakeMaxiWorkerNativeAsAlice.reinvest()).to.revertedWith(
"CakeMaxiWorker02::onlyReinvestor:: not reinvestor"
);
});
});
context("When the reinvestor reinvest in the middle of a transaction set", async () => {
context("When beneficialVaultBounty takes 0% of reinvest bounty", async () => {
it("should increase the size of total balance, bounty is sent to the reinvestor", async () => {
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.009070243237099340 = 0.207070243237097456
// amountOut of 0.1 from alice will be
// if 1.1 WBNB = (0.1 - 0.00907024323709934) FToken
// if 1.1 WBNB = 0.09092975676290066 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.09092975676290066) /(1.1 + 0.1 * 0.9975)
// = 0.0075601110540523785
// thus, the current amount accumulated with the previous one will be 0.0075601110540523785 + 0.207070243237097456 = 0.214630354291149834 CAKE
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
// after all these steps above, alice will have a balance and share in total of 0.214630354291149834
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.214630354291149834"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.214630354291149834"));
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.214630354291149834")
);
// reinvest.. the size of the reward should be 1 (blocks) * 0.1 FToken (CAKE)
await cakeMaxiWorkerNativeAsEve.reinvest();
// eve, who is a reinvestor will get her bounty for 0.1 * 1% = 0.001
// thus, current balance will be 0.214630354291149834 + (0.1 - 0.001) = 0.313630354290998067 FTOKEN
// now eve will get 0.002 + 0.001 = 0.003 FTOKEN
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.003").toString()
);
Assert.assertAlmostEqual(
(await alpaca.balanceOf(mockedBeneficialVault.address)).toString(),
ethers.utils.parseEther("0").toString()
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
// Bob start opening his position using 0.1 wbnb
// once bob call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.313630354290998067 = 0.511630354290967637
// amountOut of 0.1 will be
// if 1.2 WBNB = (0.1 - (0.00907024323709934 + 0.0075601110540523785)) FToken
// if 1.2 WBNB = 0.08336964570884828 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.08336964570884828) / (1.2+0.1*0.9975) = 0.006398247477943924
// total farming token amount will be 0.511630354290967637 + 0.006398247477943924 = 0.518028601768911561
// bob total share will be (0.006398247477943924 / 0.511630354290967637) * 0.214630354291149834 = 0.002684082583287423
const bobShare = ethers.utils.parseEther("0.002684082583287423");
const aliceShare = ethers.utils.parseEther("0.214630354291149834");
await wbnbTokenAsBob.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
1,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
const bobBalance = bobShare.mul(userInfo[0]).div(await cakeMaxiWorkerNative.totalShare());
const aliceBalance = aliceShare.mul(userInfo[0]).div(await cakeMaxiWorkerNative.totalShare());
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.518028601768911561"));
expect(await cakeMaxiWorkerNative.shares(1)).to.eq(bobShare);
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(1))).to.eq(bobBalance);
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(aliceBalance);
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
});
});
context("When beneficialVaultBounty takes 10% of reinvest bounty", async () => {
it("should increase the size of total balance, bounty is sent to the reinvestor and beneficial vault based on a correct bps", async () => {
await cakeMaxiWorkerNative.setBeneficialVaultBountyBps(BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS));
expect(await cakeMaxiWorkerNative.beneficialVaultBountyBps()).to.eq(
BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS)
);
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// total bounty will be 0.2 * 1% = 0.002
// 90% if reinvest bounty 0.002 * 90 / 100 = 0.0018
// thus, alice we get a bounty of 0.0018
// 10% of 0.002 (0.0002) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be ALPACA)
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.009070243237099340 = 0.207070243237097456
// if (0.1 - 0.00907024323709934 ) FToken = 1.1 WBNB
// 0.090929756762900660 FToken = 1.1 WBNB
// 0.0002 will be (0.0002 * 0.9975 * 1.1) / (0.090929756762900660 + 0.0002 * 0.9975) = 0.002408117961182992 WBNB
// if 10WBNB = 10ALPACA
// 0.002408117961182992 WBNB = (0.002408117961182992 * 0.9975 * 10) / (10 + 0.002408117961182992 * 0.9975) = 0.002401520797529707 ALPACA
// amountOut of 0.1 from alice will be
// if (1.1 - 0.002408117961182992) WBNB = (0.090929756762900660 - 0.0002) FToken
// if 1.097591882038817008 WBNB = 0.091129756762900658 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.091129756762900658) /(1.097591882038817008 + 0.1 * 0.9975)
// = 0.007591978008503875
// thus, the current amount accumulated with the previous one will be 0.007591978008503875 + 0.207070243237097456 = 0.214662221245601331 CAKE
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
// after all these steps above, alice will have a balance in total of 0.214662221245601331
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.214662221245601331"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.214662221245601331"));
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0018").toString()
);
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
Assert.assertAlmostEqual(
(await alpaca.balanceOf(mockedBeneficialVault.address)).toString(),
ethers.utils.parseEther("0.002401520797529707").toString()
);
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(
ethers.utils.parseEther("0.214662221245601331")
);
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.214662221245601331 = 0.313662221245495030
// total bounty will be 0.1 * 1% = 0.001
// 90% if reinvest bounty 0.001 * 90 / 100 = 0.0009
// thus, alice we get a bounty of 0.0027
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be ALPACA)
// if (0.091129756762900658 - 0.007591978008503875) FToken = 1.197591882038817008 WBNB
// 0.083537778754396783 FToken = 1.197591882038817008 WBNB
// 0.0001 will be (0.0001 * 0.9975 * 1.2) / (0.083537778754396783 + 0.0001 * 0.9975) = 0.001428303681521235 WBNB
// if 10.002408117961182992 WBNB = 9.997598479202470293 ALPACA
// 0.001428303681521235 WBNB = (0.001428303681521235 * 0.9975 * 9.997598479202470293) / (10.002408117961182992 + 0.001428303681521235 * 0.9975) = 0.001423845031174474 ALPACA
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
await cakeMaxiWorkerNativeAsEve.reinvest();
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0027").toString()
);
Assert.assertAlmostEqual(
(await alpaca.balanceOf(mockedBeneficialVault.address)).toString(),
ethers.utils
.parseEther("0.001423845031174474")
.add(ethers.utils.parseEther("0.002401520797529707"))
.toString()
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
// Bob start opening his position using 0.1 wbnb
// once bob call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.2 - 0.002 (as a reward) + 0.313662221245495030 = 0.511662221245326915
// 90% if reinvest bounty 0.002 * 90 / 100 = 0.00018
// thus, eve we get a bounty of 00018
// 10% of 0.002 (0.0002) will be distributed to the vault by swapping 0.002 of reward token into a beneficial vault token (this is scenario, it will be ALPACA)
// if 0.083637778754396675 FToken = 1.196163578357295773 WBNB
// 0.0002 FToken will be (0.0002 * 0.9975 * 1.196163578357295773) / (0.083637778754396675 + 0.0002 * 0.9975) = 0.002846402428938134 WBNB
// if 10.003836421642704227 WBNB = 9.996174634171295819 ALPACA
// 0.002846402428938134 WBNB = (0.002846402428938134 * 0.9975 * 9.996174634171295819) / (10.003836421642704227 + 0.002846402428938134 * 0.9975) = 0.002836306856284102 ALPACA
// amountOut of 0.1 will be
// if 1.193317175928357639 WBNB = 0.08366964570884827 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.08366964570884827) / (1.193317175928357639 + 0.1 * 0.9975) = 0.006467427668440323
// bob's share will be (0.006467427668440323 / 0.511662221245326915) * 0.214662221245601331 = 0.002713337689215490
// total farming token amount will be 0.511662221245326915 + 0.006467427668440323 = 0.518129648913767238
const bobShare = ethers.utils.parseEther("0.002713337689215490");
const aliceShare = ethers.utils.parseEther("0.214662221245601331");
await wbnbTokenAsBob.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
await cakeMaxiWorkerNativeAsAlice.work(
1,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
const bobBalance = bobShare.mul(userInfo[0]).div(await cakeMaxiWorkerNative.totalShare());
const aliceBalance = aliceShare.mul(userInfo[0]).div(await cakeMaxiWorkerNative.totalShare());
Assert.assertAlmostEqual(
(await alpaca.balanceOf(mockedBeneficialVault.address)).toString(),
ethers.utils
.parseEther("0.001423845031174474")
.add(ethers.utils.parseEther("0.002401520797529707").add(ethers.utils.parseEther("0.002836306856284102")))
.toString()
);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.518129648913767238"));
expect(await cakeMaxiWorkerNative.shares(1)).to.eq(bobShare);
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(1))).to.eq(bobBalance);
expect(await cakeMaxiWorkerNative.shareToBalance(await cakeMaxiWorkerNative.shares(0))).to.eq(aliceBalance);
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
});
});
});
context("When integrated with an actual vault", async () => {
it("should reinvest with updated beneficial vault reward to the beneficial vault", async () => {
await integratedCakeMaxiWorker.setBeneficialVaultBountyBps(BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS));
expect(await integratedCakeMaxiWorker.beneficialVaultBountyBps()).to.eq(
BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS)
);
// alice deposit some portion of her native bnb into a vault, thus interest will be accrued afterward
await integratedVaultAsAlice.deposit(ethers.utils.parseEther("1"), {
value: ethers.utils.parseEther("1"),
});
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB (0.05 as principal amount, 0.05 as a loan)
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await integratedVaultAsAlice.work(
0,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("0.05"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.05"),
}
);
let userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// total bounty will be 0.1 * 1% = 0.001
// 90% if reinvest bounty 0.001 * 90 / 100 = 0.0009
// thus, alice we get a bounty of 0.0018
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be wbnb)
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.009070243237099340 = 0.108070243237093908
// if (0.1 - 0.00907024323709934 ) FToken = 1.1 WBNB
// 0.090929756762900660 FToken = 1.1 WBNB
// 0.0001 will be (0.0001 * 0.9975 * 1.1) / (0.090929756762900660 + 0.0001 * 0.9975) = 0.001205378386656404 WBNB
// amountOut of 0.1 from alice will be
// if (1.1 - 0.001205378386656404) WBNB = (0.090929756762900660 - 0.0001) FToken
// if 1.098794621613343596 WBNB = 0.091029756762900654 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.091029756762900654) /(1.098794621613343596 + 0.1 * 0.9975)
// = 0.007576036864507046
// thus, the current amount accumulated with the previous one will be 0.007576036864507046 + 0.108070243237093908 = 0.115646280101600954 CAKE
await integratedVaultAsAlice.work(
1,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
// after all these steps above, alice will have a balance in total of 0.115646280101600954
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.115646280101600954"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(ethers.utils.parseEther("0.115646280101600954"));
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0009").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
expect(await await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
ethers.utils.parseEther("0.115646280101600954")
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils.parseEther("0").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0.001205378386656404").toString()
);
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.115646280101600954 = 0.214646280101518468
// total bounty will be 0.1 * 1% = 0.001
// 90% if reinvest bounty 0.001 * 90 / 100 = 0.0009
// thus, alice we get a bounty of 0.0018
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be wbnb)
// if (0.091029756762900654 - 0.007576036864507046) FToken = 1.198794621613343596 WBNB
// 0.083453719898393608 FToken = 1.198794621613343596 WBNB
// 0.0001 will be (0.0001 * 0.9975 * 1.198794621613343596) / (0.083453719898393608 + 0.0001 * 0.9975) = 0.001431176510697250 WBNB
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
await integratedCakeMaxiWorkerAsEve.reinvest();
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0018").toString()
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils
.parseEther("0.001431176510697250")
.add(ethers.utils.parseEther("0.001205378386656404"))
.toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0").toString()
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
// Bob start opening his position using 0.1 wbnb
// once bob call function `work()` the `reinvest()` will be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.21464628010160097 = 0.313646280101601
// 90% if reinvest bounty 0.002 * 90 / 100 = 0.00009
// thus, alice we get a bounty of 0.00009
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.002 of reward token into a beneficial vault token (this is scenario, it will be wbnb)
// if 0.083553719898393524 FToken = 1.197363445102646346 WBNB
// 0.0001 FToken will be (0.0001 * 0.9975 * 1.197363445102646346) / (0.083553719898393524 + 0.0001 * 0.9975) = 0.001427759109023196 WBNB
// amountOut of 0.1 will be
// if 1.195935685993623150 WBNB = 0.083653719898393390 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.083653719898393390) / (1.195935685993623150 + 0.1 * 0.9975) = 0.006440187346413124 FTOKEN
// bob's share will be (0.006440187346413124 / 0.313646280101601) * 0.115646280101600954 = 0.002374597618467932
// total farming token amount will be 0.313646280101601 + 0.006440187346413124 = 0.320086467447799501
const alicePos1Share = ethers.utils.parseEther("0.115646280101600954");
const bobPos2Share = ethers.utils.parseEther("0.002374597618467932");
await integratedVaultAsBob.work(
0,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
let alicePos1Balance = alicePos1Share.mul(userInfo[0]).div(await integratedCakeMaxiWorker.totalShare());
let bobPos2Balance = bobPos2Share.mul(userInfo[0]).div(await integratedCakeMaxiWorker.totalShare());
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.320086467447799501"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(alicePos1Share);
expect(await integratedCakeMaxiWorker.shares(2)).to.eq(bobPos2Share);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
alicePos1Balance
);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(2))).to.eq(
bobPos2Balance
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils
.parseEther("0.001431176510697250")
.add(ethers.utils.parseEther("0.001205378386656404"))
.toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0.001427759109023196").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
// Alice open another position using 0.1 wbnb
// once Alice call function `work()` the `reinvest()` wFill be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// --------
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.320086467447799501 = 0.419086467447799501
// ** actual amount = 0.098999999999785573 + 0.320086467447799501 = 0.419086467447585074 ** (diff due to rounding in PCS MasterChef)
// --------
// 90% if reinvest bounty 0.098999999999785573 * 90 / 100 = 0.000899999999999951
// --------
// thus, deployer will get a bounty of 0.000899999999999951
// 10% of 0.001 (0.000099999999999994) will be distributed to the vault by swapping 0.001 FTOKEN into a beneficial vault token (this is scenario, it will be wbnb)
// --------
// if 0.077213532551980266 FTOKEN = 1.29593568599362315 WBNB
// 0.000099999999999994 FTOKEN will be (0.000099999999999994 * 0.9975 * 1.29593568599362315) / (0.077213532551980266 + 0.000099999999999994 * 0.9975) = 0.001672022974719046 WBNB
// --------
// Hence, buyback amount should be 0.001427759109023196 + 0.001672022974719046 = 0.003099782083742242 WBNB
// --------
// amountOut of 0.1 will be
// if 1.294263663018907628 WBNB = 0.077313532551980049 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.077313532551980049) / (1.294263663018907628 + 0.1 * 0.9975) = 0.005532244824171001 FTOKEN
// Alice's share will be (0.005532244824171001 / 0.419086467447585074) * 0.118020877720068886 = 0.001557961042950235
// total farming token amount will be 0.419086467447799501 + 0.005532244824171001 = 0.424618712271970502
const alicePos3Share = ethers.utils.parseEther("0.001557961042950235");
await integratedVaultAsBob.work(
0,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
alicePos1Balance = alicePos1Share.mul(userInfo[0]).div(await integratedCakeMaxiWorker.totalShare());
bobPos2Balance = bobPos2Share.mul(userInfo[0]).div(await integratedCakeMaxiWorker.totalShare());
let alicePos3Balance = alicePos3Share.mul(userInfo[0]).div(await integratedCakeMaxiWorker.totalShare());
Assert.assertAlmostEqual(userInfo[0].toString(), ethers.utils.parseEther("0.424618712271970502").toString());
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(alicePos1Share);
expect(await integratedCakeMaxiWorker.shares(2)).to.eq(bobPos2Share);
expect(await integratedCakeMaxiWorker.shares(3)).to.eq(alicePos3Share);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
alicePos1Balance
);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(2))).to.eq(
bobPos2Balance
);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(3))).to.eq(
alicePos3Balance
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils
.parseEther("0.001431176510697250")
.add(ethers.utils.parseEther("0.001205378386656404"))
.toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0.003099782083742242").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
});
context("when the worker is an older version", async () => {
context("with upgrade during the flow", async () => {
it("should reinvest with updated beneficial vault reward to the beneficial vault", async () => {
await integratedCakeMaxiWorker01.setBeneficialVaultBountyBps(BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS));
expect(await integratedCakeMaxiWorker01.beneficialVaultBountyBps()).to.eq(
BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS)
);
// alice deposit some portion of her native bnb into a vault, thus interest will be accrued afterward
await integratedVaultAsAlice.deposit(ethers.utils.parseEther("1"), {
value: ethers.utils.parseEther("1"),
});
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB (0.05 as principal amount, 0.05 as a loan)
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await integratedVaultAsAlice.work(
0,
integratedCakeMaxiWorker01.address,
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("0.05"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.05"),
}
);
let userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker01.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker01.shares(1)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker01.shareToBalance(await integratedCakeMaxiWorker01.shares(1))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Upgrade from CakeMaxiWorker to CakeMaxiWorker02 for optimized reinvest
const CakeMaxiWorker02 = (await ethers.getContractFactory(
"CakeMaxiWorker02",
deployer
)) as CakeMaxiWorker02__factory;
const integratedCakeMaxiWorker02 = (await upgrades.upgradeProxy(
integratedCakeMaxiWorker01.address,
CakeMaxiWorker02
)) as CakeMaxiWorker02;
await integratedCakeMaxiWorker02.deployed();
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker02.shares(1)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker02.shareToBalance(await integratedCakeMaxiWorker02.shares(1))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()`, the `reinvest()` won't be triggered yet due to tresaury hasn't been set.
// since it is 2 blocks away from previous `work()`, so there will be rewards out.
// 0.1 CAKE/block = 0.1 * 2 = 0.199999999999998096 CAKE.
// This rewards won't be reinvested. Hence, it should stay in `worker.rewardBalance()`.
// amountOut of 0.1 from alice will be
// if 1.1 WBNB = 0.090929756762900660 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.090929756762900660) /(1.1 + 0.1 * 0.9975)
// = 0.007560111054052378 FTOKEN
// thus, the current amount accumulated with the previous one will be 0.007560111054052378 + 0.00907024323709934 = 0.016630354291151718 CAKE
await integratedVaultAsAlice.work(
1,
integratedCakeMaxiWorker02.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker02.address);
// after all these steps above, alice will have a balance in total of 0.016630354291151718
expect(userInfo[0], "expect worker has 0.016630354291151718 CAKE staked in MasterChef").to.eq(
ethers.utils.parseEther("0.016630354291151718")
);
expect(await integratedCakeMaxiWorker02.shares(1), "expect Alice's shares = 0.016630354291151718").to.eq(
ethers.utils.parseEther("0.016630354291151718")
);
expect(await cake.balanceOf(DEPLOYER), "expect DEPLOYER's CAKE remains 0 as no reinvest happened").to.be.eq(
0
);
expect(
await integratedCakeMaxiWorker02.rewardBalance(),
"expect worker.rewardBalance is 0.199999999999998096"
).to.be.eq(ethers.utils.parseEther("0.199999999999998096"));
expect(
await integratedCakeMaxiWorker02.shareToBalance(await integratedCakeMaxiWorker02.shares(1)),
"expect Alice's position#1 balance is 0.016630354291151718 CAKE"
).to.eq(ethers.utils.parseEther("0.016630354291151718"));
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils.parseEther("0").toString()
);
expect(
await integratedCakeMaxiWorker02.buybackAmount(),
"expect buybackAmount is 0 as no reinvest happened"
).to.be.eq(0);
// Eve calls `reinvest()`
// since it's 1 block away from the last `work()`, there will be 0.099999999999985732 pending CAKE
// there are also rewards inside `worker.rewardBalance()` = 0.199999999999998096 CAKE
// hence worker.rewardBalance() + pendingCake = 0.299999999999983828 CAKE
// total fee will be 0.299999999999983828 * 1% = 0.002999999999999838 CAKE
// thus, reward staked in the masterchef will be
// **** 0.299999999999983828 - 0.002999999999999838 (as fees) + 0.016630354291151718 = 0.313630354291135708 CAKE ******
// **** 10% of 0.002999999999999838 = 0.000299999999999983 will be distributed to the beneficial vault.
// **** 90% of 0.002999999999999838 = 0.002699999999999855 CAKE
// **** thus, Eve we get a bounty of 0.002699999999999855 CAKE
// if (0.090929756762900660 - 0.007560111054052378) CAKE = 1.2 WBNB
// 0.083369645708848282 CAKE = 1.2 WBNB
// 0.000299999999999983 will be
// (0.000299999999999983 * 0.9975 * 1.2) / (0.083369645708848282 + 0.000299999999999983 * 0.9975) = 0.004291917527507221 WBNB
await integratedCakeMaxiWorker01AsEve.reinvest();
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker02.address);
expect(userInfo[0], "expect worker staked 0.313630354291135708 CAKE").to.be.eq(
ethers.utils.parseEther("0.313630354291135708")
);
expect(await cake.balanceOf(await eve.getAddress()), "expect Eve's CAKE is 0.002699999999999855").to.be.eq(
ethers.utils.parseEther("0.002699999999999855")
);
expect(
(await wbnb.balanceOf(integratedVault.address)).sub(
ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05"))
),
"expect WBNB balance in Beneficial Vault increase by 0.004291917527507221"
).to.be.eq(ethers.utils.parseEther("0.004291917527507221"));
expect(await integratedCakeMaxiWorker02.buybackAmount(), "expect worker.buybackAmount is 0").to.be.eq("0");
// Setting tresaury config
await integratedCakeMaxiWorker02.setTreasuryConfig(DEPLOYER, REINVEST_BOUNTY_BPS);
// Bob start opening his position using 0.1 wbnb
// once bob call function `work()` the `reinvest()` will be triggered
// since it's 2 blocks away from the last `work()`, the reward will be 0.199999999999743405 CAKE
// total fee will be 0.199999999999743405 * 1% = 0.001999999999997434 CAKE
// thus, reward staked in the masterchef will be
// 0.199999999999743405 - 0.001999999999997434 + 0.313630354291135708 = 0.511630354290881679
// **** 10% of 0.001999999999997434 = 0.000199999999999743 will be distributed to the beneficial vault.
// **** 90% of 0.001999999999997434 = 0.001799999999997691 CAKE
// **** thus, DEPLOYER we get a bounty of 0.001799999999997691 CAKE
// === Swap CAKE->WBNB to increase amount of WBNB in Beneficial Vault
// if 0.083669645708848265 CAKE = 1.195708082472492779 WBNB
// 0.000199999999999743 CAKE will be
// (0.000199999999999743 * 0.9975 * 1.195708082472492779) / (0.083669645708848265 + 0.000199999999999743 * 0.9975) = 0.002844237418144941 WBNB
// amountOut of 0.1 will be
// if 1.192863845054347838 WBNB = 0.083869645708848008 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.083869645708848008) / (1.192863845054347838 + 0.1 * 0.9975) = 0.006472154999319105
// bob's share will be (0.006472154999319105 / 0.511630354290881679) * 0.016630354291151718 = 0.000210374989996647
// total farming token amount will be 0.511630354290881679 + 0.006472154999319105 = 0.518102509290200784
const bobShare = ethers.utils.parseEther("0.000210374989996647");
const aliceShare = ethers.utils.parseEther("0.016630354291151718");
await integratedVaultAsBob.work(
0,
integratedCakeMaxiWorker02.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker02.address);
const bobBalance = bobShare.mul(userInfo[0]).div(await integratedCakeMaxiWorker02.totalShare());
const aliceBalance = aliceShare.mul(userInfo[0]).div(await integratedCakeMaxiWorker02.totalShare());
expect(userInfo[0], "expect worker staked 0.518102509290200784 CAKE").to.eq(
ethers.utils.parseEther("0.518102509290200784")
);
expect(await integratedCakeMaxiWorker02.shares(2), "expect Bob's share is correct").to.eq(bobShare);
expect(
await integratedCakeMaxiWorker02.shareToBalance(await integratedCakeMaxiWorker02.shares(2)),
"expect Bob's balance is correct"
).to.eq(bobBalance);
expect(
await integratedCakeMaxiWorker02.shareToBalance(await integratedCakeMaxiWorker02.shares(1)),
"expect Alice's balance is correct"
).to.eq(aliceBalance);
expect(await cake.balanceOf(DEPLOYER), "expect DEPLOYER's CAKE is 0.001799999999997691 CAKE").to.be.eq(
ethers.utils.parseEther("0.001799999999997691")
);
expect(
(await wbnb.balanceOf(integratedVault.address)).sub(
ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05"))
),
"expect WBNB balance in Beneficial Vault remain 0.004291917527507221 WBNB"
).to.be.eq(ethers.utils.parseEther("0.004291917527507221"));
expect(
await integratedCakeMaxiWorker02.buybackAmount(),
"expect buyback amount is 0.002844237418144941"
).to.be.eq(ethers.utils.parseEther("0.002844237418144941"));
expect(await integratedCakeMaxiWorker02.rewardBalance(), "expect reward balance is 0").to.be.eq("0");
});
});
});
});
});
describe("#health()", async () => {
context("When the worker is not a native", async () => {
it("should convert CAKE(FarmingToken) back to Base Token with a correct amount out", async () => {
// Pretend that this transfer statement is from the vault
await baseTokenAsAlice.transfer(cakeMaxiWorkerNonNative.address, ethers.utils.parseEther("0.1"));
// Alice uses AddBaseTokenOnly strategy to add 0.1 BASE
// amountOut of 0.1 will be
// if 1 BASE = 1 BNB
// 0.1 BASE will be (0.1 * 0.9975 * 1) / (1 + 0.1 * 0.9975) = 0.09070243237099342 BNB
// if 1 BNB = 0.1 FTOKEN
// 0.09070243237099342 BNB = (0.09070243237099342 * 0.9975) * (0.1 / (1 + 0.09070243237099342 * 0.9975)) = 0.008296899991192416 FTOKEN
await cakeMaxiWorkerNonNativeAsAlice.work(
0,
await alice.getAddress(),
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNonNativeAsAlice.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.008296899991192416"));
expect(await cakeMaxiWorkerNonNativeAsAlice.shares(0)).to.eq(ethers.utils.parseEther("0.008296899991192416"));
// if 0.091703100008807584 FTOKEN = 1.090702432370993407 BNB
// 0.008296899991192416 FTOKEN = (0.008296899991192416 * 0.9975) * (1.090702432370993407 / (0.091703100008807584 + 0.008296899991192416 * 0.9975)) = 0.09028698134165357 BNB
// if 0.909297567629006593 BNB = 1.1 BaseToken
// 0.09028698134165357 BNB = (0.09028698134165357 * 0.9975) * (1.1 / (0.909297567629006593 + 0.09028698134165357 * 0.9975)) = 0.09913094991787623
// thus, calling health should return 0.099130949917876232
let health = await cakeMaxiWorkerNonNativeAsAlice.health(0);
expect(health).to.eq(ethers.utils.parseEther("0.099130949917876232"));
});
});
context("When the worker is native", async () => {
it("should convert CAKE(FarmingToken) back to Base Token with a correct amount out", async () => {
// Alice transfer 0.1 WBNB to StrategyAddBaseTokenOnly first
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.00907024323709934
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
// if 0.1 - 0.00907024323709934 FTOKEN = 1.1 BNB
// if 0.09092975676290066 FTOKEN = 1.1 BNB
// 0.00907024323709934 FTOKEN = (0.00907024323709934 * 0.9975) * (1.1 / (0.09092975676290066 + 0.00907024323709934 * 0.9975)) = 0.0995458165383035 BNB
// thus, calling health should return 0.099545816538303460
let health = await cakeMaxiWorkerNative.health(0);
expect(health).to.eq(ethers.utils.parseEther("0.099545816538303460"));
});
});
});
describe("#liquidate()", async () => {
it("should liquidate a position based on the share of a user", async () => {
// sending 0.1 wbnb to the worker (let's pretend to be the value from the vault)
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await wbnbTokenAsAlice.transfer(cakeMaxiWorkerNative.address, ethers.utils.parseEther("0.1"));
const aliceBaseTokenBefore = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenBefore = await cake.balanceOf(await alice.getAddress());
await cakeMaxiWorkerNativeAsAlice.work(
0,
await alice.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
)
);
let userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0").toString()
);
// Alice call liquidate strategy to close her position
await cakeMaxiWorkerNativeAsAlice.liquidate(0);
// alice will get a base token based on 0.00907024323709934 farming token (staked balance)
// if 0.1 - 0.00907024323709934 FTOKEN = 1.1 BNB
// if 0.09092975676290066 FTOKEN = 1.1 BNB
// 0.00907024323709934 FTOKEN = (0.00907024323709934 * 0.9975) * (1.1 / (0.09092975676290066 + 0.00907024323709934 * 0.9975)) = 0.0995458165383035 BNB
// thus, alice should get a baseToken amount of 0.099545816538303460
userInfo = await masterChef.userInfo(0, cakeMaxiWorkerNative.address);
const aliceBaseTokenAfter = await wbnb.balanceOf(await alice.getAddress());
const aliceFarmingTokenAfter = await cake.balanceOf(await alice.getAddress());
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0"));
expect(await cakeMaxiWorkerNative.shares(0)).to.eq(ethers.utils.parseEther("0"));
Assert.assertAlmostEqual(
(await cakeMaxiWorkerNative.rewardBalance()).toString(),
ethers.utils.parseEther("0.1").toString()
);
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.eq(ethers.utils.parseEther("0.099545816538303460"));
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.eq(ethers.utils.parseEther("0"));
});
context("When integrated with an actual vault", async () => {
context("when there is buybackAmount left when killing a position", async () => {
it("should successfully liquidate a certain position without any returning a buybackAmount", async () => {
await integratedCakeMaxiWorker.setBeneficialVaultBountyBps(BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS));
expect(await integratedCakeMaxiWorker.beneficialVaultBountyBps()).to.eq(
BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS)
);
// alice deposit some portion of her native bnb into a vault, thus interest will be accrued afterward
await integratedVaultAsAlice.deposit(ethers.utils.parseEther("1"), {
value: ethers.utils.parseEther("1"),
});
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB (0.05 as principal amount, 0.05 as a loan)
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await integratedVaultAsAlice.work(
0,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("0.05"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.05"),
}
);
let userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// total bounty will be 0.1 * 1% = 0.001
// 90% if reinvest bounty 0.001 * 90 / 100 = 0.0009
// thus, alice we get a bounty of 0.0018
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be wbnb)
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.009070243237099340 = 0.108070243237093908
// if (0.1 - 0.00907024323709934 ) FToken = 1.1 WBNB
// 0.090929756762900660 FToken = 1.1 WBNB
// 0.0001 will be (0.0001 * 0.9975 * 1.1) / (0.090929756762900660 + 0.0001 * 0.9975) = 0.001205378386656404 WBNB
// amountOut of 0.1 from alice will be
// if (1.1 - 0.001205378386656404) WBNB = (0.090929756762900660 - 0.0001) FToken
// if 1.098794621613343596 WBNB = 0.091029756762900654 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.091029756762900654) /(1.098794621613343596 + 0.1 * 0.9975)
// = 0.007576036864507046
// thus, the current amount accumulated with the previous one will be 0.007576036864507046 + 0.108070243237093908 = 0.115646280101600954 CAKE
await integratedVaultAsAlice.work(
1,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
// after all these steps above, alice will have a balance in total of 0.115646280101600954
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.115646280101600954"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(ethers.utils.parseEther("0.115646280101600954"));
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0009").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
ethers.utils.parseEther("0.115646280101600954")
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils.parseEther("0").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0.001205378386656404").toString()
);
// Now it's a liquidation part
await cakeAsAlice.approve(routerV2.address, constants.MaxUint256);
// alice buy wbnb so that the price will be fluctuated, so that the position can be liquidated
// swap tokens for exact 0.935 WBNB.
await routerV2AsAlice.swapTokensForExactETH(
ethers.utils.parseEther("0.935"),
constants.MaxUint256,
[cake.address, wbnb.address],
await alice.getAddress(),
FOREVER
);
// set interest rate to be 0 to be easy for testing.
await simpleVaultConfig.setParams(
MIN_DEBT_SIZE,
0,
RESERVE_POOL_BPS,
KILL_PRIZE_BPS,
wbnb.address,
wNativeRelayer.address,
fairLaunch.address,
KILL_TREASURY_BPS,
await deployer.getAddress()
);
// pre calculated left, liquidation reward, health
const toBeLiquidatedValue = await integratedCakeMaxiWorker.health(1);
const liquidationBounty = toBeLiquidatedValue.mul(1000).div(10000);
const treasuryKillFees = toBeLiquidatedValue.mul(100).div(10000);
const totalLiquidationFees = liquidationBounty.add(treasuryKillFees);
const bobBalanceBefore = await ethers.provider.getBalance(await bob.getAddress());
const aliceBalanceBefore = await ethers.provider.getBalance(await alice.getAddress());
const deployerBalanceBefore = await ethers.provider.getBalance(await deployer.getAddress());
const vaultBalanceBefore = await wbnb.balanceOf(integratedVault.address);
const debt = await integratedVault.debtShareToVal((await integratedVault.positions(1)).debtShare);
const left = debt.gte(toBeLiquidatedValue.sub(totalLiquidationFees))
? ethers.constants.Zero
: toBeLiquidatedValue.sub(totalLiquidationFees).sub(debt);
const repaid = debt.gte(toBeLiquidatedValue.sub(totalLiquidationFees))
? toBeLiquidatedValue.sub(totalLiquidationFees)
: debt;
// bob call `kill` alice's position, which is position #1
await integratedVaultAsBob.kill(1, {
gasPrice: 0,
});
const bobBalanceAfter = await ethers.provider.getBalance(await bob.getAddress());
const aliceBalanceAfter = await ethers.provider.getBalance(await alice.getAddress());
const vaultBalanceAfter = await wbnb.balanceOf(integratedVault.address);
const deployerBalanceAfter = await ethers.provider.getBalance(await deployer.getAddress());
expect(bobBalanceAfter.sub(bobBalanceBefore), "expect Bob to get a correct liquidation bounty").to.eq(
liquidationBounty
);
expect(aliceBalanceAfter.sub(aliceBalanceBefore), "expect Alice to get a correct left amount").to.eq(left);
expect(vaultBalanceAfter.sub(vaultBalanceBefore), "expect Vault should get its funds back").to.eq(repaid);
expect(deployerBalanceAfter.sub(deployerBalanceBefore), "expect Deployer should get tresaury fees").to.eq(
treasuryKillFees
);
expect((await integratedVaultAsAlice.positions(1)).debtShare).to.eq(0);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0.001205378386656404").toString()
);
});
});
context("when there is no buybackAmount left when killing a position", async () => {
it("should successfully liquidate a certain position after all transactions", async () => {
await integratedCakeMaxiWorker.setBeneficialVaultBountyBps(BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS));
expect(await integratedCakeMaxiWorker.beneficialVaultBountyBps()).to.eq(
BigNumber.from(BENEFICIALVAULT_BOUNTY_BPS)
);
// alice deposit some portion of her native bnb into a vault, thus interest will be accrued afterward
await integratedVaultAsAlice.deposit(ethers.utils.parseEther("1"), {
value: ethers.utils.parseEther("1"),
});
// Alice uses AddBaseTokenOnly strategy to add 0.1 WBNB (0.05 as principal amount, 0.05 as a loan)
// amountOut of 0.1 will be
// if 1WBNB = 0.1 FToken
// 0.1WBNB will be (0.1 * 0.9975 * 0.1) / (1 + 0.1 * 0.9975) = 0.009070243237099340
await integratedVaultAsAlice.work(
0,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("0.05"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.05"),
}
);
let userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(ethers.utils.parseEther("0.00907024323709934"));
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
ethers.utils.parseEther("0.00907024323709934")
);
// Alice uses AddBaseTokenOnly strategy to add another 0.1 WBNB
// once alice call function `work()` the `reinvest()` will be triggered
// since it's 1 blocks away from the last `work()`, the reward will be 0.1 CAKE
// total bounty will be 0.1 * 1% = 0.001
// 90% if reinvest bounty 0.001 * 90 / 100 = 0.0009
// thus, alice we get a bounty of 0.0018
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be wbnb)
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.009070243237099340 = 0.108070243237093908
// if (0.1 - 0.00907024323709934 ) FToken = 1.1 WBNB
// 0.090929756762900660 FToken = 1.1 WBNB
// 0.0001 will be (0.0001 * 0.9975 * 1.1) / (0.090929756762900660 + 0.0001 * 0.9975) = 0.001205378386656404 WBNB
// amountOut of 0.1 from alice will be
// if (1.1 - 0.001205378386656404) WBNB = (0.090929756762900660 - 0.0001) FToken
// if 1.098794621613343596 WBNB = 0.091029756762900654 FToken
// 0.1 WBNB will be (0.1 * 0.9975 * 0.091029756762900654) /(1.098794621613343596 + 0.1 * 0.9975)
// = 0.007576036864507046
// thus, the current amount accumulated with the previous one will be 0.007576036864507046 + 0.108070243237093908 = 0.115646280101600954 CAKE
await integratedVaultAsAlice.work(
1,
integratedCakeMaxiWorker.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0"),
"0", // max return = 0, don't return BTOKEN to the debt
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[stratAdd.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0")])]
),
{
value: ethers.utils.parseEther("0.1"),
}
);
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
// after all these steps above, alice will have a balance in total of 0.115646280101600954
expect(userInfo[0]).to.eq(ethers.utils.parseEther("0.115646280101600954"));
expect(await integratedCakeMaxiWorker.shares(1)).to.eq(ethers.utils.parseEther("0.115646280101600954"));
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0009").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.rewardBalance()).toString(),
ethers.utils.parseEther("0").toString()
);
expect(await integratedCakeMaxiWorker.shareToBalance(await integratedCakeMaxiWorker.shares(1))).to.eq(
ethers.utils.parseEther("0.115646280101600954")
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils.parseEther("0").toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0.001205378386656404").toString()
);
// since it's 1 blocks away from the last `work()`, the reward will be 0.2 CAKE
// thus, reward staked in the masterchef will be 0.1 - 0.001 (as a reward) + 0.115646280101600954 = 0.214646280101518468
// total bounty will be 0.1 * 1% = 0.001
// 90% if reinvest bounty 0.001 * 90 / 100 = 0.0009
// thus, alice we get a bounty of 0.0027
// 10% of 0.001 (0.0001) will be distributed to the vault by swapping 0.001 of reward token into a beneficial vault token (this is scenario, it will be wbnb)
// accumulated reward for alice will be 0.1 - 0.001 + 0.115646280101600954 = 0.21464628010160097 FTOKEN
// if (0.091029756762900654 - 0.007576036864507046) FToken = 1.198794621613343596 WBNB
// 0.083453719898393608 FToken = 1.198794621613343596 WBNB
// 0.0001 will be (0.0001 * 0.9975 * 1.198794621613343596) / (0.083453719898393608 + 0.0001 * 0.9975) = 0.001431176510697250 WBNB
userInfo = await masterChef.userInfo(0, integratedCakeMaxiWorker.address);
const beforeVaultTotalToken = await integratedVault.totalToken();
await integratedCakeMaxiWorkerAsEve.reinvest();
const afterVaultTotalToken = await integratedVault.totalToken();
Assert.assertAlmostEqual(
(await cake.balanceOf(await eve.getAddress())).toString(),
ethers.utils.parseEther("0.0018").toString()
);
Assert.assertAlmostEqual(
(await wbnb.balanceOf(integratedVault.address))
.sub(ethers.utils.parseEther("1").sub(ethers.utils.parseEther("0.05")))
.toString(),
ethers.utils
.parseEther("0.001431176510697250")
.add(ethers.utils.parseEther("0.001205378386656404"))
.toString()
);
Assert.assertAlmostEqual(
(await integratedCakeMaxiWorker.buybackAmount()).toString(),
ethers.utils.parseEther("0").toString()
);
// Now it's a liquidation part
await cakeAsAlice.approve(routerV2.address, constants.MaxUint256);
// alice buy wbnb so that the price will be fluctuated, so that the position can be liquidated
// swap tokens for exact 0.935 WBNB.
await routerV2AsAlice.swapTokensForExactETH(
ethers.utils.parseEther("1"),
constants.MaxUint256,
[cake.address, wbnb.address],
await alice.getAddress(),
FOREVER
);
// set interest rate to be 0 to be easy for testing.
await simpleVaultConfig.setParams(
MIN_DEBT_SIZE,
0,
RESERVE_POOL_BPS,
KILL_PRIZE_BPS,
wbnb.address,
wNativeRelayer.address,
fairLaunch.address,
KILL_TREASURY_BPS,
await deployer.getAddress()
);
// pre calculated left, liquidation reward, health
const toBeLiquidatedValue = await integratedCakeMaxiWorker.health(1);
const liquidationBounty = toBeLiquidatedValue.mul(KILL_PRIZE_BPS).div(10000);
const treasuryKillFees = toBeLiquidatedValue.mul(KILL_TREASURY_BPS).div(10000);
const totalLiquidationFees = liquidationBounty.add(treasuryKillFees);
const bobBalanceBefore = await ethers.provider.getBalance(await bob.getAddress());
const aliceBalanceBefore = await ethers.provider.getBalance(await alice.getAddress());
const vaultBalanceBefore = await wbnb.balanceOf(integratedVault.address);
const deployerBalanceBefore = await ethers.provider.getBalance(await deployer.getAddress());
const vaultDebtVal = await integratedVault.vaultDebtVal();
const debt = await integratedVault.debtShareToVal((await integratedVault.positions(1)).debtShare);
const left = debt.gte(toBeLiquidatedValue.sub(totalLiquidationFees))
? ethers.constants.Zero
: toBeLiquidatedValue.sub(totalLiquidationFees).sub(debt);
// bob call `kill` alice's position, which is position #1
await integratedVaultAsBob.kill(1, {
gasPrice: 0,
});
const bobBalanceAfter = await ethers.provider.getBalance(await bob.getAddress());
const aliceBalanceAfter = await ethers.provider.getBalance(await alice.getAddress());
const vaultBalanceAfter = await wbnb.balanceOf(integratedVault.address);
const deployerBalanceAfter = await ethers.provider.getBalance(await deployer.getAddress());
expect(deployerBalanceAfter.sub(deployerBalanceBefore)).to.be.eq(treasuryKillFees);
expect(bobBalanceAfter.sub(bobBalanceBefore)).to.eq(liquidationBounty); // bob should get liquidation reward
expect(aliceBalanceAfter.sub(aliceBalanceBefore)).to.eq(left); // alice should get her left back
expect(vaultBalanceAfter.sub(vaultBalanceBefore)).to.eq(vaultDebtVal); // vault should get it's deposit value back
expect((await integratedVaultAsAlice.positions(1)).debtShare).to.eq(0);
});
});
});
});
describe("#setBeneficialVaultBountyBps", async () => {
context("When the caller is not an owner", async () => {
it("should be reverted", async () => {
await expect(cakeMaxiWorkerNonNativeAsAlice.setBeneficialVaultBountyBps(BigNumber.from("1000"))).to.reverted;
});
});
context("When the _beneficialVaultBountyBps > 10000 (100%)", async () => {
it("should be reverted", async () => {
await expect(cakeMaxiWorkerNonNative.setBeneficialVaultBountyBps(BigNumber.from("10001"))).to.revertedWith(
"CakeMaxiWorker02::setBeneficialVaultBountyBps:: _beneficialVaultBountyBps exceeds 100%"
);
});
});
context("when the param is correct", async () => {
it("should successfully set the beneficial vault bounty bps", async () => {
expect(await cakeMaxiWorkerNonNative.beneficialVaultBountyBps()).to.eq(BigNumber.from("0"));
await expect(cakeMaxiWorkerNonNative.setBeneficialVaultBountyBps(BigNumber.from("10000"))).not.to.revertedWith(
"CakeMaxiWorker02::setBeneficialVaultBountyBps:: _beneficialVaultBountyBps exceeds 100%"
);
expect(await cakeMaxiWorkerNonNative.beneficialVaultBountyBps()).to.eq(BigNumber.from("10000"));
await expect(cakeMaxiWorkerNonNative.setBeneficialVaultBountyBps(BigNumber.from("5000"))).not.to.revertedWith(
"CakeMaxiWorker02::setBeneficialVaultBountyBps:: _beneficialVaultBountyBps exceeds 100%"
);
expect(await cakeMaxiWorkerNonNative.beneficialVaultBountyBps()).to.eq(BigNumber.from("5000"));
});
});
});
}); | the_stack |
import react = require('react');
import style = require('ts-style');
import agile_keychain = require('../lib/agile_keychain');
import auth = require('./auth');
import assign = require('../lib/base/assign');
import button = require('./controls/button');
import colors = require('./controls/colors');
import { div } from './base/dom_factory';
import dropbox_vfs = require('../lib/vfs/dropbox');
import fonts = require('./controls/fonts');
import http_vfs = require('../lib/vfs/http');
import reactutil = require('./base/reactutil');
import ripple = require('./controls/ripple');
import settings = require('./settings');
import status_message = require('./status');
import stringutil = require('../lib/base/stringutil');
import style_util = require('./base/style_util');
import text_field = require('./controls/text_field');
import toaster = require('./controls/toaster');
import vfs = require('../lib/vfs/vfs');
var mixins = style.create({
setupScreen: {
marginTop: 10,
marginBottom: 10,
backgroundColor: 'white',
borderRadius: 3,
color: colors.MATERIAL_TEXT_PRIMARY,
minHeight: 40,
padding: {
padding: 15,
paddingTop: 10,
paddingBottom: 10,
},
},
hCenter: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
});
var theme = style.create({
setupView: {
width: '100%',
height: '100%',
backgroundColor: colors.MATERIAL_COLOR_PRIMARY,
color: 'white',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
inner: {
position: 'relative',
width: 'calc(100% + 2px)',
height: 'calc(100% + 2px)',
maxWidth: 400,
maxHeight: 600,
border: '1px solid white',
overflow: 'hidden',
},
},
storeList: {
mixins: [mixins.setupScreen],
item: {
padding: 15,
paddingTop: 10,
paddingBottom: 10,
boxSizing: 'border-box',
minHeight: 40,
cursor: 'pointer',
position: 'relative',
overflow: 'hidden',
userSelect: 'none',
path: {
fontSize: fonts.itemPrimary.size,
color: colors.MATERIAL_TEXT_PRIMARY,
},
store: {
fontSize: fonts.itemSecondary.size,
color: colors.MATERIAL_TEXT_SECONDARY,
},
addStore: {
fontSize: fonts.itemPrimary.size,
textTransform: 'uppercase',
color: colors.MATERIAL_COLOR_PRIMARY,
},
},
},
cloudStoreList: {
mixins: [mixins.setupScreen],
item: {
padding: 15,
paddingTop: 10,
paddingBottom: 10,
cursor: 'pointer',
position: 'relative',
overflow: 'hidden',
userSelect: 'none',
},
},
newStore: {
mixins: [mixins.setupScreen, mixins.setupScreen.padding],
},
creatingStore: {
mixins: [mixins.setupScreen],
label: {
color: colors.MATERIAL_TEXT_PRIMARY,
fontSize: fonts.subhead.size,
},
},
screen: {
transition: style_util.transitionOn({
transform: 0.3,
opacity: 0.3,
}),
position: 'absolute',
left: 10,
top: 10,
width: 'calc(100% - 20px)',
height: 'calc(100% - 20px)',
color: 'white',
transform: 'translateX(0px)',
},
screenButtons: {
display: 'flex',
flexDirection: 'row',
spacer: {
flexGrow: 1,
},
},
header: {
fontSize: fonts.title.size,
fontWeight: fonts.title.weight,
marginTop: 10,
marginBottom: 15,
textAlign: 'center',
},
});
interface NavButtonProps extends react.Props<void> {
label: string;
onClick: () => void;
iconUrl?: string;
disabled?: boolean;
}
/** Button displayed at the bottom of the setup view
* to go to the previous/next steps.
*/
class NavButton extends react.Component<NavButtonProps, {}> {
render() {
return button.ButtonF({
style: button.Style.RaisedRectangular,
backgroundColor: 'white',
value: this.props.label,
iconUrl: this.props.iconUrl,
onClick: this.props.onClick,
disabled: this.props.disabled,
});
}
}
var NavButtonF = react.createFactory(NavButton);
interface CloudStoreListProps extends react.Props<void> {
vfs: vfs.VFS;
onSelectStore: (path: string) => void;
}
interface Store {
path: string;
}
interface CloudStoreListState {
stores?: Store[];
error?: Error;
}
/** Displays a list of available password stores in a cloud file system */
class CloudStoreList extends react.Component<
CloudStoreListProps,
CloudStoreListState
> {
constructor(props: CloudStoreListProps) {
super(props);
this.state = {};
}
private startSearch() {
this.props.vfs.search('.agilekeychain', (error, files) => {
if (error) {
this.setState({ error: error });
return;
}
var stores = this.state.stores || <Store[]>[];
stores = stores.concat(
files.map(file => {
return { path: file.path };
})
);
stores.sort((a, b) => {
return a.path.localeCompare(b.path);
});
this.setState({
stores: stores,
});
});
}
componentDidMount() {
this.startSearch();
}
render() {
if (!this.state.stores) {
if (this.state.error) {
return div(
style.mixin(theme.cloudStoreList),
`Unable to search for existing stores: ${
this.state.error.message
}`,
div(
style.mixin(theme.screenButtons),
button.ButtonF({
style: button.Style.Rectangular,
color: colors.MATERIAL_COLOR_PRIMARY,
value: 'Try Again',
onClick: () => {
this.setState({ error: null });
this.startSearch();
},
})
)
);
} else {
return div(
style.mixin(theme.cloudStoreList),
div(
style.mixin(theme.cloudStoreList.item),
'Searching for existing stores...'
)
);
}
} else {
return div(
style.mixin(theme.cloudStoreList),
this.state.stores.map(store => {
var displayPath = store.path;
if (stringutil.startsWith(displayPath, '/')) {
displayPath = displayPath.slice(1);
}
return div(
style.mixin(theme.cloudStoreList.item, {
key: store.path,
onClick: () => {
this.props.onSelectStore(store.path);
},
}),
ripple.InkRippleF({}),
displayPath
);
})
);
}
}
}
var CloudStoreListF = react.createFactory(CloudStoreList);
interface StoreListProps extends react.Props<void> {
stores: settings.AccountMap;
onSelectStore: (account: settings.Account) => void;
onAddStore: () => void;
}
/** Displays a list of password stores which have been synced to the
* current app.
*/
class StoreList extends react.Component<StoreListProps, {}> {
render() {
var stores: react.ReactElement<any>[] = [];
Object.keys(this.props.stores).forEach(id => {
var account = this.props.stores[id];
var suffixPos = account.storePath.lastIndexOf('.');
// trim leading '/' and directory/file extension
var dirStartPos = 0;
if (stringutil.startsWith(account.storePath, '/')) {
dirStartPos = 1;
}
var displayPath = account.storePath.slice(dirStartPos, suffixPos);
var cloudService = settings.CloudService[account.cloudService];
stores.push(
div(
style.mixin(theme.storeList.item, {
key: `${cloudService}.${account.id}.${displayPath}`,
onClick: () => this.props.onSelectStore(account),
}),
div(style.mixin(theme.storeList.item.path), displayPath),
div(
style.mixin(theme.storeList.item.store),
`in ${account.name}'s ${cloudService}`
),
ripple.InkRippleF({})
)
);
});
stores.push(
div(
style.mixin(theme.storeList.item, {
onClick: () => this.props.onAddStore(),
key: 'add-store',
}),
div(style.mixin(theme.storeList.item.addStore), 'Add Store'),
ripple.InkRippleF({})
)
);
return div(style.mixin(theme.storeList), stores);
}
}
var StoreListF = react.createFactory(StoreList);
export interface SetupViewProps extends react.Props<void> {
settings: settings.Store;
}
// active screen in the setup / onboarding dialog
enum Screen {
Welcome,
StoreList,
NewStore,
CloudStoreLogin,
CloudStoreSignout,
CloudStoreList,
CloudServiceList,
}
interface NewStoreOptions {
path?: string;
password?: string;
confirmPassword?: string;
hint?: string;
}
interface SlideProps extends react.Props<void> {
xTranslation: number;
opacity: number;
}
class Slide extends react.Component<SlideProps, {}> {
render() {
var screenStyles: any[] = [
theme.screen,
{
transform: `translateX(${this.props.xTranslation * 100}%)`,
opacity: this.props.opacity,
},
];
return div(style.mixin(screenStyles), this.props.children);
}
}
var SlideF = react.createFactory(Slide);
interface NewStoreFormProps extends react.Props<void> {
onGoBack: () => void;
onCreate: (options: NewStoreOptions) => Promise<void>;
storeName: string;
}
interface NewStoreFormState {
options?: NewStoreOptions;
creatingStore?: boolean;
}
class NewStoreForm extends react.Component<
NewStoreFormProps,
NewStoreFormState
> {
constructor(props: NewStoreFormProps) {
super(props);
this.state = {
options: {
path: 'Passcards/Passcards.agilekeychain',
password: '',
confirmPassword: '',
hint: '',
},
creatingStore: false,
};
}
private renderForm() {
var confirmPasswordError = '';
if (
this.state.options.confirmPassword.length > 0 &&
this.state.options.password !== this.state.options.confirmPassword
) {
confirmPasswordError = 'Passwords do not match';
}
return div(
style.mixin(theme.newStore),
text_field.TextFieldF({
type: 'text',
defaultValue: this.state.options.path,
floatingLabel: true,
placeHolder: `Location in ${this.props.storeName}`,
onChange: e => {
this.setState({
options: assign(this.state.options, {
path: (<HTMLInputElement>e.target).value,
}),
});
},
}),
text_field.TextFieldF({
type: 'password',
floatingLabel: true,
placeHolder: 'Master Password',
onChange: e => {
this.setState({
options: assign<NewStoreOptions>(this.state.options, {
password: (<HTMLInputElement>e.target).value,
}),
});
},
}),
text_field.TextFieldF({
type: 'password',
floatingLabel: true,
placeHolder: 'Re-enter Master Password',
onChange: e => {
this.setState({
options: assign<NewStoreOptions>(this.state.options, {
confirmPassword: (<HTMLInputElement>e.target).value,
}),
});
},
error: confirmPasswordError,
}),
text_field.TextFieldF({
type: 'text',
floatingLabel: true,
placeHolder: 'Master password hint',
onChange: e => {
this.setState({
options: assign<NewStoreOptions>(this.state.options, {
hint: (<HTMLInputElement>e.target).value,
}),
});
},
})
);
}
render() {
var passwordsMatch =
this.state.options.password == this.state.options.confirmPassword;
var canCreateStore =
!this.state.creatingStore &&
this.state.options.path.length > 0 &&
this.state.options.password.length > 0 &&
passwordsMatch &&
this.state.options.hint.length > 0;
var form: react.ReactElement<any>;
if (this.state.creatingStore) {
form = div(
style.mixin(theme.newStore),
div(style.mixin(theme.creatingStore.label), 'Creating store...')
);
} else {
form = this.renderForm();
}
return div(
{},
div(style.mixin(theme.header), 'Setup new store'),
form,
div(
style.mixin(theme.screenButtons),
NavButtonF({
label: 'Back',
disabled: this.state.creatingStore,
onClick: () => {
this.props.onGoBack();
},
}),
NavButtonF({
label: 'Create Store',
disabled: !canCreateStore,
onClick: () => {
this.setState({ creatingStore: true });
this.props.onCreate(this.state.options).catch(err => {
this.setState({ creatingStore: false });
});
},
})
)
);
}
}
var NewStoreFormF = react.createFactory(NewStoreForm);
interface ScreenOptions {
temporary?: boolean;
}
interface SetupViewScreen {
id: Screen;
options: ScreenOptions;
}
interface SetupViewState {
cloudServiceType?: settings.CloudService;
fs?: vfs.VFS;
accountInfo?: vfs.AccountInfo;
accessToken?: string;
newStore?: NewStoreOptions;
status?: status_message.Status;
screenStack?: SetupViewScreen[];
currentScreen?: number;
}
function isResumingOAuthLogin() {
return window.location.hash.indexOf('access_token') !== -1;
}
function cloudServiceName(cloudService: settings.CloudService) {
switch (cloudService) {
case settings.CloudService.Dropbox:
return 'Dropbox';
case settings.CloudService.LocalTestingServer:
return 'Local Testing Server';
default:
return 'Unknown';
}
}
/** App setup and onboarding screen.
*/
export class SetupView extends react.Component<SetupViewProps, SetupViewState> {
constructor(props: SetupViewProps) {
super(props);
var screenStack = [
{
id: Screen.StoreList,
options: {},
},
];
if (isResumingOAuthLogin()) {
screenStack.push({
id: Screen.CloudStoreLogin,
options: {},
});
}
this.state = {
screenStack: screenStack,
currentScreen: 0,
};
}
private pushScreen(screen: Screen, options?: ScreenOptions) {
var screens = this.state.screenStack.slice(
0,
this.state.currentScreen + 1
);
screens.push({
id: screen,
options: options || {},
});
this.setState({
screenStack: screens,
});
setTimeout(() => {
this.setState({ currentScreen: this.state.currentScreen + 1 });
}, 100);
}
private popScreen() {
var nextScreen = this.state.currentScreen - 1;
while (this.state.screenStack[nextScreen].options.temporary) {
--nextScreen;
}
this.setState({
currentScreen: nextScreen,
});
}
render() {
var screens: react.ReactElement<any>[] = [];
for (var i = 0; i < this.state.screenStack.length; i++) {
var xTranslation = i - this.state.currentScreen;
var opacity = i == this.state.currentScreen ? 1.0 : 0.0;
var screenKey: string;
var screenContent: react.ReactElement<any>;
let cloudService = cloudServiceName(this.state.cloudServiceType);
switch (this.state.screenStack[i].id) {
case Screen.Welcome:
screenKey = 'screen-welcome';
screenContent = this.renderWelcomeScreen();
break;
case Screen.StoreList:
screenKey = 'screen-store-list';
screenContent = this.renderStoreList();
break;
case Screen.NewStore:
screenKey = 'screen-new-store';
screenContent = this.renderNewStoreScreen();
break;
case Screen.CloudStoreLogin:
screenKey = 'screen-cloud-store-login';
screenContent = this.renderProgressSlide(
`Connecting to ${cloudService}...`
);
break;
case Screen.CloudStoreSignout:
screenKey = 'screen-cloud-store-signout';
screenContent = this.renderProgressSlide(
`Signing out of ${cloudService}...`
);
break;
case Screen.CloudStoreList:
screenKey = 'screen-cloud-store-list';
screenContent = this.renderCloudStoreList();
break;
case Screen.CloudServiceList:
screenKey = 'screen-cloud-service-list';
screenContent = this.renderCloudServiceList();
break;
}
screens.push(
SlideF(
{
key: screenKey,
xTranslation: xTranslation,
opacity: opacity,
},
screenContent
)
);
}
var message: react.ReactElement<toaster.ToasterProps>;
if (this.state.status) {
message = toaster.ToasterF({
message: this.state.status.text,
});
}
return div(
style.mixin(theme.setupView),
div(
style.mixin(theme.setupView.inner),
screens,
reactutil.TransitionGroupF({}, message)
)
);
}
private reportError(err: string | Error) {
var status = status_message.Status.withError(err);
status.expired.listen(() => {
this.setState({ status: null });
});
this.setState({ status: status });
}
private renderWelcomeScreen() {
return div(
{},
div(style.mixin(theme.header), 'Passcards'),
div(
style.mixin(theme.screenButtons),
NavButtonF({
label: 'Continue',
onClick: () => {
this.pushScreen(Screen.StoreList);
},
})
)
);
}
private renderCloudServiceList() {
return div(
{},
div(
style.mixin(theme.screenButtons),
NavButtonF({
label: 'Back',
onClick: () => {
this.popScreen();
},
}),
NavButtonF({
label: 'Connect to Dropbox',
onClick: () => {
this.connectToCloudService(
settings.CloudService.Dropbox
);
},
})
)
);
}
private connectToCloudService(cloudServiceType: settings.CloudService) {
let fs: vfs.VFS;
switch (cloudServiceType) {
case settings.CloudService.Dropbox:
fs = new dropbox_vfs.DropboxVFS();
break;
case settings.CloudService.LocalTestingServer:
fs = new http_vfs.Client(http_vfs.DEFAULT_URL);
break;
default:
this.reportError(new Error('Unsupported cloud service'));
return Promise.resolve<void>(null);
}
this.setState({
cloudServiceType: cloudServiceType,
});
this.pushScreen(Screen.CloudStoreLogin, { temporary: true });
let authenticator = new auth.OAuthFlow({
authServerURL: fs.authURL.bind(fs),
});
let accessToken: string;
return authenticator
.authenticate(window)
.then(credentials => {
accessToken = credentials.accessToken;
fs.setCredentials(credentials);
return fs.accountInfo();
})
.then(accountInfo => {
if (!accessToken) {
throw new Error(
'Failed to retrieve access token for cloud service'
);
}
this.setState({
accessToken: accessToken,
accountInfo: accountInfo,
fs: fs,
cloudServiceType: cloudServiceType,
});
this.pushScreen(Screen.CloudStoreList);
})
.catch(err => {
this.popScreen();
this.reportError(err);
});
}
private renderStoreList() {
var stores =
<settings.AccountMap>this.props.settings.get(
settings.Setting.Accounts
) || {};
return div(
{},
div(style.mixin(theme.header), 'Select Store'),
StoreListF({
stores: stores,
onSelectStore: account => {
this.props.settings.set(
settings.Setting.ActiveAccount,
account.id
);
},
onAddStore: () => {
this.pushScreen(Screen.CloudServiceList);
},
})
);
}
private renderNewStoreScreen() {
return NewStoreFormF({
onGoBack: () => {
this.popScreen();
},
onCreate: options => {
var store = agile_keychain.Vault.createVault(
this.state.fs,
options.path,
options.password,
options.hint
);
return store
.then(store => {
this.onSelectStore(store.vaultPath());
})
.catch(err => {
this.reportError(err);
throw err;
});
},
storeName: this.cloudServiceType(),
});
}
private onSelectStore(path: string) {
var account: settings.Account = {
id: null,
cloudService: this.state.cloudServiceType,
cloudAccountId: this.state.accountInfo.userId,
accessToken: this.state.accessToken,
name: this.state.accountInfo.name,
storePath: path,
};
account.id = settings.accountKey(account);
var appSettings = this.props.settings;
var stores =
<settings.AccountMap>appSettings.get(settings.Setting.Accounts) ||
{};
stores[account.id] = account;
appSettings.set(settings.Setting.Accounts, stores);
appSettings.set(settings.Setting.ActiveAccount, account.id);
}
private renderProgressSlide(text: string) {
return div(style.mixin(theme.header), text);
}
private cloudServiceType() {
if (typeof this.state.cloudServiceType !== 'number') {
return 'Unknown';
}
return cloudServiceName(this.state.cloudServiceType);
}
private renderCloudStoreList() {
var accountName = 'your';
if (this.state.accountInfo) {
accountName = `${this.state.accountInfo.name}'s`;
}
return div(
{},
div(
style.mixin(theme.header),
`Select store in ${accountName} ${this.cloudServiceType()}`
),
CloudStoreListF({
vfs: this.state.fs,
onSelectStore: path => {
this.onSelectStore(path);
},
}),
div(
style.mixin(theme.screenButtons),
NavButtonF({
label: 'Back',
onClick: () => {
this.popScreen();
},
}),
NavButtonF({
label: 'Create New Store',
onClick: () => {
this.pushScreen(Screen.NewStore);
},
}),
div(style.mixin(theme.screenButtons.spacer)),
NavButtonF({
label: 'Sign Out',
onClick: () => {
this.popScreen();
this.pushScreen(Screen.CloudStoreSignout, {
temporary: true,
});
this.setState({
fs: undefined,
accessToken: undefined,
});
this.popScreen();
},
})
)
);
}
}
export var SetupViewF = react.createFactory(SetupView); | the_stack |
* Copyright 2015 Dev Shop Limited
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// notice_end
import {Router, observeEvent, ObservationStage, EventEnvelope, RouterSubject, DisposableBase} from 'esp-js';
////////////////////////////////////////////////////////////// basic usage example //////////////////////////////////////////////////////////////
export const runBasicExample = () => {
// Create a simple model
class Car {
_make = 'Unknown';
_color = 'white';
_isSportModel = false;
_description = '';
_cost = 0;
constructor() { }
get make() {
return this._make;
}
set make(value) {
this._make = value;
}
get color() {
return this._color;
}
set color(value) {
this._color = value;
}
get isSportModel() {
return this._isSportModel;
}
set isSportModel(value) {
this._isSportModel = value;
}
get description() {
return this._description;
}
set description(value) {
this._description = value;
}
get cost() {
return this._cost;
}
set cost(value) {
this._cost = value;
}
}
// Create an event processor and observe events
class CarEventProcessor {
constructor(private _router: Router) { }
start() {
this._listenForCarMakeChangedEvent();
this._listenForIsSportModelChangedEvent();
this._listenForColorModelChangedEvent();
}
_listenForCarMakeChangedEvent() {
this._router
.getEventObservable('myModelId', 'carMakeChangedEvent')
.subscribe((envelope: EventEnvelope<{make: string}, Car>)=> {
envelope.model.make = envelope.event.make;
});
}
_listenForIsSportModelChangedEvent() {
this._router
.getEventObservable('myModelId', 'isSportModelChangedEvent')
.subscribe((envelope: EventEnvelope<{isSportModel: boolean}, Car>)=> {
envelope.model.isSportModel = envelope.event.isSportModel;
if(envelope.model.isSportModel) {
envelope.model.cost = 30000;
} else {
envelope.model.cost = 20000;
}
});
}
_listenForColorModelChangedEvent() {
this._router
.getEventObservable('myModelId', 'colorChangedEvent')
.subscribe(({event, context, model}) => {
model.color = event.color;
});
}
}
// create a post event processor to do some aggregate computations
const carPostEventProcessor = (model, eventsProcessed) => {
let price = 10000; // base price
if (model.make === 'BMW') {
price += 20000;
}
if (model.isSportModel) {
price += 10000;
}
model.price = price;
model.description =
'Your new ' +
(model.isSportModel ? 'sporty ' : 'standard ') +
'edition ' +
model.make +
' (' + model.color + ') ' +
'will cost £' +
model.price;
};
// Create an event raiser and publish an event
class CarScreenController {
constructor(private _router: Router) {
this._router = router;
}
start() {
this._listenForModelChanges();
console.log('Simulating some user actions over 4 seconds: ');
setTimeout(() => {
this._router.publishEvent('myModelId', 'carMakeChangedEvent', { make: 'BMW' });
}, 0);
setTimeout(() => {
this._router.publishEvent('myModelId', 'isSportModelChangedEvent', { isSportModel: true });
}, 500);
setTimeout(() => {
this._router.publishEvent('myModelId', 'colorChangedEvent', { color: 'blue' });
}, 1000);
}
_listenForModelChanges() {
this._router
.getModelObservable('myModelId')
.subscribe(model => {
// you'd sync your view here, for now just dump the description to the console
console.log(model.description);
});
}
}
// Kick it all off
let router = new Router();
router.addModel('myModelId', new Car(), { postEventProcessor : carPostEventProcessor });
let carEventProcessor = new CarEventProcessor(router);
let carScreenController = new CarScreenController(router);
carEventProcessor.start();
carScreenController.start();
};
////////////////////////////////////////////////////////////// event workflow examples //////////////////////////////////////////////////////////////
export const runEventWorkflowExample = () => {
class FruitStore {
_hasExpired = false;
_stockCount = 10;
_shouldRefreshFromStore = false;
_shouldRecalculateInventory = false;
_version = 0;
constructor() { }
get version() {
return this._version;
}
set version(value) {
this._version = value;
}
get hasExpired() {
return this._hasExpired;
}
set hasExpired(value) {
this._hasExpired = value;
}
get stockCount() {
return this._stockCount;
}
set stockCount(value) {
this._stockCount = value;
}
get shouldRefreshFromStore() {
return this._shouldRefreshFromStore;
}
set shouldRefreshFromStore(value) {
this._shouldRefreshFromStore = value;
}
get shouldRecalculateInventory() {
return this._shouldRecalculateInventory;
}
set shouldRecalculateInventory(value) {
this._shouldRecalculateInventory = value;
}
toString() {
return 'Stock count: ' + this.stockCount + ', shouldRefreshFromStore: ' + this.shouldRefreshFromStore + ', shouldRecalculateInventory: ' + this.shouldRecalculateInventory;
}
}
let preEventProcessingExample = () => {
console.log('** pre event processor example');
let router = new Router();
let store = new FruitStore();
router.addModel(
'model1',
store,
{
preEventProcessor : (model) => {
model.version++;
}
}
);
router.publishEvent('model1', 'noopEvent', { });
console.log('Store version: ' + store.version); // 1;
};
let previewStageExample = () => {
console.log('** preview stage example');
let router = new Router();
let store = new FruitStore();
router.addModel('model1', store);
router
.getEventObservable('model1', 'fruitExpiredEvent', ObservationStage.normal)
.subscribe((envelope: EventEnvelope<boolean, FruitStore>) => {
console.log('Setting hasExpired to ' + envelope.event);
envelope.model.hasExpired = envelope.event;
});
router
.getEventObservable('model1', 'buyFruitEvent', ObservationStage.preview)
.subscribe((envelope: EventEnvelope<{quantity: number}, FruitStore>) => {
if(envelope.model.hasExpired) {
console.log('Cancelling buyFruitEvent event as all fruit has expired');
envelope.context.cancel();
}
});
router
.getEventObservable('model1', 'buyFruitEvent', ObservationStage.normal)
.subscribe((envelope: EventEnvelope<{quantity: number}, FruitStore>) => {
console.log('Buying fruit, quantity: ' + envelope.event.quantity);
envelope.model.stockCount -= envelope.event.quantity;
});
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log('Stock count: ' + store.stockCount); // 'Stock count: 9'
router.publishEvent('model1', 'fruitExpiredEvent', true);
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log('Stock count: ' + store.stockCount); // still 'Stock count: 9', previous event was canceled by the preview handler
router.publishEvent('model1', 'fruitExpiredEvent', false);
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log('Stock count: ' + store.stockCount); // 'Stock count: 8'
console.log();
};
let normalStageExample = () => {
console.log('** normal stage example');
let router = new Router();
let store = new FruitStore();
router.addModel('model1', store);
let buyFruitEventSubscription = router
.getEventObservable('model1', 'buyFruitEvent') // i.e. stage = ObservationStage.normal
.subscribe((envelope: EventEnvelope<{quantity: number}, FruitStore>) => {
console.log('Buying fruit, quantity: ' + envelope.event.quantity);
envelope.model.stockCount -= envelope.event.quantity;
});
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log('Stock count: ' + store.stockCount); // 'Stock count: 9'
buyFruitEventSubscription.dispose();
router.publishEvent('model1', 'buyFruitEvent', false);
console.log('Stock count: ' + store.stockCount); // still 'Stock count: 9', event not delivered as subscription removed
console.log();
};
let committedStageExample = () => {
console.log('** committed stage example');
let router = new Router();
let store = new FruitStore();
router.addModel('model1', store);
router
.getEventObservable('model1', 'buyFruitEvent')
.subscribe((envelope: EventEnvelope<{quantity: number}, FruitStore>) => {
console.log('Buying fruit, quantity: ' + envelope.event.quantity);
envelope.model.stockCount -= envelope.event.quantity;
envelope.context.commit();
});
router
.getEventObservable('model1', 'buyFruitEvent', ObservationStage.committed)
.subscribe((envelope: EventEnvelope<{quantity: number}, FruitStore>) => {
// reacting to the buyFruitEvent we check if the shelf quantity requires refilling
let shouldRefreshFromStore = envelope.model.stockCount < 3;
console.log('Checking if we should refresh from store. Should refresh: ' + shouldRefreshFromStore);
envelope.model.shouldRefreshFromStore = shouldRefreshFromStore;
});
router
.getEventObservable('model1', 'buyFruitEvent', ObservationStage.committed)
.subscribe((envelope: EventEnvelope<{quantity: number}, FruitStore>) => {
// given we've sold something we flip a dirty flag which could be used by another
// // periodic event to determine if we should recalculate inventory
console.log('Flagging inventory recalculate');
envelope.model.shouldRecalculateInventory = true;
});
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log(store.toString()); // Stock count: 9, shouldRefreshFromStore: false, shouldRecalculateInventory: true
router.publishEvent('model1', 'buyFruitEvent', { quantity: 8 });
console.log(store.toString()); // Stock count: 1, shouldRefreshFromStore: true, shouldRecalculateInventory: true
console.log();
};
preEventProcessingExample();
previewStageExample();
normalStageExample();
committedStageExample();
};
////////////////////////////////////////////////////////////// model observation example //////////////////////////////////////////////////////////////
export const runModelObserveExample = () => {
let router = new Router();
router.addModel('modelId', { foo: 1 });
router
.getEventObservable('modelId', 'fooChanged')
.subscribe((envelope: EventEnvelope<{newFoo: number}, {foo: number}>) => {
envelope.model.foo = envelope.event.newFoo;
});
router
.getModelObservable('modelId')
.subscribe(model => {
console.log('Foo is ' + model.foo);
});
router.publishEvent('modelId', 'fooChanged', { newFoo: 2 });
};
////////////////////////////////////////////////////////////// observable API example //////////////////////////////////////////////////////////////
export const runObserveApiBasicExample = () => {
interface TheModel {
staticData: {
initialised: boolean,
clientMargin: number,
};
price: number;
}
// note there are several concerns here that would exist in different
// objects within your architecture, they are all together here to demo the concepts.
let router = new Router();
// add a basic model
router.addModel(
'modelId',
<TheModel>{
staticData:
{
initialised: false,
clientMargin: 0
},
price: 0
}
);
// create an event stream that listens for static data
let staticDataSubscriptionDisposable = router
.getEventObservable('modelId', 'staticDataReceivedEvent')
.subscribe((envelope: EventEnvelope<{clientMargin: number}, TheModel>) => {
console.log('Static data received');
envelope.model.staticData.initialised = true;
envelope.model.staticData.clientMargin = envelope.event.clientMargin;
}
);
// create an event stream that listens for prices
let eventSubscriptionDisposable = router
.getEventObservable('modelId', 'priceReceivedEvent')
// run an action when the stream yields
.do(() => console.log('Price received'))
// only procure the event if the condition matches
.filter((envelope: EventEnvelope<{price: number}, TheModel>) => envelope.model.staticData.initialised)
.subscribe((envelope: EventEnvelope<{price: number}, TheModel>) => {
envelope.model.price =
envelope.event.price +
envelope.model.staticData.clientMargin;
console.log('Price with margin was set to ' + envelope.model.price);
});
// publish some prices, the first 2 will get ignored as the .filter() waits until the
// static data has been set on the model.
router.publishEvent('modelId', 'priceReceivedEvent', { price: 100 });
router.publishEvent('modelId', 'priceReceivedEvent', { price: 101 });
router.publishEvent('modelId', 'staticDataReceivedEvent', { clientMargin: 10 });
router.publishEvent('modelId', 'priceReceivedEvent', { price: 102 });
// clean up code
staticDataSubscriptionDisposable.dispose();
eventSubscriptionDisposable.dispose();
// this one never gets delivered as we've disposed the event subscriptions
router.publishEvent('modelId', 'priceReceivedEvent', { price: 103 });
};
////////////////////////////////////////////////////////////// model to model communications with events example //////////////////////////////////////////////////////////////
export const runModelToModelCommunicationsWithEvents = () => {
interface PriceRequestedEvent { symbol: string; replyTo: string; }
interface PriceReceivedEvent { symbol: string; bid: number; ask: number; }
class BaseModel {
constructor(public modelId: string, protected _router: Router) {
this.modelId = modelId;
this._router = _router;
}
registerWithRouter() {
this._router.addModel(this.modelId, this);
this._router.observeEventsOn(this.modelId, this);
}
}
class TradingModel extends BaseModel {
constructor(_router: Router) {
super('tradingModelId', _router);
}
@observeEvent('userRequestedPrice')
_onUserRequestedPrice(priceRequestEvent: PriceRequestedEvent) {
console.log(`TradingModel: User requested price, sending request to pricing model`);
this._router.publishEvent('pricingModelId', 'priceRequested', { symbol:priceRequestEvent.symbol, replyTo:this.modelId });
}
@observeEvent('priceReceived')
_onPriceReceived(priceEvent: PriceReceivedEvent) {
console.log(`TradingModel: Price received: ${priceEvent.symbol} - ${priceEvent.bid} - ${priceEvent.ask}`);
}
}
class PricingModel extends BaseModel {
constructor(_router: Router) {
super('pricingModelId', _router);
}
@observeEvent('priceRequested')
_onPriceRequested(priceRequestedEvent: PriceRequestedEvent) {
console.log(`PricingModel: price request received, responding with last price`);
this._router.publishEvent(priceRequestedEvent.replyTo, 'priceReceived', { symbol:priceRequestedEvent.symbol, bid:1, ask:2 });
}
}
let router = new Router();
let pricingModel = new PricingModel(router);
pricingModel.registerWithRouter();
let tradingModel = new TradingModel(router);
tradingModel.registerWithRouter();
console.log(`User requesting price for EURUSD`);
router.publishEvent(tradingModel.modelId, 'userRequestedPrice', { symbol: 'EURUSD'});
};
////////////////////////////////////////////////////////////// model to model communications with runAction example //////////////////////////////////////////////////////////////
export const runModelToModelCommunicationsWithRunAction = () => {
class BaseModel {
constructor(public modelId, protected _router) { }
registerWithRouter() {
this._router.addModel(this.modelId, this);
this._router.observeEventsOn(this.modelId, this);
}
}
class TradingModel extends BaseModel {
constructor(_router, private _pricingModel) {
super('tradingModelId', _router);
}
@observeEvent('userRequestedPrice')
_onUserRequestedPrice(priceRequestEvent) {
console.log(`TradingModel: User requested price, sending request to pricing model`);
this._pricingModel.onPriceRequested({ symbol:priceRequestEvent.symbol, replyTo:this.modelId });
}
@observeEvent('priceReceived')
_onPriceReceived(priceEvent) {
console.log(`TradingModel: Price received: ${priceEvent.symbol} - ${priceEvent.bid} - ${priceEvent.ask}`);
}
}
class PricingModel extends BaseModel {
constructor(_router) {
super('pricingModelId', _router);
}
onPriceRequested(priceRequest) {
this._router.runAction(this.modelId, () => {
console.log(`PricingModel: price request received, responding with last price`);
this._router.publishEvent(priceRequest.replyTo, 'priceReceived', { symbol:priceRequest.symbol, bid:1, ask:2 });
});
}
}
let router = new Router();
let pricingModel = new PricingModel(router);
pricingModel.registerWithRouter();
let tradingModel = new TradingModel(router, pricingModel);
tradingModel.registerWithRouter();
console.log(`User requesting price for EURUSD`);
router.publishEvent(tradingModel.modelId, 'userRequestedPrice', { symbol: 'EURUSD'});
};
////////////////////////////////////////////////////////////// model to model communications with observables (Unique Request -> Many Responses) example /////////////////////////
export const runModelToModelCommunicationsWithObservables1 = () => {
class BaseModel {
constructor(public modelId, protected _router) {
this.modelId = modelId;
this._router = _router;
}
registerWithRouter() {
this._router.addModel(this.modelId, this);
this._router.observeEventsOn(this.modelId, this);
}
}
class TradingModel extends BaseModel {
lastPrice = null;
constructor(_router, private _pricingModel) {
super('tradingModelId', _router);
this._pricingModel = _pricingModel;
}
@observeEvent('userRequestedPrice')
_onUserRequestedPrice(priceRequestEvent) {
console.log(`TradingModel: User requested price, sending request to pricing model`);
// subscribe to another models observable stream.
let subscription = this._pricingModel
.getPriceStream({ symbol:priceRequestEvent.symbol})
// streamFor : ensure our observable stream yields on the dispatch loop for this model
.streamFor(this.modelId)
.subscribe(price => {
let isOnCorrectDispatchLoop = this._router.isOnDispatchLoopFor(this.modelId);
console.log(`TradingModel: Price received: ${price.symbol} - ${price.bid} - ${price.ask}. On correct dispatch loop: ${isOnCorrectDispatchLoop}`);
// Store the last price so the/a view can pick it up.
// Given we're on the dispatch loop for this model, the router will be pushing the model to observers after this function ends.
this.lastPrice = price;
});
// later : subscription.dispose();
}
}
class PricingModel extends BaseModel {
constructor(_router: Router) {
super('pricingModelId', _router);
}
getPriceStream(priceRequest) {
return this._router.createObservableFor(this.modelId, observer => {
// This gets invoked when the caller subscribes to the observable stream.
// Typically you'd wire the observer up to some async service and push updates to it
let isOnCorrectDispatchLoop = this._router.isOnDispatchLoopFor(this.modelId);
console.log(`PricingModel: price request received, responding with last price. On correct dispatch loop: ${isOnCorrectDispatchLoop}`);
observer.onNext({ symbol:priceRequest.symbol, bid:1, ask:2 });
observer.onNext({ symbol:priceRequest.symbol, bid:1.1, ask:2.1 });
return () => {
// Gets invoked when the caller disposes the subscription.
// Typically you'd un-wire the observer from any local state
};
});
}
}
let router = new Router();
let pricingModel = new PricingModel(router);
pricingModel.registerWithRouter();
let tradingModel = new TradingModel(router, pricingModel);
tradingModel.registerWithRouter();
console.log(`User requesting price for EURUSD`);
router.publishEvent(tradingModel.modelId, 'userRequestedPrice', { symbol: 'EURUSD'});
};
////////////////////////////////////////////////////////////// model to model communications with observables (streaming) example /////////////////////////
export const runModelToModelCommunicationsWithObservables2 = () => {
class BaseModel {
constructor(public modelId, protected _router) {
this.modelId = modelId;
this._router = _router;
}
registerWithRouter() {
this._router.addModel(this.modelId, this);
this._router.observeEventsOn(this.modelId, this);
}
}
class TradingModel extends BaseModel {
_currentSymbol = 'EURUSD';
lastPrice = null;
constructor(_router: Router, private _pricingModel: PricingModel) {
super('tradingModelId', _router);
this._currentSymbol = 'EURUSD';
this.lastPrice = null;
}
registerWithRouter() {
super.registerWithRouter();
this._observePriceStream();
}
_observePriceStream() {
let subscription = this._pricingModel.priceStream
.streamFor(this.modelId)
.filter(price => price.symbol === this._currentSymbol)
.subscribe(price => {
let isOnCorrectDispatchLoop = this._router.isOnDispatchLoopFor(this.modelId);
console.log(`TradingModel: Price received: ${price.symbol} - ${price.bid} - ${price.ask}. On correct dispatch loop: ${isOnCorrectDispatchLoop}`);
this.lastPrice = price;
});
// later, when the model is destroyed : subscription.dispose();
}
@observeEvent('userRequestedPrice')
_onUserRequestedPrice(priceRequestEvent) {
this._currentSymbol = priceRequestEvent.symbol;
}
}
class PricingModel extends BaseModel {
private _priceSubject: RouterSubject<any>;
constructor(_router: Router) {
super('pricingModelId', _router);
this._priceSubject = _router.createSubject();
}
get priceStream() {
// Expose our internal price stream.
// `asRouterObservable()` wraps the subject hiding functions such as onNext from consumers
return this._priceSubject.asRouterObservable(this._router);
}
// expose a function so we can push prices, in a real app
// this model would own interactions with downstream objects, receive prices and push them internally
pushPrice(price) {
this._priceSubject.onNext(price);
}
}
let router = new Router();
let pricingModel = new PricingModel(router);
pricingModel.registerWithRouter();
let tradingModel = new TradingModel(router, pricingModel);
tradingModel.registerWithRouter();
console.log(`Prices received from network`);
pricingModel.pushPrice({ symbol:'EURUSD', bid:1, ask:2 });
pricingModel.pushPrice({ symbol:'USDJPY', bid:3, ask:4 });
console.log(`User changed symbol to USDJPY`);
router.publishEvent(tradingModel.modelId, 'userRequestedPrice', { symbol: 'USDJPY'});
console.log(`More prices received from network`);
pricingModel.pushPrice({ symbol:'USDJPY', bid:5, ask:6 });
};
////////////////////////////////////////////////////////////// async operation with workitem //////////////////////////////////////////////////////////////
export const runAcyncOperationWithWorkItemExample = () => {
interface StaticDataModel {
staticData: string[];
}
class GetUserStaticDataWorkItem extends DisposableBase {
constructor(private _router: Router) {
super();
}
start() {
setTimeout(() => {
console.log('Sending results event for StaticDataA');
this._router.publishEvent('modelId', 'userStaticReceivedEvent', 'StaticDataA');
}, 1000);
setTimeout(() => {
console.log('Sending results event for StaticDataB');
this._router.publishEvent('modelId', 'userStaticReceivedEvent', 'StaticDataB');
}, 2000);
}
}
class StaticDataEventProcessor extends DisposableBase {
constructor(private _router: Router) {
super();
this._router = router;
}
initialise() {
this._listenForInitialiseEvent();
this._listenForStaticDataReceivedEvent();
}
_listenForInitialiseEvent() {
this.addDisposable(this._router
.getEventObservable('modelId', 'initialiseEvent')
.take(1)
.subscribe(() => {
console.log('Starting work item to get static data');
let getUserStaticWorkItem = new GetUserStaticDataWorkItem(this._router);
this.addDisposable(getUserStaticWorkItem);
getUserStaticWorkItem.start();
})
);
}
_listenForStaticDataReceivedEvent() {
// note you could wire up more advanced disposal of this stream (i.e. write
// a .takeUntilInclusive() extension method, you could also leave it
// open if you were to later expect events matching its eventType
this.addDisposable(this._router
.getEventObservable('modelId', 'userStaticReceivedEvent')
.subscribe((envelope: EventEnvelope<string, StaticDataModel>) => {
console.log('Adding static data [' + envelope.event + '] to model');
envelope.model.staticData.push(envelope.event);
})
);
}
}
let router = new Router();
router.addModel('modelId', <StaticDataModel>{ staticData:[]});
let staticDataEventProcessor = new StaticDataEventProcessor(router);
staticDataEventProcessor.initialise();
console.log('Sending initialiseEvent');
router.publishEvent('modelId', 'initialiseEvent', {});
};
////////////////////////////////////////////////////////////// async operation with runAction //////////////////////////////////////////////////////////////
export const runAcyncOperationWithRunActionExample = () => {
interface TestModel {
foo: number;
backgroundOperations: number;
}
let myModel: TestModel = {
foo:0,
backgroundOperations: 0
};
let router = new Router();
router.addModel('myModelId', myModel);
router
.getEventObservable('myModelId', 'getAsyncDataEvent')
.subscribe((envelope: EventEnvelope<string, TestModel>) => {
console.log('About to do async work');
envelope.model.backgroundOperations++;
setTimeout(() => {
router.runAction('myModelId', (m2: TestModel) => { // you could close over m here if you prefer
m2.backgroundOperations--;
console.log('Async work received. Updating model');
m2.foo = 1;
});
}, 2000);
});
router.publishEvent('myModelId', 'getAsyncDataEvent', { request: 'someRequest' });
router.getModelObservable('myModelId').subscribe(m => {
console.log('Update, background operation count is: %s. foo is %s', m.backgroundOperations, m.foo);
});
};
////////////////////////////////////////////////////////////// SingleModelRouter example //////////////////////////////////////////////////////////////
export const runModelRouter = () => {
interface TestModel {
foo: number;
}
let myModel: TestModel = {
foo:0
};
let router = new Router();
router.addModel('myModel', myModel);
let modelRouter = router.createModelRouter('myModel');
modelRouter
.getEventObservable('fooEvent')
.subscribe((envelope: EventEnvelope<{ theFoo: number }, TestModel>) => {
envelope.model.foo = envelope.event.theFoo;
});
modelRouter.getModelObservable().subscribe(m => {
console.log('Update, foo is: %s', m.foo);
});
modelRouter.publishEvent('fooEvent', { theFoo: 1});
modelRouter.publishEvent('fooEvent', { theFoo: 2});
};
////////////////////////////////////////////////////////////// error flows example //////////////////////////////////////////////////////////////
export const runErrorFlowsExample = () => {
let router = new Router();
router.addModel('modelId', { });
router
.getEventObservable('modelId', 'boomEvent')
.do(() => {throw new Error('Boom');})
.subscribe(
() => {
console.log('This never run');
}
);
try {
router.publishEvent('modelId', 'boomEvent', {});
} catch(err) {
console.log('Error caught: ' + err.message);
}
// this won't make it to any observers as the router is halted
try {
router.publishEvent('modelId', 'boomEvent', {});
} catch(err) {
console.log('Error caught 2: ' + err.message);
}
}; | the_stack |
import { events } from "../event";
import { NetworkIdentifier } from "./networkidentifier";
import { MinecraftPacketIds } from "./packetids";
import { ModalFormRequestPacket, SetTitlePacket } from "./packets";
const formMaps = new Map<number, SentForm>();
// rua.kr: I could not find the internal form id counter, It seems BDS does not use the form.
// But I set the minimum for the unexpected situation.
const MINIMUM_FORM_ID = 0x10000000;
const MAXIMUM_FORM_ID = 0x7fffffff; // 32bit signed integer maximum
let formIdCounter = MINIMUM_FORM_ID;
class SentForm {
public readonly id: number;
constructor(
public readonly networkIdentifier:NetworkIdentifier,
public readonly resolve: (data:FormResponse<any>)=>void,
public readonly reject: (err:Error)=>void) {
// allocate id without dupication
for (;;) {
const id = formIdCounter++;
if (formIdCounter >= MAXIMUM_FORM_ID) formIdCounter = MINIMUM_FORM_ID;
// logically it will enter the infinity loop when it fulled. but technically it will crash by out of memory before
if (!formMaps.has(id)) {
formMaps.set(id, this);
this.id = id;
break;
}
}
}
}
export interface FormItemButton {
text: string;
image?: {
type: "path" | "url",
data: string,
};
}
export interface FormItemLabel {
type: 'label';
text: string;
image?: {
type: "path" | "url",
data: string,
};
}
export interface FormItemToggle {
type: 'toggle';
text: string;
default?:boolean;
}
export interface FormItemSlider {
type: 'slider';
text: string;
min: number;
max: number;
step?: number;
default?: number;
}
export interface FormItemStepSlider {
type: 'step_slider';
text: string;
steps: string[];
default?: number;
}
export interface FormItemDropdown {
type: 'dropdown';
text: string;
options: string[];
default?: number;
}
export interface FormItemInput {
type: 'input';
text: string;
placeholder?: string;
default?: string;
}
export type FormItem = FormItemLabel | FormItemToggle | FormItemSlider | FormItemStepSlider | FormItemDropdown | FormItemInput;
export type FormResponse<T extends FormData['type']> =
T extends 'form' ? number|null :
T extends 'modal' ? boolean :
T extends 'custom_form' ? any[]|null :
never;
export interface FormDataSimple {
type: 'form';
title: string;
content: string;
buttons: FormItemButton[];
}
export interface FormDataModal {
type: 'modal';
title: string;
content: string;
button1: string;
button2: string;
}
export interface FormDataCustom {
type: 'custom_form';
title: string;
content: FormItem[];
}
export type FormData = FormDataSimple | FormDataModal | FormDataCustom;
export class FormButton {
text: string;
image: {
type: "path" | "url",
data: string,
};
constructor(text: string, imageType?: "path" | "url", imagePath: string = "") {
this.text = text;
if (imageType) {
this.image = {
type: imageType,
data: imagePath,
};
}
}
}
class FormComponent {
text: string;
type: string;
constructor(text: string) {
this.text = text;
}
}
export class FormLabel extends FormComponent implements FormItemLabel {
readonly type = "label";
constructor(text: string) {
super(text);
}
}
export class FormToggle extends FormComponent implements FormItemToggle {
readonly type = "toggle";
default: boolean;
constructor(text: string, defaultValue?: boolean) {
super(text);
if (defaultValue) this.default = defaultValue;
}
}
export class FormSlider extends FormComponent implements FormItemSlider {
readonly type = "slider";
min: number;
max: number;
step: number;
default: number;
constructor(text: string, min: number, max: number, step?: number, defaultValue?: number) {
super(text);
this.min = min;
this.max = max;
if (step) this.step = step;
if (defaultValue) this.default = defaultValue;
}
}
export class FormStepSlider extends FormComponent implements FormItemStepSlider {
readonly type = "step_slider";
steps: string[];
default: number;
constructor(text: string, steps: string[], defaultIndex?: number) {
super(text);
this.steps = steps;
if (defaultIndex) this.default = defaultIndex;
}
}
export class FormDropdown extends FormComponent implements FormItemDropdown {
readonly type = "dropdown";
options: string[];
default: number;
constructor(text: string, options: string[], defaultIndex?: number) {
super(text);
this.options = options;
if (defaultIndex) this.default = defaultIndex;
}
}
export class FormInput extends FormComponent implements FormItemInput {
readonly type = "input";
placeholder: string;
default: string;
constructor(text: string, placeholder?: string, defaultValue?: string) {
super(text);
if (placeholder) this.placeholder = placeholder;
if (defaultValue) this.default = defaultValue;
}
}
export class Form<DATA extends FormData> {
labels: Map<number, string> = new Map<number, string>();
response:any;
constructor(public data:DATA) {
}
static sendTo<T extends FormData['type']>(target:NetworkIdentifier, data:FormData&{type:T}, opts?:Form.Options):Promise<FormResponse<T>> {
return new Promise((resolve:(res:FormResponse<T>)=>void, reject)=>{
const submitted = new SentForm(target, resolve, reject);
const pk = ModalFormRequestPacket.create();
pk.id = submitted.id;
if (opts != null) opts.id = pk.id;
pk.content = JSON.stringify(data);
pk.sendTo(target);
pk.dispose();
const formdata:FormData = data;
if (formdata.type === 'form') {
if (formdata.buttons != null) {
for (const button of formdata.buttons) {
if (button.image?.type === "url") {
setTimeout(() => {
const pk = SetTitlePacket.create();
pk.sendTo(target);
pk.dispose();
}, 1000);
break;
}
}
}
}
});
}
sendTo(target:NetworkIdentifier, callback?: (form: Form<DATA>, networkIdentifier: NetworkIdentifier) => any):number {
const opts:Form.Options = {};
Form.sendTo(target, this.data, opts).then(res=>{
if (callback == null) return;
switch (this.data.type) {
case "form":
this.response = this.labels.get(res as any) || res;
break;
case "modal":
this.response = res;
break;
case "custom_form":
this.response = res;
if (res !== null) {
for (const [index, label] of this.labels) {
(res as any)[label] = (res as any)[index];
}
}
break;
}
callback(this, target);
});
return opts.id!;
}
toJSON():FormData {
return this.data;
}
}
export namespace Form {
export interface Options {
/**
* a field for the output.
* this function will record the id to it
*/
id?:number;
}
}
export class SimpleForm extends Form<FormDataSimple> {
constructor(title = "", content = "", buttons: FormButton[] = []) {
super({
type: 'form',
title,
content,
buttons
});
}
getTitle():string {
return this.data.title;
}
setTitle(title:string):void {
this.data.title = title;
}
getContent():string {
return this.data.content;
}
setContent(content:string):void {
this.data.content = content;
}
addButton(button: FormButton, label?: string):void {
this.data.buttons!.push(button);
if (label) this.labels.set(this.data.buttons!.length - 1, label);
}
getButton(indexOrLabel: string | number):FormButton | null {
if (typeof indexOrLabel === "string") {
for (const [index, label] of this.labels) {
if (label === indexOrLabel) return this.data.buttons![index] as FormButton;
}
} else {
return this.data.buttons![indexOrLabel] as FormButton;
}
return null;
}
}
export class ModalForm extends Form<FormDataModal> {
constructor(title = "", content = "") {
super({
type: 'modal',
title,
content,
button1: '',
button2: '',
});
}
getTitle():string {
return this.data.title;
}
setTitle(title:string):void {
this.data.title = title;
}
getContent():string {
return this.data.content as string;
}
setContent(content:string):void {
this.data.content = content;
}
getButtonConfirm():string {
return this.data.button1;
}
setButtonConfirm(text:string):void {
this.data.button1 = text;
}
getButtonCancel():string {
return this.data.button2;
}
setButtonCancel(text:string):void {
this.data.button2 = text;
}
}
export class CustomForm extends Form<FormDataCustom> {
constructor(title = "", content: FormComponent[] = []) {
super({
type: 'custom_form',
title,
content: content as FormItem[]
});
}
getTitle():string {
return this.data.title;
}
setTitle(title:string):void {
this.data.title = title;
}
addComponent(component: FormComponent, label?: string):void {
(this.data.content as FormComponent[]).push(component);
if (label) this.labels.set(this.data.content!.length - 1, label);
}
getComponent(indexOrLabel: string | number):FormComponent | null {
if (typeof indexOrLabel === "string") {
for (const [index, label] of this.labels) {
if (label === indexOrLabel) return (this.data.content as FormComponent[])[index];
}
} else {
return (this.data.content as FormComponent[])[indexOrLabel];
}
return null;
}
}
events.packetAfter(MinecraftPacketIds.ModalFormResponse).on((pk, ni) => {
const sent = formMaps.get(pk.id);
if (sent == null) return;
if (sent.networkIdentifier !== ni) return; // other user is responsing
formMaps.delete(pk.id);
try {
const response = JSON.parse(pk.response);
sent.resolve(response);
} catch (err) {
sent.reject(err);
}
}); | the_stack |
import * as L from 'leaflet';
declare module 'leaflet' {
namespace Routing {
class Control extends Itinerary {
constructor(options?: RoutingControlOptions);
getWaypoints(): Waypoint[];
setWaypoints(waypoints: Waypoint[] | LatLng[]): this;
spliceWaypoints(index: number, waypointsToRemove: number, ...wayPoints: Waypoint[]): Waypoint[];
getPlan(): Plan;
getRouter(): IRouter;
route(): void;
on(type: string, fn: (event: any) => void, context?: any): this;
}
interface RoutingControlOptions extends ItineraryOptions {
waypoints?: Waypoint[] | LatLng[] | undefined;
router?: IRouter | undefined;
plan?: Plan | undefined;
geocoder?: any; // IGeocorder is from other library;
fitSelectedRoutes?: 'smart' | boolean | undefined;
lineOptions?: LineOptions | undefined;
routeLine?: ((route: IRoute, options: LineOptions) => Line) | undefined;
autoRoute?: boolean | undefined;
routeWhileDragging?: boolean | undefined;
routeDragInterval?: number | undefined;
waypointMode?: 'connect' | 'snap' | undefined;
useZoomParameter?: boolean | undefined;
showAlternatives?: boolean | undefined;
altLineOptions?: LineOptions | undefined;
addWaypoints?: boolean | undefined;
defaultErrorHandler?: ((error: any) => void) | undefined;
}
class Itinerary extends L.Control {
constructor(options: ItineraryOptions);
setAlternatives(routes: IRoute[]): any;
show(): void;
hide(): void;
createAlternativesContainer(): HTMLElement;
}
interface ItineraryOptions {
pointMarkerStyle?: CircleMarkerOptions | undefined;
summaryTemplate?: string | undefined;
distanceTemplate?: string | undefined;
timeTemplate?: string | undefined;
containerClassName?: string | undefined;
alternativeClassName?: string | undefined;
minimizedClassName?: string | undefined;
itineraryClassName?: string | undefined;
show?: boolean | undefined;
formatter?: Formatter | undefined;
itineraryFormatter?: ItineraryBuilder | undefined;
collapsible?: boolean | undefined;
collapseBtn?: ((itinerary: Itinerary) => void) | undefined;
collapseBtnClass?: string | undefined;
totalDistanceRoundingSensitivity?: number | undefined;
itineraryBuilder?: ItineraryBuilder | undefined;
}
class Plan extends Layer {
constructor(waypoints: Waypoint[] | LatLng[], options?: PlanOptions);
isReady(): boolean;
getWaypoints(): Waypoint[];
setWaypoints(waypoints: Waypoint[] | LatLng[]): any;
spliceWaypoints(index: number, waypointsToRemove: number, ...wayPoints: Waypoint[]): Waypoint[];
createGeocoders(): any;
}
interface PlanOptions {
geocoder?: any; // IGeocoder
addWaypoints?: boolean | undefined;
draggableWaypoints?: boolean | undefined;
dragStyles?: PathOptions[] | undefined;
maxGeocoderTolerance?: number | undefined;
geocoderPlaceholder?: ((waypointIndex: number, numberWaypoints: number) => string) | undefined;
geocodersClassName?: string | undefined;
geocoderClass?: ((waypointIndex: number, numberWaypoints: number) => void) | undefined;
waypointNameFallback?: ((latLng: LatLng) => string) | undefined;
createGeocoder?: ((waypointIndex: number, numberWaypoints: number, plan: Plan) => {}) | undefined;
addButtonClassName?: string | undefined;
createMarker?: ((waypointIndex: number, waypoint: Waypoint, numberWaypoints: number) => Marker) | undefined;
routeWhileDragging?: boolean | undefined;
reverseWaypoints?: boolean | undefined;
language?: string | undefined;
createGeocoderElement?: ((waypoint: Waypoint, waypointIndex: number, numberWaypoints: number, options: PlanOptions) => GeocoderElement) | undefined;
}
class Line extends LayerGroup {
constructor(route: IRoute, options?: LineOptions);
getBounds(): LatLngBounds;
}
interface LineOptions {
styles?: PathOptions[] | undefined;
missingRouteStyles?: PathOptions[] | undefined;
addWaypoints?: boolean | undefined;
extendToWaypoints: boolean;
missingRouteTolerance: number;
}
class OSRMv1 implements IRouter {
constructor(options?: OSRMOptions);
route(waypoints: Waypoint[], callback: (args?: any) => void, context?: {}, options?: RoutingOptions): void ;
buildRouteUrl(waypoints: Waypoint[], options: RoutingOptions): string;
requiresMoreDetail(route: { inputWaypoints: Waypoint, waypoints: Waypoint, properties?: any }, zoom: any, bounds: LatLng[]): boolean;
}
interface OSRMOptions {
serviceUrl?: string | undefined;
timeout?: number | undefined;
profile?: string | undefined;
polylinePrecision?: number | undefined;
useHints?: boolean | undefined;
routingOptions?: any;
suppressDemoServerWarning?: boolean | undefined;
language?: string | undefined;
requestParameters?: { [key: string]: any } | undefined;
stepToText?: ((step: any, leg: { legCount: number, legIndex: number }) => any) | undefined;
}
class Formatter {
constructor(options?: FormatterOptions);
formatDistance(d: number, precision?: number): string;
formatTime(t: number): string;
formatInstruction(instruction: IInstruction): string;
getIconName(instruction: IInstruction, index: number):
'depart' | 'via' | 'enter-roundabout' | 'arrive' | 'continue' | 'bear-right' | 'turn-right'
| 'sharp-right' | 'u-turn' | 'sharp-left' | 'turn-left' | 'bear-left';
capitalize(s: string): string;
}
interface FormatterOptions {
language?: string | undefined;
units?: 'metric' | 'imperial' | undefined;
roundingSensitivity?: number | undefined;
unitNames?: {} | undefined;
distanceTemplate: string;
}
class ItineraryBuilder {
constructor();
createContainer(className?: string): HTMLElement;
createStepsContainer(): HTMLElement;
createStep(text: string, distance: string, icon: string, steps: HTMLElement): void;
}
interface ItineraryBuilderOptions {
containerClassName: string;
}
class Localization {
constructor(langs: LocalizationOptions | LocalizationOptions[]);
localize(text: string | string[]): string;
}
interface LocalizationOptions {
directions: { N: string, NE: string, E: string, SE: string, S: string, SW: string, W: string, NW: string,
SlightRight: string, Right: string, SharpRight: string, SlightLeft: string, Left: string,
SharpLeft: string, Uturn: string };
instructions: { [key: string]: string[] | string };
formatOrder: (n: number | string) => string;
ui: { startPlaceholder: string, viaPlaceholder: string, endPlaceholder: string };
units: { meters: string, kilometers: string, yards: string, miles: string, hours: string, minutes: string, seconds: string };
}
class Waypoint {
constructor(latLng: LatLng, name: string, options: WaypointOptions);
latLng: LatLng;
name?: string | undefined;
options?: WaypointOptions | undefined;
}
interface WaypointOptions {
allowUTurn?: boolean | undefined;
}
class GeocoderElement {
constructor(wp: Waypoint, i: number, numberWaypoints: number, options: GeocoderElementOptions);
getContainer(): HTMLElement;
setValue(v: any): void;
update(force: any): void;
focus(): void;
}
interface GeocoderElementOptions {
createGeocoder?: ((i: number, nWps: number, options: GeocoderElementOptions) => any) | undefined;
geocoderPlaceholder?: ((i: number, numberWaypoints: number, geocoderElement: GeocoderElement) => string) | undefined;
geocoderClass?: (() => string) | undefined;
waypointNameFallback?: ((latLng: LatLng) => string) | undefined;
maxGeocoderTolerance?: number | undefined;
autocompleteOptions?: {} | undefined;
language?: string | undefined;
}
class ErrorControl extends L.Control {
constructor(routingControl: Control, options: ErrorControlOptions) ;
}
interface ErrorControlOptions {
header?: string | undefined;
formatMessage?: ((error: IError) => string) | undefined;
}
class AutoComplete {
constructor(element: HTMLElement, callback: any, context: any, options: AutoCompleteOptions) ;
close(): void;
}
interface AutoCompleteOptions {
timeout?: number | undefined;
blurTimeout?: number | undefined;
noResultsMessage?: string | undefined;
}
class MapBox extends OSRMv1 {
constructor(accessToken: string, options: OSRMOptions) ;
}
// Event Objects
interface RoutingEvent {
waypoints: Waypoint[];
}
interface RoutingResultEvent {
waypoints: Waypoint[];
routes: IRoute[];
}
interface RoutingErrorEvent {
error: IError;
}
interface RouteSelectedEvent {
route: IRoute;
}
interface WaypointsSplicedEvent {
index: number;
nRemoved: number;
added: Waypoint[];
}
interface LineTouchedEvent {
afterIndex: number;
latlng: number;
}
interface GeocodingEvent {
waypointIndex: number;
waypoint: Waypoint;
}
// Interfaces
interface RoutingOptions {
z: number;
allowUTurns: boolean;
geometryOnly: boolean;
fileFormat: string;
simplifyGeometry: boolean;
}
// tslint:disable-next-line interface-name
interface IRouter {
route(waypoints: Waypoint[], callback: (error?: IError, routes?: IRoute[]) => any, context?: {}, options?: RoutingOptions): void;
}
// tslint:disable-next-line interface-name
interface IRoute {
name?: string | undefined;
summary?: IRouteSummary | undefined;
coordinates?: LatLng[] | undefined;
waypoints?: LatLng[] | undefined;
instructions?: IInstruction[] | undefined;
}
// tslint:disable-next-line interface-name
interface IRouteSummary {
totalTime: number;
totalDistance: number;
}
// tslint:disable-next-line interface-name
interface IInstruction {
distance: number;
time: number;
text?: string | undefined;
type?: 'Straight' | 'SlightRight' | 'Right' | 'SharpRight' | 'TurnAround' | 'SharpLeft' | 'Left' | 'SlightLeft' | 'WaypointReached' |
'Roundabout' | 'StartAt' | 'DestinationReached' | 'EnterAgainstAllowedDirection' | 'LeaveAgainstAllowedDirection' | undefined;
road?: string | undefined;
direction?: string | undefined;
exit?: number | undefined;
}
// tslint:disable-next-line interface-name
interface IGeocoderElement {
container: HTMLElement;
input: HTMLElement;
closeButton: HTMLElement;
}
// tslint:disable-next-line interface-name
interface IError {
status: string | number;
message: string;
}
function control(options?: RoutingControlOptions): Control;
function itinerary(options?: ItineraryOptions): Itinerary;
function line(route: IRoute, options?: LineOptions): Line;
function plan(waypoints: Waypoint[] | LatLng[], options?: PlanOptions): Plan;
function waypoint(latLng: LatLng, name?: string, options?: WaypointOptions): Waypoint;
function osrmv1(options?: OSRMOptions): OSRMv1;
function localization(options?: LocalizationOptions): Localization;
function formatter(options?: FormatterOptions): Formatter;
function geocoderElement(waypoint: Waypoint, i: number, numberWaypoints: number, options: GeocoderElementOptions): GeocoderElement;
function itineraryBuilder(options?: ItineraryBuilderOptions): ItineraryBuilder;
function mapbox(accessToken: string, options: OSRMOptions): MapBox;
function errorControl(routingControl: Control, options: ErrorControlOptions): ErrorControl ;
function autocomplete(element: HTMLElement, callback: any, context: any, options: AutoCompleteOptions): AutoComplete;
}
namespace routing {
function control(options?: Routing.RoutingControlOptions): Routing.Control;
function itinerary(options?: Routing.ItineraryOptions): Routing.Itinerary;
function line(route: Routing.IRoute, options?: Routing.LineOptions): Routing.Line;
function plan(waypoints: Routing.Waypoint[] | LatLng[], options?: Routing.PlanOptions): Routing.Plan;
function waypoint(latLng: LatLng, name?: string, options?: Routing.WaypointOptions): Routing.Waypoint;
function osrmv1(options?: Routing.OSRMOptions): Routing.OSRMv1;
function localization(options?: Routing.LocalizationOptions): Routing.Localization;
function formatter(options?: Routing.FormatterOptions): Routing.Formatter;
function geocoderElement(waypoint: Routing.Waypoint, i: number, numberWaypoints: number, options: Routing.GeocoderElementOptions): Routing.GeocoderElement;
function itineraryBuilder(options?: Routing.ItineraryBuilderOptions): Routing.ItineraryBuilder;
function mapbox(accessToken: string, options: Routing.OSRMOptions): Routing.MapBox;
function errorControl(routingControl: Routing.Control, options: Routing.ErrorControlOptions): Routing.ErrorControl;
function autocomplete(element: HTMLElement, callback: any, context: any, options: Routing.AutoCompleteOptions): Routing.AutoComplete;
}
} | the_stack |
import { useState } from "react";
import { makeAutoObservable, observable, runInAction } from "mobx";
import dateAdd from "date-fns/add";
import { Rtm as RTMAPI, RTMessageType } from "../api-middleware/Rtm";
import { SmartPlayer, SmartPlayerEventType } from "../api-middleware/SmartPlayer";
import { globalStore } from "./GlobalStore";
import { RoomItem, roomStore } from "./room-store";
import { NODE_ENV } from "../constants/process";
import { useAutoRun } from "../utils/mobx";
import { RoomType } from "../api-middleware/flatServer/constants";
import { UserStore } from "./user-store";
import { RTMChannelMessage } from "./class-room-store";
export class ClassRoomReplayStore {
public readonly roomUUID: string;
public readonly userUUID: string;
public readonly rtm = new RTMAPI();
public readonly smartPlayer = new SmartPlayer();
public readonly users: UserStore;
/** RTM messages */
public messages = observable.array<RTMChannelMessage>([]);
public withRTCVideo = false;
public isReady = false;
public isPlaying = false;
public error?: Error;
/** All of the fetched messages */
private cachedMessages = observable.array<RTMChannelMessage>([]);
/** This ownerUUID is from url params matching which cannot be trusted */
private readonly ownerUUIDFromParams: string;
private readonly roomTypeFromParams: RoomType;
/** Player unix time */
private _currentPlayTime = -1;
/** The timestamp when seeking the first chunk of the current messages */
private _oldestSeekTime = -1;
private _isLoadingHistory = false;
/** The timestamp of the newest message on remote */
private _remoteNewestTimestamp = Infinity;
public constructor(config: { roomUUID: string; ownerUUID: string; roomType: RoomType }) {
if (!globalStore.userUUID) {
throw new Error("Missing userUUID");
}
this.roomUUID = config.roomUUID;
this.ownerUUIDFromParams = config.ownerUUID;
this.roomTypeFromParams = config.roomType;
this.userUUID = globalStore.userUUID;
this.users = new UserStore({
roomUUID: this.roomUUID,
ownerUUID: this.ownerUUID,
userUUID: this.userUUID,
});
makeAutoObservable<
this,
"_remoteNewestTimestamp" | "_isLoadingHistory" | "_currentPlayTime" | "_oldestSeekTime"
>(this, {
rtm: observable.ref,
smartPlayer: observable.ref,
_remoteNewestTimestamp: false,
_isLoadingHistory: false,
_currentPlayTime: false,
_oldestSeekTime: false,
});
this.smartPlayer.on(SmartPlayerEventType.Ready, () => {
this.updateReadyState(true);
this.updatePlayingState();
});
this.smartPlayer.on(SmartPlayerEventType.Play, this.updatePlayingState);
this.smartPlayer.on(SmartPlayerEventType.Pause, this.updatePlayingState);
this.smartPlayer.on(SmartPlayerEventType.Ended, this.updatePlayingState);
this.smartPlayer.on(SmartPlayerEventType.Error, this.updateError);
}
public get ownerUUID(): string {
if (this.roomInfo) {
if (NODE_ENV === "development") {
if (this.roomInfo.ownerUUID !== this.ownerUUIDFromParams) {
throw new Error("ClassRoom Error: ownerUUID mismatch!");
}
}
return this.roomInfo.ownerUUID;
}
return this.ownerUUIDFromParams;
}
public get roomInfo(): RoomItem | undefined {
return roomStore.rooms.get(this.roomUUID);
}
public get isCreator(): boolean {
return this.ownerUUID === this.userUUID;
}
public get roomType(): RoomType {
if (this.roomInfo?.roomType) {
if (NODE_ENV === "development") {
if (this.roomInfo.roomType !== this.roomTypeFromParams) {
throw new Error("ClassRoom Error: roomType mismatch!");
}
}
return this.roomInfo.roomType;
}
return this.roomTypeFromParams;
}
public init = async (
whiteboardEl: HTMLDivElement,
videoEl: HTMLVideoElement,
): Promise<void> => {
await roomStore.syncRecordInfo(this.roomUUID);
if (!globalStore.whiteboardRoomUUID || !globalStore.whiteboardRoomToken) {
throw new Error("Missing Whiteboard UUID and Token");
}
try {
await this.smartPlayer.load({
roomUUID: this.roomUUID,
isCreator: this.isCreator,
whiteboardUUID: globalStore.whiteboardRoomUUID,
whiteboardRoomToken: globalStore.whiteboardRoomToken,
region: globalStore.region ?? undefined,
whiteboardEl,
videoEl,
recording:
(this.roomInfo?.recordings?.length as number) > 0
? this.roomInfo?.recordings?.[0]
: void 0,
});
} catch (error) {
console.error(error);
this.updateError(error as Error);
}
runInAction(() => {
this.isReady = this.smartPlayer.isReady;
this.isPlaying = this.smartPlayer.isPlaying;
this.withRTCVideo = Boolean(this.smartPlayer.combinePlayer);
});
this.smartPlayer.whiteboardPlayer?.callbacks.on(
"onProgressTimeChanged",
this.onPlayerProgressTimeChanged,
);
await this.rtm.init(this.userUUID, this.roomUUID);
};
public destroy = (): void => {
this.smartPlayer.destroy();
this.smartPlayer.removeAllListeners();
void this.rtm.destroy();
this.smartPlayer.whiteboardPlayer?.callbacks.off(
"onProgressTimeChanged",
this.onPlayerProgressTimeChanged,
);
};
public togglePlayPause = (): void => {
if (!this.smartPlayer.isReady) {
return;
}
if (this.smartPlayer.isPlaying) {
this.smartPlayer.pause();
} else {
if (this.smartPlayer.isEnded) {
this.smartPlayer.seek(0);
}
this.smartPlayer.play();
}
};
/** Sync messages according to replay player time */
private syncMessages = async (): Promise<void> => {
if (this._isLoadingHistory) {
return;
}
if (this.cachedMessages.length <= 0) {
// cache the timestamp from this
const newestTimestamp = this._currentPlayTime;
const newMessages = await this.getHistory(newestTimestamp - 1);
if (newMessages.length <= 0) {
return;
}
this._oldestSeekTime = newestTimestamp;
runInAction(() => {
this.cachedMessages.replace(newMessages);
});
return this.syncMessages();
}
if (this._currentPlayTime < this._oldestSeekTime) {
// user seeked backward
// start over
runInAction(() => {
this.messages.clear();
this.cachedMessages.clear();
});
return this.syncMessages();
}
if (
this.messages.length > 0 &&
this._currentPlayTime < this.messages[this.messages.length - 1].timestamp
) {
// user seeked backward but still within total loaded messages range.
// reset rendered messages
runInAction(() => {
this.messages.clear();
});
return this.syncMessages();
}
let start = this.messages.length;
while (
start < this.cachedMessages.length &&
this._currentPlayTime >= this.cachedMessages[start].timestamp
) {
start += 1;
}
if (start === this.messages.length) {
// no new messages
return;
}
if (start >= this.cachedMessages.length) {
// more messages need to be loaded
const newMessages = await this.getHistory(
this.cachedMessages[this.cachedMessages.length - 1].timestamp,
);
if (newMessages.length > 0) {
runInAction(() => {
this.cachedMessages.push(...newMessages);
});
return this.syncMessages();
}
}
runInAction(() => {
this.messages.push(...this.cachedMessages.slice(this.messages.length, start));
});
};
private getHistory = async (newestTimestamp: number): Promise<RTMChannelMessage[]> => {
let histories: RTMChannelMessage[] = [];
if (newestTimestamp >= this._remoteNewestTimestamp) {
return histories;
}
this._isLoadingHistory = true;
try {
const messages = await this.rtm.fetchTextHistory(
newestTimestamp + 1,
dateAdd(newestTimestamp, { years: 1 }).valueOf(),
);
if (messages.length <= 0) {
this._remoteNewestTimestamp = newestTimestamp;
}
histories = messages.filter(
(message): message is RTMChannelMessage =>
message.type === RTMessageType.ChannelMessage,
);
// fetch user name first to avoid flashing
await this.users
.syncExtraUsersInfo(histories.map(msg => msg.userUUID))
.catch(console.warn); // swallow error
} catch (e) {
console.warn(e);
}
this._isLoadingHistory = false;
return histories;
};
private onPlayerProgressTimeChanged = (offset: number): void => {
// always keep the latest current time
this._currentPlayTime = this.smartPlayer.whiteboardPlayer!.beginTimestamp + offset;
void this.syncMessages();
};
private updateReadyState = (ready: boolean): void => {
this.isReady = ready;
};
private updatePlayingState = (): void => {
this.isPlaying = this.smartPlayer.isPlaying;
};
private updateError = (error: Error): void => {
this.error = error;
};
}
export function useClassRoomReplayStore(
roomUUID: string,
ownerUUID: string,
roomType: RoomType,
): ClassRoomReplayStore {
const [classRoomReplayStore] = useState(
() => new ClassRoomReplayStore({ roomUUID, ownerUUID, roomType }),
);
useAutoRun(() => {
const title = classRoomReplayStore.roomInfo?.title;
if (title) {
document.title = title;
}
});
return classRoomReplayStore;
} | the_stack |
import Point from '../point/Point';
import Rectangle from '../rectangle/Rectangle';
/**
* An Ellipse object.
*
* This is a geometry object, containing numerical values and related methods to inspect and modify them.
* It is not a Game Object, in that you cannot add it to the display list, and it has no texture.
* To render an Ellipse you should look at the capabilities of the Graphics class.
*/
declare class Ellipse {
/**
*
* @param x The x position of the center of the ellipse. Default 0.
* @param y The y position of the center of the ellipse. Default 0.
* @param width The width of the ellipse. Default 0.
* @param height The height of the ellipse. Default 0.
*/
constructor(x?: number, y?: number, width?: number, height?: number);
/**
* Calculates the area of the Ellipse.
* @param ellipse The Ellipse to get the area of.
*/
static Area(ellipse: Ellipse): number;
/**
* Returns the circumference of the given Ellipse.
* @param ellipse The Ellipse to get the circumference of.
*/
static Circumference(ellipse: Ellipse): number;
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Ellipse based on the given angle.
* @param ellipse The Ellipse to get the circumference point on.
* @param angle The angle from the center of the Ellipse to the circumference to return the point from. Given in radians.
* @param out A Point, or point-like object, to store the results in. If not given a Point will be created.
*/
static CircumferencePoint<O extends Point>(ellipse: Ellipse, angle: number, out?: O): O;
/**
* Creates a new Ellipse instance based on the values contained in the given source.
* @param source The Ellipse to be cloned. Can be an instance of an Ellipse or a ellipse-like object, with x, y, width and height properties.
*/
static Clone(source: Ellipse): Ellipse;
/**
* Check to see if the Ellipse contains the given x / y coordinates.
* @param ellipse The Ellipse to check.
* @param x The x coordinate to check within the ellipse.
* @param y The y coordinate to check within the ellipse.
*/
static Contains(ellipse: Ellipse, x: number, y: number): boolean;
/**
* Check to see if the Ellipse contains the given Point object.
* @param ellipse The Ellipse to check.
* @param point The Point object to check if it's within the Circle or not.
*/
static ContainsPoint(ellipse: Ellipse, point: Point | object): boolean;
/**
* Check to see if the Ellipse contains all four points of the given Rectangle object.
* @param ellipse The Ellipse to check.
* @param rect The Rectangle object to check if it's within the Ellipse or not.
*/
static ContainsRect(ellipse: Ellipse, rect: Rectangle | object): boolean;
/**
* Copies the `x`, `y`, `width` and `height` properties from the `source` Ellipse
* into the given `dest` Ellipse, then returns the `dest` Ellipse.
* @param source The source Ellipse to copy the values from.
* @param dest The destination Ellipse to copy the values to.
*/
static CopyFrom<O extends Ellipse>(source: Ellipse, dest: O): O;
/**
* The geometry constant type of this object: `GEOM_CONST.ELLIPSE`.
* Used for fast type comparisons.
*/
readonly type: number;
/**
* The x position of the center of the ellipse.
*/
x: number;
/**
* The y position of the center of the ellipse.
*/
y: number;
/**
* The width of the ellipse.
*/
width: number;
/**
* The height of the ellipse.
*/
height: number;
/**
* Check to see if the Ellipse contains the given x / y coordinates.
* @param x The x coordinate to check within the ellipse.
* @param y The y coordinate to check within the ellipse.
*/
contains(x: number, y: number): boolean;
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Ellipse
* based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give the point
* at 180 degrees around the circle.
* @param position A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 around the ellipse.
* @param out An object to store the return values in. If not given a Point object will be created.
*/
getPoint<O extends Point>(position: number, out?: O): O;
/**
* Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse,
* based on the given quantity or stepRate values.
* @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead.
* @param stepRate Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate.
* @param output An array to insert the points in to. If not provided a new array will be created.
*/
getPoints<O extends Point[]>(quantity: number, stepRate?: number, output?: O): O;
/**
* Returns a uniformly distributed random point from anywhere within the given Ellipse.
* @param point A Point or point-like object to set the random `x` and `y` values in.
*/
getRandomPoint<O extends Point>(point?: O): O;
/**
* Sets the x, y, width and height of this ellipse.
* @param x The x position of the center of the ellipse.
* @param y The y position of the center of the ellipse.
* @param width The width of the ellipse.
* @param height The height of the ellipse.
*/
setTo(x: number, y: number, width: number, height: number): this;
/**
* Sets this Ellipse to be empty with a width and height of zero.
* Does not change its position.
*/
setEmpty(): this;
/**
* Sets the position of this Ellipse.
* @param x The x position of the center of the ellipse.
* @param y The y position of the center of the ellipse.
*/
setPosition(x: number, y: number): this;
/**
* Sets the size of this Ellipse.
* Does not change its position.
* @param width The width of the ellipse.
* @param height The height of the ellipse. Default width.
*/
setSize(width: number, height?: number): this;
/**
* Checks to see if the Ellipse is empty: has a width or height equal to zero.
*/
isEmpty(): boolean;
/**
* Returns the minor radius of the ellipse. Also known as the Semi Minor Axis.
*/
getMinorRadius(): number;
/**
* Returns the major radius of the ellipse. Also known as the Semi Major Axis.
*/
getMajorRadius(): number;
/**
* The left position of the Ellipse.
*/
left: number;
/**
* The right position of the Ellipse.
*/
right: number;
/**
* The top position of the Ellipse.
*/
top: number;
/**
* The bottom position of the Ellipse.
*/
bottom: number;
/**
* Compares the `x`, `y`, `width` and `height` properties of the two given Ellipses.
* Returns `true` if they all match, otherwise returns `false`.
* @param ellipse The first Ellipse to compare.
* @param toCompare The second Ellipse to compare.
*/
static Equals(ellipse: Ellipse, toCompare: Ellipse): boolean;
/**
* Returns the bounds of the Ellipse object.
* @param ellipse The Ellipse to get the bounds from.
* @param out A Rectangle, or rectangle-like object, to store the ellipse bounds in. If not given a new Rectangle will be created.
*/
static GetBounds<O extends Rectangle>(ellipse: Ellipse, out?: O): O;
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Ellipse
* based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give the point
* at 180 degrees around the circle.
* @param ellipse The Ellipse to get the circumference point on.
* @param position A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 around the ellipse.
* @param out An object to store the return values in. If not given a Point object will be created.
*/
static GetPoint<O extends Point>(ellipse: Ellipse, position: number, out?: O): O;
/**
* Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse,
* based on the given quantity or stepRate values.
* @param ellipse The Ellipse to get the points from.
* @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead.
* @param stepRate Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate.
* @param out An array to insert the points in to. If not provided a new array will be created.
*/
static GetPoints<O extends Point[]>(ellipse: Ellipse, quantity: number, stepRate?: number, out?: O): O;
/**
* Offsets the Ellipse by the values given.
* @param ellipse The Ellipse to be offset (translated.)
* @param x The amount to horizontally offset the Ellipse by.
* @param y The amount to vertically offset the Ellipse by.
*/
static Offset<O extends Ellipse>(ellipse: O, x: number, y: number): O;
/**
* Offsets the Ellipse by the values given in the `x` and `y` properties of the Point object.
* @param ellipse The Ellipse to be offset (translated.)
* @param point The Point object containing the values to offset the Ellipse by.
*/
static OffsetPoint<O extends Ellipse>(ellipse: O, point: Point | object): O;
/**
* Returns a uniformly distributed random point from anywhere within the given Ellipse.
* @param ellipse The Ellipse to get a random point from.
* @param out A Point or point-like object to set the random `x` and `y` values in.
*/
static Random<O extends Point>(ellipse: Ellipse, out?: O): O;
}
export default Ellipse; | the_stack |
import React from 'react';
import { mount } from './util/wrapper';
import KeyCode from 'rc-util/lib/KeyCode';
import InputNumber from '../src';
describe('InputNumber.Props', () => {
it('max', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber max={10} onChange={onChange} />);
for (let i = 0; i < 100; i += 1) {
wrapper.find('.rc-input-number-handler-up').simulate('mouseDown');
}
expect(onChange.mock.calls[onChange.mock.calls.length - 1][0]).toEqual(10);
expect(wrapper.find('input').props()).toEqual(expect.objectContaining({
'aria-valuemax': 10,
'aria-valuenow': '10',
}));
});
it('min', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber min={-10} onChange={onChange} />);
for (let i = 0; i < 100; i += 1) {
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
}
expect(onChange.mock.calls[onChange.mock.calls.length - 1][0]).toEqual(-10);
expect(wrapper.find('input').props()).toEqual(expect.objectContaining({
'aria-valuemin': -10,
'aria-valuenow': '-10',
}));
});
it('disabled', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber onChange={onChange} disabled />);
wrapper.find('.rc-input-number-handler-up').simulate('mouseDown');
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
expect(wrapper.exists('.rc-input-number-disabled')).toBeTruthy();
expect(onChange).not.toHaveBeenCalled();
});
it('readOnly', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber onChange={onChange} readOnly />);
wrapper.find('.rc-input-number-handler-up').simulate('mouseDown');
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
wrapper.findInput().simulate('keyDown', { which: KeyCode.UP });
wrapper.findInput().simulate('keyDown', { which: KeyCode.DOWN });
expect(wrapper.exists('.rc-input-number-readonly')).toBeTruthy();
expect(onChange).not.toHaveBeenCalled();
});
it('autofocus', () => {
const wrapper = mount(<InputNumber autoFocus />);
expect(wrapper.findInput().props().autoFocus).toBeTruthy();
});
describe('step', () => {
it('basic', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber onChange={onChange} step={5} />);
for (let i = 0; i < 3; i += 1) {
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
expect(onChange).toHaveBeenCalledWith(-5 * (i + 1));
}
expect(wrapper.find('input').props().step).toEqual(5);
});
it('stringMode', () => {
const onChange = jest.fn();
const wrapper = mount(
<InputNumber
stringMode
onChange={onChange}
step="0.000000001"
defaultValue="0.000000001"
/>,
);
for (let i = 0; i < 11; i += 1) {
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
}
expect(onChange).toHaveBeenCalledWith('-0.00000001');
});
it('decimal', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber onChange={onChange} step={0.1} defaultValue={0.9} />);
for (let i = 0; i < 3; i += 1) {
wrapper.find('.rc-input-number-handler-up').simulate('mouseDown');
}
expect(onChange).toHaveBeenCalledWith(1.2);
});
});
describe('controlled', () => {
it('restore when blur input', () => {
const wrapper = mount(<InputNumber value={9} />);
wrapper.focusInput();
wrapper.changeValue('3');
expect(wrapper.getInputValue()).toEqual('3');
wrapper.blurInput();
expect(wrapper.getInputValue()).toEqual('9');
});
it('dynamic change value', () => {
const wrapper = mount(<InputNumber value={9} />);
wrapper.setProps({ value: '3' });
wrapper.update();
expect(wrapper.getInputValue()).toEqual('3');
});
// Origin https://github.com/ant-design/ant-design/issues/7334
// zombieJ: We should error this instead of auto change back to a normal value since it makes un-controlled
it('show limited value when input is not focused', () => {
const Demo = () => {
const [value, setValue] = React.useState<string | number>(2);
return (
<div>
<button
type="button"
onClick={() => {
setValue('103aa');
}}
>
change value
</button>
<InputNumber min={1} max={10} value={value} />
</div>
);
};
const wrapper = mount(<Demo />);
expect(wrapper.getInputValue()).toEqual('2');
wrapper.find('button').simulate('click');
expect(wrapper.getInputValue()).toEqual('103aa');
expect(wrapper.exists('.rc-input-number-not-a-number')).toBeTruthy();
});
// https://github.com/ant-design/ant-design/issues/7358
it('controlled component should accept undefined value', () => {
const Demo = () => {
const [value, setValue] = React.useState<string | number>(2);
return (
<div>
<button
type="button"
onClick={() => {
setValue(undefined);
}}
>
change value
</button>
<InputNumber min={1} max={10} value={value} />
</div>
);
};
const wrapper = mount(<Demo />);
expect(wrapper.getInputValue()).toEqual('2');
wrapper.find('button').simulate('click');
expect(wrapper.getInputValue()).toEqual('');
});
});
describe('defaultValue', () => {
it('default value should be empty', () => {
const wrapper = mount(<InputNumber />);
expect(wrapper.getInputValue()).toEqual('');
});
it('default value should be empty when step is decimal', () => {
const wrapper = mount(<InputNumber step={0.1} />);
expect(wrapper.getInputValue()).toEqual('');
});
it('default value should be 1', () => {
const wrapper = mount(<InputNumber defaultValue={1} />);
expect(wrapper.getInputValue()).toEqual('1');
});
it('default value could be null', () => {
const wrapper = mount(<InputNumber defaultValue={null} />);
expect(wrapper.getInputValue()).toEqual('');
});
it('warning when defaultValue higher than max', () => {
const wrapper = mount(<InputNumber min={0} max={10} defaultValue={13} />);
expect(wrapper.getInputValue()).toEqual('13');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeTruthy();
});
it('warning when defaultValue lower than min', () => {
const wrapper = mount(<InputNumber min={0} max={10} defaultValue={-1} />);
expect(wrapper.getInputValue()).toEqual('-1');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeTruthy();
});
it('default value can be a string greater than 16 characters', () => {
const wrapper = mount(<InputNumber max={10} defaultValue="-3.637978807091713e-12" />);
expect(wrapper.getInputValue()).toEqual('-0.000000000003637978807091713');
});
it('invalidate defaultValue', () => {
const wrapper = mount(<InputNumber defaultValue="light" />);
expect(wrapper.getInputValue()).toEqual('light');
});
});
describe('value', () => {
it("value shouldn't higher than max", () => {
const wrapper = mount(<InputNumber min={0} max={10} value={13} />);
expect(wrapper.getInputValue()).toEqual('13');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeTruthy();
});
it("value shouldn't lower than min", () => {
const wrapper = mount(<InputNumber min={0} max={10} value={-1} />);
expect(wrapper.getInputValue()).toEqual('-1');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeTruthy();
});
it('value can be a string greater than 16 characters', () => {
const wrapper = mount(<InputNumber max={10} value="-3.637978807091713e-12" />);
expect(wrapper.getInputValue()).toEqual('-0.000000000003637978807091713');
});
it('value decimal over six decimal not be scientific notation', () => {
const onChange = jest.fn();
const wrapper = mount(<InputNumber precision={7} step={0.0000001} onChange={onChange} />);
for (let i = 1; i <= 9; i += 1) {
wrapper.find('.rc-input-number-handler-up').simulate('mouseDown');
expect(wrapper.getInputValue()).toEqual(`0.000000${i}`);
expect(onChange).toHaveBeenCalledWith(0.0000001 * i);
}
for (let i = 8; i >= 1; i -= 1) {
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
expect(wrapper.getInputValue()).toEqual(`0.000000${i}`);
expect(onChange).toHaveBeenCalledWith(0.0000001 * i);
}
wrapper.find('.rc-input-number-handler-down').simulate('mouseDown');
expect(wrapper.getInputValue()).toEqual(`0.0000000`);
expect(onChange).toHaveBeenCalledWith(0);
});
it('value can be changed when dynamic setting max', () => {
const wrapper = mount(<InputNumber value={11} max={10} />);
// Origin logic shows `10` as `max`. But it breaks form logic.
expect(wrapper.getInputValue()).toEqual('11');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeTruthy();
wrapper.setProps({ max: 20 });
wrapper.update();
expect(wrapper.getInputValue()).toEqual('11');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeFalsy();
});
it('value can be changed when dynamic setting min', () => {
const wrapper = mount(<InputNumber value={9} min={10} />);
// Origin logic shows `10` as `max`. But it breaks form logic.
expect(wrapper.getInputValue()).toEqual('9');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeTruthy();
wrapper.setProps({ min: 0 });
wrapper.update();
expect(wrapper.getInputValue()).toEqual('9');
expect(wrapper.exists('.rc-input-number-out-of-range')).toBeFalsy();
});
it('value can override given defaultValue', () => {
const wrapper = mount(<InputNumber value={2} defaultValue={1} />);
expect(wrapper.getInputValue()).toEqual('2');
});
});
describe(`required prop`, () => {
it(`should add required attr to the input tag when get passed as true`, () => {
const wrapper = mount(<InputNumber required />);
expect(wrapper.findInput().props().required).toBeTruthy();
});
it(`should not add required attr to the input as default props when not being supplied`, () => {
const wrapper = mount(<InputNumber />);
expect(wrapper.findInput().props().required).toBeFalsy();
});
it(`should not add required attr to the input tag when get passed as false`, () => {
const wrapper = mount(<InputNumber required={false} />);
expect(wrapper.findInput().props().required).toBeFalsy();
});
});
describe('Pattern prop', () => {
it(`should render with a pattern attribute if the pattern prop is supplied`, () => {
const wrapper = mount(<InputNumber pattern="\d*" />);
expect(wrapper.findInput().props().pattern).toEqual('\\d*');
});
it(`should render with no pattern attribute if the pattern prop is not supplied`, () => {
const wrapper = mount(<InputNumber />);
expect(wrapper.findInput().props().pattern).toBeFalsy();
});
});
describe('onPaste props', () => {
it('passes onPaste event handler', () => {
const onPaste = jest.fn();
const wrapper = mount(<InputNumber value={1} onPaste={onPaste} />);
wrapper.findInput().simulate('paste');
expect(onPaste).toHaveBeenCalled();
});
});
describe('aria and data props', () => {
it('passes data-* attributes', () => {
const wrapper = mount(<InputNumber value={1} data-test="test-id" data-id="12345" />);
expect(wrapper.findInput().props()).toEqual(
expect.objectContaining({
'data-test': 'test-id',
'data-id': '12345',
}),
);
});
it('passes aria-* attributes', () => {
const wrapper = mount(
<InputNumber value={1} aria-labelledby="test-id" aria-label="some-label" />,
);
expect(wrapper.findInput().props()).toEqual(
expect.objectContaining({
'aria-labelledby': 'test-id',
'aria-label': 'some-label',
}),
);
});
it('passes role attribute', () => {
const wrapper = mount(<InputNumber value={1} role="searchbox" />);
expect(wrapper.findInput().props()).toEqual(
expect.objectContaining({
role: 'searchbox',
}),
);
});
});
}); | the_stack |
// layui方法和属性
function B_method() {
window.lay().find;
window.layer.v;
window.layui.v;
layui['layui.all'];
layui.v;
$.ajax;
// layui.modules['all'];
// layui.modules['notExists'];
// layui.define
layui.define(['layer', 'form'], exports => {
const layer = layui.layer;
const form = layui.form;
layer.msg('Hello World');
exports('index', {}); // 注意,这里是模块输出的核心,模块名必须和 use 时的模块名一致
});
layui.define(exports => {
// 从 layui 2.6 开始,如果你引入的是构建后的 layui.js,里面即包含了 layui 所有的内置模块,无需再指定内置模块。如
// 需确保您的 layui.js 是引入的构建后的版本(即官网下载或 git 平台的发行版)
// 直接可得到各种内置模块
const layer = layui.layer;
const form = layui.form;
const table = layui.table;
// …
layer.msg('Hello World');
exports('index', {}); // 注意,这里是模块输出的核心,模块名必须和 use 时的模块名一致
});
layui.define(['layer', 'laypage', 'mod1'], exports => {
// 此处 mod1 为你的任意扩展模块
// do something
exports('demo', {
msg: 'Hello Demo',
});
});
// layui 模块的使用
layui.use(['mod1', 'mod2'], args => {
// 缺陷1:没法给namespace添加数组支持
// layui["a"];
// ……
});
// 引用指定模块
layui.use(['layer', 'laydate'], () => {
// console.log(this.$);
const layer = layui.layer;
const laydate = layui.laydate;
// do something
});
// 引用所有模块(layui 2.6 开始支持)
layui.use(() => {
// console.log(this.carousel);
const layer = layui.layer;
const laydate = layui.laydate;
const table = layui.table;
// …
// do something
});
// 通过回调的参数得到模块对象
layui.use(['layer', 'laydate', 'table'], (layer: Layui.Layer, laydate, table) => {
// console.log(this.carousel);
// 使用 layer
layer.msg('test');
// 使用 laydate
laydate.render({});
// 使用 table
table.render({});
});
layui
.config({
base: '/res/js/modules/', // 你的扩展模块所在目录
})
.use(() => {}); // 这里的 main 模块包含了 mod1、mod2、mod3 等等扩展模块
layui.config({
dir: '/res/layui/', // layui.js 所在目录(如果是 script 单独引入 layui.js,无需设定该参数)一般可无视
version: false, // 一般用于更新模块缓存,默认不开启。设为 true 即让浏览器不缓存。也可以设为一个固定的值,如:201610
debug: false, // 用于开启调试模式,默认 false,如果设为 true,则JS模块的节点会保留在页面
base: '', // 设定扩展的 layui 模块的所在目录,一般用于外部模块扩展
});
layui.use(['layer', 'form'], () => {
const layer = layui.layer;
const form = layui.form;
layer.msg('Hello World');
});
layui.use(() => {});
layui.link('a.js');
layui.link('a.js', alert);
layui.link('a.js', alert, 'cc');
layui.config({ debug: true });
// 【增】:向 test 表插入一个 nickname 字段,如果该表不存在,则自动建立。
layui.data('test', {
key: 'nickname',
value: '贤心',
});
// 【删】:删除 test 表的 nickname 字段
layui.data('test', {
key: 'nickname',
remove: true,
});
layui.data('test', null); // 删除test表
// 【改】:同【增】,会覆盖已经存储的数据
// 【查】:向 test 表读取全部的数据
let localTest = layui.data('test');
layui.data('test');
console.log(localTest.nickname); // 获得“贤心”
const device = layui.device();
device.os === 'Windows';
device.android;
layui.device('android');
layui.device('myflag');
layui.device().myflag;
layui.device()['myflag'];
layui.device('os');
// 其他底层方法
layui['cache'];
layui.cache.base;
// layui.cache.builtin['all'];
// layui.cache.callback.colorpicker;
// layui.cache.callback['notExists'];
layui.cache.dir;
layui.cache.event;
layui.cache.event['carousel.change'];
layui.cache.event['element.tab:'];
layui.cache.event['form.select'];
layui.cache.event['carousel.change']['site-top-carousel'][0].call;
layui.cache.host;
layui.cache.modules['global'];
layui.cache.modules.global;
layui.cache.status.colorpicker;
layui.cache.status['notExists'];
layui.cache.timeout;
layui.cache.version;
// config的设置是全局的
layui
.config({
base: '/res/js/', // 假设这是你存放拓展模块的根目录
})
.extend({
// 设定模块别名
mymod: 'mymod', // 如果 mymod.js 是在根目录,也可以不用设定别名
mod1: 'admin/mod1', // 相对于上述 base 目录的子目录
});
// 你也可以忽略 base 设定的根目录,直接在 extend 指定路径(主要:该功能为 layui 2.2.0 新增)
layui.extend({
mod2: '{/}http://cdn.xxx.com/lib/mod2', // {/}的意思即代表采用自有路径,即不跟随 base 路径
});
layui.extend({ test: '/res/js/test' });
// 使用拓展模块
layui.use(['mymod', 'mod1'], () => {
// let mymod = layui.mymod;
// mymod.hello('World!'); // 弹出 Hello World!
});
layui.each({ a: 1 }, (k, v) => {
console.log(k + v);
});
layui.each(['a', 'b'], (k, v) => {
console.log(k + v);
});
layui._typeof('');
layui._typeof([]);
layui._typeof(() => 1);
layui._isArray([]);
layui.getStyle(document.forms[0], 'font-size');
layui.getStyle(document.getElementById('test'), 'font-size');
layui.img('');
layui.img('', () => 1);
layui.img(
'',
img => {
img.sizes;
},
e => {},
);
layui.router(location.hash);
layui.router().href == null;
layui.router().path[0];
layui.router().search['m'];
layui.router().search.constructor;
// 【增】:向 test 表插入一个 nickname 字段,如果该表不存在,则自动建立。
layui.sessionData('test', {
key: 'nickname',
value: '贤心',
});
// 【删】:删除 test 表的 nickname 字段
layui.sessionData('test', {
key: 'nickname',
remove: true,
});
layui.sessionData('test', null); // 删除test表
// 【改】:同【增】,会覆盖已经存储的数据
// 【查】:向 test 表读取全部的数据
localTest = layui.sessionData('test');
layui.sessionData('test');
console.log(localTest.nickname); // 获得“贤心”
layui.sort([{ a: 3 }, { a: 1 }, { a: 5 }], 'a');
layui.sort([1, 2, 3, 4], 'a');
window.document.onkeydown = e => {
console.log(e);
layui.stope(e);
};
layui.url().hash.href;
layui.url('').hash.href;
layui.url().pathname[0];
layui.hint().error('出错啦');
layui.hint().error(null, 'log');
layui.on('select(*)', 'form').v;
layui.on('select(*)', 'form', console.log)();
layui.onevent('form', 'select(*)').v === '';
const x = layui.onevent('form', 'select(*)', console.log);
let y = layui.event('form', 'select(abc)', 2);
y = layui.event('form', 'select(abc)', [1, 2, 3]);
layui.off('select(filter)', 'form');
const factoryCallback = layui.factory('form');
if (factoryCallback) {
factoryCallback();
}
}
// ---------------------------- 组件测试----------
function carousel() {
layui.use('carousel', () => {
const carousel = layui.carousel;
carousel.config['a'];
carousel.config.nothing;
// 建造实例
carousel.render({
elem: '#test1',
width: '100%', // 设置容器宽度
arrow: 'always', // 始终显示箭头
anim: 'updown', // 切换动画方式
});
carousel.reload({
elem: '#test1',
width: '100%', // 设置容器宽度
arrow: 'always', // 始终显示箭头
anim: 'updown', // 切换动画方式
});
carousel.on('change(test1)', obj => {
// test1来源于对应HTML容器的 lay-filter="test1" 属性值
// this.config.width;
// this.elemItem;
// this.render();
// this.reload({});
// this.prevIndex() == 1;
// this.nextIndex() == 2;
// this.addIndex(1);
// this.events();
console.log(obj.index); // 当前条目的索引
console.log(obj.prevIndex); // 上一个条目的索引
console.log(obj.item); // 当前条目的元素对象
obj.item.length;
});
carousel.set({ autoplay: true });
});
}
function code() {
layui.use('code', () => {
// 加载code模块
layui.code(); // 引用code方法
layui.code({
title: 'NotePad++的风格',
skin: 'notepad', // 如果要默认风格,不用设定该key。
});
});
}
function colorpicker() {
layui.use('colorpicker', () => {
const colorpicker = layui.colorpicker;
// 渲染
colorpicker.render({
elem: '#test1',
predefine: true,
colors: ['#F00', '#0F0', '#00F', 'rgb(255, 69, 0)', 'rgba(255, 69, 0, 0.5)'],
});
colorpicker.render({
elem: '#test1',
change: color => {
console.log(color);
},
});
colorpicker.render({
elem: '#test1',
done: color => {
// this.format;
// this.change;
console.log(color);
// 譬如你可以在回调中把得到的 color 赋值给表单
},
});
colorpicker.index === 0;
colorpicker.set({
elem: '#test1',
predefine: true,
colors: ['#F00', '#0F0', '#00F', 'rgb(255, 69, 0)', 'rgba(255, 69, 0, 0.5)'],
});
colorpicker.on('confirm', a => {
console.log(a + ',');
});
layui.event('colorpicker', 'confirm', [1, 2]);
});
}
function dropdown() {
layui.use('dropdown', () => {
const dropdown = layui.dropdown;
const ret = dropdown.render({
elem: '#demo1', // 可绑定在任意元素中,此处以上述按钮为例
data: [
{
title: 'menu item 1',
id: 100,
href: '#',
},
{
title: 'menu item 2',
id: 101,
href: 'https:// www.layui.com/', // 开启超链接
target: '_blank', // 新窗口方式打开
},
{ type: '-' },
{
title: 'menu item 3',
id: 102,
type: 'group', // 菜单类型,支持:normal/group/parent/-
child: [
{
title: 'menu item 3-1',
id: 103,
},
{
title: 'menu item 3-2',
id: 104,
child: [
{
title: 'menu item 3-2-1',
id: 105,
},
{
title: 'menu item 3-2-2',
id: 106,
},
],
},
{
title: 'menu item 3-3',
id: 107,
},
],
},
{ type: '-' },
{
title: 'menu item 4',
id: 108,
},
{
title: 'menu item 5',
id: 109,
child: [
{
title: 'menu item 5-1',
id: 11111,
child: [
{
title: 'menu item 5-1-1',
id: 2111,
},
{
title: 'menu item 5-1-2',
id: 3111,
},
],
},
{
title: 'menu item 5-2',
id: 52,
},
],
},
{ type: '-' },
{
title: 'menu item 6',
id: 6,
type: 'group',
isSpreadItem: false,
child: [
{
title: 'menu item 6-1',
id: 61,
},
{
title: 'menu item 6-2',
id: 62,
},
],
},
],
id: 'demo1',
// 菜单被点击的事件
click: (data, othis) => {
console.log(data); // 得到当前所点击的菜单项对应的数据
console.log(othis); // 得到当前所点击的菜单项 DOM 对象
// console.log(this.elem); // 得到当前组件绑定的原始 DOM 对象,批量绑定中常用。
},
ready: (elemPanel, elem) => {
console.log(elemPanel[0]); // 得到组件面板的 DOM 对象
console.log(elem.hide()); // 得到基础参数 elem 所绑定的元素 DOM 对象
},
});
ret.reload({ elem: '' });
ret.config.data[0].child;
ret.config.data[0].notExists;
const c = layui.dropdown.reload('demo1', {
data: [
{
title: 'abc',
id: 100,
href: '#',
},
],
});
c.config.data;
c.reload;
function cb(this: HTMLElement, obj: any): any {
console.log(this.title);
console.log(obj.nothing);
}
layui.dropdown.on('click(id)', cb);
});
}
function elementTest() {
layui.use('element', () => {
const element = layui.element;
element.config['notExists'];
// 一些事件监听
element.on('tab(demo)', data => {
console.log(data);
});
element.tabDelete('demo', 'xxx'); // 删除 lay-id="xxx" 的这一项
element.tabAdd('demo', {
title: '选项卡的标题',
content: '选项卡的内容', // 支持传入html
id: '选项卡标题的lay-id属性值',
});
element.tabAdd('demo', {});
element.tabChange('demo', 'layid');
element.tab({
headerElem: '#tabHeader>li', // 指定tab头元素项
bodyElem: '#tabBody>.xxx', // 指定tab主体元素项
});
element.tab({
headerElem: $(), // 指定tab头元素项
bodyElem: document.body, // 指定tab主体元素项
});
element.progress('demo', '30%');
element.init(); // 更新全部 2.1.6 可用 element.render() 方法替代
element.render('nav'); // 重新对导航进行渲染。注:layui 2.1.6 版本新增
element.render('nav', 'test1'); // 对 lay-filter="test1" 所在导航重新渲染。注:layui 2.1.6 版本新增
element.on('tab(filter)', data => {
// console.log(this); // 当前Tab标题所在的原始DOM元素
console.log(data.index); // 得到当前Tab的所在下标
console.log(data.elem); // 得到当前的Tab大容器
});
element.on('tabDelete(filter)', data => {
// console.log(this); // 当前Tab标题所在的原始DOM元素
console.log(data.index); // 得到当前Tab的所在下标
console.log(data.elem); // 得到当前的Tab大容器
});
element.on('nav(filter)', elem => {
console.log(elem); // 得到当前点击的DOM对象
});
element.on('collapse(filter)', data => {
console.log(data.show); // 得到当前面板的展开状态,true或者false
console.log(data.title); // 得到当前点击面板的标题区域DOM对象
console.log(data.content); // 得到当前点击面板的内容区域DOM对象
});
});
}
function flowTest() {
layui.use('flow', () => {
const flow = layui.flow;
// 信息流
flow.load({ elem: '' });
flow.load({ elem: '', scrollElem: '' });
// 图片懒加载
flow.lazyimg({});
});
layui.use('flow', () => {
const $ = layui.jquery; // 不用额外加载jQuery,flow模块本身是有依赖jQuery的,直接用即可。
const flow = layui.flow;
flow.load({
elem: '#demo', // 指定列表容器
done: (page, next) => {
// 到达临界点(默认滚动触发),触发下一页
const lis: string[] = [];
// 以jQuery的Ajax请求为例,请求下一页数据(注意:page是从2开始返回)
$.get('/api/list?page=' + page, res => {
// 假设你的列表返回在data集合中
layui.each(res.data, (index, item) => {
lis.push(`<li>${item.title}</li>`);
});
// 执行下一页渲染,第二参数为:满足“加载更多”的条件,即后面仍有分页
// pages为Ajax返回的总页数,只有当前页小于总页数的情况下,才会继续出现加载更多
next(lis.join(''), page < res.pages);
});
},
});
});
}
function formTest() {
layui.use('form', () => {
const form = layui.form;
// 监听提交
form.on('submit(formDemo)', data => {
// layer.msg(JSON.stringify(data.field));
return false;
});
form.verify({
username: (value: string, item: HTMLElement) => {
// value:表单的值、item:表单的DOM对象
if (!new RegExp('^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$').test(value)) {
return '用户名不能有特殊字符';
}
if (/(^\_)|(\__)|(\_+$)/.test(value)) {
return "用户名首尾不能出现下划线'_'";
}
if (/^\d+\d+\d$/.test(value)) {
return '用户名不能全为数字';
}
// 如果不想自动弹出默认提示框,可以直接返回 true,这时你可以通过其他任意方式提示(v2.5.7 新增)
if (value === 'xxx') {
alert('用户名不能为敏感词');
return true;
}
},
// 我们既支持上述函数式的方式,也支持下述数组的形式
// 数组的两个值分别代表:[正则匹配、匹配不符时的提示文字]
pass: [/^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'],
});
});
layui.form.getValue('test2')['file'];
const t = $(document.body);
layui.form.getValue('test2');
layui.form.on('select(select)', data => {
console.log(data);
});
layui.form.on('checkbox(checkbox)', data => {
data.othis.find('');
console.log(data);
});
layui.form.val('filter', new Date());
layui.form.val('filter', { a: 1, b: true });
layui.form.config.autocomplete;
layui.form.config.verify.date;
}
function testJquery() {
layui.define(exports => {
layui.$ = jQuery;
exports('jquery', jQuery);
});
}
function layTest() {
const a = { a: [1, 2, 3] };
const b = {};
layui.lay.extend(b, a, { b: 'ok' });
layui.lay.ie;
layui.lay.layui;
layui.lay.getPath;
layui.lay.stope;
layui.each([1, 2, 3], console.log);
layui.lay.digit(1, 4);
const input = layui.lay.elem('input', { id: 'abc' });
const img = layui.lay.elem('img', { id: 'abc' });
layui.lay.hasScrollbar;
layui.lay.position;
layui.lay.options('.a');
layui.lay.options('.a', 'id');
const ll = layui.lay(document.body);
ll.addClass('abc a', false);
ll.addClass('abc b', true);
ll.removeClass('')[0].title;
ll.hasClass('abc');
ll.css('');
ll.css('', '');
const x = window.lay.each([0, 1])('div');
x.selector;
window.lay.each({})('div').selector;
layui.lay.each([]);
layui.lay('div').each((index, ele) => {
// console.log(index+ele)
})[0].title;
window.lay('div').find('input').addClass;
layui.lay('');
layui.lay('').each;
layui.lay('').addClass('');
layui.lay('').length;
layui.lay('#abc').on('click', e => {
console.log();
});
layui.laypage.on(document.getElementById('abc'), 'click', e => {
console.log(e);
});
const eme = document.getElementById('abc');
if (eme) {
// let elem: HTMLButtonElement = eme;
layui.laypage.on(null, 'click', e => {
console.log(e);
});
}
}
function laydateTest() {
layui.use('laydate', () => {
const laydate = layui.laydate;
// 日期范围选择
laydate.render({
elem: '#test',
range: true, // 或 range: '~' 来自定义分割字符
});
// 日期时间范围选择
laydate.render({
elem: '#test',
type: 'datetime',
range: true,
});
// 时间范围选择
laydate.render({
elem: '#test',
type: 'time',
range: true,
});
// 年范围选择
laydate.render({
elem: '#test',
type: 'year',
range: true,
});
// 年月范围选择
const ins1 = laydate.render({
elem: '#test',
type: 'month',
range: true,
show: true, // 直接显示
closeStop: '#test1',
position: 'static',
showBottom: false,
zIndex: 99999999,
btns: ['now'],
calendar: true,
mark: {
'0-10-14': '生日',
'0-12-31': '跨年', // 每年12月31日
'0-0-10': '工资', // 每个月10号
'2017-8-15': '', // 具体日期
'2017-8-20': '预发', // 如果为空字符,则默认显示数字+徽章
'2017-8-21': '发布',
},
ready: date => {
ins1.hint('打开'); // 在控件上弹出value值
console.log(date); // 得到初始的日期时间对象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
},
done: (value, date, endDate) => {
console.log(value); // 得到日期生成的值,如:2017-08-18
console.log(date); // 得到日期时间对象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
console.log(endDate); // 得结束的日期时间对象,开启范围选择(range: true)才会返回。对象成员同上。
},
change: (value, date, endDate) => {
console.log(value); // 得到日期生成的值,如:2017-08-18
console.log(date); // 得到日期时间对象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
console.log(endDate); // 得结束的日期时间对象,开启范围选择(range: true)才会返回。对象成员同上。
},
});
laydate.path = '/static/xxx/'; // laydate.js 所在目录
layui.laydate.getEndDate();
});
}
function layeditTest() {
layui.use('layedit', () => {
const layedit = layui.layedit;
layedit.build('demo'); // 建立编辑器
layedit.build('id', {
tool: ['left', 'center', 'right', '|', 'face'],
});
layedit.build('id', {
tool: [
'strong', // 加粗
'italic', // 斜体
'underline', // 下划线
'del', // 删除线
'|', // 分割线
'left', // 左对齐
'center', // 居中对齐
'right', // 右对齐
'link', // 超链接
'unlink', // 清除链接
'face', // 表情
'image', // 插入图片
'help', // 帮助
],
});
layedit.set({
uploadImage: {
url: '', // 接口url
type: '', // 默认post
},
});
// 注意:layedit.set 一定要放在 build 前面,否则配置全局接口将无效。
layedit.build('demo'); // 建立编辑器
});
}
function layerTest() {
layui.use('layer', layer => {
/*
如果是页面层
*/
layer.open({
type: 1,
content: '传入任意的文本或html', // 这里content是一个普通的String
});
layer.open({
type: 1,
content: $('#id'), // 这里content是一个DOM,注意:最好该元素要存放在body最外层,否则可能被其它的相对元素所影响
});
// Ajax获取
$.post('url', {}, str => {
layer.open({
type: 1,
content: str, // 注意,如果str是object,那么需要字符拼接。
});
});
/*
如果是iframe层
*/
layer.open({
type: 2,
content: 'http://sentsin.com', // 这里content是一个URL,如果你不想让iframe出现滚动条,你还可以content: ['http://sentsin.com', 'no']
});
/*
如果是用layer.open执行tips层
*/
layer.open({
type: 4,
content: ['内容', '#id'], // 数组第二项即吸附元素选择器或者DOM
});
// 单个使用
layer.open({
skin: 'demo-class',
});
// 全局使用。即所有弹出层都默认采用,但是单个配置skin的优先级更高
layer.config({
skin: 'demo-class',
});
// eg1
layer.alert('酷毙了', { icon: 1 });
// eg2
layer.msg('不开心。。', { icon: 5 });
// eg3
layer.load(1); // 风格1的加载
// eg1
layer.confirm(
'纳尼?',
{
btn: ['按钮一', '按钮二', '按钮三'], // 可以无限个按钮
btn3: (index, layero) => {
// 按钮【按钮三】的回调
},
},
(index, layero) => {
// 按钮【按钮一】的回调
},
index => {
// 按钮【按钮二】的回调
},
);
// eg2
layer.open({
content: 'test',
btn: ['按钮一', '按钮二', '按钮三'],
yes: (index, layero) => {
// 按钮【按钮一】的回调
},
btn2: (index, layero) => {
// 按钮【按钮二】的回调
// return false 开启该代码可禁止点击该按钮关闭
},
btn3: (index, layero) => {
// 按钮【按钮三】的回调
// return false 开启该代码可禁止点击该按钮关闭
},
cancel: () => {
// 右上角关闭回调
// return false 开启该代码可禁止点击该按钮关闭
},
resizing: layero => {
console.log(layero);
},
success: (layero, index) => {
console.log(layero, index);
},
});
layer.msg('hello');
layer.open({
minStack: true,
content: '测试回调',
success: (layero, index) => {
console.log(layero, index);
},
cancel: (index, layero) => {
if (confirm('确定要关闭么')) {
// 只有当点击confirm框的确定时,该层才会关闭
layer.close(index);
}
return false;
},
});
layer.config({
anim: 1, // 默认动画风格
skin: 'layui-layer-molv', // 默认皮肤
// …
});
// 除此之外,extend 还允许你加载拓展的 css 皮肤,如:
layer.config({
// 如果是独立版的layer,则将 myskin 存放在 ./skin 目录下
// 如果是layui中使用layer,则将 myskin 存放在 ./css/modules/layer 目录下
extend: 'myskin/style.css',
});
// 页面一打开就执行弹层
layer.ready(() => {
layer.msg('很高兴一开场就见到你');
});
let index = layer.open({
content: 'test',
});
// eg1
layer.alert('只想简单的提示');
// eg2
layer.alert('加了个图标', { icon: 1 }); // 这时如果你也还想执行yes回调,可以放在第三个参数中。
// eg3
layer.alert('有了回调', index => {
// do something
layer.close(index);
});
layer.confirm(1);
// eg1
layer.confirm('is not?', { icon: 3, title: '提示' }, index => {
// do something
layer.close(index);
});
// eg2
layer.confirm('is not?', (index, layero) => {
// do something
layer.close(index);
});
layer.confirm(
'is not?',
{
icon: 3,
title: '提示',
cancel: (index, layero) => {
console.log('点击了右上角关闭');
// return false // 点击右上角叉号不能关闭
},
},
(index, layero) => {
console.log("点击了下边的第一个按钮'确定'");
layer.close(index); // 需要手动关闭
},
(index, layero) => {
console.log("点击了下边的第二个按钮'取消'");
// return false // 点击取消不能关闭
},
);
layer.confirm(
'is not?',
(index, layero) => {
// do something
layer.close(index);
},
(index, layero) => {},
);
// eg1
layer.msg('只想弱弱提示');
// eg2
layer.msg('有表情地提示', { icon: 6 });
// eg3
layer.msg('关闭后想做些什么', () => {
// do something
});
// eg
layer.msg(
'同上',
{
icon: 1,
time: 2000, // 2秒关闭(如果不配置,默认是3秒)
},
() => {
// do something
},
);
// eg1
index = layer.load();
// eg2
index = layer.load(1); // 换了种风格
// eg3
index = layer.load(2, { time: 10 * 1000 }); // 又换了种风格,并且设定最长等待10秒
// 关闭
// eg1
layer.tips('只想提示地精准些', '#id');
// eg 2
$('#id').on('click', () => {
layer.tips('只想提示地精准些'); // 在元素的事件回调体中,follow直接赋予this即可
});
// eg 3
layer.tips('在上面', '#id', {
tips: 1,
});
// 当你想关闭当前页的某个层时
index = layer.open();
index = layer.alert();
index = layer.load();
index = layer.tips();
// 正如你看到的,每一种弹层调用方式,都会返回一个index
layer.close(index); // 此时你只需要把获得的index,轻轻地赋予layer.close即可
// 如果你想关闭最新弹出的层,直接获取layer.index即可
layer.close(layer.index); // 它获取的始终是最新弹出的某个层,值是由layer内部动态递增计算的
layer.ie;
layer.index;
layer.path;
layer.v;
layer.zIndex;
// 当你在iframe页面关闭自身时
window.layui;
window.lay;
window.layer;
if (parent) {
parent.layer;
parent.layer.close(index); // 再执行关闭
}
index = layui.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
// 关闭后的回调(layui 2.6.5、layer 3.4.0 新增)
layer.close(index, () => {
// do something
});
layer.open({
type: 2,
shade: false,
area: '500px',
maxmin: true,
content: 'http://www.layui.com',
zIndex: layer.zIndex, // 重点1
success: layero => {
layer.setTop(layero); // 重点2
layero.css('z-index', 0);
},
});
layer.closeAll(); // 疯狂模式,关闭所有层
layer.closeAll('dialog'); // 关闭信息框
layer.closeAll('page'); // 关闭所有页面层
layer.closeAll('iframe'); // 关闭所有的iframe层
layer.closeAll('loading'); // 关闭加载层
layer.closeAll('tips'); // 关闭所有的tips层
// 关闭后的回调(layui 2.6.5、layer 3.4.0 新增)
layer.closeAll('loading', () => {
// 关闭 loading 并执行回调
// do something
});
layer.closeAll(() => {
// 关闭所有层并执行回调
// do something
});
layer.style(index, {
width: '1000px',
top: '10px',
});
layer.title('标题变了', index);
layer.open({
type: 2,
content: 'test/iframe.html',
success: (layero, index) => {
const body = layer.getChildFrame('body', index);
// let iframeWin = window[layero.find('iframe')[0]['name']]; // 得到iframe页的窗口对象,执行iframe页的方法:iframeWin.method();
console.log(body.html()); // 得到iframe页的body内容
body.find('input').val('Hi,我是从父页来的');
},
});
// 假设这是iframe页
if (parent) {
index = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
parent.layer.close(index); // 再执行关闭
}
// 通过这种方式弹出的层,每当它被选择,就会置顶。
layer.open({
type: 2,
shade: false,
area: '500px',
maxmin: true,
content: 'http://www.layui.com',
zIndex: layer.zIndex, // 重点1
success: layero => {
layer.setTop(layero); // 重点2
},
});
layer.full(index); // 执行最大化
layer.min(index); // 执行最小化
layer.restore(index); // 执行还原
// 例子1
layer.prompt((value, index, elem) => {
alert(value); // 得到value
layer.close(index);
});
// 例子2
layui.layer.prompt(
{
formType: 2, // 输入框类型,支持0(文本)默认1(密码)2(多行文本)
value: '初始值', // 初始时的值,默认空字符
maxlength: 140, // 可输入文本的最大长度,默认500
title: '请输入值',
area: ['800px', '350px'], // 自定义文本域宽高
},
(value, index, elem) => {
layui.layer.alert(value); // 得到value
layui.layer.close(index);
},
);
layer.tab({
area: ['600px', '300px'],
tab: [
{
title: 'TAB1',
content: '内容1',
},
{
title: 'TAB2',
content: '内容2',
},
{
title: 'TAB3',
content: '内容3',
},
],
});
$.getJSON('/jquery/layer/test/photos.json', json => {
layer.photos({
photos: json,
anim: 5, // 0-6的选择,指定弹出图片动画类型,默认随机(请注意,3.0之前的版本用shift参数)
});
});
layer.photos({
photos: {
title: '', // 相册标题
id: 123, // 相册id
start: 0, // 初始显示的图片序号,默认0
data: [
// 相册包含的图片,数组格式
{
alt: '图片名',
pid: 666, // 图片id
src: '', // 原图地址
thumb: '', // 缩略图地址
},
],
},
tab: (pic, layero) => {
console.log(pic); // 当前图片的一些信息
},
});
});
}
function laytplTest() {
layui.use('laytpl', () => {
const laytpl = layui.laytpl;
// 直接解析字符
laytpl('{{ d.name }}是一位公猿').render(
{
name: '贤心',
},
string => {
console.log(string); // 贤心是一位公猿
},
);
// 你也可以采用下述同步写法,将 render 方法的回调函数剔除,可直接返回渲染好的字符
const string = laytpl('{{ d.name }}是一位公猿').render({
name: '贤心',
});
console.log(string); // 贤心是一位公猿
// 如果模板较大,你也可以采用数据的写法,这样会比较直观一些
laytpl(['{{ d.name }}是一位公猿', '其它字符 {{ d.content }} 其它字符'].join(''));
const data = {
// 数据
title: 'Layui常用模块',
list: [
{ modname: '弹层', alias: 'layer', site: 'layer.layui.com' },
{ modname: '表单', alias: 'form' },
],
};
const getTpl = document.body.innerHTML;
const view = document.getElementById('view');
laytpl(getTpl).render(data, html => {
if (view) {
view['innerHTML'] = html;
}
});
laytpl('').parse('', {});
laytpl('').render({});
laytpl('').tpl;
laytpl.config({
open: '<%',
close: '%>',
});
laytpl.config({
// open: '<%',
close: '%>',
});
laytpl.config();
// 分割符将必须采用上述定义的
laytpl(
[
'<%# let type = "公"; %>', // JS 表达式
'<% d.name %>是一位<% type %>猿。',
].join(''),
).render(
{
name: '贤心',
},
string => {
console.log(string); // 贤心是一位公猿
},
);
});
}
function rateTest() {
layui.use('rate', () => {
const rate = layui.rate;
rate.set();
rate.config;
rate.on;
rate.index;
// 渲染
const ins1 = rate.render({
elem: '#test1', // 绑定元素
});
ins1;
rate.render({
elem: '#test1',
setText(value) {
/* let arrs = {
1: '极差',
2: '差',
3: '中等',
4: '好',
};*/
// arrs[String(value)] || ( value + "星");
},
});
});
}
function SliderTest() {
layui.use('slider', () => {
const slider = layui.slider;
// 渲染
const x = slider.render({
elem: '#slideTest1',
range: true,
change: value => {
// console.log(value[0]); // 得到开始值
// console.log(value[1]); // 得到结尾值
// do something
},
});
slider.config;
slider.set;
slider.on;
x.config.disabled;
x.setValue(1);
x.setValue(1, 0);
});
}
function tableTest() {
layui.use(a => {
layui.layer.load(1, {});
layui.form.on('', a => {
layui.form.val('', {});
});
layui.form.getValue('', $(''));
layui.table.init;
const rendered = layui.table.render({
elem: '#demo',
cols: [
[
// 标题栏
{ checkbox: true },
{ field: 'test', title: 'abc', width: '12', minWidth: 12, type: 'space', templet: '#titleTpl' },
{ LAY_CHECKED: true, fixed: 'left', hide: true },
{
totalRow: { score: '666', experience: '999' },
templet: d => {
return d.aa;
},
},
{ totalRowText: '合计:', sort: true, unresize: true, edit: 'text' },
{ event: 'btn01', style: 'background-color: #5FB878; color: #fff;' },
{ align: 'left', colspan: 1, rowspan: 2 },
{
templet() {
return '{{d.test}}';
},
toolbar: '#barDemo',
},
],
],
url: '/demo/table/user/', // 数据接口
toolbar: 'default',
defaultToolbar: ['', { title: '', layEvent: '', icon: '' }],
width: '12',
height: 12,
cellMinWidth: 12,
done(a, b, c) {},
data: [{}, {}],
totalRow: true,
page: { theme: '#c00' },
limit: 10,
limits: [1, 2, 3],
loading: true,
title: '标题',
text: { none: 'abc' },
autoSort: true,
initSort: { field: 'id', type: 'desc' },
id: 'id',
skin: 'nob',
even: true,
size: 'lg',
method: 'get',
where: null, // {}
contentType: "application/json'",
headers: { token: '' },
parseData(res) {
// res 即为原始返回的数据
return {
code: 200, // 解析接口状态
msg: 'res', // 解析提示文本
// count: 123, // 解析数据长度
data: res, // 解析数据列表
};
},
request: {
pageName: 'curr', // 页码的参数名称,默认:page
limitName: 'nums', // 每页数据量的参数名,默认:limit
},
response: {
statusName: 'status', // 规定数据状态的字段名称,默认:code
statusCode: 200, // 规定成功的状态码,默认:0
msgName: 'hint', // 规定状态信息的字段名称,默认:msg
countName: 'total', // 规定数据总数的字段名称,默认:count
dataName: 'rows', // 规定数据列表的字段名称,默认:data
},
});
rendered.config.cols;
layui.use(['table', 'laytpl', 'element'], () => {
const table = layui.table;
const rr = table.render({
elem: '#demo',
toolbar: true,
title: '用户数据表',
totalRow: true,
text: {
none: '暂无相关数据', // 默认:无数据。
},
defaultToolbar: ['filter', { title: '123', layEvent: '', icon: '' }],
cols: [
[
// {LAY_CHECKED: true,checkbox: true,fixed: "left"}
{ field: 'id', title: 'ID', unresize: true, sort: true, totalRowText: '合计行', rowspan: 2 },
{ field: 'username', title: '用户名', edit: 'text', rowspan: 2 },
{ title: '个人信息', colspan: 2, align: 'center' },
/*
,{field:'sex', title:'性别', width:80, edit: 'text', sort: true,rowspan:2}
,{field:'logins', title:'登入次数', width:100, sort: true, totalRow: true,rowspan:2}
,{field:'sign', title:'签名',rowspan:2}
,{field:'city', title:'城市', width:100,rowspan:2}
,{field:'ip', title:'IP', width:120,rowspan:2 }
,{field:'joinTime', title:'加入时间', width:120,event: "btn01", style: "background-color: #5FB878; color: #fff;",rowspan:2 }
,{title:"no",templet(d) {return d.city;},rowspan:2 }
*/
],
[
{
field: 'email',
title: '邮箱',
edit: 'text',
rowspan: 1,
templet(d) {
d.LAY_COL.type;
d['你可以用 d.xx 来使用当前行的其他属性'] === undefined;
return d.LAY_COL.type + d.email;
},
},
{ field: 'experience', title: '积分', sort: true, totalRow: true, rowspan: 1 },
],
],
data: [
{
id: '10001',
username: '杜甫',
email: 'test@email.com',
sex: '男',
city: '浙江杭州',
sign: '点击此处,显示更多。当内容超出时,点击单元格会自动显示更多内容。',
experience: '116',
ip: '192.168.0.8',
logins: '108',
joinTime: '2016-10-14',
},
{
id: '10002',
username: '李白',
email: 'test@email.com',
sex: '男',
city: '浙江杭州',
sign: '君不见,惟 美酒,与尔同销万古愁。',
experience: '12.25',
ip: '192.168.0.8',
logins: '106',
joinTime: '2016-10-14',
},
],
page: true,
response: {
statusCode: 200, // 重新规定成功的状态码为 200,table 组件默认为 0
},
parseData: res => {
// 将原始数据解析成 table 组件所规定的数据
return {
code: res.status, // 解析接口状态
msg: res.message, // 解析提示文本
count: res.total, // 解析数据长度
data: res.rows.item, // 解析数据列表
};
},
done(res) {
res;
},
error(e, msg) {
console.log(e, msg);
},
});
rr.reload({}, false);
layui.table.reload('id', {});
});
rendered.config.id;
rendered.reload({});
rendered.setColsWidth();
rendered.resize();
layui.table.on('tool(test)', obj => {
// 注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
const data = obj.data; // 获得当前行数据
const layEvent = obj.event; // 获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
const tr = obj.tr; // 获得当前行 tr 的 DOM 对象(如果有的话)
switch (layEvent) {
case 'detail':
break;
case 'del':
layui.layer.confirm('真的删除行么', index => {
obj.del(); // 删除对应行(tr)的DOM结构,并更新缓存
layui.layer.close(index);
// 向服务端发送删除指令
});
break;
case 'edit':
obj.update({
username: '123',
title: 'xxx',
});
break;
case 'LAYTABLE_TIPS':
layui.layer.alert('Hi,头部工具栏扩展的右侧图标。');
break;
}
});
const checkStatus = layui.table.checkStatus('idTest'); // idTest 即为基础参数 id 对应的值
if (checkStatus.isAll) {
checkStatus.data.length;
}
layui.table.exportFile('id', []);
layui.table.on('sort(test)', obj => {
// 注:sort 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
console.log(obj.field); // 当前排序的字段名
console.log(obj.type); // 当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序)
// console.log(this); // 当前排序的 th 对象
// 尽管我们的 table 自带排序功能,但并没有请求服务端。
// 有些时候,你可能需要根据当前排序的字段,重新向服务端发送请求,从而实现服务端排序,如:
layui.table.reload('idTest', {
initSort: obj, // 记录初始排序,如果不设的话,将无法标记表头的排序状态。
where: {
// 请求参数(注意:这里面的参数可任意定义,并非下面固定的格式)
field: obj.field, // 排序字段
order: obj.type, // 排序方式
},
});
layui.layer.msg(`服务端排序。order by {obj.field} ={obj.type}`);
});
});
layui.table.on('checkbox(test)', obj => {
const data: Layui.TableOnCheckbox = obj;
data.del;
data.checked;
data.tr[0];
data.type;
data.update({});
});
layui.table.on('toolbar(test)', obj => {
const data: Layui.TableOnToolbar = obj;
data.config.autoSort;
data.event;
});
layui.table.on('tool(test)', obj => {
const data: Layui.TableOnTool = obj;
data.data;
data.del();
data.event;
data.tr[0];
data.update({});
});
layui.table.on('row(test)', obj => {
const data: Layui.TableOnRow = obj;
data.data;
data.del();
data.tr[0];
data.update({});
});
layui.table.on('edit(test)', obj => {
const data: Layui.TableOnEdit = obj;
data.data;
data.del();
data.field;
data.tr[0];
data.update({});
data.value;
});
layui.table.on('sort(test)', obj => {
const data: Layui.TableOnSort = obj;
data.field;
data.type;
});
layui.table.reload('id', {
url: null,
data: [],
where: null,
});
// 工具条事件
layui.table.on('tool(test)', obj => {
// 注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
const data = obj.data; // 获得当前行数据
const layEvent = obj.event; // 获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
const tr = obj.tr; // 获得当前行 tr 的 DOM 对象(如果有的话)
switch (layEvent) {
case 'detail': {
break;
}
case 'del': {
// 删除
layui.layer.confirm('真的删除行么', index => {
obj.del(); // 删除对应行(tr)的DOM结构,并更新缓存
layui.layer.close(index);
// 向服务端发送删除指令
});
}
case 'edit': {
// 编辑
// do something
// 同步更新缓存对应的值
obj.update({
username: '123',
title: 'xxx',
});
}
case 'LAYTABLE_TIPS': {
layui.layer.alert('Hi,头部工具栏扩展的右侧图标。');
}
}
});
layui.table.set({}); // 设定全局默认参数。options即各项基础参数
layui.table.on('event(filter)', () => {}); // 事件。event为内置事件名(详见下文),filter为容器lay-filter设定的值
layui.table.init('filter', {}); // filter为容器lay-filter设定的值,options即各项基础参数。例子见:转换静态表格
layui.table.checkStatus('id'); // 获取表格选中行(下文会有详细介绍)。id 即为 id 参数对应的值
layui.table.render({}); // 用于表格方法级渲染,核心方法。应该不用再过多解释了,详见:方法级渲染
layui.table.reload('id', {}, false); // 表格重载
layui.table.resize('id'); // 重置表格尺寸
layui.table.exportFile('id', [], 'type'); // 导出数据
layui.table.getData('id'); // 用于获取表格当前页的所有行数据(layui 2.6.0 开始新增)
// 所获得的 tableIns 即为当前容器的实例
const tableIns = layui.table.render({
elem: '#id',
cols: [], // 设置表头
url: '/api/data', // 设置异步接口
id: 'idTest',
});
// 这里以搜索为例
tableIns.reload({
where: {
// 设定异步数据接口的额外参数,任意设
aaaaaa: 'xxx',
bbb: 'yyy',
// …
},
page: {
curr: 1, // 重新从第 1 页开始
},
});
// 上述方法等价于
layui.table.reload('idTest', {
where: {
// 设定异步数据接口的额外参数,任意设
aaaaaa: 'xxx',
bbb: 'yyy',
// …
},
page: {
curr: 1, // 重新从第 1 页开始
},
}); // 只重载数据
layui.table.exportFile('abc');
layui.table.exportFile('abc', null);
layui.table.exportFile(
['名字', '性别', '年龄'],
[
['张三', '男', '20'],
['李四', '女', '18'],
['王五', '女', '19'],
],
'csv',
);
layui.table.exportFile(
'abc',
[
['张三', '男', '20'],
['李四', '女', '18'],
['王五', '女', '19'],
],
'csv',
);
}
function transferTest() {
layui.use('transfer', () => {
const transfer = layui.transfer;
// 渲染
transfer.render({
elem: '#test1', // 绑定元素
data: [
{ value: '1', title: '李白', disabled: '', checked: '' },
{ value: '2', title: '杜甫', disabled: '', checked: '' },
{ value: '3', title: '贤心', disabled: '', checked: '' },
],
id: 'demo1', // 定义索引
});
transfer.render({
elem: '#test',
data: [],
id: 'demo1', // 定义索引
});
// 可以重载所有基础参数
transfer.reload('demo1', {
title: ['新列表1', '新列表2'],
});
// 获得右侧数据
const getData = transfer.getData('demo1');
transfer.set({}); // 设定全局默认参数。options 即各项基础参数
transfer.getData('id'); // 获得右侧数据
transfer.reload('id', {}); // 重载实例
});
}
function treeTest() {
layui.use('tree', () => {
const tree = layui.tree;
// 渲染
const inst1 = tree.render({
elem: '#test1', // 绑定元素
data: [
{
title: '江西', // 一级菜单
children: [
{
title: '南昌', // 二级菜单
children: [
{
title: '高新区', // 三级菜单
// …… // 以此类推,可无限层级
},
],
},
],
},
{
title: '陕西', // 一级菜单
children: [
{
title: '西安', // 二级菜单
},
],
},
],
});
layui.tree.render({
elem: '#test1',
click: obj => {
console.log(obj.data); // 得到当前点击的节点数据
console.log(obj.state); // 得到当前节点的展开状态:open、close、normal
console.log(obj.elem); // 得到当前节点元素
console.log(obj.data.children); // 当前节点下是否有子节点
},
oncheck: obj => {
const checkData = tree.getChecked('abcd');
checkData[0].checked;
tree.setChecked('abcd', [1]);
const x = tree.reload('abcd', {
showCheckbox: false,
edit: [],
accordion: true,
// 新的参数
});
console.log(obj.data); // 得到当前点击的节点数据
console.log(obj.checked); // 得到当前节点的展开状态:open、close、normal
console.log(obj.elem); // 得到当前节点元素
},
operate: obj => {
const type = obj.type; // 得到操作类型:add、update、del
const data = obj.data; // 得到当前节点的数据
const elem = obj.elem; // 得到当前节点元素
// Ajax 操作
const id = data.id; // 得到节点索引
switch (type) {
case 'add': {
// 增加节点
// 返回 key 值
return 123;
}
case 'update': {
// 修改节点
console.log(elem.find('.layui-tree-txt').html()); // 得到修改后的内容
break;
}
default: {
// 删除节点
break;
}
}
},
});
const treeReloaded = tree.reload('demoId', {
showCheckbox: false,
edit: [],
accordion: true,
// 新的参数
});
treeReloaded.config.abc;
layui.tree.on('click', () => {
console.log();
});
layui.event('tree', 'click', 'params-a');
});
}
function uploadTest() {
layui.use('upload', () => {
const upload = layui.upload;
// 执行实例
const uploadInst = upload.render({
elem: '#test1', // 绑定元素
url: '/upload/', // 上传接口
method: '', // 可选项。HTTP类型,默认post
data: { a: '123', b: () => 123 },
accept: 'images', // 允许上传的文件类型:images/file/video/audio
exts: '', // 允许上传的文件后缀名
auto: true, // 是否选完文件后自动上传
bindAction: '', // 手动上传触发的元素
// ,url: '' // 上传地址
field: 'file', // 文件字段名
acceptMime: '', // 筛选出的文件类型,默认为所有文件
// ,method: 'post' // 请求上传的 http 类型
// ,data: {} // 请求上传的额外参数
drag: true, // 是否允许拖拽上传
size: 0, // 文件限制大小,默认不限制
number: 0, // 允许同时上传的文件数,默认不限制
multiple: false, // 是否允许多文件上传,不支持ie8-9
before: obj => {
// obj参数包含的信息,跟 choose回调完全一致,可参见上文。
// this.item;
layui.layer.load(); // 上传loading
},
allDone: obj => {
// 当文件全部被提交后,才触发
console.log(obj.total); // 得到总文件数
console.log(obj.successful); // 请求成功的文件数
console.log(obj.aborted); // 请求失败的文件数
},
progress: (n, elem: HTMLButtonElement, res, index) => {
const x: HTMLButtonElement = elem;
x.value;
x.addEventListener('click', e => 1);
elem.value;
const percent = n + '%'; // 获取进度百分比
layui.element.progress('demo', percent); // 可配合 layui 进度条元素使用
console.log(elem); // 得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。
console.log(res); // 得到 progress 响应信息
console.log(index); // 得到当前上传文件的索引,多文件上传时的进度条控制,如:
layui.element.progress('demo-' + index, n + '%'); // 进度条
},
done: (res, index, upload) => {
// 假设code=0代表上传成功
// this.item;
if (res.code === 0) {
// do something (比如将res返回的图片链接保存到表单的隐藏域)
}
// 获取当前触发上传的元素,一般用于 elem 绑定 class 的情况,注意:此乃 layui 2.1.0 新增
// let item = this.item;
// 文件保存失败
// do something
upload([]);
},
error: (index, upload) => {
upload();
// 当上传失败时,你可以生成一个“重新上传”的按钮,点击该按钮时,执行 upload() 方法即可实现重新上传
},
choose: obj => {
const f = new File(['', ''], '');
const formData = new FormData();
formData.append(',', f);
// 将每次选择的文件追加到文件队列
const files = obj.pushFile();
files['a'].lastModified;
// 预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
obj.preview((index, file, result) => {
console.log(index); // 得到文件索引
console.log(file.lastModified); // 得到文件对象
console.log(result); // 得到文件base64编码,比如图片
obj.resetFile(index, file, '123.jpg'); // 重命名文件名,layui 2.3.0 开始新增
// 这里还可以做一些 append 文件列表 DOM 的操作
obj.upload(index, file); // 对上传失败的单个文件重新上传,一般在某个事件中使用
// delete files[index]; // 删除列表中对应的文件,一般在某个事件中使用
});
},
});
uploadInst.config;
uploadInst.reload({
accept: 'images', // 只允许上传图片
acceptMime: 'image/*', // 只筛选图片
size: 1024 * 2, // 限定大小
});
uploadInst.upload();
});
}
function utilTest() {
// 单个模块导入测试
function useTest1() {
// 导出的模块
const exported: any[] = [];
const x = layui.use(
'util',
util => {
util.toDateString;
},
exported,
);
console.log(x.v);
// config的设置是全局的
layui
.config({
base: '/res/js/', // 假设这是你存放拓展模块的根目录
})
.extend({
// 设定模块别名
mymod: 'mymod', // 如果 mymod.js 是在根目录,也可以不用设定别名
mod1: 'admin/mod1', // 相对于上述 base 目录的子目录
});
// 你也可以忽略 base 设定的根目录,直接在 extend 指定路径(主要:该功能为 layui 2.2.0 新增)
layui.extend({
mod2: '{/}http:// cdn.xxx.com/lib/mod2', // {/}的意思即代表采用自有路径,即不跟随 base 路径
});
// 使用拓展模块
layui.use(['mymod', 'mod1'], () => {
// let mymod = layui['mymod'];
// mymod.hello('World!'); // 弹出 Hello World!
});
}
// 多个模块导入测试
function useTest2() {
// 导出的模块
const exported: any[] = [];
// 单个存在
let x = layui.use(
'util',
util => {
util.toDateString;
},
exported,
);
console.log(x.v);
// 单个不存在
x = layui.use(
'a',
util => {
util.toDateString;
},
exported,
);
console.log(x.v);
// 单个数组存在
x = layui.use(
['util'],
util => {
util.toDateString;
},
exported,
);
console.log(x.v);
// 单个数组不存在
x = layui.use(
['a'],
util => {
util.toDateString;
},
exported,
);
console.log(x.v);
x = layui.use(['util', 'form', 'b'], (a: Layui.Util, b, c) => {}, exported);
layui.use(aa => {
aa.config;
aa.time;
});
}
layui.use(['layer', 'util'], (layer, util) => {
util.event('lay-active', {
btnA: (othis: JQuery) => {
othis[0];
alert('触发了事件1');
},
btnB: (othis: JQuery) => {
alert('触发了事件2');
},
btnC: (othis: JQuery) => {
alert('触发了事件3');
},
});
});
layui.use('util', () => {
const util = layui.util;
// 执行
util.fixbar({
bar1: true,
click: type => {
console.log(type);
if (type === 'bar1') {
alert('点击了bar1');
}
},
});
// 示例
const endTime = new Date(2099, 1, 1).getTime(); // 假设为结束日期
const serverTime = new Date(); // .getTime(); // 假设为当前服务器时间,这里采用的是本地时间,实际使用一般是取服务端的
util.countdown(endTime, serverTime, (date, serverTime2, timer) => {
const str = ` ${date[0]}天${date[1]}时${date[2]}分${date[3]}秒`;
layui.$('#test').html(`'距离2099年1月1日还有:${str}`);
});
util.timeAgo(new Date(2099, 1, 1), true);
layui.util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');
layui.util.toDateString(new Date());
layui.util.digit(1, 4);
layui.util.escape();
// 处理属性 为 lay-active 的所有元素事件
util.event('lay-active', {
e1: othis => {
alert('触发了事件1');
},
e2: othis => {
alert('触发了事件2');
},
e3: othis => {
alert('触发了事件3');
},
});
});
} | the_stack |
import * as JSONCparser from 'jsonc-parser'
import * as path from 'path'
import * as fs from 'fs'
import 'isomorphic-fetch'
import TelemetryReporter from 'vscode-extension-telemetry'
import { TextEditor } from 'vscode'
import * as NodeCache from 'node-cache'
import * as utils from './utils'
import ARMExpressionParser from './arm-exp-parser'
import { Template, CytoscapeNode, Resource } from './arm-parser-types'
export default class ARMParser {
private template: Template
private expParser: ARMExpressionParser
private error: Error | undefined
private elements: CytoscapeNode[]
private iconBasePath: string
private reporter: TelemetryReporter | undefined
private editor: TextEditor | undefined
private name: string
private cache: NodeCache | undefined
//
// Create a new ARM Parser
//
constructor(
iconBasePath: string,
name: string,
reporter?: TelemetryReporter,
editor?: TextEditor,
cache?: NodeCache
) {
// Both of these are overwritten when parse() is called
this.template = { $schema: '', parameters: {}, variables: {}, resources: [] }
this.expParser = new ARMExpressionParser(this.template)
this.elements = []
this.iconBasePath = iconBasePath
this.reporter = reporter
this.editor = editor
this.name = name
// Cache only used for external URLs of linked templates
this.cache = cache
}
//
// Load and parse a ARM template from given string
//
public async parse(templateJSON: string, parameterJSON?: string): Promise<CytoscapeNode[]> {
console.log(`### ArmView: Start parsing JSON template: ${this.name}`)
this.elements = []
// Try to parse JSON file
this.template = this.parseJSON(templateJSON)
// Some simple validation it is an ARM template
if (!this.template.resources ||
!this.template.$schema ||
!this.template.$schema.toString().toLowerCase().includes('deploymenttemplate.json')) {
throw new Error('File doesn\'t appear to be an ARM template, but is valid JSON')
}
// From here, we're pretty sure we're dealing with a legit and valid ARM template
this.expParser = new ARMExpressionParser(this.template)
// New first pass, apply supplied parameters if any
if (parameterJSON) {
this.applyParams(parameterJSON)
if (this.error) { throw this.error }
console.log('### ArmView: Parameter file applied')
}
// First pass, fix types and assign ids with a hash function
this.preProcess(this.template.resources, null)
if (this.error) { throw this.error }
console.log('### ArmView: Pre-process pass complete')
// 2nd pass, work on resources
await this.processResources(this.template.resources)
// Check for errors
if (this.error) { throw this.error }
console.log(`### ArmView: Parsing complete, found ${this.elements.length} elements in template ${this.name}`)
// return result elements
return this.elements
}
//
// Try to parse JSON file with the various "relaxations" to the JSON spec that ARM permits
//
private parseJSON(content: string): any {
// Strip out BOM characters for those mac owning weirdos, not sure this is still needed
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1)
}
// ARM also allows for multi-line strings, which is AWFUL
// This is a crude attempt to cope with them by simply stripping the newlines if we find any
// Find all strings in double quotes (thankfully JSON only allows double quotes)
const re = /(".*?")/gims
let match
// tslint:disable: no-conditional-assignment
while ((match = re.exec(content)) != null) {
const stringVal = match[1]
// Only work on strings that include a newline (or \n\r)
if (stringVal.includes('\n')) {
console.log(`### ArmView: Found a multi-line string in your template at offset ${match.index}. Attempting to rectify to valid JSON`)
// Mangle the content ripping the matched string out
const front = content.substr(0, match.index)
const back = content.substr(match.index + stringVal.length, content.length)
// Brute force removal!
// We preserve whitespace, but not sure if it's correct. We're outside the JSON spec!
let cleanString = stringVal.replace(/\n/g, '') // string.replace(/\s*\n\s*/g, ' ')
cleanString = cleanString.replace(/\r/g, '')
// Glue it back together
content = front + cleanString + back
}
}
// Switched to Microsoft jsonc-parser
const errors: JSONCparser.ParseError[] = []
const parsedTemplate = JSONCparser.parse(content, errors)
// We have to manually check for errors
if(errors.length > 0) {
const errMessage = errors.map(err => {
// jsonc-parser doesn't give line numbers for errors :(
// Horrific quick & dirty to convert the error offset to line number
const lineNum = (content.substr(0, err.offset).match(/\n/g) || []).length + 1
return `${JSONCparser.printParseErrorCode(err.error)} on line ${lineNum}`
}).join('\n')
throw new Error(errMessage)
}
// Otherwise we're good! We have something parsed
return parsedTemplate
}
//
// Pre-parser function, does some work to make life easier for the main parser
//
private preProcess(resources: Resource[], parentRes: any): void {
console.log('### ArmView: Pre-process starting...')
resources.forEach(res => {
try {
// Resolve and eval resource name
res.name = this.expParser.eval(res.name, true)
// Resolve and eval resource location
if (res.location) {
res.location = this.expParser.eval(res.location, true)
}
// Resolve and eval resource kind
if (res.kind) {
res.kind = this.expParser.eval(res.kind, true)
}
// Removed, I don't think this is ever valid in any template
// if(res.tags && typeof res.tags == "string") {
// res.tags = this.expParser.eval(res.tags, true)
// }
// Resolve and eval resource tags
if (res.tags && typeof res.tags === 'object') {
Object.keys(res.tags).forEach(tagname => {
const tagval = res.tags[tagname].toString()
res.tags[tagname] = this.expParser.eval(tagval, true)
})
}
// Resolve and eval sku object
if (res.sku && typeof res.sku === 'object') {
Object.keys(res.sku).forEach(propName => {
if (res.sku) {
const propVal = res.sku[propName].toString()
res.sku[propName] = this.expParser.eval(propVal, true)
}
})
}
// Make all res types fully qualified, solves a lots of headaches
if (parentRes) {
res.type = parentRes.type.toLowerCase() + '/' + res.type.toLowerCase()
} else {
res.type = res.type.toLowerCase()
}
// Assign a hashed id & full qualified name
res.id = utils.hashCode(this.name + '_' + res.type + '_' + res.name)
res.fqn = res.type + '/' + res.name
// Recurse into nested resources
if (res.resources) {
this.preProcess(res.resources, res)
}
} catch (err) {
this.error = err // `Unable to pre-process ARM resources, template is probably invalid. ${ex}`
}
})
}
//
// Inject parameter file values into template
//
private applyParams(parameterJSON: string): void {
// Try to parse JSON file
const paramObject = this.parseJSON(parameterJSON)
// Some simple ARM parameters validation
if(!paramObject.parameters ||
!paramObject.$schema ||
!paramObject.$schema.toString().toLowerCase().includes('deploymentparameters.json')) {
throw new Error('File doesn\'t appear to be an ARM parameters file, but is valid JSON')
}
// Loop over all parameters
for (const param in paramObject.parameters) {
try {
const pVal = paramObject.parameters[param].value
if (pVal !== '') {
// A cheap trick to force value into `defaultValue` to be picked up later
this.template.parameters[param].defaultValue = pVal
}
} catch (err) {
console.log(`### ArmView: Error applying parameter '${param}' Err: ${err}`)
}
}
}
//
// Main function to parse a resource, this will recurse into nested resources
//
private async processResources(resources: Resource[]): Promise<any> {
for (const res of resources) {
try {
// eslint-disable-next-line prefer-const
let extraData: any = {}
// Label is the last part of the resource type
const label = res.type.replace(/^.*\//i, '')
// Workout which icon image to use, no way to catch missing images client side so we do it here
let img = 'default.svg'
const iconExists = fs.existsSync(path.join(this.iconBasePath, `/${res.type}.svg`))
if (iconExists) {
img = `${res.type}.svg`
} else {
// API Management has about 7 million sub-resources, rather than include them all,
// we assign a custom default for APIM
if (res.type.includes('apimanagement')) {
img = 'microsoft.apimanagement/default.svg'
} else {
// Send telemetry on missing icons, this helps me narrow down which ones to add in the future
let hash = ''
if (this.editor) {
hash = this.editor.document.fileName
hash = utils.hashCode(this.editor.document.fileName)
}
// Send resource type, FQN and a hashed/obscured version of the filename
if (this.reporter) {
this.reporter.sendTelemetryEvent('missingIcon', {
fileHash: `${hash}`, resourceFQN: res.fqn, resourceType: res.type
})
}
// Use default icon as nothing else found
img = 'default.svg'
}
}
// App Services - Sites & plans can have different icons depending on 'kind'
if (res.kind && res.type.includes('microsoft.web')) {
if (res.kind.toLowerCase().includes('api')) { img = 'microsoft.web/apiapp.svg' }
if (res.kind.toLowerCase().includes('mobile')) { img = 'microsoft.web/mobileapp.svg' }
if (res.kind.toLowerCase().includes('function')) { img = 'microsoft.web/functionapp.svg' }
if (res.kind.toLowerCase().includes('linux')) { img = 'microsoft.web/serverfarmslinux.svg' }
}
// Event grid subscriptions can sit under many resource types
if (res.type.includes('eventsubscriptions')) {
img = 'microsoft.eventgrid/eventsubscriptions.svg'
}
// Linux VM icon with Tux :)
if (res.type.includes('microsoft.compute') && res.properties && res.properties.osProfile) {
if (res.properties.osProfile.linuxConfiguration) {
img = 'microsoft.compute/virtualmachines-linux.svg'
}
}
// Handle linked templates, oh boy, this is a whole world of pain
if (res.type === 'microsoft.resources/deployments' && res.properties
&& res.properties.templateLink && res.properties.templateLink.uri) {
let linkUri = res.properties.templateLink.uri
linkUri = this.expParser.eval(linkUri, true)
// Strip off everything weird after file extension, i.e. after any ? or { characters we find
const match = linkUri.match(/(.*?\.\w*?)($|\?|{)/)
if (match) {
linkUri = match[1]
}
extraData['template-url'] = linkUri
// OK let's try to handle linked templates shall we? O_O
console.log('### ArmView: Processing linked template: ' + linkUri)
let subTemplate = ''
let cacheResult
try {
if (this.cache) {
cacheResult = this.cache.get<string>(linkUri)
}
if (cacheResult === undefined) {
// With some luck it will be an accessible directly via public URL
// Use the isomorphic fetch to get the content of the URL, (Note. was using axios but that had bugs)
// As fetch has no timeout we use a wrapper function and a 5sec timeout
const fetchResult = await utils.timeoutPromise(5000, fetch(linkUri), 'HTTP network timeout')
if (!(fetchResult.status >= 200 && fetchResult.status < 300)) {
throw new Error(`Fetch failed, status code: ${fetchResult.status}`)
}
// Traps those cases where a 200 + HTML page masks an error or 404
const contentType = fetchResult.headers.get('Content-Type')
if (contentType && contentType.includes('text/html')) {
throw new Error('Returned data wasn\'t JSON!')
}
// Get the plain text body, don't need it in JSON
subTemplate = await fetchResult.text()
console.log('### ArmView: Linked template was fetched from external URL')
// Cache results
if (this.cache) {
this.cache.set(linkUri, subTemplate)
console.log('### ArmView: Cache available. Stored external URL result in cache')
}
} else {
console.log('### ArmView: Cache hit, cached results used')
subTemplate = cacheResult
}
} catch (err) {
// That failed, in most cases we'll end up here
console.log(`### ArmView: '${err}' URL not available, will search filesystem`)
subTemplate = '' // IMPORTANT! The above step might have failed but set subTemplate to invalid
// This crazy code tries to search the loaded workspace for the file, two different ways
if (this.editor) {
// Why do we do this? It lets us use this class without VS Code
const vscode = await import('vscode') // await on import! Voodoo!
// File name only of linked template, we'll need this a LOT
const fileName = path.basename(linkUri)
// Try to guess directory it is in (don't worry if it's wrong, it might be)
const linkParts = linkUri.split('/')
const fileParentDir = linkParts[linkParts.length - 2]
// Try loading the from the workspace - assume file is in `fileParentDir` sub-folder
// Most people store templates in a sub-folder and that sub-folder is included in the URL
if (fileParentDir && fileName) {
// wsPath is local VS Code folder where the open editor doc is located
const wsPath = path.dirname(this.editor.document.uri.toString())
const filePath = `${wsPath}/${fileParentDir}/${fileName}`
console.log(`### ArmView: Will try to load file: ${filePath}`)
// Let's give it a try and see if it's there and loads
try {
const fileContent = await vscode.workspace.fs.readFile(vscode.Uri.parse(`${wsPath}/${fileParentDir}/${fileName}`))
subTemplate = fileContent.toString()
} catch (err) {
console.log(`### ArmView: failed to load ${filePath}`)
}
}
// Direct access didn't work, now try a glob search in workspace
const wsLocalFile = path.basename(vscode.workspace.asRelativePath(this.editor.document.uri))
// Only search if prev step failed and the filename we're looking for is NOT the same as the main template
if (!subTemplate && fileName && wsLocalFile !== fileName) {
const wsLocalDir = path.dirname(vscode.workspace.asRelativePath(this.editor.document.uri))
.split(path.sep)
.pop()
let search = `**/${wsLocalDir}/**/${fileName}`
if (wsLocalDir === '.') { search = `**/${fileName}` } // Handle case where folder is at root of ws
console.log(`### ArmView: That didn't work. So will search workspace for: ${search}`)
// Try to run the search
let searchResult
try {
searchResult = await vscode.workspace.findFiles(search)
if (searchResult && searchResult.length > 0) {
console.log(`### ArmView: Found & using file: ${searchResult[0]}`)
const fileContent = await vscode.workspace.fs.readFile(searchResult[0])
subTemplate = fileContent.toString()
}
} catch (err) {
console.log('### ArmView: Warn! Local file error: ' + err)
}
}
}
}
// If we have some data in subTemplate we were successful somehow reading the linked template!
if (subTemplate) {
await this.parseLinkedOrNested(res, subTemplate)
} else {
console.log('### ArmView: Warn! Unable to locate linked template')
}
}
// For nested templates
if (res.type === 'microsoft.resources/deployments' && res.properties && res.properties.template) {
let subTemplate
try {
console.log('### ArmView: Processing nested template in: ' + res.name)
subTemplate = JSON.stringify(res.properties.template)
} catch (err) {
// Do nothing
}
// If we have some data
if (subTemplate) {
await this.parseLinkedOrNested(res, subTemplate)
} else {
console.log('### ArmView: Warn! Unable to parse nested template')
}
}
// Process resource tags, can be objects or strings
if (res.tags && typeof res.tags === 'object') {
Object.keys(res.tags).forEach(tagname => {
const tagval = res.tags[tagname]
// OLD CODE tagval = utils.encode(this._evalExpression(tagval))
// Some crazy people put expressions in their tag names, I mean really...
tagname = utils.encode(this.expParser.eval(tagname))
// Handle special case for displayName tag, which some people use. I dunno
if (tagname.toLowerCase() === 'displayname') {
res.name = tagval
}
// Store tags in 'extra' node data
extraData['Tag ' + tagname] = tagval
})
} else if (res.tags && typeof res.tags === 'string') {
extraData.tags = res.tags
}
// Process SKU
if (res.sku && typeof res.sku === 'object') {
Object.keys(res.sku).forEach(skuname => {
if (res.sku) {
const skuval = res.sku[skuname]
// OLD skuval = utils.encode(this._evalExpression(skuval))
// OLD skuname = utils.encode(this._evalExpression(skuname))
// Store SKU details in 'extra' node data
extraData['SKU ' + skuname] = skuval
}
})
} else if (res.sku && typeof res.sku === 'string') {
extraData.sku = res.sku
}
// Virtual Machines - Try and grab some of the VM info
if (res.type === 'microsoft.compute/virtualmachines') {
try {
if (res.properties.osProfile.linuxConfiguration) {
extraData.os = 'Linux'
}
if (res.properties.osProfile.windowsConfiguration) {
extraData.os = 'Windows'
}
if (res.properties.osProfile.computerName) {
extraData.hostname = utils.encode(this.expParser.eval(res.properties.osProfile.computerName))
}
if (res.properties.osProfile.adminUsername) {
extraData.user = utils.encode(this.expParser.eval(res.properties.osProfile.adminUsername))
}
if (res.properties.hardwareProfile.vmSize) {
extraData.size = utils.encode(this.expParser.eval(res.properties.hardwareProfile.vmSize))
}
if (res.properties.storageProfile.imageReference) {
extraData.image = ''
if (res.properties.storageProfile.imageReference.publisher) {
extraData.image += this.expParser.eval(res.properties.storageProfile.imageReference.publisher)
}
if (res.properties.storageProfile.imageReference.offer) {
extraData.image += '/' + this.expParser.eval(res.properties.storageProfile.imageReference.offer)
}
if (res.properties.storageProfile.imageReference.sku) {
extraData.image += '/' + this.expParser.eval(res.properties.storageProfile.imageReference.sku)
}
}
} catch (ex) {
console.log('### ArmView: Warn! Error when parsing VM resource details: ', res.name)
}
}
// Stick resource node in resulting elements list
const cyNode = new CytoscapeNode('nodes')
cyNode.data = {
extra: extraData,
id: res.id,
img,
kind: res.kind ? res.kind : '',
label,
location: res.location ? utils.encode(res.location) : '',
name: utils.encode(res.name),
type: res.type,
fqn: res.fqn
}
this.elements.push(cyNode)
// Serious business - find the dependsOn dependencies between resources
if (res.dependsOn) {
res.dependsOn.forEach((dependsOn: string) => {
// Most dependsOn are not static strings, they will be expressions
const dependsOnParsed = this.expParser.eval(dependsOn, true)
// Find resource by eval'ed dependsOn string
const dependantRes = this.findResource(this.template.resources, dependsOnParsed)
// Then create a link between this resource and the found dependency
if (dependantRes) { this.addLink(res, dependantRes) }
})
}
// Now recurse into nested resources
if (res.resources) {
await this.processResources(res.resources)
}
} catch (err) {
this.error = err
}
} // end for
}
//
// Create a link "edge" between resources
//
private addLink(r1: any, r2: any): void {
const edge = new CytoscapeNode('edges')
edge.data = {
id: `${r1.id}_${r2.id}`,
source: r1.id,
target: r2.id,
}
this.elements.push(edge)
}
//
// Sub-parse linked and nested templates
//
private async parseLinkedOrNested(res: any, subTemplate: string): Promise<number> {
// If we've got some actual data, means we read the linked file somehow
if (subTemplate) {
const subParser = new ARMParser(this.iconBasePath, res.name, this.reporter, this.editor, this.cache)
try {
const linkRes = await subParser.parse(subTemplate)
// This means we successfully resolved/loaded the linked deployment
if (linkRes.length === 0) {
console.log('### ArmView: Warn! Linked template contained no resources!')
}
for (const subres of linkRes) {
if (subres) {
// IMPORTANT! Only set the parent if it's not already set
// Otherwise we overwrite the value when working with multiple levels deep of linkage
if (subres.data && !subres.data.parent) {
subres.data.parent = res.id
}
// Push linked resources into the main list
this.elements.push(subres)
}
}
return linkRes.length
} catch (err) {
return 0
// linked template parsing error here
}
} else {
console.log('### ArmView: Warn! Unable to locate linked template')
}
return 0
}
//
// Locate a resource by resource id
//
private findResource(resources: Resource[], name: string): any {
for(const res of resources) {
// Handle nested resources recursively
if(res.resources) {
const result = this.findResource(res.resources, name)
if(result) { return result }
}
// Simple match on substring is possible after fully resolving names & types
// Switched to endsWith rather than include, less generous but more correct
// OLD return res.fqn.toLowerCase().includes(name.toLowerCase())
if(res.fqn.toLowerCase().endsWith(name.toLowerCase())) {
return res
}
}
return null
}
} | the_stack |
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator";
import {
join as _join,
wrap as _wrap
} from "apollo-codegen-core/lib/utilities/printing";
export interface Class {
className: string;
modifiers: string[];
superClass?: string;
adoptedProtocols?: string[];
}
export interface Struct {
structName: string;
adoptedProtocols?: string[];
description?: string;
namespace?: string;
}
export interface Protocol {
protocolName: string;
adoptedProtocols?: string[];
}
export interface Property {
propertyName: string;
typeName: string;
isOptional?: boolean;
description?: string;
}
/**
* Swift identifiers that are keywords
*
* Some of these are context-dependent and can be used as identifiers outside of the relevant
* context. As we don't understand context, we will treat them as keywords in all contexts.
*
* This list does not include keywords that aren't identifiers, such as `#available`.
*/
// prettier-ignore
const reservedKeywords = new Set([
// https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID413
// Keywords used in declarations
'associatedtype', 'class', 'deinit', 'enum', 'extension', 'fileprivate',
'func', 'import', 'init', 'inout', 'internal', 'let', 'open', 'operator',
'private', 'protocol', 'public', 'static', 'struct', 'subscript',
'typealias', 'var',
// Keywords used in statements
'break', 'case', 'continue', 'default', 'defer', 'do', 'else', 'fallthrough',
'for', 'guard', 'if', 'in', 'repeat', 'return', 'switch', 'where', 'while',
// Keywords used in expressions and types
'as', 'Any', 'catch', 'false', 'is', 'nil', 'rethrows', 'super', 'self',
'Self', 'throw', 'throws', 'true', 'try',
// Keywords used in patterns
'_',
// Keywords reserved in particular contexts
'associativity', 'convenience', 'dynamic', 'didSet', 'final', 'get', 'infix',
'indirect', 'lazy', 'left', 'mutating', 'none', 'nonmutating', 'optional',
'override', 'postfix', 'precedence', 'prefix', 'Protocol', 'required',
'right', 'set', 'Type', 'unowned', 'weak', 'willSet'
]);
/**
* Swift identifiers that are keywords in member position
*
* This is the subset of keywords that are known to still be keywords in member position. The
* documentation is not explicit about which keywords qualify, but these are the ones that are
* known to have meaning in member position.
*
* We use this to avoid unnecessary escaping with expressions like `.public`.
*/
const reservedMemberKeywords = new Set(["self", "Type", "Protocol"]);
/**
* A class that represents Swift source.
*
* Instances of this type will not undergo escaping when used with the `swift` template tag.
*/
export class SwiftSource {
source: string;
constructor(source: string) {
this.source = source;
}
/**
* Returns the input wrapped in quotes and escaped appropriately.
* @param string The input string, to be represented as a Swift string.
* @param trim If true, trim the string of whitespace and join into a single line.
* @returns A `SwiftSource` containing the Swift string literal.
*/
static string(string: string, trim: boolean = false): SwiftSource {
if (trim) {
string = string
.split(/\n/g)
.map(line => line.trim())
.join(" ");
}
return new SwiftSource(
// String literal grammar:
// https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID417
// Technically we only need to escape ", \, newline, and carriage return, but as Swift
// defines escapes for NUL and horizontal tab, it produces nicer output to escape those as
// well.
`"${string.replace(/[\0\\\t\n\r"]/g, c => {
switch (c) {
case "\0":
return "\\0";
case "\t":
return "\\t";
case "\n":
return "\\n";
case "\r":
return "\\r";
default:
return `\\${c}`;
}
})}"`
);
}
/**
* Returns the input wrapped in a Swift multiline string with escaping.
* @param string The input string, to be represented as a Swift multiline string.
* @returns A `SwiftSource` containing the Swift multiline string literal.
*/
static multilineString(string: string): SwiftSource {
let rawCount = 0;
if (/"""|\\/.test(string)) {
// There's a """ (which would need escaping) or a backslash. Let's do a raw string literal instead.
// We can't just assume a single # is sufficient as it's possible to include the tokens `"""#` or
// `\#n` in a GraphQL multiline string so let's look for those.
let re = /"""(#+)|\\(#+)/g;
for (let ary = re.exec(string); ary !== null; ary = re.exec(string)) {
rawCount = Math.max(
rawCount,
(ary[1] || "").length,
(ary[2] || "").length
);
}
rawCount += 1; // add 1 to get whatever won't collide with the string
}
const rawToken = "#".repeat(rawCount);
return new SwiftSource(
`${rawToken}"""\n${string.replace(/[\0\r]/g, c => {
// Even in a raw string, we want to escape a couple of characters.
// It would be exceedingly weird to have these, but we can still handle them.
switch (c) {
case "\0":
return `\\${rawToken}0`;
case "\r":
return `\\${rawToken}r`;
default:
return c;
}
})}\n"""${rawToken}`
);
}
/**
* Escapes the input if it contains a reserved keyword.
*
* For example, the input `Self?` requires escaping or it will match the keyword `Self`.
*
* @param identifier The input containing identifiers to escape.
* @returns The input with all identifiers escaped.
*/
static identifier(input: string): SwiftSource {
// Swift identifiers use a significantly more complicated definition, but GraphQL names are
// limited to ASCII, so we only have to worry about ASCII strings here.
return new SwiftSource(
input.replace(/[a-zA-Z_][a-zA-Z0-9_]*/g, (match, offset, fullString) => {
if (reservedKeywords.has(match)) {
// If this keyword comes after a '.' make sure it's also a reservedMemberKeyword.
if (
offset == 0 ||
fullString[offset - 1] !== "." ||
reservedMemberKeywords.has(match)
) {
return `\`${match}\``;
}
}
return match;
})
);
}
/**
* Escapes the input if it begins with a reserved keyword not valid in member position.
*
* Most keywords are valid in member position (e.g. after a period), but a few aren't. This
* method escapes just those keywords not valid in member position, and therefore must only be
* used on input that is guaranteed to come after a dot.
* @param input The input containing identifiers to escape.
* @returns The input with relevant identifiers escaped.
*/
static memberName(input: string): SwiftSource {
return new SwiftSource(
// This behaves nearly identically to `SwiftSource.identifier` except for the logic around
// offset zero, but it's structured a bit differently to optimize for the fact that most
// matched identifiers are at offset zero.
input.replace(/[a-zA-Z_][a-zA-Z0-9_]*/g, (match, offset, fullString) => {
if (!reservedMemberKeywords.has(match)) {
// If we're not at offset 0 and not after a period, check the full set.
if (
offset == 0 ||
fullString[offset - 1] === "." ||
!reservedKeywords.has(match)
) {
return match;
}
}
return `\`${match}\``;
})
);
}
/**
* Returns whether the given name is valid as a method parameter name.
*
* Certain tokens aren't valid as method parameter names, even when escaped with backticks, as
* the compiler interprets the keyword and identifier as the same thing. In particular, `self`
* works this way.
* @param input The proposed parameter name.
* @returns `true` if the name can be used, or `false` if it needs a separate internal parameter
* name.
*/
static isValidParameterName(input: string): boolean {
// Right now `self` is the only known token that we can't use with escaping.
return input !== "self";
}
/**
* Template tag for producing a `SwiftSource` value without performing escaping.
*
* This is identical to evaluating the template without the tag and passing the result to `new
* SwiftSource(…)`.
*/
static raw(
literals: TemplateStringsArray,
...placeholders: any[]
): SwiftSource {
// We can't just evaluate the original template directly, but we can replicate its semantics.
// NB: The semantics of untagged template literals matches String.prototype.concat rather than
// the + operator. Since String.prototype.concat is documented as slower than the + operator,
// we'll just use individual template strings to do the concatenation.
var result = literals[0];
placeholders.forEach((value, i) => {
result += `${value}${literals[i + 1]}`;
});
return new SwiftSource(result);
}
toString(): string {
return this.source;
}
/**
* Concatenates multiple `SwiftSource`s together.
*/
concat(...sources: SwiftSource[]): SwiftSource {
// Documentation says + is faster than String.concat, so let's use that
return new SwiftSource(
sources.reduce((accum, value) => accum + value.source, this.source)
);
}
/**
* Appends one or more `SwiftSource`s to the end of a `SwiftSource`.
* @param sources The `SwiftSource`s to append to the end.
*/
append(...sources: SwiftSource[]) {
for (let value of sources) {
this.source += value.source;
}
}
/**
* If maybeSource is not undefined or empty, then wrap with start and end, otherwise return
* undefined.
*
* This is largely just a wrapper for `wrap()` from apollo-codegen-core/lib/utilities/printing.
*/
static wrap(
start: SwiftSource,
maybeSource?: SwiftSource,
end?: SwiftSource
): SwiftSource | undefined {
const result = _wrap(
start.source,
maybeSource !== undefined ? maybeSource.source : undefined,
end !== undefined ? end.source : undefined
);
return result ? new SwiftSource(result) : undefined;
}
/**
* Given maybeArray, return undefined if it is undefined or empty, otherwise return all items
* together separated by separator if provided.
*
* This is largely just a wrapper for `join()` from apollo-codegen-core/lib/utilities/printing.
*
* @param separator The separator to put between elements. This is typed as `string` with the
* expectation that it's generally something like `', '` but if it contains identifiers it should
* be escaped.
*/
static join(
maybeArray?: (SwiftSource | undefined)[],
separator?: string
): SwiftSource | undefined {
const result = _join(maybeArray, separator);
return result ? new SwiftSource(result) : undefined;
}
}
/**
* Template tag for producing a `SwiftSource` value by escaping expressions.
*
* All interpolated expressions will undergo identifier escaping unless the expression value is of
* type `SwiftSource`. If any interpolated expressions are actually intended as string literals, use
* the `SwiftSource.string()` function on the expression.
*/
export function swift(
literals: TemplateStringsArray,
...placeholders: any[]
): SwiftSource {
let result = literals[0];
placeholders.forEach((value, i) => {
result += _escape(value);
result += literals[i + 1];
});
return new SwiftSource(result);
}
function _escape(value: any): string {
if (value instanceof SwiftSource) {
return value.source;
} else if (typeof value === "string") {
return SwiftSource.identifier(value).source;
} else if (Array.isArray(value)) {
// I don't know why you'd be interpolating an array, but let's recurse into it.
return value.map(_escape).join();
} else if (typeof value === "object") {
// use `${…}` instead of toString to preserve string conversion semantics from untagged
// template literals.
return SwiftSource.identifier(`${value}`).source;
} else if (value === undefined) {
return "";
} else {
// Other primitives don't need to be escaped.
return `${value}`;
}
}
// Convenience accessors for wrap/join
const { wrap, join } = SwiftSource;
export class SwiftGenerator<Context> extends CodeGenerator<
Context,
{ typeName: string },
SwiftSource
> {
constructor(context: Context) {
super(context);
}
/**
* Outputs a multi-line string
*
* @param string - The Multi-lined string to output
* @param suppressMultilineStringLiterals - If true, will output the multiline string as a single trimmed
* string to save bandwidth.
* NOTE: String trimming will be disabled if the string contains a
* `"""` sequence as whitespace is significant in GraphQL multiline
* strings.
*/
multilineString(string: string, suppressMultilineStringLiterals: Boolean) {
if (suppressMultilineStringLiterals) {
this.printOnNewline(
SwiftSource.string(string, /* trim */ !string.includes('"""'))
);
} else {
SwiftSource.multilineString(string)
.source.split("\n")
.forEach(line => {
this.printOnNewline(new SwiftSource(line));
});
}
}
comment(comment?: string, trim: Boolean = true) {
comment &&
comment.split("\n").forEach(line => {
this.printOnNewline(SwiftSource.raw`/// ${trim ? line.trim() : line}`);
});
}
deprecationAttributes(
isDeprecated: boolean | undefined,
deprecationReason: string | undefined
) {
if (isDeprecated !== undefined && isDeprecated) {
deprecationReason =
deprecationReason !== undefined && deprecationReason.length > 0
? deprecationReason
: "";
this.printOnNewline(
swift`@available(*, deprecated, message: ${SwiftSource.string(
deprecationReason,
/* trim */ true
)})`
);
}
}
namespaceDeclaration(namespace: string | undefined, closure: Function) {
if (namespace) {
this.printNewlineIfNeeded();
this.printOnNewline(SwiftSource.raw`/// ${namespace} namespace`);
this.printOnNewline(swift`public enum ${namespace}`);
this.pushScope({ typeName: namespace });
this.withinBlock(closure);
this.popScope();
} else {
if (closure) {
closure();
}
}
}
namespaceExtensionDeclaration(
namespace: string | undefined,
closure: Function
) {
if (namespace) {
this.printNewlineIfNeeded();
this.printOnNewline(SwiftSource.raw`/// ${namespace} namespace`);
this.printOnNewline(swift`public extension ${namespace}`);
this.pushScope({ typeName: namespace });
this.withinBlock(closure);
this.popScope();
} else {
if (closure) {
closure();
}
}
}
classDeclaration(
{ className, modifiers, superClass, adoptedProtocols = [] }: Class,
closure: Function
) {
this.printNewlineIfNeeded();
this.printOnNewline(
(
wrap(swift``, new SwiftSource(_join(modifiers, " ")), swift` `) ||
swift``
).concat(swift`class ${className}`)
);
this.print(
wrap(
swift`: `,
join(
[
superClass !== undefined
? SwiftSource.identifier(superClass)
: undefined,
...adoptedProtocols.map(SwiftSource.identifier)
],
", "
)
)
);
this.pushScope({ typeName: className });
this.withinBlock(closure);
this.popScope();
}
/**
* Generates the declaration for a struct
*
* @param param0 The struct name, description, adoptedProtocols, and namespace to use to generate the struct
* @param outputIndividualFiles If this operation is being output as individual files, to help prevent
* redundant usages of the `public` modifier in enum extensions.
* @param closure The closure to execute which generates the body of the struct.
*/
structDeclaration(
{
structName,
description,
adoptedProtocols = [],
namespace = undefined
}: Struct,
outputIndividualFiles: boolean,
closure: Function
) {
this.printNewlineIfNeeded();
this.comment(description);
const isRedundant =
adoptedProtocols.includes("GraphQLFragment") &&
!!namespace &&
outputIndividualFiles;
const modifier = new SwiftSource(isRedundant ? "" : "public ");
this.printOnNewline(swift`${modifier}struct ${structName}`);
this.print(
wrap(swift`: `, join(adoptedProtocols.map(SwiftSource.identifier), ", "))
);
this.pushScope({ typeName: structName });
this.withinBlock(closure);
this.popScope();
}
propertyDeclaration({ propertyName, typeName, description }: Property) {
this.comment(description);
this.printOnNewline(swift`public var ${propertyName}: ${typeName}`);
}
propertyDeclarations(properties: Property[]) {
if (!properties) return;
properties.forEach(property => this.propertyDeclaration(property));
}
protocolDeclaration(
{ protocolName, adoptedProtocols }: Protocol,
closure: Function
) {
this.printNewlineIfNeeded();
this.printOnNewline(swift`public protocol ${protocolName}`);
this.print(
wrap(
swift`: `,
join(
adoptedProtocols !== undefined
? adoptedProtocols.map(SwiftSource.identifier)
: undefined,
", "
)
)
);
this.pushScope({ typeName: protocolName });
this.withinBlock(closure);
this.popScope();
}
protocolPropertyDeclaration({ propertyName, typeName }: Property) {
this.printOnNewline(swift`var ${propertyName}: ${typeName} { get }`);
}
protocolPropertyDeclarations(properties: Property[]) {
if (!properties) return;
properties.forEach(property => this.protocolPropertyDeclaration(property));
}
} | the_stack |
var Sortable; // avoid TS compilation errors but still get working JS code
namespace SSS_Settings
{
// NOTE: When adding new references, keep the same order used in the settings page, roughly divided by section.
const page = {
engines: undefined,
inputs: undefined,
toggleDarkMode: undefined,
addEngineButton: undefined,
addGroupButton: undefined,
addSeparatorButton: undefined,
importBrowserEnginesButton: undefined,
resetSearchEnginesButton: undefined,
minSelectedCharacters: undefined,
maxSelectedCharacters: undefined,
popupDelay: undefined,
middleMouseSelectionClickMargin: undefined,
websiteBlocklist: undefined,
selectionTextFieldLocation: undefined,
nPopupIconsPerRow: undefined,
iconAlignmentInGrid: undefined,
popupBackgroundColorPicker: undefined,
popupBackgroundColor: undefined,
popupHighlightColorPicker: undefined,
popupHighlightColor: undefined,
useCustomPopupCSS: undefined,
customPopupCSS: undefined,
exportSettingsToFileButton: undefined,
importSettingsFromFileButton: undefined,
importSettingsFromFileButton_real: undefined,
saveSettingsToSyncButton: undefined,
loadSettingsFromSyncButton: undefined,
resetSettingsButton: undefined,
};
class EncodingGroup
{
constructor(public name: string, public encodings: string[][]) { }
}
// https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings
const encodings: EncodingGroup[] =
[
new EncodingGroup("Native", [
[ "Default (UTF-8)", "utf8" ],
[ "UCS2", "ucs2" ],
[ "ASCII", "ascii" ],
// [ "Binary", "binary" ],
// [ "Base64", "base64" ],
// [ "Hex", "hex" ],
]),
new EncodingGroup("ISO codepages", [
[ "ISO-8859-1 (Latin-1)", "iso88591" ],
[ "ISO-8859-16 (Latin-10)", "iso885916" ],
]),
new EncodingGroup("Cyrillic (Russia, Ukraine)", [
[ "KOI8-R", "koi8r" ],
[ "KOI8-U", "koi8u" ],
[ "KOI8-RU", "koi8ru" ],
[ "KOI8-T", "koi8t" ],
[ "Windows-1251", "windows1251" ],
]),
new EncodingGroup("Chinese (China)", [
[ "GBK", "gbk" ],
[ "GB 18030", "gb18030" ],
[ "EUC-CN", "euccn" ],
]),
new EncodingGroup("Chinese (Taiwan, Hong Kong)", [
[ "Big5", "big5" ],
[ "Code page 950", "cp950" ],
]),
new EncodingGroup("Japanese", [
[ "Shift JIS", "shiftjis" ],
[ "EUC-JP", "eucjp" ],
]),
new EncodingGroup("Korean", [
[ "EUC-KR", "euckr" ],
]),
];
let settings: SSS.Settings;
let hasPageLoaded: boolean = false;
let isFocused: boolean = true;
let isPendingSettings: boolean = false;
let DEBUG;
let log;
let sssIcons: { [id: string] : SSS.SSSIconDefinition; };
let defaultSettings: SSS.Settings;
let browserVersion: number; // unused for now, but we may want it to control compatibility
let hasDOMContentLoaded: boolean = false;
document.addEventListener("DOMContentLoaded", onDOMContentLoaded);
// ask all needed information from the background script (can't use browser.extension.getBackgroundPage() in private mode, so it has to be this way)
browser.runtime.sendMessage({ type: "getDataForSettingsPage" }).then(
data => {
DEBUG = data.DEBUG;
browserVersion = data.browserVersion;
sssIcons = data.sssIcons;
defaultSettings = data.defaultSettings;
// now we can initialize things
if (DEBUG) {
log = console.log;
}
// Load settings. The last of either onSettingsAcquired and onPageLoaded will update the UI with the loaded settings.
browser.storage.local.get().then(onSettingsAcquired, getErrorHandler("Error getting settings in settings page."));
browser.storage.onChanged.addListener(onSettingsChanged);
// if DOM already loaded by now, setup page
if (hasDOMContentLoaded) {
onPageLoaded();
}
// if it isn't, set up page when DOM loads (onDOMContentLoaded)
},
getErrorHandler("Error sending getDataForSettingsPage message from settings.")
);
// default error handler for promises
function getErrorHandler(text: string): (reason: any) => void
{
if (DEBUG) {
return error => { log(`${text} (${error})`); };
} else {
return undefined;
}
}
async function createDefaultEngine(engine: SSS.SearchEngine): Promise<SSS.SearchEngine>
{
engine.uniqueId = await browser.runtime.sendMessage({ type: "generateUniqueEngineId" });
engine.isEnabled = true;
engine.isEnabledInContextMenu = true;
return engine;
}
// adds to SSS all engines from the browser (these are special and contain very little information)
async function addBrowserEnginesToEnginesList(browserSearchEngines: browser.search.SearchEngine[])
{
// "hash set" of search URLs (will help avoiding duplicates of previously imported browser engines)
const names = {};
for (const engine of settings.searchEngines) {
if (engine.type === SSS.SearchEngineType.BrowserSearchApi) {
names[(engine as SSS.SearchEngine_BrowserSearchApi).name] = true;
}
}
let nAddedEngines = 0;
// add all browser search engines
for (const browserSearchEngine of browserSearchEngines)
{
// avoid duplicates if this browser engine is already in the "hash set"
if (names.hasOwnProperty(browserSearchEngine.name)) continue;
// create an engine object compatible with class SearchEngine_BrowserSearchApi
settings.searchEngines.push(await createDefaultEngine({
type: SSS.SearchEngineType.BrowserSearchApi,
name: browserSearchEngine.name,
iconUrl: browserSearchEngine.favIconUrl ?? "",
} as SSS.SearchEngine_BrowserSearchApi));
nAddedEngines++;
}
if (nAddedEngines == 0) {
alert("No new engines were added.");
}
}
// Hackish way to get the image data (base64 data:image) from the URL of an image.
// Sets the URL as img source, waits for download, then scales it down if needed, draws to a canvas and gets the resulting pixel data.
function getDataUriFromImgUrl(imageUrl, callback)
{
var img = new Image();
img.crossOrigin = "Anonymous";
img.onload = _ => {
const maxSize = 48;
let width;
let height;
let xPos = 0;
let yPos = 0;
// Scale image to smaller icon if needed (always keep aspect ratio).
// We don't want stored SSS icons to take a lot of space.
if (img.width > img.height) {
width = Math.min(maxSize, img.width);
height = width * img.height / img.width;
yPos = (width - height) / 2;
} else if (img.height > img.width) {
height = Math.min(maxSize, img.height);
width = height * img.width / img.height;
xPos = (height - width) / 2;
} else {
width = Math.min(maxSize, img.width);
height = width;
}
if (DEBUG) { log(img.width + "x" + img.height + " became " + width + "x" + height); }
// canvas is always a square (using larger dimension)
const canvas = document.createElement("canvas");
canvas.width = canvas.height = Math.max(width, height);
// draw image with size and position defined above
const ctx = canvas.getContext("2d");
ctx.drawImage(img, xPos, yPos, width, height);
// finally get the image data (base64 data:image)
const dataURL = canvas.toDataURL();
if (DEBUG) { log(dataURL.length); }
if (DEBUG) { log(imageUrl); }
if (DEBUG) { log(dataURL); }
callback(dataURL);
};
img.src = imageUrl; // starts the download and will call onload eventually
}
function onDOMContentLoaded()
{
// if we have the defaultSettings already, it means we have everything from the background script
if (defaultSettings !== undefined) {
onPageLoaded();
}
hasDOMContentLoaded = true;
}
function setGroupIconColor(iconCanvas: HTMLCanvasElement, colorAsString: string)
{
const iconSize: number = iconCanvas.width; // same as height
const ctx = iconCanvas.getContext("2d");
ctx.clearRect(0, 0, iconSize, iconSize);
ctx.beginPath();
ctx.arc(iconSize/2, iconSize/2, iconSize/2, 0, 2 * Math.PI); // (centerX, centerY, radius, startAngle, endAngle)
// Apply a random color to the icon whenever a group is created. If editing, apply the color that was saved before.
ctx.fillStyle = colorAsString;
ctx.fill();
}
// generates a random color string like #f6592b
function generateRandomColorAsString(): string
{
function channelToHex(channel) {
const hex = channel.toString(16);
return hex.length == 2 ? hex : "0" + hex; // pad with zero if needed
}
return "#" + channelToHex(Math.floor(Math.random() * 256))
+ channelToHex(Math.floor(Math.random() * 256))
+ channelToHex(Math.floor(Math.random() * 256));
}
// This is called to either create or edit a group.
// When editing, we pass the group as a parameter.
function showGroupPopup(groupEngineToEdit: SSS.SearchEngine_Group = null)
{
const groupEnginePopup = document.querySelector("#group-popup") as HTMLDivElement;
groupEnginePopup.classList.remove("hidden");
// This div overlays the whole page while the popup is showing. Clicking it hides the popup.
const backgroundDiv = document.querySelector("#group-background-div") as HTMLDivElement;
backgroundDiv.onclick = _ => hideGroupPopup();
// Prevent body from scrolling in the background.
document.body.style.overflow = "hidden";
const isEditing: boolean = groupEngineToEdit !== null;
// This array stores the engines that are selected for the group.
const groupEngineUniqueIds: string[] = isEditing ? [...groupEngineToEdit.enginesUniqueIds] : [];
// Group icon can be an image or a canvas. We get both elements and use whichever is needed later.
const groupIconAsImage: HTMLImageElement = document.querySelector("#group-icon-img") as HTMLImageElement;
const groupIconAsCanvas: HTMLCanvasElement = document.querySelector("#group-icon-canvas") as HTMLCanvasElement;
const groupColorPicker = document.querySelector("#group-color-picker") as HTMLInputElement;
let color: string = isEditing ? groupEngineToEdit.color : generateRandomColorAsString();
let wasIconModifiedByUser: boolean = isEditing && !groupEngineToEdit.iconUrl.startsWith("data:image/png");
if (wasIconModifiedByUser)
{
groupIconAsImage.classList.remove("hidden");
groupIconAsImage.src = groupEngineToEdit.iconUrl;
// Implement onclick to ask for confirmation if the icon was hand-modified by the user.
groupColorPicker.onclick = ev => {
if (!wasIconModifiedByUser) return;
if (confirm("Revert to the default icon?")) {
groupIconAsImage.classList.add("hidden");
groupIconAsCanvas.classList.remove("hidden");
setGroupIconColor(groupIconAsCanvas, color);
groupColorPicker.value = color;
wasIconModifiedByUser = false;
} else {
ev.preventDefault();
}
};
}
else
{
groupIconAsCanvas.classList.remove("hidden");
setGroupIconColor(groupIconAsCanvas, color);
groupColorPicker.value = color;
}
groupColorPicker.oninput = _ => {
color = groupColorPicker.value;
setGroupIconColor(groupIconAsCanvas, color);
};
const groupTitleField = document.querySelector("#group-title-field") as HTMLInputElement;
groupTitleField.placeholder = "Group name";
groupTitleField.value = isEditing ? groupEngineToEdit.name : "";
groupTitleField.focus();
// This stores the rows (node) of the selected engines.
// Useful when editing a group, to show the engines in the exact order
// the user selected them when creating it.
const engineRows = [];
const selectedEnginesContainer = document.querySelector("#group-selected-engines-container") as HTMLDivElement; // for engines in the group
const availableEnginesContainer = document.querySelector("#group-available-engines-container") as HTMLDivElement; // for engines NOT in the group
const engineRowTemplate = document.querySelector("#group-engines-list-row-template") as HTMLTemplateElement; // will be cloned for each engine to create in the list
const availableEngines = settings.searchEngines.filter(e => e !== groupEngineToEdit && e.type !== SSS.SearchEngineType.SSS && e.type !== SSS.SearchEngineType.BrowserSearchApi);
for (let i = 0; i < availableEngines.length; i++)
{
const engine = availableEngines[i];
const groupEnginesListRow = engineRowTemplate.content.firstElementChild.cloneNode(true) as HTMLDivElement;
// HACK-ish. Saves the index to use later when removing the engine from the group and adding it to the available engines again.
groupEnginesListRow["engineIndex"] = i;
const dragger = groupEnginesListRow.querySelector(".engine-dragger") as HTMLDivElement;
dragger.style.display = "none"; // The dragger will only show for the selected engines.
// When editing, check the engines that are already on the group.
let isSelected: boolean = isEditing && groupEngineUniqueIds.indexOf(engine.uniqueId) > -1;
// Clicking on the row itself selects the engine.
groupEnginesListRow.onclick = _ => {
if (isSelected) return;
// if adding a group to this group, make sure it doesn't contain this group (directly or indirectly), as it would create a cycle
if (isEditing && engine.type === SSS.SearchEngineType.Group)
{
// recursively search the clicked group for the engine we're editing
function findRecursively(groupEngine: SSS.SearchEngine_Group, engineToFind: SSS.SearchEngine): boolean
{
for (const engineId of (groupEngine as SSS.SearchEngine_Group).enginesUniqueIds)
{
const engine = settings.searchEngines.find(eng => eng.uniqueId === engineId);
if (engine.type === SSS.SearchEngineType.Group) {
if (engine === engineToFind) return true;
if (findRecursively(engine as SSS.SearchEngine_Group, engineToFind)) return true;
}
}
return false;
}
if (findRecursively(engine as SSS.SearchEngine_Group, groupEngineToEdit)) {
alert("Adding this group engine would create an infinite cycle, since it contains (directly or indirectly) the group you're currently editing. You can't do that! ;)")
return;
}
}
isSelected = true;
groupEngineUniqueIds.push(engine.uniqueId);
dragger.style.display = "block";
// The first selected engine will be the main one and stays at the top of the list.
// All the others will be appended after the last selected.
selectedEnginesContainer.appendChild(groupEnginesListRow);
saveButton.disabled = false;
};
const engineIconImg = groupEnginesListRow.querySelector(".engine-icon-img > img") as HTMLImageElement;
setupEngineIconImg(engine, engineIconImg);
const engineName = groupEnginesListRow.querySelector(".engine-in-group-name") as HTMLSpanElement;
engineName.textContent = (engine as SSS.SearchEngine_NonSSS).name;
const deleteButton = groupEnginesListRow.querySelector(".group-remove-engine-button > input") as HTMLInputElement;
deleteButton.onclick = ev => {
const index = groupEngineUniqueIds.indexOf(engine.uniqueId);
groupEngineUniqueIds.splice(index, 1);
// Find the correct place to insert the engine back in the available engines list,
// even if other engines were removed from there in the meantime.
const engineIndex = groupEnginesListRow["engineIndex"];
let wasInserted = false;
for (const child of availableEnginesContainer.children)
{
if (child["engineIndex"] > engineIndex) {
availableEnginesContainer.insertBefore(groupEnginesListRow, child);
wasInserted = true;
break;
}
}
if (!wasInserted) {
availableEnginesContainer.appendChild(groupEnginesListRow);
}
dragger.style.display = "none";
isSelected = false;
saveButton.disabled = groupEngineUniqueIds.length === 0;
ev.stopPropagation(); // block parent from also receiving click and selecting the engine again
};
if (isSelected) {
// engineRows stores the rows in the same order the engines were selected
// which is the same order in groupEngines. This allows the user to
// change the position of the engines according to their needs.
engineRows[groupEngineUniqueIds.indexOf(engine.uniqueId)] = groupEnginesListRow;
dragger.style.display = "block"; // Show dragger only for the selected engines
}
availableEnginesContainer.appendChild(groupEnginesListRow);
}
// When editing, place the engines of the group at the top of the list.
selectedEnginesContainer.append(...engineRows);
/* ---- Popup footer ---- */
const cancelButton = document.querySelector("#group-popup-cancel-button") as HTMLInputElement;
cancelButton.onclick = _ => hideGroupPopup();
const saveButton = document.querySelector("#group-popup-save-button") as HTMLInputElement;
saveButton.disabled = groupEngineUniqueIds.length === 0;
saveButton.onclick = async _ => {
const groupName = groupTitleField.value.length > 0 ? groupTitleField.value : groupEngineToEdit?.name || "Group";
const iconUrl: string = wasIconModifiedByUser ? groupIconAsImage.src : groupIconAsCanvas.toDataURL();
const groupData = {
name: groupName,
enginesUniqueIds: groupEngineUniqueIds,
iconUrl: iconUrl,
color: color,
type: SSS.SearchEngineType.Group,
};
if (groupEngineToEdit) {
Object.assign(groupEngineToEdit, groupData);
} else {
settings.searchEngines.push(await createDefaultEngine(groupData as SSS.SearchEngine_Group));
}
saveSettings({ searchEngines: settings.searchEngines });
updateUIWithSettings();
hideGroupPopup();
};
// setup draggable elements to be able to sort engines
const groupPopupSortableManager = Sortable.create(selectedEnginesContainer, {
handle: ".engine-dragger",
onEnd: ev => {
groupEngineUniqueIds.splice(ev.newIndex, 0, groupEngineUniqueIds.splice(ev.oldIndex, 1)[0]);
},
});
groupEnginePopup.onkeydown = ev => {
switch (ev.key) {
case "Escape":
hideGroupPopup();
break;
case "Enter":
saveButton.click();
break;
}
};
function hideGroupPopup()
{
// Hide the popup
groupEnginePopup.classList.add("hidden");
selectedEnginesContainer.innerHTML = "";
availableEnginesContainer.innerHTML = "";
groupIconAsImage.classList.add("hidden");
groupIconAsCanvas.classList.add("hidden");
groupPopupSortableManager.destroy();
// Make body scrollable again.
document.body.style.overflow = "auto";
}
}
// main setup for settings page, called when page loads
function onPageLoaded()
{
// save all form elements for easy access
page.engines = document.querySelector("#engines");
page.inputs = document.querySelectorAll("input, select, textarea");
for (const item of page.inputs) {
page[item.name] = item;
}
// register change event for anything in the form
const container: any = document.querySelector("#settings");
container.onchange = ev => {
const item = ev.target;
if (DEBUG) { log("onFormChanged target: " + item.name + ", value: " + item.value); }
// special things in the options page need special code
if (item.name === "importSettingsFromFileButton_real")
{
const reader = new FileReader();
reader.onload = _ => {
const importedSettings = JSON.parse(reader.result as string);
importSettings(importedSettings);
// alert("All settings were imported!");
};
reader.readAsText(ev.target.files[0]);
}
// otherwise, if not a "special thing", this is a field
else {
saveElementValueToSettings(item, true);
}
};
page.importBrowserEnginesButton.onclick = async _ =>
{
if (confirm("Really import your browser's search engines?"))
{
const browserSearchEngines: browser.search.SearchEngine[] = await browser.search.get();
if (DEBUG) { log(browserSearchEngines); }
await addBrowserEnginesToEnginesList(browserSearchEngines);
updateUIWithSettings();
saveSettings({ searchEngines: settings.searchEngines });
}
}
page.exportSettingsToFileButton.onclick = _ =>
{
// to save as a file we need the "downloads permission"
browser.permissions.request({ permissions: ["downloads"] }).then(wasPermissionGranted =>
{
if (!wasPermissionGranted) {
alert("Sorry, you cannot export your file without the \"Downloads\" permission! I know it's weird, but it's really needed. :(");
return;
}
// remove useless stuff that doesn't need to be stored
var blob = runActionOnDietSettings(settings, (settings: SSS.Settings) => new Blob([JSON.stringify(settings)]));
// save with current date and time
const filename = "SSS settings backup (" + new Date(Date.now()).toJSON().replace(/:/g, ".") + ").json";
browser.downloads.download({
"saveAs": true,
"url": URL.createObjectURL(blob),
"filename": filename,
});
});
};
// There are two elements for the import button: a button for display and the actual "real" button that lets the user pick the file.
// This is done because the file picker button can't be formatted and would look very ugly.
// When we click the visual one, we want to call the real one.
page.importSettingsFromFileButton.onclick = _ => page.importSettingsFromFileButton_real.click();
// register events for specific behaviour when certain fields change (color pickers change their text and vice versa)
page.popupBackgroundColorPicker.oninput = _ => updateColorText (page.popupBackgroundColor, page.popupBackgroundColorPicker.value);
page.popupBackgroundColor.oninput = _ => updatePickerColor(page.popupBackgroundColorPicker, page.popupBackgroundColor.value);
page.popupHighlightColorPicker.oninput = _ => updateColorText (page.popupHighlightColor, page.popupHighlightColorPicker.value);
page.popupHighlightColor.oninput = _ => updatePickerColor(page.popupHighlightColorPicker, page.popupHighlightColor.value);
// this should use "onfocus" instead of "onclick" but permissions.request can only be called on user input... (it still works with onfocus, but prints errors)
page.websiteBlocklist.onclick = _ => {
// to use the website blocklist we need the tabs permission
browser.permissions.request({ permissions: ["tabs"] }).then(wasPermissionGranted =>
{
if (!wasPermissionGranted) {
page.websiteBlocklist.blur(); // remove focus
alert("Sorry, the website blocklist won't work without the \"Tabs\" permission!");
}
});
};
// setup reset buttons for each option
for (const elem of document.querySelectorAll(".setting-reset"))
{
const inputElements = elem.querySelectorAll("input");
if (inputElements.length == 0) continue;
inputElements[0].onclick = _ => {
const parent = elem.closest(".setting");
const formElement = parent.querySelector(".setting-input") as HTMLFormElement;
const settingName = formElement.name;
// register the change and save in storage
const defaultValue = defaultSettings[settingName];
settings[settingName] = defaultValue;
saveSettings({ [settingName]: defaultValue });
loadSettingValueIntoElement(formElement);
};
}
// sections' collapse/expand code
for (const sectionNameElement of document.querySelectorAll(".section-name"))
{
// toggle entire section on clicking the title, and save in settings the resulting state (open/closed)
(sectionNameElement as HTMLElement).onclick = _ => {
if (settings.sectionsExpansionState === undefined) {
settings.sectionsExpansionState = {};
}
const isCollapsed = sectionNameElement.parentElement.classList.toggle("collapsed-section");
settings.sectionsExpansionState[sectionNameElement.parentElement.id] = !isCollapsed;
saveSettings({ sectionsExpansionState: settings.sectionsExpansionState });
};
}
// show platform-specific sections (some info on the page is related to a specific OS and should only appear in that OS)
browser.runtime.getPlatformInfo().then(info => {
let platformSpecificElements;
switch (info.os)
{
case "android":
case "cros":
case "linux":
case "openbsd":
platformSpecificElements = document.querySelectorAll(".os-linux");
break;
case "mac":
platformSpecificElements = document.querySelectorAll(".os-mac");
break;
case "win":
default:
platformSpecificElements = document.querySelectorAll(".os-windows");
break;
}
for (const elem of platformSpecificElements) {
elem.style.display = "inline";
}
});
// entering/leaving settings page
window.onfocus = _ => {
// if settings changed while page was not focused, reload settings and UI
if (isPendingSettings) {
browser.storage.local.get().then(onSettingsAcquired, getErrorHandler("Error getting settings in settings page."));
}
isFocused = true;
};
window.onblur = _ => {
isFocused = false;
};
// register events for more button clicks
page.toggleDarkMode.setDarkModeState = enable => {
if (enable) {
document.body.classList.add("dark");
} else {
document.body.classList.remove("dark");
}
};
page.toggleDarkMode.onclick = _ => {
settings.useDarkModeInOptionsPage = !settings.useDarkModeInOptionsPage;
page.toggleDarkMode.setDarkModeState(settings.useDarkModeInOptionsPage);
saveSettings({ useDarkModeInOptionsPage: settings.useDarkModeInOptionsPage });
};
page.addEngineButton.onclick = async _ => {
const searchUrl = "https://www.google.com/search?q={searchTerms}"; // use google as an example
const iconUrl = getIconUrlFromSearchUrl(searchUrl); // by default try to get a favicon for the domain
settings.searchEngines.push(await createDefaultEngine({
type: SSS.SearchEngineType.Custom,
name: "New Search Engine",
searchUrl: searchUrl,
iconUrl: iconUrl
} as SSS.SearchEngine_Custom));
saveSettings({ searchEngines: settings.searchEngines });
updateUIWithSettings();
};
page.addGroupButton.onclick = _ => {
showGroupPopup();
};
page.addSeparatorButton.onclick = async _ => {
settings.searchEngines.push(await createDefaultEngine({
type: SSS.SearchEngineType.SSS,
id: "separator",
} as SSS.SearchEngine_SSS));
saveSettings({ searchEngines: settings.searchEngines });
updateUIWithSettings();
};
// saves settings to Firefox Sync
page.saveSettingsToSyncButton.onclick = _ => {
if (DEBUG) { log("saving!"); }
// remove useless stuff that doesn't need to be stored
var settingsStr = runActionOnDietSettings(settings, (settings: SSS.Settings) => JSON.stringify(settings));
// divide into different fields so as not to trigger Firefox's "Maximum bytes per object exceeded ([number of bytes] > 16384 Bytes.)"
const chunks = {};
let chunkIndex = 0;
for (let i = 0, length = settingsStr.length; i < length; i += 1000, chunkIndex++) {
chunks["p"+chunkIndex] = settingsStr.substring(i, i + 1000);
}
browser.storage.sync.clear();
browser.storage.sync.set(chunks).then(
() => { if (DEBUG) { log("All settings and engines were saved in Sync!"); } },
() => { if (DEBUG) { log("Uploading to Sync failed! Is your network working? Are you under the 100KB size limit?"); } }
);
if (DEBUG) { log("saved in sync!", chunks); }
};
// buttons with confirmation
page.resetSearchEnginesButton.onclick = _ =>
{
if (confirm("Really reset search engines to the default ones?"))
{
const defaultEngines = JSON.parse(JSON.stringify(defaultSettings.searchEngines));
settings.searchEngines = defaultEngines;
updateUIWithSettings();
saveSettings({ searchEngines: settings.searchEngines });
}
};
page.resetSettingsButton.onclick = _ =>
{
if (confirm("Really reset all settings to their default values?"))
{
const searchEngines = settings.searchEngines; // stash engines
settings = JSON.parse(JSON.stringify(defaultSettings)); // copy default settings
settings.searchEngines = searchEngines; // restore engines
updateUIWithSettings();
saveSettings(settings);
}
};
page.loadSettingsFromSyncButton.onclick = _ =>
{
if (confirm("Really load all settings from Firefox Sync?"))
{
browser.storage.sync.get().then(chunks => {
if (DEBUG) { log(chunks); }
// join all chunks of data we uploaded to sync in a list
const chunksList = [];
let p;
for (let i = 0; (p = chunks["p"+i]) !== undefined; i++) {
chunksList.push(p);
}
// parse the chunks into an actual object
const parsedSettings = parseSyncChunksList(chunksList);
// finally try importing the read settings
if (parsedSettings !== null) {
importSettings(parsedSettings);
}
}, getErrorHandler("Error getting settings from sync."));
}
};
// finish and set elements based on settings, if they are already loaded
hasPageLoaded = true;
if (settings !== undefined) {
updateUIWithSettings();
}
// make page content visible, but only after a minimum of time, so that the UI adjusts beforehand
setTimeout(() => {
document.body.style.display = "inherit";
}, 0);
}
function parseSyncChunksList(chunksList: string[])
{
// NOTE: due to an old SSS bug (now fixed), there can be chunks in Sync that are not actually part of the last "Save to Sync".
// (For example if the last save uploaded only chunks p0 and p1, but Sync already had chunks p0, p1 AND p2 in there.)
// Due to this, parsing the concatenated chunks would result in JSON errors, so if they happen we try removing the last chunks
// one by one until parsing works.
// The origin of the bug was fixed by clearing all Sync storage before setting new data.
let settingsStr: string = "";
let parsedSettings = null;
while (chunksList.length > 0)
{
// compact the list into a large string and try parsing it
settingsStr = chunksList.join("");
try {
parsedSettings = JSON.parse(settingsStr);
break; // break from loop if successful
} catch {
if (DEBUG) { log("error parsing settings from sync: " + settingsStr); }
if (DEBUG) { log("trying again with one chunk fewer"); }
chunksList.pop();
}
}
if (DEBUG) { log("settings from sync, as string: " + settingsStr); }
return parsedSettings;
}
function onSettingsAcquired(_settings)
{
settings = _settings;
if (hasPageLoaded) {
updateUIWithSettings();
}
}
function onSettingsChanged()
{
if (!isFocused) {
isPendingSettings = true;
}
}
function updateUIWithSettings()
{
if (DEBUG) { log("updateUIWithSettings", settings); }
// load UI values from settings
for (const item of page.inputs) {
loadSettingValueIntoElement(item);
}
// calculate storage size (helpful for Firefox Sync)
calculateAndShowSettingsSize();
// update engines
if (settings.searchEngines !== undefined)
{
// delete existing engine HTML elements for engines
const engineParent = page.engines;
while (engineParent.firstChild) {
engineParent.removeChild(engineParent.firstChild);
}
let currentlyExpandedEngineOptions = null;
// add all engines
for (let i = 0; i < settings.searchEngines.length; i++)
{
const engine = settings.searchEngines[i];
const tableRow = buildSearchEngineTableRow();
const engineRow = buildSearchEngineRow(engine, i);
tableRow.appendChild(engineRow);
const optionsRow = buildSearchEngineOptionsTableRow(engine, i);
tableRow.appendChild(optionsRow);
// expand engine options when clicking somewhere in the engine (and guarantee there's only one expanded at any time)
tableRow.onclick = ev => {
if (currentlyExpandedEngineOptions !== null && currentlyExpandedEngineOptions !== optionsRow) {
currentlyExpandedEngineOptions.style.display = "none";
}
optionsRow.style.display = "initial";
currentlyExpandedEngineOptions = optionsRow;
ev.stopPropagation();
};
page.engines.appendChild(tableRow);
}
// set an event to close any expanded engine options when clicking outisde a section
document.onclick = ev => {
if (currentlyExpandedEngineOptions !== null) {
// hide if neither itself or any parent is a table row
if ((ev.target as Element).closest(".engine-table-row") === null) {
currentlyExpandedEngineOptions.style.display = "none";
}
}
};
// setup draggable elements to be able to sort engines
Sortable.create(page.engines, {
handle: ".engine-dragger",
onStart: ev => {
if (DEBUG) { log("start drag", ev.oldIndex); }
},
onUpdate: ev => {
var item = ev.item; // the current dragged HTMLElement
if (DEBUG) { log("onUpdate", item); }
},
onEnd: ev => {
if (DEBUG) { log("onEnd", settings); }
settings.searchEngines.splice(ev.newIndex, 0, settings.searchEngines.splice(ev.oldIndex, 1)[0]);
saveSettings({ searchEngines: settings.searchEngines });
updateUIWithSettings();
},
});
}
// collapse or expand sections
if (settings.sectionsExpansionState !== undefined)
{
for (const sectionId of Object.keys(settings.sectionsExpansionState))
{
const classList = document.querySelector("#" + sectionId).classList;
const isExpanded = settings.sectionsExpansionState[sectionId];
classList.toggle("collapsed-section", !isExpanded);
}
}
// set dark/light mode
page.toggleDarkMode.setDarkModeState(settings.useDarkModeInOptionsPage);
}
function saveElementValueToSettings(item: HTMLFormElement, didElementValueChange: boolean = false): boolean
{
const name = item.name;
if (!(name in settings)) return false;
// different fields have different ways to get their value
let value;
if (item.type === "checkbox") {
value = item.checked;
} else if (item.type === "number") {
value = parseInt(item.value);
} else {
value = item.value;
}
if (didElementValueChange) {
updateSetting(name, value);
}
// register the change and save in storage
settings[name] = value;
saveSettings({ [name]: value });
return true;
}
function loadSettingValueIntoElement(item: HTMLFormElement): boolean
{
const name = item.name;
// all settings are saved with the same name as the input elements in the page
if (!(name in settings)) return false;
const value = settings[name];
// each kind of input element has a different value to set
if (item.type === "checkbox") {
item.checked = value;
} else {
item.value = value;
}
updateSetting(name, value);
return true;
}
function updateSetting(name: string, value: any)
{
switch (name)
{
// update color pickers from their hexadecimal text
case "popupBackgroundColor":
updatePickerColor(page.popupBackgroundColorPicker, value);
break;
case "popupHighlightColor":
updatePickerColor(page.popupHighlightColorPicker, value);
break;
// some options only appear if some other option has a certain value
case "popupOpenBehaviour":
updateHtmlElementSetting(page.popupDelay, value === SSS.PopupOpenBehaviour.Auto);
updateHtmlElementSetting(page.minSelectedCharacters, value === SSS.PopupOpenBehaviour.Auto);
updateHtmlElementSetting(page.maxSelectedCharacters, value === SSS.PopupOpenBehaviour.Auto);
updateHtmlElementSetting(page.middleMouseSelectionClickMargin, value === SSS.PopupOpenBehaviour.MiddleMouse);;
break;
case "showSelectionTextField":
updateHtmlElementSetting(page.selectionTextFieldLocation, value === true);
break;
case "useSingleRow":
updateHtmlElementSetting(page.nPopupIconsPerRow, value === false);
updateHtmlElementSetting(page.iconAlignmentInGrid, value === false);
break;
case "useCustomPopupCSS":
updateHtmlElementSetting(page.customPopupCSS, value === true);
break;
}
function updateHtmlElementSetting(element: HTMLElement, enabled: boolean)
{
const setting = element.closest(".setting");
if (enabled) {
setting.classList.remove("hidden");
} else {
setting.classList.add("hidden");
}
}
}
// estimates size of settings in bytes and shows warning messages if this is a problem when using Firefox Sync
function calculateAndShowSettingsSize()
{
const storageSize = runActionOnDietSettings(settings, settings => JSON.stringify(settings).length * 2); // times 2 because each char is 2 bytes
const maxRecommendedStorageSize = 100 * 1024;
for (const elem of document.querySelectorAll(".warn-when-over-storage-limit")) {
(elem as HTMLElement).style.color = storageSize > maxRecommendedStorageSize ? "red" : "";
}
document.querySelector("#storage-size").textContent = getSizeWithUnit(storageSize);
}
// creates a row for the engines table
function buildSearchEngineTableRow()
{
const parent = document.createElement("div");
parent.className = "engine-table-row";
return parent;
}
// creates a search engine for the engines table (each in a different row)
function buildSearchEngineRow(engine, i)
{
const engineRow = document.createElement("div");
engineRow.className = "engine-itself";
// dragger element
const dragger = createElement_EngineDragger();
engineRow.appendChild(dragger);
// "is enabled" element
const isEnabledCheckboxParent = document.createElement("div");
isEnabledCheckboxParent.className = "engine-is-enabled";
const isEnabledCheckbox = document.createElement("input");
isEnabledCheckbox.type = "checkbox";
isEnabledCheckbox.checked = engine.isEnabled;
isEnabledCheckbox.autocomplete = "off";
isEnabledCheckbox.title = "Show in popup";
isEnabledCheckbox.onchange = _ => {
setEnabledInPopup(engine, i, isEnabledCheckbox.checked);
};
isEnabledCheckboxParent.appendChild(isEnabledCheckbox);
engineRow.appendChild(isEnabledCheckboxParent);
// "is enabled in context menu" element
const isEnabledInContextMenuCheckboxParent = document.createElement("div");
isEnabledInContextMenuCheckboxParent.className = "engine-is-enabled-in-context-menu";
const isEnabledInContextMenuCheckbox = document.createElement("input");
isEnabledInContextMenuCheckbox.type = "checkbox";
isEnabledInContextMenuCheckbox.checked = engine.isEnabledInContextMenu;
isEnabledInContextMenuCheckbox.autocomplete = "off";
isEnabledInContextMenuCheckbox.title = "Show in context menu";
isEnabledInContextMenuCheckbox.onchange = _ => {
setEnabledInContextMenu(engine, i, isEnabledInContextMenuCheckbox.checked);
};
isEnabledInContextMenuCheckboxParent.appendChild(isEnabledInContextMenuCheckbox);
engineRow.appendChild(isEnabledInContextMenuCheckboxParent);
// icon
const engineIcon = document.createElement("div");
engineIcon.className = "engine-icon-img";
const iconImg = document.createElement("img");
engineIcon.appendChild(iconImg);
setupEngineIconImg(engine, iconImg);
engineRow.appendChild(engineIcon);
if (engine.type === SSS.SearchEngineType.SSS)
{
// create columns for this row, most disabled because special SSS icons can't be edited
const sssIcon = sssIcons[engine.id];
// name
engineRow.appendChild(createElement_UneditableEngineName(sssIcon.name));
// description
const engineDescription = document.createElement("div");
engineDescription.className = "engine-uneditable engine-uneditable-description";
engineDescription.textContent = sssIcon.description;
engineRow.appendChild(engineDescription);
if (engine.id === "separator") {
engineRow.appendChild(createElement_EngineShortcutFieldDiv());
engineRow.appendChild(createElement_DeleteButton(i));
} else {
engineRow.appendChild(createElement_EngineShortcutField(engine));
engineRow.appendChild(createElement_DeleteButtonDiv());
}
}
else
{
// create columns for "normal" icons
if (engine.type === SSS.SearchEngineType.BrowserSearchApi) {
// browser-imported engines can't have their names modified
engineRow.appendChild(createElement_UneditableEngineName(engine.name));
} else {
engineRow.appendChild(createElement_EngineName(engine));
}
// This object keeps references to a few variables so that when the user changes the search URL
// we can update the icon URL (if it was using the default URL), and when the icon URL is cleared
// it can use the search URL to generate a new icon URL.
// Only the anonymous callbacks inside the following functions will use values inside this object.
const references = {};
if (engine.type === SSS.SearchEngineType.BrowserSearchApi)
{
const engineDescription = document.createElement("div");
engineDescription.className = "engine-uneditable engine-description-small";
engineDescription.textContent = "[Browser] Engine imported from the browser.";
engineRow.appendChild(engineDescription);
}
else if (engine.type === SSS.SearchEngineType.Group)
{
// create columns for groups
const engineDescription = document.createElement("div");
engineDescription.title = "Click to edit this group";
engineDescription.className = "engine-uneditable engine-description-small group-engine-description";
engineDescription.textContent = getGroupEngineDescription(engine);
engineDescription.onclick = _ => showGroupPopup(engine);
engineRow.appendChild(engineDescription);
}
else
{
engineRow.appendChild(createElement_EngineSearchLink(engine, references));
}
engineRow.appendChild(createElement_EngineIconLink(engine, iconImg, references));
engineRow.appendChild(createElement_EngineShortcutField(engine));
engineRow.appendChild(createElement_DeleteButton(i));
}
return engineRow;
}
function getGroupEngineDescription(groupEngine: SSS.SearchEngine_Group): string
{
// Create a comma-separated string containing the names of the engines.
return groupEngine.enginesUniqueIds
.map(engineId => {
const engine = settings.searchEngines.find(eng => eng.uniqueId === engineId);
return engine.type === SSS.SearchEngineType.SSS
? sssIcons[(engine as SSS.SearchEngine_SSS).id].name
: (engine as SSS.SearchEngine_NonSSS).name;
})
.join(", ");
}
function createElement_EngineDragger(): HTMLDivElement
{
const dragger = document.createElement("div");
dragger.className = "engine-dragger";
dragger.textContent = "☰";
return dragger;
}
function setupEngineIconImg(engine: SSS.SearchEngine, iconImg: HTMLImageElement)
{
let iconImgSource;
if (engine.type === SSS.SearchEngineType.SSS) {
// special SSS icons have data that never changes, so just get it from constants
const sssIcon = sssIcons[(engine as SSS.SearchEngine_SSS).id];
iconImgSource = browser.extension.getURL(sssIcon.iconPath);
} else {
iconImgSource = (engine as SSS.SearchEngine_NonSSS).iconUrl;
}
// Sets the icon for a search engine.
// "data:" links are data, URLs are cached as data too.
if (iconImgSource.startsWith("data:") || iconImgSource.startsWith("moz-extension:")) {
iconImg.src = iconImgSource;
} else if (settings.searchEnginesCache[iconImgSource] === undefined && iconImgSource) {
iconImg.src = iconImgSource;
getDataUriFromImgUrl(iconImgSource, base64Img => {
iconImg.src = base64Img;
settings.searchEnginesCache[iconImgSource] = base64Img;
// console.log("\"" + iconImgSource + "\": \"" + base64Img + "\",");
saveSettings({ searchEnginesCache: settings.searchEnginesCache });
});
} else {
iconImg.src = settings.searchEnginesCache[iconImgSource];
}
}
// creates and adds a row with options for a certain search engine to the engines table
function buildSearchEngineOptionsTableRow(engine: SSS.SearchEngine, i: number)
{
const engineOptions = document.createElement("div");
engineOptions.className = "engine-options";
if (engine.type === SSS.SearchEngineType.SSS && (engine as SSS.SearchEngine_SSS).id === "copyToClipboard")
{
const copyEngine = engine as SSS.SearchEngine_SSS_Copy;
const isPlainTextCheckboxParent = createCheckbox(
"Copy as plain-text",
`copy-as-plain-text`,
copyEngine.isPlainText,
isOn => {
copyEngine.isPlainText = isOn;
saveSettings({ searchEngines: settings.searchEngines });
}
);
engineOptions.appendChild(isPlainTextCheckboxParent);
}
if (engine.type === SSS.SearchEngineType.Custom)
{
const customEngine = engine as SSS.SearchEngine_Custom;
const textEncodingDropdownParent = createDropdown(
"Text encoding",
`encoding-dropdown-${i}`,
encodings,
customEngine.encoding,
value => {
if (value !== null) {
customEngine.encoding = value;
} else {
delete customEngine.encoding;
}
saveSettings({ searchEngines: settings.searchEngines });
}
);
textEncodingDropdownParent.title = "If this is a search engine for non-latin alphabets, like Cyrillic, Chinese, Japanese, etc, it might use a different text encoding. You can change it here.";
engineOptions.appendChild(textEncodingDropdownParent);
const discardOnOpenCheckboxParent = createCheckbox(
"Discard on open (Advanced)",
`discard-on-open-${i}`,
customEngine.discardOnOpen,
isOn => {
customEngine.discardOnOpen = isOn;
saveSettings({ searchEngines: settings.searchEngines });
}
);
discardOnOpenCheckboxParent.title = "Opens the search but discards the resulting page. Useful if this is a \"non-http\" search engine that opens outside the browser, because that would generate an empty tab/page.";
engineOptions.appendChild(discardOnOpenCheckboxParent);
}
if (!engineOptions.hasChildNodes())
{
const noExtraOptionsLabel = document.createElement("label");
noExtraOptionsLabel.textContent = "No extra options.";
noExtraOptionsLabel.style.color = "#999";
engineOptions.appendChild(noExtraOptionsLabel);
}
return engineOptions;
}
function createCheckbox(labelText: string, elementId: string, checked: boolean, onChange: { (isOn: boolean): void; })
{
const parent = document.createElement("div");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = elementId;
checkbox.checked = checked;
checkbox.autocomplete = "off";
checkbox.onchange = _ => onChange(checkbox.checked);
parent.appendChild(checkbox);
const label = document.createElement("label");
label.htmlFor = checkbox.id;
label.textContent = " " + labelText; // space adds padding between checkbox and label
parent.appendChild(label);
return parent;
}
function createDropdown(labelText: string, elementId: string, encodingGroups: EncodingGroup[], currentValue: string, onChange: { (value: string): void; })
{
const parent = document.createElement("div");
const dropdown = document.createElement("select");
dropdown.style.maxWidth = "250px";
dropdown.style.marginLeft = "10px";
for (let i = 0; i < encodingGroups.length; i++)
{
const encodingGroup = encodingGroups[i];
var optionGroup = document.createElement("optgroup");
optionGroup.label = encodingGroup.name;
dropdown.appendChild(optionGroup);
for (let j = 0; j < encodingGroup.encodings.length; j++)
{
const value = encodingGroup.encodings[j];
var option = document.createElement("option");
option.text = value[0];
option.value = value[1];
optionGroup.appendChild(option)
}
}
dropdown.id = elementId;
if (currentValue) {
dropdown.value = currentValue;
}
dropdown.onchange = _ => onChange(dropdown.value);
const label = document.createElement("label");
label.textContent = " " + labelText; // space adds padding between checkbox and label
parent.appendChild(label);
parent.appendChild(dropdown);
return parent;
}
function setEnabledInPopup(engine: SSS.SearchEngine, i: number, value: boolean)
{
const engineRow = page.engines.children[i];
const checkbox = engineRow.querySelector(".engine-is-enabled input");
checkbox.checked = value;
engine.isEnabled = value;
saveSettings({ searchEngines: settings.searchEngines });
}
function setEnabledInContextMenu(engine: SSS.SearchEngine, i: number, value: boolean)
{
const engineRow = page.engines.children[i];
const checkbox = engineRow.querySelector(".engine-is-enabled-in-context-menu input");
checkbox.checked = value;
engine.isEnabledInContextMenu = value;
saveSettings({ searchEngines: settings.searchEngines });
}
// sets the uneditable name for a search engine in the engines table
function createElement_UneditableEngineName(name: string)
{
const engineName = document.createElement("div");
engineName.className = "engine-uneditable engine-uneditable-name";
engineName.textContent = name;
return engineName;
}
// sets the name field for a search engine in the engines table
function createElement_EngineName(engine)
{
const parent = document.createElement("div");
parent.className = "engine-name";
const nameInput = document.createElement("input");
nameInput.type = "text";
nameInput.value = engine.name;
nameInput.onchange = _ => {
engine.name = nameInput.value;
// make sure groups containing this engine get the updated engine name in their descriptions
const groupEngines = settings.searchEngines.filter(engine => engine.type === SSS.SearchEngineType.Group);
const groupEngineDescriptions = document.querySelectorAll(".group-engine-description");
for (let i = 0; i < groupEngines.length; i++) {
groupEngineDescriptions[i].textContent = getGroupEngineDescription(groupEngines[i] as SSS.SearchEngine_Group);
}
saveSettings({ searchEngines: settings.searchEngines });
calculateAndShowSettingsSize();
};
parent.appendChild(nameInput);
return parent;
}
// sets the search URL field for a search engine in the engines table
function createElement_EngineSearchLink(engine, references)
{
const parent = document.createElement("div");
parent.className = "engine-search-link";
const searchLinkInput = document.createElement("input");
searchLinkInput.type = "text";
searchLinkInput.value = engine.searchUrl;
let previousSearchLinkInputValue = engine.searchUrl; // keeps the previous value when it changes
searchLinkInput.onchange = _ => {
// trim search url and prepend "http://" if it doesn't begin with a protocol
let url = searchLinkInput.value.trim();
if (url.length > 0 && !url.match(/^[0-9a-zA-Z\-+]+:(\/\/)?/)) {
url = "http://" + url;
}
if (previousSearchLinkInputValue !== url) {
// if we're using the default icon source for the previous search url, update it
if (engine.iconUrl.length == 0 || engine.iconUrl === getIconUrlFromSearchUrl(previousSearchLinkInputValue)) {
const iconUrl = getIconUrlFromSearchUrl(url);
references.iconLinkInput.value = iconUrl; // doesn't trigger oninput or onchange
setIconUrlInput(engine, references.iconLinkInput, references.icon);
}
previousSearchLinkInputValue = url;
}
// if trimming and checks changed the url, set it on the input element
if (searchLinkInput.value !== url) {
searchLinkInput.value = url;
}
engine.searchUrl = url;
saveSettings({ searchEngines: settings.searchEngines });
calculateAndShowSettingsSize();
};
parent.appendChild(searchLinkInput);
references.searchLinkInput = searchLinkInput; // save reference in element
return parent;
}
// sets the icon URL field for a search engine in the engines table
function createElement_EngineIconLink(engine, icon, references)
{
const parent = document.createElement("div");
parent.className = "engine-icon-link";
const iconLinkInput = document.createElement("input");
iconLinkInput.type = "text";
iconLinkInput.value = engine.iconUrl;
iconLinkInput.oninput = _ => {
setIconUrlInput(engine, iconLinkInput, icon);
};
iconLinkInput.onchange = _ => {
if (iconLinkInput.value.length == 0 && references.searchLinkInput !== undefined) {
iconLinkInput.value = getIconUrlFromSearchUrl(references.searchLinkInput.value);
setIconUrlInput(engine, iconLinkInput, icon);
}
trimSearchEnginesCache(settings);
saveSettings({ searchEngines: settings.searchEngines, searchEnginesCache: settings.searchEnginesCache });
calculateAndShowSettingsSize();
};
// save the reference to the icon and input field in the search input's parent, as we'll need them to update the default favicon
references.icon = icon;
references.iconLinkInput = iconLinkInput;
parent.appendChild(iconLinkInput);
return parent;
}
// sets the engine icon from the icon url present in the iconLinkInput input field
function setIconUrlInput(engine, iconLinkInput, icon)
{
engine.iconUrl = iconLinkInput.value.trim();
icon.src = engine.iconUrl;
// if not a data link already, try downloading the image and cache it as one
if (!engine.iconUrl.startsWith("data:")) {
getDataUriFromImgUrl(engine.iconUrl, base64Img => {
icon.src = base64Img;
settings.searchEnginesCache[engine.iconUrl] = base64Img;
});
}
}
function createElement_EngineShortcutField(engine)
{
const parent = createElement_EngineShortcutFieldDiv();
const shortcutField = document.createElement("input");
shortcutField.type = "text";
shortcutField.title = "Type a single character to use as a shortcut for this engine. Shortcuts can then be used when the popup is visible."
// If this engine already has a shortcut, populate the field with its value.
if (engine.shortcut) {
shortcutField.value = engine.shortcut;
}
// Disable modifiers when setting shortcuts
shortcutField.onkeydown = (e) => {
if (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) e.preventDefault();
};
// Setting the shortcut
shortcutField.oninput = (e) => {
let newValue = shortcutField.value;
// The shortcut must be a single character.
if (newValue.length > 1) {
newValue = newValue[shortcutField.selectionStart-1]; // gets the last inserted char
shortcutField.value = newValue;
}
newValue = newValue.toUpperCase();
// Only check for duplicate when the user types a new value.
// Otherwise, this would be called when pressing backspace.
if (newValue.length > 0 && newValue !== engine.shortcut)
{
const engineWithShortcut = settings.searchEngines.find(e => e.shortcut === newValue);
if (engineWithShortcut)
{
const engineName = engineWithShortcut.type === SSS.SearchEngineType.SSS
? sssIcons[(engineWithShortcut as SSS.SearchEngine_SSS).id].name
: (engineWithShortcut as SSS.SearchEngine_NonSSS).name;
const override = confirm(`This shortcut is already assigned to "${engineName}"! Override?`);
if (override) {
engine.shortcut = newValue;
// Overwriting implies emptying the shortcut value of the engine to which it was assigned earlier.
// This way each engine has an unique shortcut.
engineWithShortcut.shortcut = undefined;
updateUIWithSettings();
} else {
// If the user decides not to override (cancel), nothing is set.
shortcutField.value = engine.shortcut || "";
return;
}
}
}
engine.shortcut = newValue;
saveSettings({ searchEngines: settings.searchEngines });
};
parent.appendChild(shortcutField);
return parent;
}
function createElement_EngineShortcutFieldDiv()
{
const parent = document.createElement("div");
parent.className = "engine-shortcut";
return parent;
}
// sets the delete button for a search engine in the engines table
function createElement_DeleteButton(i: number): HTMLDivElement
{
const parent = createElement_DeleteButtonDiv();
const deleteButton = document.createElement("input");
deleteButton.type = "button";
deleteButton.value = "✖";
deleteButton.title = "Delete";
deleteButton.onclick = _ => {
// Deleting an engine that belongs to one or more groups must also remove it from the groups, so we ask the user for confirmation.
const engineToDelete = settings.searchEngines[i];
const groupsContainingEngine = settings.searchEngines.filter(
engine => engine.type === SSS.SearchEngineType.Group && (engine as SSS.SearchEngine_Group).enginesUniqueIds.indexOf(engineToDelete.uniqueId) > -1
) as SSS.SearchEngine_Group[];
if (groupsContainingEngine.length > 0)
{
// Create a formatted list with the names of the groups
const groupNames = groupsContainingEngine.map(group => `\u2022 ${group.name}`).join("\n");
if (confirm(`This engine will also be removed from the following group(s): \n\n${groupNames}\n\nAre you sure?`)) {
for (const group of groupsContainingEngine) {
group.enginesUniqueIds.splice(group.enginesUniqueIds.indexOf(engineToDelete.uniqueId), 1);
}
} else {
return;
}
}
settings.searchEngines.splice(i, 1); // remove element at i
trimSearchEnginesCache(settings);
saveSettings({ searchEngines: settings.searchEngines, searchEnginesCache: settings.searchEnginesCache });
updateUIWithSettings();
};
parent.appendChild(deleteButton);
return parent;
}
function createElement_DeleteButtonDiv(): HTMLDivElement
{
const parent = document.createElement("div");
parent.className = "engine-delete";
return parent;
}
// removes all non-existent engines from the icon cache
function trimSearchEnginesCache(settings)
{
const newCache = {};
for (const engine of settings.searchEngines)
{
if (!engine.iconUrl || engine.iconUrl.startsWith("data:")) {
continue;
}
const cachedIcon = settings.searchEnginesCache[engine.iconUrl];
if (cachedIcon) {
newCache[engine.iconUrl] = cachedIcon;
}
}
settings.searchEnginesCache = newCache;
}
// removes from settings any objects that are easily re-calculatable (ex.: caches)
// in order to reduce size for an action, and then places them back and returns the action's result
function runActionOnDietSettings(settings, onCleaned)
{
const cache = settings.searchEnginesCache;
delete settings.searchEnginesCache;
const result = onCleaned(settings);
settings.searchEnginesCache = cache;
return result;
}
// applies a set of settings to the options page (reloads everything as if getting the user settings for the first time)
function importSettings(importedSettings)
{
if (importedSettings.searchEngines === undefined) {
if (DEBUG) { log("imported settings are empty!", importedSettings); }
return;
}
importedSettings.searchEnginesCache = {};
// run compatibility updates in case this is a backup made in an old version of SSS
browser.runtime.sendMessage({ type: "runBackwardsCompatibilityUpdates", settings: importedSettings }).then(
(_settings) => {
settings = _settings;
if (DEBUG) { log("imported settings!", settings); }
saveSettings(settings);
updateUIWithSettings();
},
getErrorHandler("Error sending runBackwardsCompatibilityUpdates message from settings.")
);
}
function updateColorText(text, value)
{
value = value.toUpperCase();
if (text.value !== value) {
text.value = value;
saveSettings({ [text.name]: value });
}
}
function updatePickerColor(picker, value)
{
// when selecting a color using the picker, disregard alpha (last two chars)
value = value.substring(0, 7);
if (picker.value !== value) {
picker.value = value;
}
}
// gets a much more readable string for a size in bytes (ex.: 25690112 bytes is "24.5MB")
function getSizeWithUnit(size: number)
{
let unit = 0;
while (size >= 1024 && unit <= 2) {
size /= 1024;
unit++;
}
size = Math.round(size);
if (unit == 0) return size + "B";
if (unit == 1) return size + "KB";
if (unit == 2) return size + "MB";
return size + "GB";
}
// just a wrapper for saving the settings to storage and logging info
function saveSettings(obj)
{
browser.storage.local.set(obj);
if (DEBUG) { log("saved!", settings); }
}
function getIconUrlFromSearchUrl(url)
{
if (settings.searchEngineIconsSource === SSS.SearchEngineIconsSource.FaviconKit) {
return "https://api.faviconkit.com/" + getDomainFromUrl(url) + "/64";
} else {
return "";
}
}
function getDomainFromUrl(url)
{
if (url.indexOf("//") !== -1) {
url = url.split("//")[1];
}
url = url.split("/")[0]; // url after domain
url = url.split(":")[0]; // port
url = url.split("?")[0]; // args
return url;
}
} | the_stack |
import { Buffer } from "buffer/"
import BN from "bn.js"
import BinTools from "../../utils/bintools"
import { AVMConstants } from "./constants"
import {
Output,
StandardAmountOutput,
StandardTransferableOutput,
BaseNFTOutput
} from "../../common/output"
import { Serialization, SerializedEncoding } from "../../utils/serialization"
import { OutputIdError, CodecIdError } from "../../utils/errors"
const bintools: BinTools = BinTools.getInstance()
const serialization: Serialization = Serialization.getInstance()
/**
* Takes a buffer representing the output and returns the proper Output instance.
*
* @param outputid A number representing the inputID parsed prior to the bytes passed in
*
* @returns An instance of an [[Output]]-extended class.
*/
export const SelectOutputClass = (outputid: number, ...args: any[]): Output => {
if (
outputid === AVMConstants.SECPXFEROUTPUTID ||
outputid === AVMConstants.SECPXFEROUTPUTID_CODECONE
) {
return new SECPTransferOutput(...args)
} else if (
outputid === AVMConstants.SECPMINTOUTPUTID ||
outputid === AVMConstants.SECPMINTOUTPUTID_CODECONE
) {
return new SECPMintOutput(...args)
} else if (
outputid === AVMConstants.NFTMINTOUTPUTID ||
outputid === AVMConstants.NFTMINTOUTPUTID_CODECONE
) {
return new NFTMintOutput(...args)
} else if (
outputid === AVMConstants.NFTXFEROUTPUTID ||
outputid === AVMConstants.NFTXFEROUTPUTID_CODECONE
) {
return new NFTTransferOutput(...args)
}
throw new OutputIdError(
"Error - SelectOutputClass: unknown outputid " + outputid
)
}
export class TransferableOutput extends StandardTransferableOutput {
protected _typeName = "TransferableOutput"
protected _typeID = undefined
//serialize is inherited
deserialize(fields: object, encoding: SerializedEncoding = "hex") {
super.deserialize(fields, encoding)
this.output = SelectOutputClass(fields["output"]["_typeID"])
this.output.deserialize(fields["output"], encoding)
}
fromBuffer(bytes: Buffer, offset: number = 0): number {
this.assetID = bintools.copyFrom(
bytes,
offset,
offset + AVMConstants.ASSETIDLEN
)
offset += AVMConstants.ASSETIDLEN
const outputid: number = bintools
.copyFrom(bytes, offset, offset + 4)
.readUInt32BE(0)
offset += 4
this.output = SelectOutputClass(outputid)
return this.output.fromBuffer(bytes, offset)
}
}
export abstract class AmountOutput extends StandardAmountOutput {
protected _typeName = "AmountOutput"
protected _typeID = undefined
//serialize and deserialize both are inherited
/**
*
* @param assetID An assetID which is wrapped around the Buffer of the Output
*/
makeTransferable(assetID: Buffer): TransferableOutput {
return new TransferableOutput(assetID, this)
}
select(id: number, ...args: any[]): Output {
return SelectOutputClass(id, ...args)
}
}
export abstract class NFTOutput extends BaseNFTOutput {
protected _typeName = "NFTOutput"
protected _typeID = undefined
//serialize and deserialize both are inherited
/**
*
* @param assetID An assetID which is wrapped around the Buffer of the Output
*/
makeTransferable(assetID: Buffer): TransferableOutput {
return new TransferableOutput(assetID, this)
}
select(id: number, ...args: any[]): Output {
return SelectOutputClass(id, ...args)
}
}
/**
* An [[Output]] class which specifies an Output that carries an ammount for an assetID and uses secp256k1 signature scheme.
*/
export class SECPTransferOutput extends AmountOutput {
protected _typeName = "SECPTransferOutput"
protected _codecID = AVMConstants.LATESTCODEC
protected _typeID =
this._codecID === 0
? AVMConstants.SECPXFEROUTPUTID
: AVMConstants.SECPXFEROUTPUTID_CODECONE
//serialize and deserialize both are inherited
/**
* Set the codecID
*
* @param codecID The codecID to set
*/
setCodecID(codecID: number): void {
if (codecID !== 0 && codecID !== 1) {
/* istanbul ignore next */
throw new CodecIdError(
"Error - SECPTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1."
)
}
this._codecID = codecID
this._typeID =
this._codecID === 0
? AVMConstants.SECPXFEROUTPUTID
: AVMConstants.SECPXFEROUTPUTID_CODECONE
}
/**
* Returns the outputID for this output
*/
getOutputID(): number {
return this._typeID
}
create(...args: any[]): this {
return new SECPTransferOutput(...args) as this
}
clone(): this {
const newout: SECPTransferOutput = this.create()
newout.fromBuffer(this.toBuffer())
return newout as this
}
}
/**
* An [[Output]] class which specifies an Output that carries an ammount for an assetID and uses secp256k1 signature scheme.
*/
export class SECPMintOutput extends Output {
protected _typeName = "SECPMintOutput"
protected _codecID = AVMConstants.LATESTCODEC
protected _typeID =
this._codecID === 0
? AVMConstants.SECPMINTOUTPUTID
: AVMConstants.SECPMINTOUTPUTID_CODECONE
//serialize and deserialize both are inherited
/**
* Set the codecID
*
* @param codecID The codecID to set
*/
setCodecID(codecID: number): void {
if (codecID !== 0 && codecID !== 1) {
/* istanbul ignore next */
throw new CodecIdError(
"Error - SECPMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1."
)
}
this._codecID = codecID
this._typeID =
this._codecID === 0
? AVMConstants.SECPMINTOUTPUTID
: AVMConstants.SECPMINTOUTPUTID_CODECONE
}
/**
* Returns the outputID for this output
*/
getOutputID(): number {
return this._typeID
}
/**
*
* @param assetID An assetID which is wrapped around the Buffer of the Output
*/
makeTransferable(assetID: Buffer): TransferableOutput {
return new TransferableOutput(assetID, this)
}
create(...args: any[]): this {
return new SECPMintOutput(...args) as this
}
clone(): this {
const newout: SECPMintOutput = this.create()
newout.fromBuffer(this.toBuffer())
return newout as this
}
select(id: number, ...args: any[]): Output {
return SelectOutputClass(id, ...args)
}
}
/**
* An [[Output]] class which specifies an Output that carries an NFT Mint and uses secp256k1 signature scheme.
*/
export class NFTMintOutput extends NFTOutput {
protected _typeName = "NFTMintOutput"
protected _codecID = AVMConstants.LATESTCODEC
protected _typeID =
this._codecID === 0
? AVMConstants.NFTMINTOUTPUTID
: AVMConstants.NFTMINTOUTPUTID_CODECONE
//serialize and deserialize both are inherited
/**
* Set the codecID
*
* @param codecID The codecID to set
*/
setCodecID(codecID: number): void {
if (codecID !== 0 && codecID !== 1) {
/* istanbul ignore next */
throw new CodecIdError(
"Error - NFTMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1."
)
}
this._codecID = codecID
this._typeID =
this._codecID === 0
? AVMConstants.NFTMINTOUTPUTID
: AVMConstants.NFTMINTOUTPUTID_CODECONE
}
/**
* Returns the outputID for this output
*/
getOutputID(): number {
return this._typeID
}
/**
* Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[NFTMintOutput]] and returns the size of the output.
*/
fromBuffer(utxobuff: Buffer, offset: number = 0): number {
this.groupID = bintools.copyFrom(utxobuff, offset, offset + 4)
offset += 4
return super.fromBuffer(utxobuff, offset)
}
/**
* Returns the buffer representing the [[NFTMintOutput]] instance.
*/
toBuffer(): Buffer {
let superbuff: Buffer = super.toBuffer()
let bsize: number = this.groupID.length + superbuff.length
let barr: Buffer[] = [this.groupID, superbuff]
return Buffer.concat(barr, bsize)
}
create(...args: any[]): this {
return new NFTMintOutput(...args) as this
}
clone(): this {
const newout: NFTMintOutput = this.create()
newout.fromBuffer(this.toBuffer())
return newout as this
}
/**
* An [[Output]] class which contains an NFT mint for an assetID.
*
* @param groupID A number specifies the group this NFT is issued to
* @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing addresses
* @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime
* @param threshold A number representing the the threshold number of signers required to sign the transaction
*/
constructor(
groupID: number = undefined,
addresses: Buffer[] = undefined,
locktime: BN = undefined,
threshold: number = undefined
) {
super(addresses, locktime, threshold)
if (typeof groupID !== "undefined") {
this.groupID.writeUInt32BE(groupID, 0)
}
}
}
/**
* An [[Output]] class which specifies an Output that carries an NFT and uses secp256k1 signature scheme.
*/
export class NFTTransferOutput extends NFTOutput {
protected _typeName = "NFTTransferOutput"
protected _codecID = AVMConstants.LATESTCODEC
protected _typeID =
this._codecID === 0
? AVMConstants.NFTXFEROUTPUTID
: AVMConstants.NFTXFEROUTPUTID_CODECONE
serialize(encoding: SerializedEncoding = "hex"): object {
let fields: object = super.serialize(encoding)
return {
...fields,
payload: serialization.encoder(
this.payload,
encoding,
"Buffer",
"hex",
this.payload.length
)
}
}
deserialize(fields: object, encoding: SerializedEncoding = "hex") {
super.deserialize(fields, encoding)
this.payload = serialization.decoder(
fields["payload"],
encoding,
"hex",
"Buffer"
)
this.sizePayload = Buffer.alloc(4)
this.sizePayload.writeUInt32BE(this.payload.length, 0)
}
protected sizePayload: Buffer = Buffer.alloc(4)
protected payload: Buffer
/**
* Set the codecID
*
* @param codecID The codecID to set
*/
setCodecID(codecID: number): void {
if (codecID !== 0 && codecID !== 1) {
/* istanbul ignore next */
throw new CodecIdError(
"Error - NFTTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1."
)
}
this._codecID = codecID
this._typeID =
this._codecID === 0
? AVMConstants.NFTXFEROUTPUTID
: AVMConstants.NFTXFEROUTPUTID_CODECONE
}
/**
* Returns the outputID for this output
*/
getOutputID(): number {
return this._typeID
}
/**
* Returns the payload as a {@link https://github.com/feross/buffer|Buffer} with content only.
*/
getPayload = (): Buffer => bintools.copyFrom(this.payload)
/**
* Returns the payload as a {@link https://github.com/feross/buffer|Buffer} with length of payload prepended.
*/
getPayloadBuffer = (): Buffer =>
Buffer.concat([
bintools.copyFrom(this.sizePayload),
bintools.copyFrom(this.payload)
])
/**
* Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[NFTTransferOutput]] and returns the size of the output.
*/
fromBuffer(utxobuff: Buffer, offset: number = 0): number {
this.groupID = bintools.copyFrom(utxobuff, offset, offset + 4)
offset += 4
this.sizePayload = bintools.copyFrom(utxobuff, offset, offset + 4)
let psize: number = this.sizePayload.readUInt32BE(0)
offset += 4
this.payload = bintools.copyFrom(utxobuff, offset, offset + psize)
offset = offset + psize
return super.fromBuffer(utxobuff, offset)
}
/**
* Returns the buffer representing the [[NFTTransferOutput]] instance.
*/
toBuffer(): Buffer {
const superbuff: Buffer = super.toBuffer()
const bsize: number =
this.groupID.length +
this.sizePayload.length +
this.payload.length +
superbuff.length
this.sizePayload.writeUInt32BE(this.payload.length, 0)
const barr: Buffer[] = [
this.groupID,
this.sizePayload,
this.payload,
superbuff
]
return Buffer.concat(barr, bsize)
}
create(...args: any[]): this {
return new NFTTransferOutput(...args) as this
}
clone(): this {
const newout: NFTTransferOutput = this.create()
newout.fromBuffer(this.toBuffer())
return newout as this
}
/**
* An [[Output]] class which contains an NFT on an assetID.
*
* @param groupID A number representing the amount in the output
* @param payload A {@link https://github.com/feross/buffer|Buffer} of max length 1024
* @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing addresses
* @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime
* @param threshold A number representing the the threshold number of signers required to sign the transaction
*/
constructor(
groupID: number = undefined,
payload: Buffer = undefined,
addresses: Buffer[] = undefined,
locktime: BN = undefined,
threshold: number = undefined
) {
super(addresses, locktime, threshold)
if (typeof groupID !== "undefined" && typeof payload !== "undefined") {
this.groupID.writeUInt32BE(groupID, 0)
this.sizePayload.writeUInt32BE(payload.length, 0)
this.payload = bintools.copyFrom(payload, 0, payload.length)
}
}
} | the_stack |
import { expect } from '../setup'
/* Imports: External */
import hre from 'hardhat'
import { Contract, Signer } from 'ethers'
import { getContractFactory } from '@eth-optimism/contracts'
import { smockit } from '@eth-optimism/smock'
import { toPlainObject } from 'lodash'
/* Imports: Internal */
import {
getMerkleTreeProof,
getMessagesAndProofsForL2Transaction,
getStateRootBatchByTransactionIndex,
getStateBatchAppendedEventByTransactionIndex,
getMessagesByTransactionHash,
} from '../../src/relay-tx'
describe('relay transaction generation functions', () => {
const ethers = (hre as any).ethers
const l1RpcProvider = ethers.provider
const l2RpcProvider = ethers.provider
let signer1: Signer
before(async () => {
;[signer1] = await ethers.getSigners()
})
let MockL2CrossDomainMessenger: Contract
beforeEach(async () => {
const factory = await ethers.getContractFactory(
'MockL2CrossDomainMessenger'
)
MockL2CrossDomainMessenger = await factory.deploy()
})
let StateCommitmentChain: Contract
beforeEach(async () => {
const factory1 = getContractFactory('Lib_AddressManager')
const factory2 = getContractFactory('OVM_ChainStorageContainer')
const factory3 = getContractFactory('OVM_StateCommitmentChain')
const mockBondManager = await smockit(getContractFactory('OVM_BondManager'))
const mockCanonicalTransactionChain = await smockit(
getContractFactory('OVM_CanonicalTransactionChain')
)
mockBondManager.smocked.isCollateralized.will.return.with(true)
mockCanonicalTransactionChain.smocked.getTotalElements.will.return.with(
999999
)
const AddressManager = await factory1.connect(signer1).deploy()
const ChainStorageContainer = await factory2
.connect(signer1)
.deploy(AddressManager.address, 'OVM_StateCommitmentChain')
StateCommitmentChain = await factory3
.connect(signer1)
.deploy(AddressManager.address, 0, 0)
await AddressManager.setAddress(
'OVM_ChainStorageContainer-SCC-batches',
ChainStorageContainer.address
)
await AddressManager.setAddress(
'OVM_StateCommitmentChain',
StateCommitmentChain.address
)
await AddressManager.setAddress('OVM_BondManager', mockBondManager.address)
await AddressManager.setAddress(
'OVM_CanonicalTransactionChain',
mockCanonicalTransactionChain.address
)
})
describe('getMessageByTransactionHash', () => {
it('should throw an error if a transaction with the given hash does not exist', async () => {
await expect(
getMessagesByTransactionHash(
l2RpcProvider,
MockL2CrossDomainMessenger.address,
ethers.constants.HashZero
)
).to.be.rejected
})
it('should return null if the transaction did not emit a SentMessage event', async () => {
const tx = await MockL2CrossDomainMessenger.doNothing()
expect(
await getMessagesByTransactionHash(
l2RpcProvider,
MockL2CrossDomainMessenger.address,
tx.hash
)
).to.deep.equal([])
})
it('should return the parsed event if the transaction emitted exactly one SentMessage event', async () => {
const message = {
target: ethers.constants.AddressZero,
sender: ethers.constants.AddressZero,
message: '0x',
messageNonce: 0,
}
const tx = await MockL2CrossDomainMessenger.emitSentMessageEvent(message)
expect(
await getMessagesByTransactionHash(
l2RpcProvider,
MockL2CrossDomainMessenger.address,
tx.hash
)
).to.deep.equal([message])
})
it('should return the parsed events if the transaction emitted more than one SentMessage event', async () => {
const messages = [
{
target: ethers.constants.AddressZero,
sender: ethers.constants.AddressZero,
message: '0x',
messageNonce: 0,
},
{
target: ethers.constants.AddressZero,
sender: ethers.constants.AddressZero,
message: '0x',
messageNonce: 1,
},
]
const tx = await MockL2CrossDomainMessenger.emitMultipleSentMessageEvents(
messages
)
expect(
await getMessagesByTransactionHash(
l2RpcProvider,
MockL2CrossDomainMessenger.address,
tx.hash
)
).to.deep.equal(messages)
})
})
describe('getStateBatchAppendedEventByTransactionIndex', () => {
it('should return null when there are no batches yet', async () => {
expect(
await getStateBatchAppendedEventByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
0
)
).to.equal(null)
})
it('should return null if a batch for the index does not exist', async () => {
// Should have a total of 1 element now.
await StateCommitmentChain.appendStateBatch(
[ethers.constants.HashZero],
0
)
expect(
await getStateBatchAppendedEventByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
1 // Index 0 is ok but 1 should return null
)
).to.equal(null)
})
it('should return the batch if the index is part of the first batch', async () => {
// 5 elements
await StateCommitmentChain.appendStateBatch(
[
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
],
0
)
// Add another 5 so we have two batches and can isolate tests against the first.
await StateCommitmentChain.appendStateBatch(
[
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
],
5
)
const event = await getStateBatchAppendedEventByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
1
)
expect(toPlainObject(event.args)).to.deep.include({
_batchIndex: ethers.BigNumber.from(0),
_batchSize: ethers.BigNumber.from(5),
_prevTotalElements: ethers.BigNumber.from(0),
})
})
it('should return the batch if the index is part of the last batch', async () => {
// 5 elements
await StateCommitmentChain.appendStateBatch(
[
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
],
0
)
// Add another 5 so we have two batches and can isolate tests against the second.
await StateCommitmentChain.appendStateBatch(
[
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
ethers.constants.HashZero,
],
5
)
const event = await getStateBatchAppendedEventByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
7
)
expect(toPlainObject(event.args)).to.deep.include({
_batchIndex: ethers.BigNumber.from(1),
_batchSize: ethers.BigNumber.from(5),
_prevTotalElements: ethers.BigNumber.from(5),
})
})
for (const numBatches of [1, 2, 8]) {
const elementsPerBatch = 8
describe(`when there are ${numBatches} batch(es) of ${elementsPerBatch} elements each`, () => {
const totalElements = numBatches * elementsPerBatch
beforeEach(async () => {
for (let i = 0; i < numBatches; i++) {
await StateCommitmentChain.appendStateBatch(
new Array(elementsPerBatch).fill(ethers.constants.HashZero),
i * elementsPerBatch
)
}
})
for (let i = 0; i < totalElements; i += elementsPerBatch) {
it(`should be able to get the correct event for the ${i}th/st/rd/whatever element`, async () => {
const event = await getStateBatchAppendedEventByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
i
)
expect(toPlainObject(event.args)).to.deep.include({
_batchIndex: ethers.BigNumber.from(i / elementsPerBatch),
_batchSize: ethers.BigNumber.from(elementsPerBatch),
_prevTotalElements: ethers.BigNumber.from(i),
})
})
}
})
}
})
describe('getStateRootBatchByTransactionIndex', () => {
it('should return null if a batch for the index does not exist', async () => {
// Should have a total of 1 element now.
await StateCommitmentChain.appendStateBatch(
[ethers.constants.HashZero],
0
)
expect(
await getStateRootBatchByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
1 // Index 0 is ok but 1 should return null
)
).to.equal(null)
})
it('should return the full batch for a given index when it exists', async () => {
// Should have a total of 1 element now.
await StateCommitmentChain.appendStateBatch(
[ethers.constants.HashZero],
0
)
const batch = await getStateRootBatchByTransactionIndex(
l1RpcProvider,
StateCommitmentChain.address,
0 // Index 0 is ok but 1 should return null
)
expect(batch.header).to.deep.include({
batchIndex: ethers.BigNumber.from(0),
batchSize: ethers.BigNumber.from(1),
prevTotalElements: ethers.BigNumber.from(0),
})
expect(batch.stateRoots).to.deep.equal([ethers.constants.HashZero])
})
})
describe('makeRelayTransactionData', () => {
it('should throw an error if the transaction does not exist', async () => {
await expect(
getMessagesAndProofsForL2Transaction(
l1RpcProvider,
l2RpcProvider,
StateCommitmentChain.address,
MockL2CrossDomainMessenger.address,
ethers.constants.HashZero
)
).to.be.rejected
})
it('should throw an error if the transaction did not send a message', async () => {
const tx = await MockL2CrossDomainMessenger.doNothing()
await expect(
getMessagesAndProofsForL2Transaction(
l1RpcProvider,
l2RpcProvider,
StateCommitmentChain.address,
MockL2CrossDomainMessenger.address,
tx.hash
)
).to.be.rejected
})
it('should throw an error if the corresponding state batch has not been submitted', async () => {
const tx = await MockL2CrossDomainMessenger.emitSentMessageEvent({
target: ethers.constants.AddressZero,
sender: ethers.constants.AddressZero,
message: '0x',
messageNonce: 0,
})
await expect(
getMessagesAndProofsForL2Transaction(
l1RpcProvider,
l2RpcProvider,
StateCommitmentChain.address,
MockL2CrossDomainMessenger.address,
tx.hash
)
).to.be.rejected
})
// Unfortunately this is hard to test here because hardhat doesn't support eth_getProof.
// Because this function is embedded into the message relayer, we should be able to use
// integration tests to sufficiently test this.
it.skip('should otherwise return the encoded transaction data', () => {
// TODO?
})
})
})
describe('getMerkleTreeProof', () => {
let leaves: string[] = [
'the',
'quick',
'brown',
'fox',
'jumps',
'over',
'the',
'lazy',
'dog',
]
const index: number = 4
it('should generate a merkle tree proof from an odd number of leaves at the correct index', () => {
const expectedProof = [
'0x6f766572',
'0x123268ec1a3f9aac2bc68e899fe4329eefef783c76265722508b8abbfbf11440',
'0x12aaa1b2e09f26e14d86aa3b157b94cfeabe815e44b6742d00c47441a576b12d',
'0x297d90df3f77f93eefdeab4e9f6e9a074b41a3508f9d265e92e9b5449c7b11c8',
]
expect(getMerkleTreeProof(leaves, index)).to.deep.equal(expectedProof)
})
it('should generate a merkle tree proof from an even number of leaves at the correct index', () => {
const expectedProof = [
'0x6f766572',
'0x09e430fa7b513203dd9c74afd734267a73f64299d9dac61ef09e96c3b3b3fe96',
'0x12aaa1b2e09f26e14d86aa3b157b94cfeabe815e44b6742d00c47441a576b12d',
]
leaves = leaves.slice(0, leaves.length - 2)
expect(getMerkleTreeProof(leaves, index)).to.deep.equal(expectedProof)
})
}) | the_stack |
import React, { useState, useEffect, useCallback, useMemo, useRef, isValidElement } from 'react';
import classnames from 'classnames';
import { ChevronLeftIcon, ChevronRightIcon } from 'tdesign-icons-react';
import useConfig from '../_util/useConfig';
import noop from '../_util/noop';
import { TdSwiperProps, SwiperChangeSource, SwiperNavigation } from './type';
import { StyledProps } from '../common';
import SwiperItem from './SwiperItem';
export interface SwiperProps extends TdSwiperProps, StyledProps {
children?: React.ReactNode;
}
enum CreateArrow {
Default = 'default',
Fraction = 'fraction',
}
enum ArrowClickDirection {
Left = 'left',
Right = 'right',
}
enum MouseAction {
Enter = 'enter',
Leave = 'leave',
Click = 'click',
}
const defaultNavigation: SwiperNavigation = {
placement: 'inside',
showSlideBtn: 'always',
size: 'medium',
type: 'bars',
};
const Swiper = (props: SwiperProps) => {
const {
// theme
animation = 'slide', // 轮播切换动画效果类型
autoplay = true, // 是否自动播放
current = 0, // 当前轮播在哪一项(下标)
defaultCurrent = 0, // 当前轮播在哪一项(下标),非受控属性
direction = 'horizontal', // 轮播滑动方向,包括横向滑动和纵向滑动两个方向
duration = 300, // 滑动动画时长
interval = 5000, // 轮播间隔时间
trigger = 'hover',
height,
loop = true,
stopOnHover = true,
onChange = noop, // 轮播切换时触发
className,
children,
navigation,
type = 'default',
} = props;
const { classPrefix } = useConfig();
let navigationConfig = defaultNavigation;
let navigationNode = null;
if (isValidElement(navigation)) {
navigationNode = navigation;
} else {
navigationConfig = { ...defaultNavigation, ...(navigation as SwiperNavigation) };
}
const [currentIndex, setCurrentIndex] = useState(defaultCurrent);
const [needAnimation, setNeedAnimation] = useState(false);
const [arrowShow, setArrowShow] = useState(navigationConfig.showSlideBtn === 'always');
const swiperTimer = useRef(null); // 计时器指针
const swiperAnimationTimer = useRef(null); // 计时器指针
const isHovering = useRef(false);
const swiperWrap = useRef(null);
const getWrapAttribute = (attr) => swiperWrap.current?.parentNode?.[attr];
// 进行子组件筛选,创建子节点列表
const childrenList = useMemo(
() =>
React.Children.toArray(children).filter(
(child: JSX.Element) => child.type.displayName === SwiperItem.displayName,
),
[children],
);
const childrenLength = childrenList.length;
// 创建渲染用的节点列表
const swiperItemList = childrenList.map((child: JSX.Element, index: number) =>
React.cloneElement(child, {
key: index,
index,
currentIndex,
needAnimation,
childrenLength,
getWrapAttribute,
...props,
...child.props,
}),
);
// 子节点不为空时,复制第一个子节点到列表最后
if (childrenLength > 0 && type === 'default') {
const firstEle = swiperItemList[0];
swiperItemList.push(
React.cloneElement(firstEle, { ...firstEle.props, key: childrenLength, index: childrenLength }),
);
}
const swiperItemLength = swiperItemList.length;
// 统一跳转处理函数
const swiperTo = useCallback(
(index: number, context: { source: SwiperChangeSource }) => {
// 事件通知
onChange(index % childrenLength, context);
// 设置内部 index
setNeedAnimation(true);
setCurrentIndex(index);
},
[childrenLength, onChange],
);
// 定时器
const setTimer = useCallback(() => {
if (autoplay && interval > 0) {
swiperTimer.current = setTimeout(
() => {
swiperTo(currentIndex + 1, { source: 'autoplay' });
},
currentIndex === 0 ? interval - (duration + 50) : interval, // 当 index 为 0 的时候,表明刚从克隆的最后一项跳转过来,已经经历了duration + 50 的间隔时间,减去即可
);
}
}, [autoplay, currentIndex, duration, interval, swiperTo]);
const clearTimer = useCallback(() => {
if (swiperTimer.current) {
clearTimeout(swiperTimer.current);
swiperTimer.current = null;
}
}, []);
const isEnd = useCallback(() => {
if (type === 'card') {
return !loop && currentIndex + 1 >= swiperItemLength;
}
return !loop && currentIndex + 2 >= swiperItemLength;
}, [loop, currentIndex, swiperItemLength, type]);
// 监听 current 参数变化
useEffect(() => {
if (current !== undefined) {
swiperTo(current % childrenLength, { source: 'autoplay' });
}
}, [current, childrenLength, swiperTo]);
// 监听每次轮播结束
useEffect(() => {
if (currentIndex + 1 > swiperItemLength && type === 'card') {
return setCurrentIndex(0);
}
if (swiperAnimationTimer.current) {
clearTimeout(swiperAnimationTimer.current);
swiperAnimationTimer.current = null;
}
swiperAnimationTimer.current = setTimeout(() => {
setNeedAnimation(false);
if (isEnd()) {
clearTimer();
}
if (currentIndex + 1 >= swiperItemLength && type !== 'card') {
setCurrentIndex(0);
}
}, duration + 50); // 多 50ms 的间隔时间参考了 react-slick 的动画间隔取值
}, [currentIndex, swiperItemLength, duration, type, clearTimer, isEnd]);
useEffect(() => {
if (!isHovering.current || !stopOnHover) {
clearTimer();
setTimer();
}
}, [setTimer, clearTimer, stopOnHover]);
// 鼠标移入移出事件
const onMouseEnter = () => {
isHovering.current = true;
if (stopOnHover) {
clearTimer();
}
if (navigationConfig.showSlideBtn === 'hover') {
setArrowShow(true);
}
};
const onMouseLeave = () => {
isHovering.current = false;
if (!isEnd()) {
setTimer();
}
if (navigationConfig.showSlideBtn === 'hover') {
setArrowShow(false);
}
};
const navMouseAction = (action: MouseAction, index: number) => {
if (action === MouseAction.Enter && trigger === 'hover') {
swiperTo(index, { source: 'hover' });
}
if (action === MouseAction.Click && trigger === 'click') {
swiperTo(index, { source: 'click' });
}
};
const arrowClick = (direction: ArrowClickDirection) => {
if (needAnimation) {
return false;
}
if (direction === ArrowClickDirection.Right) {
if (type === 'card') {
return swiperTo(currentIndex + 1 >= swiperItemLength ? 0 : currentIndex + 1, { source: 'click' });
}
return swiperTo(currentIndex + 1, { source: 'click' });
}
if (direction === ArrowClickDirection.Left) {
if (currentIndex - 1 < 0) {
return swiperTo(childrenLength - 1, { source: 'click' });
}
return swiperTo(currentIndex - 1, { source: 'click' });
}
};
const createArrow = (type: CreateArrow) => {
if (!arrowShow) {
return '';
}
if (navigationConfig.type === 'fraction' && type === CreateArrow.Default) {
return '';
}
const fractionIndex = currentIndex + 1 > childrenLength ? 1 : currentIndex + 1;
return (
<div
className={classnames(`${classPrefix}-swiper__arrow`, {
[`${classPrefix}-swiper__arrow--default`]: type === 'default',
})}
>
<div className={`${classPrefix}-swiper__arrow-left`} onClick={() => arrowClick(ArrowClickDirection.Left)}>
<ChevronLeftIcon />
</div>
{type === CreateArrow.Fraction ? (
<div className={`${classPrefix}-swiper__navigation-text-fraction`}>
{fractionIndex}/{childrenLength}
</div>
) : (
''
)}
<div className={`${classPrefix}-swiper__arrow-right`} onClick={() => arrowClick(ArrowClickDirection.Right)}>
<ChevronRightIcon />
</div>
</div>
);
};
const createNavigation = () => {
if (navigationConfig.type === 'fraction') {
return (
<div className={classnames(`${classPrefix}-swiper__navigation`, `${classPrefix}-swiper__navigation--fraction`)}>
{createArrow(CreateArrow.Fraction)}
</div>
);
}
return navigationNode ? (
<>{navigationNode}</>
) : (
<ul
className={classnames(`${classPrefix}-swiper__navigation`, {
[`${classPrefix}-swiper__navigation-bars`]: navigationConfig.type === 'bars',
})}
>
{childrenList.map((_: JSX.Element, i: number) => (
<li
key={i}
className={classnames(`${classPrefix}-swiper__navigation-item`, {
[`${classPrefix}-is-active`]: i === currentIndex % childrenLength,
})}
onClick={() => navMouseAction(MouseAction.Click, i)}
onMouseEnter={() => navMouseAction(MouseAction.Enter, i)}
onMouseLeave={() => navMouseAction(MouseAction.Leave, i)}
>
<span></span>
</li>
))}
</ul>
);
};
// 构造 css 对象
const getWrapperStyle = () => {
const offsetHeight = height ? `${height}px` : `${getWrapAttribute('offsetHeight')}px`;
if (type === 'card' || animation === 'fade') {
return {
height: offsetHeight,
};
}
if (animation === 'slide') {
if (direction === 'vertical') {
return {
height: offsetHeight,
msTransform: `translate3d(0, -${currentIndex * 100}%, 0px)`,
WebkitTransform: `translate3d(0, -${currentIndex * 100}%, 0px)`,
transform: `translate3d(0, -${currentIndex * 100}%, 0px)`,
transition: needAnimation ? `transform ${duration / 1000}s ease` : '',
};
}
return {
msTransform: `translate3d(-${currentIndex * 100}%, 0px, 0px)`,
WebkitTransform: `translate3d(-${currentIndex * 100}%, 0px, 0px)`,
transform: `translate3d(-${currentIndex * 100}%, 0px, 0px)`,
transition: needAnimation ? `transform ${duration / 1000}s ease` : '',
};
}
};
return (
<div
className={classnames(`${classPrefix}-swiper`, className)}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
ref={swiperWrap}
>
<div
className={classnames(`${classPrefix}-swiper__wrap`, {
[`${classPrefix}-swiper--inside`]: navigationConfig.placement === 'inside',
[`${classPrefix}-swiper--outside`]: navigationConfig.placement === 'outside',
[`${classPrefix}-swiper--vertical`]: direction === 'vertical',
[`${classPrefix}-swiper--large`]: navigationConfig.size === 'large',
[`${classPrefix}-swiper--small`]: navigationConfig.size === 'small',
})}
>
<div
className={classnames(`${classPrefix}-swiper__content`, {
[`${classPrefix}-swiper-fade`]: animation === 'fade',
[`${classPrefix}-swiper-card`]: type === 'card',
})}
style={{ height: '' }}
>
<div className={`${classPrefix}-swiper__container`} style={getWrapperStyle()}>
{swiperItemList}
</div>
</div>
{createNavigation()}
{createArrow(CreateArrow.Default)}
</div>
</div>
);
};
Swiper.SwiperItem = SwiperItem;
Swiper.displayName = 'Swiper';
export default Swiper; | the_stack |
import { View, Template, KeyedTemplate } from '../core/view';
import { ScopeError, SourceError, Source } from '../../utils/debug';
import * as xml from '../../xml';
import { isString, isObject } from '../../utils/types';
import { getComponentModule } from './component-builder';
import type { ComponentModule } from './component-builder';
import { Device } from '../../platform';
import { profile } from '../../profiling';
import { android, ios, loadCustomComponent, defaultNameSpaceMatcher, getExports, Builder } from './index';
export namespace xml2ui {
/**
* Pipes and filters:
* https://en.wikipedia.org/wiki/Pipeline_(software)
*/
interface XmlProducer {
pipe<Next extends XmlConsumer>(next: Next): Next;
}
interface XmlConsumer {
parse(args: xml.ParserEvent);
}
interface ParseInputData extends String {
default?: string;
}
export class XmlProducerBase implements XmlProducer {
private _next: XmlConsumer;
public pipe<Next extends XmlConsumer>(next: Next) {
this._next = next;
return next;
}
protected next(args: xml.ParserEvent) {
this._next.parse(args);
}
}
export class XmlStringParser extends XmlProducerBase implements XmlProducer {
private error: ErrorFormatter;
constructor(error?: ErrorFormatter) {
super();
this.error = error || PositionErrorFormat;
}
public parse(value: ParseInputData) {
if (__UI_USE_XML_PARSER__) {
const xmlParser = new xml.XmlParser(
(args: xml.ParserEvent) => {
try {
this.next(args);
} catch (e) {
throw this.error(e, args.position);
}
},
(e, p) => {
throw this.error(e, p);
},
true
);
if (isString(value)) {
xmlParser.parse(<string>value);
} else if (isObject(value) && isString(value.default)) {
xmlParser.parse(value.default);
}
}
}
}
interface ErrorFormatter {
(e: Error, p: xml.Position): Error;
}
export function PositionErrorFormat(e: Error, p: xml.Position): Error {
return new ScopeError(e, 'Parsing XML at ' + p.line + ':' + p.column);
}
export function SourceErrorFormat(uri): ErrorFormatter {
return (e: Error, p: xml.Position) => {
const source = p ? new Source(uri, p.line, p.column) : new Source(uri, -1, -1);
e = new SourceError(e, source, 'Building UI from XML.');
return e;
};
}
interface SourceTracker {
(component: any, p: xml.Position): void;
}
export function ComponentSourceTracker(uri): SourceTracker {
return (component: any, p: xml.Position) => {
if (!Source.get(component)) {
const source = p ? new Source(uri, p.line, p.column) : new Source(uri, -1, -1);
Source.set(component, source);
}
};
}
export class PlatformFilter extends XmlProducerBase implements XmlProducer, XmlConsumer {
private currentPlatformContext: string;
public parse(args: xml.ParserEvent) {
if (args.eventType === xml.ParserEventType.StartElement) {
if (PlatformFilter.isPlatform(args.elementName)) {
if (this.currentPlatformContext) {
throw new Error("Already in '" + this.currentPlatformContext + "' platform context and cannot switch to '" + args.elementName + "' platform! Platform tags cannot be nested.");
}
this.currentPlatformContext = args.elementName;
return;
}
}
if (args.eventType === xml.ParserEventType.EndElement) {
if (PlatformFilter.isPlatform(args.elementName)) {
this.currentPlatformContext = undefined;
return;
}
}
if (this.currentPlatformContext && !PlatformFilter.isCurentPlatform(this.currentPlatformContext)) {
return;
}
this.next(args);
}
private static isPlatform(value: string): boolean {
if (value) {
const toLower = value.toLowerCase();
return toLower === android || toLower === ios;
}
return false;
}
private static isCurentPlatform(value: string): boolean {
return value && value.toLowerCase() === Device.os.toLowerCase();
}
}
export class XmlArgsReplay extends XmlProducerBase implements XmlProducer {
private error: ErrorFormatter;
private args: xml.ParserEvent[];
constructor(args: xml.ParserEvent[], errorFormat: ErrorFormatter) {
super();
this.args = args;
this.error = errorFormat;
}
public replay() {
this.args.forEach((args: xml.ParserEvent) => {
try {
this.next(args);
} catch (e) {
throw this.error(e, args.position);
}
});
}
}
interface TemplateProperty {
context?: any;
parent: ComponentModule;
name: string;
elementName: string;
templateItems: Array<string>;
errorFormat: ErrorFormatter;
sourceTracker: SourceTracker;
}
/**
* It is a state pattern
* https://en.wikipedia.org/wiki/State_pattern
*/
export class XmlStateParser implements XmlConsumer {
private state: XmlStateConsumer;
constructor(state: XmlStateConsumer) {
this.state = state;
}
parse(args: xml.ParserEvent) {
this.state = this.state.parse(args);
}
}
interface XmlStateConsumer extends XmlConsumer {
parse(args: xml.ParserEvent): XmlStateConsumer;
}
export class TemplateParser implements XmlStateConsumer {
private _context: any;
private _recordedXmlStream: Array<xml.ParserEvent>;
private _templateProperty: TemplateProperty;
private _nestingLevel: number;
private _state: TemplateParser.State;
private parent: XmlStateConsumer;
private _setTemplateProperty: boolean;
constructor(parent: XmlStateConsumer, templateProperty: TemplateProperty, setTemplateProperty = true) {
this.parent = parent;
this._context = templateProperty.context;
this._recordedXmlStream = new Array<xml.ParserEvent>();
this._templateProperty = templateProperty;
this._nestingLevel = 0;
this._state = TemplateParser.State.EXPECTING_START;
this._setTemplateProperty = setTemplateProperty;
}
public parse(args: xml.ParserEvent): XmlStateConsumer {
if (args.eventType === xml.ParserEventType.StartElement) {
this.parseStartElement(args.prefix, args.namespace, args.elementName, args.attributes);
} else if (args.eventType === xml.ParserEventType.EndElement) {
this.parseEndElement(args.prefix, args.elementName);
}
this._recordedXmlStream.push(args);
return this._state === TemplateParser.State.FINISHED ? this.parent : this;
}
public get elementName(): string {
return this._templateProperty.elementName;
}
private parseStartElement(prefix: string, namespace: string, elementName: string, attributes: Object) {
if (this._state === TemplateParser.State.EXPECTING_START) {
this._state = TemplateParser.State.PARSING;
} else if (this._state === TemplateParser.State.FINISHED) {
throw new Error('Template must have exactly one root element but multiple elements were found.');
}
this._nestingLevel++;
}
private parseEndElement(prefix: string, elementName: string) {
if (this._state === TemplateParser.State.EXPECTING_START) {
throw new Error('Template must have exactly one root element but none was found.');
} else if (this._state === TemplateParser.State.FINISHED) {
throw new Error('No more closing elements expected for this template.');
}
this._nestingLevel--;
if (this._nestingLevel === 0) {
this._state = TemplateParser.State.FINISHED;
if (this._setTemplateProperty && this._templateProperty.name in this._templateProperty.parent.component) {
const template = this.buildTemplate();
this._templateProperty.parent.component[this._templateProperty.name] = template;
}
}
}
public buildTemplate(): Template {
if (__UI_USE_XML_PARSER__) {
const context = this._context;
const errorFormat = this._templateProperty.errorFormat;
const sourceTracker = this._templateProperty.sourceTracker;
const template: Template = <Template>profile('Template()', () => {
let start: xml2ui.XmlArgsReplay;
let ui: xml2ui.ComponentParser;
(start = new xml2ui.XmlArgsReplay(this._recordedXmlStream, errorFormat))
// No platform filter, it has been filtered already
.pipe(new XmlStateParser((ui = new ComponentParser(context, errorFormat, sourceTracker))));
start.replay();
return ui.rootComponentModule.component;
});
return template;
} else {
return null;
}
}
}
export class MultiTemplateParser implements XmlStateConsumer {
private _childParsers = new Array<TemplateParser>();
private _value: KeyedTemplate[];
get value(): KeyedTemplate[] {
return this._value;
}
constructor(private parent: XmlStateConsumer, private templateProperty: TemplateProperty) {}
public parse(args: xml.ParserEvent): XmlStateConsumer {
if (args.eventType === xml.ParserEventType.StartElement && args.elementName === 'template') {
const childParser = new TemplateParser(this, this.templateProperty, false);
childParser['key'] = args.attributes['key'];
this._childParsers.push(childParser);
return childParser;
}
if (args.eventType === xml.ParserEventType.EndElement) {
const name = ComponentParser.getComplexPropertyName(args.elementName);
if (name === this.templateProperty.name) {
const templates = new Array<KeyedTemplate>();
for (let i = 0; i < this._childParsers.length; i++) {
templates.push({
key: this._childParsers[i]['key'],
createView: this._childParsers[i].buildTemplate(),
});
}
this._value = templates;
return this.parent.parse(args);
}
}
return this;
}
}
export namespace TemplateParser {
export const enum State {
EXPECTING_START,
PARSING,
FINISHED,
}
}
export class ComponentParser implements XmlStateConsumer {
private static KNOWNCOLLECTIONS = 'knownCollections';
private static KNOWNTEMPLATES = 'knownTemplates';
private static KNOWNMULTITEMPLATES = 'knownMultiTemplates';
public rootComponentModule: ComponentModule;
private context: any;
private currentRootView: View;
private parents = new Array<ComponentModule>();
private complexProperties = new Array<ComponentParser.ComplexProperty>();
private error: ErrorFormatter;
private sourceTracker: SourceTracker;
constructor(context: any, errorFormat: ErrorFormatter, sourceTracker: SourceTracker, private moduleName?: string) {
this.context = context;
this.error = errorFormat;
this.sourceTracker = sourceTracker;
}
@profile
private buildComponent(args: xml.ParserEvent): ComponentModule {
if (args.prefix && args.namespace) {
// Custom components
return loadCustomComponent(args.namespace, args.elementName, args.attributes, this.context, this.currentRootView, !this.currentRootView, this.moduleName);
} else {
// Default components
let namespace = args.namespace;
if (defaultNameSpaceMatcher.test(namespace || '')) {
//Ignore the default ...tns.xsd namespace URL
namespace = undefined;
}
return getComponentModule(args.elementName, namespace, args.attributes, this.context, this.moduleName, !this.currentRootView);
}
}
public parse(args: xml.ParserEvent): XmlStateConsumer {
// Get the current parent.
const parent = this.parents[this.parents.length - 1];
const complexProperty = this.complexProperties[this.complexProperties.length - 1];
// Create component instance from every element declaration.
if (args.eventType === xml.ParserEventType.StartElement) {
if (ComponentParser.isComplexProperty(args.elementName)) {
const name = ComponentParser.getComplexPropertyName(args.elementName);
const complexProperty: ComponentParser.ComplexProperty = {
parent: parent,
name: name,
items: [],
};
this.complexProperties.push(complexProperty);
if (ComponentParser.isKnownTemplate(name, parent.exports)) {
return new TemplateParser(this, {
context: (parent ? getExports(parent.component) : null) || this.context,
parent: parent,
name: name,
elementName: args.elementName,
templateItems: [],
errorFormat: this.error,
sourceTracker: this.sourceTracker,
});
}
if (ComponentParser.isKnownMultiTemplate(name, parent.exports)) {
const parser = new MultiTemplateParser(this, {
context: (parent ? getExports(parent.component) : null) || this.context,
parent: parent,
name: name,
elementName: args.elementName,
templateItems: [],
errorFormat: this.error,
sourceTracker: this.sourceTracker,
});
complexProperty.parser = parser;
return parser;
}
} else {
const componentModule = this.buildComponent(args);
if (componentModule) {
this.sourceTracker(componentModule.component, args.position);
if (parent) {
if (complexProperty) {
// Add component to complex property of parent component.
ComponentParser.addToComplexProperty(parent, complexProperty, componentModule);
} else if ((<any>parent.component)._addChildFromBuilder) {
(<any>parent.component)._addChildFromBuilder(args.elementName, componentModule.component);
}
} else if (this.parents.length === 0) {
// Set root component.
this.rootComponentModule = componentModule;
if (this.rootComponentModule) {
this.currentRootView = this.rootComponentModule.component;
if ((<any>this.currentRootView).exports) {
this.context = (<any>this.currentRootView).exports;
}
}
}
// Add the component instance to the parents scope collection.
this.parents.push(componentModule);
}
}
} else if (args.eventType === xml.ParserEventType.EndElement) {
if (ComponentParser.isComplexProperty(args.elementName)) {
if (complexProperty) {
if (complexProperty.parser) {
parent.component[complexProperty.name] = complexProperty.parser.value;
} else if (parent && (<any>parent.component)._addArrayFromBuilder) {
// If parent is AddArrayFromBuilder call the interface method to populate the array property.
(<any>parent.component)._addArrayFromBuilder(complexProperty.name, complexProperty.items);
complexProperty.items = [];
}
}
// Remove the last complexProperty from the complexProperties collection (move to the previous complexProperty scope).
this.complexProperties.pop();
} else {
// Remove the last parent from the parents collection (move to the previous parent scope).
this.parents.pop();
}
}
return this;
}
private static isComplexProperty(name: string): boolean {
return isString(name) && name.indexOf('.') !== -1;
}
public static getComplexPropertyName(fullName: string): string {
let name: string;
if (isString(fullName)) {
const names = fullName.split('.');
name = names[names.length - 1];
}
return name;
}
private static isKnownTemplate(name: string, exports: any): boolean {
return Builder.knownTemplates.has(name);
}
private static isKnownMultiTemplate(name: string, exports: any): boolean {
return Builder.knownMultiTemplates.has(name);
}
private static addToComplexProperty(parent: ComponentModule, complexProperty: ComponentParser.ComplexProperty, elementModule: ComponentModule) {
// If property name is known collection we populate array with elements.
const parentComponent = <any>parent.component;
if (ComponentParser.isKnownCollection(complexProperty.name, parent.exports)) {
complexProperty.items.push(elementModule.component);
} else if (parentComponent._addChildFromBuilder) {
parentComponent._addChildFromBuilder(complexProperty.name, elementModule.component);
} else {
// Or simply assign the value;
parentComponent[complexProperty.name] = elementModule.component;
}
}
private static isKnownCollection(name: string, context: any): boolean {
return Builder.knownCollections.has(name);
}
}
export namespace ComponentParser {
export interface ComplexProperty {
parent: ComponentModule;
name: string;
items?: Array<any>;
parser?: { value: any };
}
}
} | the_stack |
module VORLON {
export class InteractiveConsoleClient extends ClientPlugin {
_cache = [];
_pendingEntries: ConsoleEntry[] = [];
private _maxBatchSize = 50;
private _maxBatchTimeout = 200;
private _pendingEntriesTimeout: any;
private _objPrototype = Object.getPrototypeOf({});
private _hooks = {
clear: null,
dir: null,
log: null,
debug: null,
error: null,
warn: null,
info: null
};
constructor() {
super("interactiveConsole");
this._ready = false;
this._id = "CONSOLE";
this.traceLog = (msg) => {
if (this._hooks && this._hooks.log) {
this._hooks.log.call(console, msg);
} else {
console.log(msg);
}
}
}
private inspect(obj: any, context: any, deepness: number): ObjectDescriptor {
if (!obj || typeof obj != "object") {
return null;
}
var objProperties = Object.getOwnPropertyNames(obj);
var proto = Object.getPrototypeOf(obj);
var res = <ObjectDescriptor>{
functions: [],
properties: []
};
if (proto && proto != this._objPrototype)
res.proto = this.inspect(proto, context, deepness + 1);
for (var i = 0, l = objProperties.length; i < l; i++) {
var p = objProperties[i];
var propertyType = "";
if (p === '__vorlon')
continue;
try {
var objValue = context[p];
propertyType = typeof objValue;
if (propertyType === 'function') {
res.functions.push(p);
} else if (propertyType === 'undefined') {
res.properties.push({ name: p, val: undefined });
} else if (propertyType === 'null') {
res.properties.push({ name: p, val: null });
} else if (propertyType === 'object') {
if (deepness > 5) {
res.properties.push({ name: p, val: "Vorlon cannot inspect deeper, try inspecting the proper object directly" });
} else {
res.properties.push({ name: p, val: this.inspect(objValue, objValue, deepness + 1) });
}
} else {
res.properties.push({ name: p, val: objValue.toString() });
}
} catch (exception) {
this.trace('error reading property ' + p + ' of type ' + propertyType);
this.trace(exception);
res.properties.push({ name: p, val: "oups, Vorlon has an error reading this " + propertyType + " property..." });
}
}
res.functions = res.functions.sort(function (a, b) {
var lowerAName = a.toLowerCase();
var lowerBName = b.toLowerCase();
if (lowerAName > lowerBName)
return 1;
if (lowerAName < lowerBName)
return -1;
return 0;
});
res.properties = res.properties.sort(function (a, b) {
var lowerAName = a.name.toLowerCase();
var lowerBName = b.name.toLowerCase();
if (lowerAName > lowerBName)
return 1;
if (lowerAName < lowerBName)
return -1;
return 0;
});
return res;
}
private getMessages(messages: IArguments): Array<any> {
var resmessages = [];
if (messages && messages.length > 0){
for (var i = 0, l = messages.length; i < l; i++) {
var msg = messages[i];
if (typeof msg === 'string' || typeof msg === 'number') {
resmessages.push(msg);
} else {
if (!Tools.IsWindowAvailable){
resmessages.push(this.inspect(msg, msg, 0));
}
else if(msg == window || msg == document) {
resmessages.push('VORLON : object cannot be inspected, too big...');
} else {
resmessages.push(this.inspect(msg, msg, 0));
}
}
}
}
return resmessages;
}
private addEntry(entry: ConsoleEntry) {
this._cache.push(entry);
//non batch send
//this.sendCommandToDashboard('entries', { entries: [entry] });
this._pendingEntries.push(entry);
if (this._pendingEntries.length > this._maxBatchSize) {
this.sendPendings();
} else {
this.checkPendings();
}
}
private checkPendings() {
if (!this._pendingEntriesTimeout) {
this._pendingEntriesTimeout = setTimeout(() => {
this._pendingEntriesTimeout = null;
this.sendPendings();
}, this._maxBatchTimeout);
}
}
private sendPendings() {
var currentPendings = this._pendingEntries;
this._pendingEntries = [];
this.sendCommandToDashboard('entries', { entries: currentPendings });
}
private batchSend(items: any[]) {
if (this._pendingEntriesTimeout) {
clearTimeout(this._pendingEntriesTimeout);
this._pendingEntriesTimeout = null;
}
var batch = [];
for (var i = 0, l = items.length; i < l; i++) {
if (batch.length < this._maxBatchSize) {
batch.push(items[i]);
} else {
this.sendCommandToDashboard('entries', { entries: batch });
batch = [];
}
}
this.sendCommandToDashboard('entries', { entries: batch });
}
public startClientSide(): void {
this._cache = [];
this._pendingEntries = [];
var console = Tools.IsWindowAvailable ? window.console : global.console;
// Overrides clear, log, error and warn
this._hooks.clear = Tools.Hook(console, "clear",(): void => {
this.clearClientConsole();
});
this._hooks.dir = Tools.Hook(console, "dir",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "dir"
};
this.addEntry(data);
});
this._hooks.log = Tools.Hook(console, "log", (message: any): void => {
var data = {
messages: this.getMessages(message),
type: "log"
};
this.addEntry(data);
});
this._hooks.debug = Tools.Hook(console, "debug", (message: any): void => {
var data = {
messages: this.getMessages(message),
type: "debug"
};
this.addEntry(data);
});
this._hooks.info = Tools.Hook(console, "info",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "info"
};
this.addEntry(data);
});
this._hooks.warn = Tools.Hook(console, "warn",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "warn"
};
this.addEntry(data);
});
this._hooks.error = Tools.Hook(console, "error",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "error"
};
this.addEntry(data);
});
// Override Error constructor
var previousError = Error;
Error = <any>((message: any) => {
var error = new previousError(message);
var data = {
messages: this.getMessages(message),
type: "exception"
};
this.addEntry(data);
return error;
});
Error.prototype = previousError.prototype;
if (Tools.IsWindowAvailable) {
window.addEventListener('error', (err) => {
if (err && (<any>err).error) {
//this.addEntry({ messages: [err.error.message], type: "exception" });
this.addEntry({ messages: [(<any>err).error.stack], type: "exception" });
}
});
}
this._ready = true;
}
public clearClientConsole() {
this.sendCommandToDashboard('clear');
this._cache = [];
}
public evalOrderFromDashboard(order: string) {
try {
eval(order);
} catch (e) {
console.error("Unable to execute order: " + e.message);
}
}
public refresh(): void {
//delay sending cache to dashboard to let other plugins load...
setTimeout(() => {
this.sendCommandToDashboard("clear");
this.batchSend(this._cache);
}, 300);
}
}
InteractiveConsoleClient.prototype.ClientCommands = {
order: function (data: any) {
var plugin = <InteractiveConsoleClient>this;
plugin.evalOrderFromDashboard(data.order);
},
clear: function (data: any) {
var plugin = <InteractiveConsoleClient>this;
console.clear();
}
};
// Register
Core.RegisterClientPlugin(new InteractiveConsoleClient());
} | the_stack |
import { View16, Edit16 } from '@carbon/icons-react';
import fileEdit from '@iconify-icons/mdi/file-edit';
import { Icon } from '@iconify/react';
import dayjs from 'dayjs';
import {
CommandBar,
ICommandBarItemProps,
IContextualMenuItem,
Pivot,
PivotItem,
Stack,
TooltipHost,
} from 'office-ui-fabric-react';
import React, { useCallback, useMemo, useEffect, useState } from 'react';
import Avatar from 'react-avatar';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, Link } from 'react-router-dom';
import { DriveIcon, Tags } from '../components';
import useFileMeta from '../hooks/useFileMeta';
import responsiveStyle from '../layout/responsive.module.scss';
import { selectDocMode, resetDocMode } from '../reduxSlices/doc';
import { selectDriveId, selectRootFolderId } from '../reduxSlices/files';
import {
canChangeSettings,
canEdit,
inlineEditable,
DocMode,
DriveFile,
MimeTypes,
docModes,
isTouchScreen,
} from '../utils';
import { folderPageId } from './ContentPage/FolderPage';
import { showCreateFile } from './FileAction.createFile';
import { showCreateLink } from './FileAction.createLink';
import styles from './FileAction.module.scss';
import { showMoveFile } from './FileAction.moveFile';
import { showRenameFile } from './FileAction.renameFile';
import { showTrashFile } from './FileAction.trashFile';
function Revisions(props: { file: DriveFile }) {
const revs: Array<gapi.client.drive.Revision> = [];
const [revisions, setRevisions] = useState(revs);
const [isLoading, setIsLoading] = useState(true);
const { file } = props;
useEffect(() => {
if (file.id === folderPageId) {
return;
}
const fields = 'revisions(id, modifiedTime, lastModifyingUser, exportLinks)';
async function loadRevisions() {
try {
const resp = await gapi.client.drive.revisions.list({ fileId: file.id!, fields })
setRevisions(resp.result.revisions!.reverse());
} catch (e) {
console.error('DocPage files.revisions', file, e);
} finally {
setIsLoading(false);
}
}
loadRevisions();
}, [file]);
const link = inlineEditable(file.mimeType ?? '') ? `/view/${file.id}/versions` : null;
return (
<div className="revisions">
{isLoading && <p>Loading Revisions ...</p>}
{revisions.map((revision) => {
const timeAgo = dayjs(revision.modifiedTime).fromNow();
return (
<Stack
key={revision.id}
verticalAlign="center"
horizontal
tokens={{ childrenGap: 16, padding: 2 }}
className={styles.note}
>
{link ? <Link to={link}>{timeAgo}</Link> : <span>{timeAgo}</span>}
<div>
<Avatar
name={revision.lastModifyingUser?.displayName}
src={revision.lastModifyingUser?.photoLink}
size="20"
round
/>
<span>
{revision.lastModifyingUser?.displayName}
</span>
</div>
</Stack>
)
})}
<hr />
</div>
);
}
function FileAction(props: { file: DriveFile, allOverflow?: boolean }) {
const [revisionsEnabled, setRevisionsEnabled] = useState(false);
const dispatch = useDispatch();
const history = useHistory();
let file = props.file;
const outerFolderId = file.mimeType === MimeTypes.GoogleFolder ? file.id : file.parents?.[0];
const outerFolder = useFileMeta(outerFolderId);
const docMode = useSelector(selectDocMode(file.mimeType ?? '')) || 'view';
const rootId = useSelector(selectRootFolderId);
useEffect(() => {
return () => {
if (!file.mimeType) {
return;
}
dispatch(resetDocMode(file.mimeType));
};
}, [dispatch, file]);
const settingsCommand = useCallback(
(file: DriveFile) => {
return {
key: 'settings',
text: 'Tag',
iconProps: { iconName: 'Settings' },
onClick: () => {
history.push(`/view/${file.id}/settings`);
},
};
},
[history]
);
const chooseDocMode = useMemo(() => {
return !isTouchScreen && file.mimeType && docModes(file.mimeType).length > 1;
}, [file.mimeType]);
const commandBarItems: ICommandBarItemProps[] = useMemo(() => {
function toggleRevisions() {
setRevisionsEnabled((v) => !v);
}
const commands: ICommandBarItemProps[] = [];
if (file.mimeType !== MimeTypes.GoogleFolder) {
if (file.webViewLink) {
const showText = props.allOverflow || !chooseDocMode;
commands.push({
key: 'launch',
text: showText ? 'Open in Google' : undefined,
title: showText ? undefined : 'Open in Google',
iconProps: { iconName: 'Launch' },
onClick: () => {
window.open(file.webViewLink, '_blank');
},
});
}
// For non-folder, show modify date, and how to open it.
commands.push({
key: 'modify_user',
onClick: () => {
toggleRevisions();
},
text: (
<Stack
verticalAlign="center"
horizontal
tokens={{ childrenGap: 8 }}
className={styles.note}
>
<Avatar
name={file.lastModifyingUser?.displayName}
src={file.lastModifyingUser?.photoLink}
size="20"
round
/>
<span className={responsiveStyle.hideInPhone}>
{file.lastModifyingUser?.displayName}
{' edited '}
{dayjs(file.modifiedTime).fromNow()}
</span>
<span className={responsiveStyle.showInPhone}>
{file.lastModifyingUser?.displayName}
</span>
</Stack>
) as any,
});
} else {
// Open folder command
const folderValid =
outerFolder.file?.mimeType === MimeTypes.GoogleFolder && outerFolder.file?.webViewLink;
commands.push({
key: 'open_folder',
text: 'Open Folder',
// Always occupy a place
disabled: !folderValid,
iconProps: { iconName: 'ColorGoogleDrive' },
onClick: () => {
window.open(outerFolder.file?.webViewLink, '_blank');
},
});
}
return commands;
}, [file, outerFolder.file, props.allOverflow]);
const commandBarOverflowItems = useMemo(() => {
const commands: ICommandBarItemProps[] = [];
if (outerFolder.file?.id && outerFolder.file?.capabilities?.canAddChildren) {
// Add file command
const addFileMenuItems: IContextualMenuItem[] = [];
const s: [string, string][] = [
['Page', MimeTypes.GoogleDocument],
['Sheet', MimeTypes.GoogleSpreadsheet],
['Slide', MimeTypes.GooglePresentation],
['Folder', MimeTypes.GoogleFolder],
];
s.forEach(([text, mimeType]) => {
addFileMenuItems.push({
key: text,
text: text,
iconProps: {
imageProps: { src: DriveIcon.getIconSrc(mimeType), width: 16 },
},
onClick: () => {
showCreateFile(text, mimeType, outerFolder.file!.id!);
},
});
});
commands.push({
key: 'create_file_in_folder',
text: 'Create',
iconProps: { iconName: 'Add' },
subMenuProps: {
items: [
...addFileMenuItems,
{
key: 'link',
text: 'Link',
iconProps: {
iconName: 'link',
},
onClick: () => {
showCreateLink(outerFolder.file!.id!);
},
},
{
key: 'move',
text: 'Import by Move',
iconProps: {
iconName: 'StackedMove',
},
onClick: () => {
showMoveFile(outerFolder.file!);
},
},
],
},
});
}
if (file && canChangeSettings(file)) {
commands.push(settingsCommand(file));
}
if (file) {
let fileKind;
switch (file.mimeType) {
case MimeTypes.GoogleFolder:
fileKind = 'Folder';
break;
case MimeTypes.GoogleShortcut:
fileKind = 'Shortcut';
break;
default:
fileKind = 'File';
}
if (file.capabilities?.canRename) {
// Rename
commands.push({
key: 'rename',
text: `Rename ${fileKind}`,
iconProps: { iconName: 'Edit' },
onClick: () => {
showRenameFile(fileKind, file);
},
});
}
if (file.mimeType !== MimeTypes.GoogleFolder && file.webViewLink) {
commands.push({
key: 'launch_preview',
text: 'Preview in Google',
iconProps: { iconName: 'DocumentView' },
onClick: () => {
const link = file.webViewLink?.replace(/\/(edit|view)\?usp=drivesdk/, '/preview');
window.open(link, '_blank');
},
});
}
// Do not allow trash root folder..
if (file.id !== rootId && file.capabilities?.canTrash) {
// Trash
commands.push({
key: 'trash',
text: `Trash ${fileKind}`,
iconProps: { iconName: 'Trash' },
onClick: () => {
showTrashFile(fileKind, file);
},
});
}
}
return commands;
}, [file, outerFolder.file, settingsCommand, rootId]);
const switchDocMode = useCallback(
(item) => {
const mode = item.props['itemKey'];
if (file) {
history.push(`/view/${file.id}/${mode}`);
}
},
[history, file]
);
if (!file) {
console.log('no file, return null');
return null;
}
if (commandBarItems.length === 0 && commandBarOverflowItems.length === 0) {
console.log('no command bar items, return null');
return null;
}
function tooltip(mode: DocMode, icon: JSX.Element) {
return () => <TooltipHost content={mode}>{icon}</TooltipHost>;
}
const showEditLink = file.mimeType && inlineEditable(file.mimeType) && canEdit(file);
return (
<div style={{ marginLeft: '1rem' }}>
<Stack horizontal>
{chooseDocMode && (
<Stack.Item disableShrink>
<Pivot onLinkClick={switchDocMode} selectedKey={docMode}>
<PivotItem
itemKey="view"
onRenderItemLink={tooltip('view', <Icon icon={fileEdit} />)}
/>
<PivotItem itemKey="preview" onRenderItemLink={tooltip('preview', <View16 />)} />
{showEditLink && (
<PivotItem itemKey="edit" onRenderItemLink={tooltip('edit', <Edit16 />)} />
)}
</Pivot>
</Stack.Item>
)}
<Stack.Item disableShrink grow={1} style={{ paddingLeft: '1em' }}>
{file.mimeType === MimeTypes.GoogleFolder ? (
<CommandBar items={commandBarItems.concat(commandBarOverflowItems)} />
) : props.allOverflow ? (
<CommandBar
items={[]}
overflowItems={commandBarItems.concat(commandBarOverflowItems)}
/>
) : (
<CommandBar items={commandBarItems} overflowItems={commandBarOverflowItems} />
)}
</Stack.Item>
{docMode !== 'view' && (
<Stack.Item disableShrink grow={1}>
<Tags file={file} add={true} style={{ paddingLeft: 8, paddingTop: 12 }} />
</Stack.Item>
)}
</Stack>
{revisionsEnabled && <Revisions file={file} />}
{docMode === 'view' && (
<Tags file={file} add={true} style={{ marginTop: '0.5rem', padding: '0.4rem' }} />
)}
</div>
);
}
export default React.memo(FileAction); | the_stack |
"use strict";
import { Dispatcher } from "./Dispatcher";
import { UseCase } from "./UseCase";
import { DispatcherPayloadMeta, DispatcherPayloadMetaImpl } from "./DispatcherPayloadMeta";
import { UseCaseInstanceMap } from "./UseCaseInstanceMap";
// payloads
import { CompletedPayload } from "./payload/CompletedPayload";
import { DidExecutedPayload } from "./payload/DidExecutedPayload";
import { WillExecutedPayload } from "./payload/WillExecutedPayload";
import { UseCaseLike } from "./UseCaseLike";
import { Payload } from "./payload/Payload";
import { WillNotExecutedPayload } from "./payload/WillNotExecutedPayload";
import { assertOK } from "./util/assert";
import { Events } from "./Events";
// TS 2.8+: Conditional Typing
// TS 3.0+: Tuple rest Generics
// Get Arguments of T function and return tuple
// https://github.com/Microsoft/TypeScript/issues/5453#issuecomment-414768143
type Arguments<F extends (...x: any[]) => any> =
F extends (...x: infer A) => any ? A : never;
interface InvalidUsage {
type: "InvalidUsage";
error: Error;
}
interface ShouldNotExecute {
type: "ShouldNotExecute";
}
interface ErrorInExecute {
type: "ErrorInExecute";
error: Error;
}
interface SuccessExecuteReturnValue {
type: "SuccessExecuteReturnValue";
value: any;
}
interface SuccessExecuteNoReturnValue {
type: "SuccessExecuteNoReturnValue";
}
type EXECUTING_RESULT =
| InvalidUsage
| ShouldNotExecute
| ErrorInExecute
| SuccessExecuteReturnValue
| SuccessExecuteNoReturnValue;
interface newProxifyUseCaseArgs {
onWillNotExecute(args: Array<any>): void;
onWillExecute(args: Array<any>): void;
onDidExecute(result?: any): void;
onError(error: Error): void;
}
/**
* Create wrapper object of a UseCase.
* This wrapper object only has `execute()` method.
*/
const proxifyUseCase = <T extends UseCaseLike>(useCase: T, handlers: newProxifyUseCaseArgs): T => {
let isExecuted = false;
const execute = (...args: Arguments<T["execute"]>): EXECUTING_RESULT => {
if (process.env.NODE_ENV !== "production") {
if (isExecuted) {
console.error(`Warning(UseCase): ${useCase.name}#execute was called more than once.`);
}
}
isExecuted = true;
// should the useCase execute?
if (typeof useCase.shouldExecute === "function") {
const shouldExecute = useCase.shouldExecute(args);
if (typeof shouldExecute !== "boolean") {
const error = new Error(
`<${useCase.name}>#shouldExecute should return boolean value. Actual return value: ${shouldExecute}`
);
return {
type: "InvalidUsage",
error
};
}
if (!shouldExecute) {
handlers.onWillNotExecute(args);
return {
type: "ShouldNotExecute"
};
}
}
// will execute
handlers.onWillExecute(args);
try {
// execute
const result = useCase.execute(...args);
handlers.onDidExecute(result);
return {
type: "SuccessExecuteReturnValue",
value: result
};
} catch (error) {
handlers.onError(error);
handlers.onDidExecute();
return {
type: "ErrorInExecute",
error
};
}
};
// Add debug displayName
if (process.env.NODE_ENV !== "production") {
(execute as any).displayName = `Wrapped<${useCase.name}>#execute`;
}
return {
execute: execute
} as T;
};
/**
* When child is completed after parent did completed, display warning warning message
* @private
*/
const warningUseCaseIsAlreadyReleased = (
parentUseCase: UseCaseLike,
useCase: UseCaseLike,
payload: Payload,
meta: DispatcherPayloadMeta
) => {
console.error(
`Warning(UseCase): ${useCase.name}'s parent UseCase(${parentUseCase.name}) is already released.
This UseCase(${useCase.name}) will not work correctly.
https://almin.js.org/docs/warnings/usecase-is-already-released.html
`,
payload,
meta
);
};
export interface UseCaseExecutor<T extends UseCaseLike> extends Dispatcher {
useCase: T;
execute<P extends Arguments<T["execute"]>>(...args: P): Promise<void>;
executor(executor: (useCase: Pick<T, "execute">) => any): Promise<void>;
release(): void;
onReleaseOnce(handler: () => void): void;
}
/**
* `UseCaseExecutor` is a helper class for executing UseCase.
*
* You can not create the instance of UseCaseExecutor directory.
* You can get the instance by `Context#useCase(useCase)`,
*
*/
export class UseCaseExecutorImpl<T extends UseCaseLike> extends Dispatcher implements UseCaseExecutor<T> {
/**
* A executable useCase
*/
useCase: T;
/**
* A parent useCase
*/
private _parentUseCase: UseCase | null;
/**
* callable release handlers that are called in release()
*/
private _releaseHandlers: Array<() => void>;
private releaseEvents: Events<void>;
/**
* @param useCase
* @param parent
* parent is parent of `useCase`
* @param dispatcher
* @public
*
* **internal** documentation
*/
constructor({ useCase, parent }: { useCase: T; parent: UseCase | null }) {
super();
if (process.env.NODE_ENV !== "production") {
// execute and finish =>
const useCaseName = useCase.name;
assertOK(typeof useCaseName === "string", `UseCase instance should have constructor.name ${useCase}`);
assertOK(
typeof useCase.execute === "function",
`UseCase instance should have #execute function: ${useCaseName}`
);
}
this.useCase = useCase;
this._parentUseCase = parent;
this._releaseHandlers = [];
/**
* ## Delegating Payload
*
* UseCase -> UseCaseExecutor -> UnitOfWork -> Dispatcher
*
*/
const unListenUseCaseToDispatcherHandler = this.useCase.pipe(this);
this._releaseHandlers.push(unListenUseCaseToDispatcherHandler);
// If this is parent UseCase, Parent UseCase -> UnitOfWork
if (this._parentUseCase) {
// Child -> Parent
const unListenUseCaseExecutorToDispatcherHandler = this.pipe(this._parentUseCase);
this._releaseHandlers.push(unListenUseCaseExecutorToDispatcherHandler);
}
this.releaseEvents = new Events<void>();
}
private willNotExecuteUseCase(args?: any[]): void {
const payload = new WillNotExecutedPayload({
args
});
const meta = new DispatcherPayloadMetaImpl({
useCase: this.useCase,
parentUseCase: this._parentUseCase,
isTrusted: true,
isUseCaseFinished: true
});
this.dispatch(payload, meta);
}
/**
* @param [args] arguments of the UseCase
*/
private willExecuteUseCase(args?: any[]): void {
// Add instance to manager
// It should be removed when it will be completed.
UseCaseInstanceMap.set(this.useCase, this as UseCaseExecutor<T>);
const payload = new WillExecutedPayload({
args
});
const meta = new DispatcherPayloadMetaImpl({
useCase: this.useCase,
parentUseCase: this._parentUseCase,
isTrusted: true,
isUseCaseFinished: false
});
this.dispatch(payload, meta);
// Warning: parentUseCase is already released
if (process.env.NODE_ENV !== "production") {
if (this._parentUseCase && !UseCaseInstanceMap.has(this._parentUseCase)) {
warningUseCaseIsAlreadyReleased(this._parentUseCase, this.useCase, payload, meta);
}
}
}
/**
* dispatch did execute each UseCase
*/
private didExecuteUseCase(value?: any): void {
// if the UseCase return a promise, almin recognize the UseCase as continuous.
// In other word, If the UseCase want to continue, please return a promise object.
const isResultPromise = typeof value === "object" && value !== null && typeof value.then == "function";
const isUseCaseFinished = !isResultPromise;
const payload = new DidExecutedPayload({
value
});
const meta = new DispatcherPayloadMetaImpl({
useCase: this.useCase,
parentUseCase: this._parentUseCase,
isTrusted: true,
isUseCaseFinished
});
this.dispatch(payload, meta);
}
/**
* dispatch complete each UseCase
* @param [value] unwrapped result value of the useCase executed
*/
private completeUseCase(value?: any): void {
const payload = new CompletedPayload({
value
});
const meta = new DispatcherPayloadMetaImpl({
useCase: this.useCase,
parentUseCase: this._parentUseCase,
isTrusted: true,
isUseCaseFinished: true
});
this.dispatch(payload, meta);
// Warning: parentUseCase is already released
if (process.env.NODE_ENV !== "production") {
if (this._parentUseCase && !UseCaseInstanceMap.has(this._parentUseCase)) {
warningUseCaseIsAlreadyReleased(this._parentUseCase, this.useCase, payload, meta);
}
}
// Delete the reference from instance manager
// It prevent leaking of instance.
UseCaseInstanceMap.delete(this.useCase);
}
/**
* Call handler when this UseCaseExecutor will be released
* @param handler
*/
onReleaseOnce(handler: () => void): void {
this.releaseEvents.addEventListenerOnce(handler);
}
/**
* **Stability**: Deprecated(Previously: experimental)
*
* - This feature is subject to change. It may change or be removed in future versions.
* - If you inserting in this, please see <https://github.com/almin/almin/issues/193>
*
* Similar to `execute(arguments)`, but it accept an executor function insteadof `arguments`
* `executor(useCase => useCase.execute())` return a Promise object that resolved with undefined.
*
* This method is type-safe. It is useful for TypeScript.
*
* ## Example
*
* ```js
* context.useCase(new MyUseCase())
* .executor(useCase => useCase.execute("value"))
* .then(() => {
* console.log("test");
* });
* ```
*
* ## Notes
*
* ### What is difference between `executor(executor)` and `execute(arguments)`?
*
* The `execute(arguments)` is a alias of following codes:
*
* ```js
* context.useCase(new MyUseCase())
* .execute("value")
* // ===
* context.useCase(new MyUseCase())
* .executor(useCase => useCase.execute("value"))
* ```
*
* ### Why executor's result always to be undefined?
*
* `execute()` return a Promise that will resolve `undefined` by design.
* In CQRS, the command always have returned void type.
*
* - http://cqrs.nu/Faq
*
* So, `execute()` only return command result that is success or failure.
* You should not relay on the result value of the useCase#execute.
*
* @deprecated Use `execute()` instead of `executor()`
* Almin 0.18+ make `execute` type complete.
* It will be remove in the future.
*
* Please apply migration scripts:
* https://github.com/almin/almin/issues/356
*
*/
executor(executor: (useCase: Pick<T, "execute">) => any): Promise<void> {
// TODO: executor() is duplication function of execute()
// It will be removed in the future.
// Show deprecated waring
console.warn(`Warning(UseCase): \`executor(useCase => useCase.execute(args))\` is deprecated.
Use \`execute(args)\` insteadof it.
See https://github.com/almin/almin/issues/356`);
if (typeof executor !== "function") {
console.error(
"Warning(UseCase): executor argument should be function. But this argument is not function: ",
executor
);
return Promise.reject(new Error("executor(fn) arguments should be function"));
}
const proxyfiedUseCase = proxifyUseCase<T>(this.useCase, {
onWillNotExecute: (args: any[]) => {
this.willNotExecuteUseCase(args);
},
onWillExecute: (args: any[]) => {
this.willExecuteUseCase(args);
},
onDidExecute: (result?: any) => {
this.didExecuteUseCase(result);
},
onError: (error: Error) => {
this.useCase.throwError(error);
}
});
const executorResult: EXECUTING_RESULT | undefined = executor(proxyfiedUseCase);
const executedResult: EXECUTING_RESULT =
executorResult !== undefined
? executorResult
: {
type: "SuccessExecuteNoReturnValue"
};
if (executedResult.type === "ShouldNotExecute") {
this.release();
return Promise.resolve();
}
const startingExecutor = new Promise((resolve, reject) => {
switch (executedResult.type) {
case "InvalidUsage":
return reject(executedResult.error);
case "ErrorInExecute":
return reject(executedResult.error);
case "SuccessExecuteReturnValue": {
return Promise.resolve(executedResult.value).then(resolve, error => {
this.useCase.throwError(error);
return reject(error);
});
}
case "SuccessExecuteNoReturnValue":
return resolve();
}
});
return startingExecutor
.then(result => {
this.completeUseCase(result);
this.release();
})
.catch(error => {
this.completeUseCase();
this.release();
return Promise.reject(error);
});
}
/**
* Execute UseCase instance.
* UseCase is a executable object that has `execute` method.
*
* This method invoke UseCase's `execute` method and return a promise<void>.
* The promise will be resolved when the UseCase is completed finished.
*
* ### Why executor's result always to be undefined?
*
* `execute()` return a Promise that will resolve `undefined` by design.
* In CQRS, the command always have returned void type.
*
* - http://cqrs.nu/Faq
*
* So, `execute()` only return command result that is success or failure.
* You should not relay on the result value of the useCase#execute.
*
* ## Notes
*
* > Added: Almin 0.17.0+
*
* `execute()` support type check in Almin 0.17.0.
* However, it has a limitation about argument lengths.
* For more details, please see <https://github.com/almin/almin/issues/107#issuecomment-384993458>
*
* > Added: Almin 0.18.0+
*
* `execute()` support type check completely.
* No more need to use `executor()` for typing.
*
*/
execute<P extends Arguments<T["execute"]>>(...args: P): Promise<void> {
// Notes: proxyfiedUseCase has not timeout
// proxiedUseCase will resolve by UseCaseWrapper#execute
// For more details, see <UseCaseLifeCycle-test.ts>
const proxyfiedUseCase = proxifyUseCase<T>(this.useCase, {
onWillNotExecute: (args: any[]) => {
this.willNotExecuteUseCase(args);
},
onWillExecute: (args: any[]) => {
this.willExecuteUseCase(args);
},
onDidExecute: (result?: any) => {
this.didExecuteUseCase(result);
},
onError: (error: Error) => {
this.useCase.throwError(error);
}
});
// Note: almin disallow to call `executor(useCase => { setTimeout(() => useCase.execute(), 0}})` asynchronously
// You should call UseCase#execute synchronously.
const executorResult: EXECUTING_RESULT | undefined = proxyfiedUseCase.execute(...args);
// `executorResult` is undefined means that the UseCase#execute never return any value
// In JavaScript, no return as undefined value
const executedResult: EXECUTING_RESULT =
executorResult !== undefined
? executorResult
: {
type: "SuccessExecuteNoReturnValue"
};
// if does not execute, release and resolve as soon as possible
if (executedResult.type === "ShouldNotExecute") {
this.release();
return Promise.resolve();
}
const startingExecutor = new Promise((resolve, reject) => {
switch (executedResult.type) {
case "InvalidUsage":
return reject(executedResult.error);
case "ErrorInExecute":
return reject(executedResult.error);
case "SuccessExecuteReturnValue": {
// try to resolve return value
// if the return promise is reject, report error from UseCase
return Promise.resolve(executedResult.value).then(resolve, error => {
this.useCase.throwError(error);
return reject(error);
});
}
case "SuccessExecuteNoReturnValue":
// The UseCase#execute just success without return value
return resolve();
}
});
return startingExecutor
.then(result => {
this.completeUseCase(result);
this.release();
})
.catch(error => {
this.completeUseCase();
this.release();
return Promise.reject(error);
});
}
/**
* release all events handler.
* You can call this when no more call event handler
*
* **internal**
*/
release(): void {
this._releaseHandlers.forEach(releaseHandler => releaseHandler());
this._releaseHandlers.length = 0;
this.releaseEvents.emit(undefined);
}
} | the_stack |
import { MIRAssembly, MIRConceptTypeDecl, MIRConstructableEntityTypeDecl, MIRConstructableInternalEntityTypeDecl, MIRDataBufferInternalEntityTypeDecl, MIRDataStringInternalEntityTypeDecl, MIREnumEntityTypeDecl, MIREphemeralListType, MIRFieldDecl, MIRObjectEntityTypeDecl, MIRPrimitiveInternalEntityTypeDecl, MIRPrimitiveListEntityTypeDecl, MIRPrimitiveMapEntityTypeDecl, MIRPrimitiveQueueEntityTypeDecl, MIRPrimitiveSetEntityTypeDecl, MIRPrimitiveStackEntityTypeDecl, MIRRecordType, MIRStringOfInternalEntityTypeDecl, MIRTupleType, MIRType } from "../../../compiler/mir_assembly";
import { MIRFieldKey, MIRGlobalKey, MIRInvokeKey, MIRResolvedTypeKey, MIRVirtualMethodKey } from "../../../compiler/mir_ops";
import { ICPPParseTag } from "./icppdecls_emitter";
import { Argument, ICPPOp, ParameterInfo } from "./icpp_exp";
import * as assert from "assert";
type TranspilerOptions = {
};
type SourceInfo = {
line: number;
column: number;
};
const ICPP_WORD_SIZE = 8;
const UNIVERSAL_CONTENT_SIZE = 32;
const UNIVERSAL_TOTAL_SIZE = 40;
const UNIVERSAL_MASK = "51111";
type RefMask = string;
class ICPPTypeSizeInfo {
readonly tkey: MIRResolvedTypeKey;
readonly isinlinevalue: boolean; //if this value is represented by an inline value (otherwise by a pointer to a heap allocated value)
readonly realdatasize: number; //number of bytes needed in storage location for this (EXCLUDES type tag for inline union)
readonly heapsize: number; //number of bytes needed to represent the data (no type ptr) when storing in the heap
readonly inlinedatasize: number; //number of bytes needed in storage location for this (includes type tag for inline union -- is the size of a pointer for ref -- and word size for BSQBool)
readonly assigndatasize: number; //number of bytes needed to copy when assigning this to a location -- 1 for BSQBool -- others should be same as inlined size
readonly heapmask: RefMask | undefined; //The mask to used to traverse this object during gc (if it is heap allocated) -- null if this is a leaf object -- partial if tailing scalars
readonly inlinedmask: RefMask; //The mask used to traverse this object as part of inline storage (on stack or inline in an object) -- must traverse full object
constructor(tkey: MIRResolvedTypeKey, realdatasize: number, heapsize: number, inlinedatasize: number, assigndatasize: number, heapmask: RefMask | undefined, inlinedmask: RefMask, isinlinevalue: boolean)
{
this.tkey = tkey;
this.isinlinevalue = isinlinevalue;
this.realdatasize = realdatasize;
this.heapsize = heapsize;
this.inlinedatasize = inlinedatasize;
this.assigndatasize = assigndatasize;
this.heapmask = heapmask;
this.inlinedmask = inlinedmask;
}
static isScalarOnlyMask(mask: RefMask): boolean {
return /^1+$/.test(mask);
}
static createByRegisterSizeInfo(tkey: MIRResolvedTypeKey, inlinedatasize: number, assigndatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfo {
return new ICPPTypeSizeInfo(tkey, inlinedatasize, inlinedatasize, inlinedatasize, assigndatasize, undefined, inlinedmask, true);
}
static createByValueSizeInfo(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfo {
return new ICPPTypeSizeInfo(tkey, inlinedatasize, inlinedatasize, inlinedatasize, inlinedatasize, undefined, inlinedmask, true);
}
static createByRefSizeInfo(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask | undefined): ICPPTypeSizeInfo {
if(heapmask !== undefined && ICPPTypeSizeInfo.isScalarOnlyMask(heapmask)) {
heapmask = undefined;
}
return new ICPPTypeSizeInfo(tkey, ICPP_WORD_SIZE, heapsize, ICPP_WORD_SIZE, ICPP_WORD_SIZE, heapmask, "2", false);
}
static createInlineUnionSizeInfo(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfo {
return new ICPPTypeSizeInfo(tkey, inlinedatasize - ICPP_WORD_SIZE, inlinedatasize, inlinedatasize, inlinedatasize, undefined, inlinedmask, true);
}
createFromSizeInfo(tkey: MIRResolvedTypeKey): ICPPTypeSizeInfo {
return new ICPPTypeSizeInfo(tkey, this.inlinedatasize, this.heapsize, this.inlinedatasize, this.assigndatasize, this.heapmask, this.inlinedmask, this.isinlinevalue);
}
jemit(): any {
return {realdatasize: this.realdatasize, heapsize: this.heapsize, inlinedatasize: this.inlinedatasize, assigndatasize: this.assigndatasize, heapmask: this.heapmask || null, inlinedmask: this.inlinedmask};
}
}
enum ICPPLayoutCategory {
Inline = 0x0,
Ref,
UnionRef,
UnionInline,
UnionUniversal
}
abstract class ICPPLayoutInfo {
readonly tkey: MIRResolvedTypeKey;
readonly allocinfo: ICPPTypeSizeInfo;
readonly layout: ICPPLayoutCategory;
constructor(tkey: MIRResolvedTypeKey, allocinfo: ICPPTypeSizeInfo, layout: ICPPLayoutCategory) {
this.tkey = tkey;
this.allocinfo = allocinfo;
this.layout = layout;
}
abstract createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo;
canScalarStackAllocate(): boolean {
if(this.layout === ICPPLayoutCategory.Inline) {
return /^1+$/.test(this.allocinfo.inlinedmask);
}
else if(this.layout === ICPPLayoutCategory.UnionInline) {
return /^51+$/.test(this.allocinfo.inlinedmask);
}
else {
return false;
}
}
needsBoxableType(): boolean {
return this.layout === ICPPLayoutCategory.Inline && this.allocinfo.inlinedatasize > UNIVERSAL_CONTENT_SIZE;
}
}
class ICPPLayoutInfoFixed extends ICPPLayoutInfo {
constructor(tkey: MIRResolvedTypeKey, allocinfo: ICPPTypeSizeInfo, layout: ICPPLayoutCategory) {
super(tkey, allocinfo, layout);
}
static createByRegisterLayout(tkey: MIRResolvedTypeKey, inlinedatasize: number, assigndatasize: number, inlinedmask: RefMask): ICPPLayoutInfoFixed {
return new ICPPLayoutInfoFixed(tkey, ICPPTypeSizeInfo.createByRegisterSizeInfo(tkey, inlinedatasize, assigndatasize, inlinedmask), ICPPLayoutCategory.Inline);
}
static createByValueLayout(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask): ICPPLayoutInfoFixed {
return new ICPPLayoutInfoFixed(tkey, ICPPTypeSizeInfo.createByValueSizeInfo(tkey, inlinedatasize, inlinedmask), ICPPLayoutCategory.Inline);
}
static createByRefLayout(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask | undefined): ICPPLayoutInfoFixed {
return new ICPPLayoutInfoFixed(tkey, ICPPTypeSizeInfo.createByRefSizeInfo(tkey, heapsize, heapmask), ICPPLayoutCategory.Ref);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), this.layout);
}
}
class ICPPTupleLayoutInfo extends ICPPLayoutInfo {
readonly maxIndex: number;
readonly ttypes: MIRResolvedTypeKey[];
readonly idxoffsets: number[];
constructor(tkey: MIRResolvedTypeKey, allocinfo: ICPPTypeSizeInfo, idxtypes: MIRResolvedTypeKey[], idxoffsets: number[], layout: ICPPLayoutCategory) {
super(tkey, allocinfo, layout);
this.maxIndex = idxtypes.length;
this.ttypes = idxtypes;
this.idxoffsets = idxoffsets;
}
static createByValueTuple(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, idxtypes: MIRResolvedTypeKey[], idxoffsets: number[]): ICPPTupleLayoutInfo {
return new ICPPTupleLayoutInfo(tkey, ICPPTypeSizeInfo.createByValueSizeInfo(tkey, inlinedatasize, inlinedmask), idxtypes, idxoffsets, ICPPLayoutCategory.Inline);
}
static createByRefTuple(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask, idxtypes: MIRResolvedTypeKey[], idxoffsets: number[]): ICPPTupleLayoutInfo {
return new ICPPTupleLayoutInfo(tkey, ICPPTypeSizeInfo.createByRefSizeInfo(tkey, heapsize, heapmask), idxtypes, idxoffsets, ICPPLayoutCategory.Ref);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), this.layout);
}
}
class ICPPRecordLayoutInfo extends ICPPLayoutInfo {
readonly propertynames: string[];
readonly propertytypes: MIRResolvedTypeKey[];
readonly propertyoffsets: number[];
constructor(tkey: MIRResolvedTypeKey, allocinfo: ICPPTypeSizeInfo, propertynames: string[], propertytypes: MIRResolvedTypeKey[], propertyoffsets: number[], layout: ICPPLayoutCategory) {
super(tkey, allocinfo, layout);
this.propertynames = propertynames;
this.propertytypes = propertytypes;
this.propertyoffsets = propertyoffsets;
}
static createByValueRecord(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, propertynames: string[], propertytypes: MIRResolvedTypeKey[], propertyoffsets: number[]): ICPPRecordLayoutInfo {
return new ICPPRecordLayoutInfo(tkey, ICPPTypeSizeInfo.createByValueSizeInfo(tkey, inlinedatasize, inlinedmask), propertynames, propertytypes, propertyoffsets, ICPPLayoutCategory.Inline);
}
static createByRefRecord(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask, propertynames: string[], propertytypes: MIRResolvedTypeKey[], propertyoffsets: number[]): ICPPRecordLayoutInfo {
return new ICPPRecordLayoutInfo(tkey, ICPPTypeSizeInfo.createByRefSizeInfo(tkey, heapsize, heapmask), propertynames, propertytypes, propertyoffsets, ICPPLayoutCategory.Ref);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), this.layout);
}
}
class ICPPEntityLayoutInfo extends ICPPLayoutInfo {
readonly fieldnames: MIRFieldKey[];
readonly fieldtypes: MIRResolvedTypeKey[];
readonly fieldoffsets: number[];
constructor(tkey: MIRResolvedTypeKey, allocinfo: ICPPTypeSizeInfo, fieldnames: string[], fieldtypes: MIRResolvedTypeKey[], fieldoffsets: number[], layout: ICPPLayoutCategory) {
super(tkey, allocinfo, layout);
this.fieldnames = fieldnames;
this.fieldtypes = fieldtypes;
this.fieldoffsets = fieldoffsets;
}
static createByValueEntity(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, fieldnames: string[], fieldtypes: MIRResolvedTypeKey[], fieldoffsets: number[]): ICPPEntityLayoutInfo {
return new ICPPEntityLayoutInfo(tkey, ICPPTypeSizeInfo.createByValueSizeInfo(tkey, inlinedatasize, inlinedmask), fieldnames, fieldtypes, fieldoffsets, ICPPLayoutCategory.Inline);
}
static createByRefEntity(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask, fieldnames: string[], fieldtypes: MIRResolvedTypeKey[], fieldoffsets: number[]): ICPPEntityLayoutInfo {
return new ICPPEntityLayoutInfo(tkey, ICPPTypeSizeInfo.createByRefSizeInfo(tkey, heapsize, heapmask), fieldnames, fieldtypes, fieldoffsets, ICPPLayoutCategory.Ref);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), this.layout);
}
}
class ICPPCollectionInternalsLayoutInfo extends ICPPLayoutInfo {
readonly xinfo: {name: string, type: MIRResolvedTypeKey, size: number, offset: number}[];
constructor(tkey: MIRResolvedTypeKey, allocinfo: ICPPTypeSizeInfo, xinfo: {name: string, type: MIRResolvedTypeKey, size: number, offset: number}[]) {
super(tkey, allocinfo, ICPPLayoutCategory.Ref);
this.xinfo = xinfo;
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), this.layout);
}
}
class ICPPEphemeralListLayoutInfo extends ICPPLayoutInfo {
readonly etypes: MIRResolvedTypeKey[];
readonly eoffsets: number[];
constructor(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, etypes: MIRResolvedTypeKey[], eoffsets: number[]) {
super(tkey, ICPPTypeSizeInfo.createByValueSizeInfo(tkey, inlinedatasize, inlinedmask), ICPPLayoutCategory.Inline);
this.etypes = etypes;
this.eoffsets = eoffsets;
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), this.layout);
}
}
class ICPPLayoutRefUnion extends ICPPLayoutInfo {
constructor(tkey: MIRResolvedTypeKey) {
super(tkey, ICPPTypeSizeInfo.createByRefSizeInfo(tkey, 0, "2"), ICPPLayoutCategory.UnionRef);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), ICPPLayoutCategory.Ref);
}
}
class ICPPLayoutInlineUnion extends ICPPLayoutInfo {
constructor(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask) {
super(tkey, ICPPTypeSizeInfo.createInlineUnionSizeInfo(tkey, inlinedatasize, inlinedmask), ICPPLayoutCategory.UnionInline);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), ICPPLayoutCategory.Inline);
}
}
class ICPPLayoutUniversalUnion extends ICPPLayoutInfo {
constructor(tkey: MIRResolvedTypeKey) {
super(tkey, ICPPTypeSizeInfo.createInlineUnionSizeInfo(tkey, UNIVERSAL_TOTAL_SIZE, UNIVERSAL_MASK), ICPPLayoutCategory.UnionUniversal);
}
createFromLayoutInfo(tkey: MIRResolvedTypeKey): ICPPLayoutInfo {
return new ICPPLayoutInfoFixed(tkey, this.allocinfo.createFromSizeInfo(tkey), ICPPLayoutCategory.Inline);
}
}
class ICPPFunctionParameter {
readonly name: string;
readonly ptype: MIRResolvedTypeKey;
constructor(name: string, ptype: MIRResolvedTypeKey) {
this.name = name;
this.ptype = ptype;
}
jsonEmit(): object {
return {name: this.name, ptype: this.ptype};
}
}
class ICPPInvokeDecl {
readonly name: string;
readonly ikey: MIRInvokeKey;
readonly srcFile: string;
readonly sinfoStart: SourceInfo;
readonly sinfoEnd: SourceInfo;
readonly recursive: boolean;
readonly params: ICPPFunctionParameter[];
readonly resultType: MIRResolvedTypeKey;
readonly scalarStackBytes: number;
readonly mixedStackBytes: number;
readonly mixedStackMask: RefMask;
readonly maskSlots: number;
readonly isUserCode: boolean;
constructor(name: string, ikey: MIRInvokeKey, srcFile: string, sinfoStart: SourceInfo, sinfoEnd: SourceInfo, recursive: boolean, params: ICPPFunctionParameter[], resultType: MIRResolvedTypeKey, scalarStackBytes: number, mixedStackBytes: number, mixedStackMask: RefMask, maskSlots: number, isUserCode: boolean) {
this.name = name;
this.ikey = ikey;
this.srcFile = srcFile;
this.sinfoStart = sinfoStart;
this.sinfoEnd = sinfoEnd;
this.recursive = recursive;
this.params = params;
this.resultType = resultType;
this.scalarStackBytes = scalarStackBytes;
this.mixedStackBytes = mixedStackBytes;
this.mixedStackMask = mixedStackMask;
this.maskSlots = maskSlots;
this.isUserCode = isUserCode;
}
jsonEmit(): object {
return {name: this.name, ikey: this.ikey, srcFile: this.srcFile, sinfoStart: this.sinfoStart, sinfoEnd: this.sinfoEnd, recursive: this.recursive, params: this.params.map((param) => param.jsonEmit()), resultType: this.resultType, scalarStackBytes: this.scalarStackBytes, mixedStackBytes: this.mixedStackBytes, mixedStackMask: this.mixedStackMask, maskSlots: this.maskSlots, isUserCode: this.isUserCode};
}
}
class ICPPInvokeBodyDecl extends ICPPInvokeDecl {
readonly body: ICPPOp[];
readonly paraminfo: ParameterInfo[];
readonly resultArg: Argument;
readonly argmaskSize: number;
constructor(name: string, ikey: MIRInvokeKey, srcFile: string, sinfoStart: SourceInfo, sinfoEnd: SourceInfo, recursive: boolean, params: ICPPFunctionParameter[], paraminfo: ParameterInfo[], resultType: MIRResolvedTypeKey, resultArg: Argument, scalarStackBytes: number, mixedStackBytes: number, mixedStackMask: RefMask, maskSlots: number, body: ICPPOp[], argmaskSize: number, isUserCode: boolean) {
super(name, ikey, srcFile, sinfoStart, sinfoEnd, recursive, params, resultType, scalarStackBytes, mixedStackBytes, mixedStackMask, maskSlots, isUserCode);
this.body = body;
this.paraminfo = paraminfo;
this.resultArg = resultArg;
this.argmaskSize = argmaskSize;
}
jsonEmit(): object {
return {...super.jsonEmit(), isbuiltin: false, paraminfo: this.paraminfo, resultArg: this.resultArg, body: this.body, argmaskSize: this.argmaskSize};
}
}
class ICPPPCode
{
readonly code: MIRInvokeKey;
readonly ctypes: MIRResolvedTypeKey[];
readonly cargpos: number[];
constructor(code: MIRInvokeKey, ctypes: MIRResolvedTypeKey[], cargpos: number[]) {
this.code = code;
this.ctypes = ctypes;
this.cargpos = cargpos;
}
jsonEmit(): object {
return {code: this.code, ctypes: this.ctypes, cargs: this.cargpos};
}
}
class ICPPInvokePrimitiveDecl extends ICPPInvokeDecl {
readonly enclosingtype: string | undefined;
readonly implkeyname: string;
readonly binds: Map<string, MIRResolvedTypeKey>;
readonly pcodes: Map<string, ICPPPCode>;
constructor(name: string, ikey: MIRInvokeKey, srcFile: string, sinfoStart: SourceInfo, sinfoEnd: SourceInfo, recursive: boolean, params: ICPPFunctionParameter[], resultType: MIRResolvedTypeKey, enclosingtype: string | undefined, implkeyname: string, binds: Map<string, MIRResolvedTypeKey>, pcodes: Map<string, ICPPPCode>) {
super(name, ikey, srcFile, sinfoStart, sinfoEnd, recursive, params, resultType, 0, 0, "", 0, false);
this.enclosingtype = enclosingtype;
this.implkeyname = implkeyname;
this.binds = binds;
this.pcodes = pcodes;
}
jsonEmit(): object {
const binds = [...this.binds].map((v) => {
return {name: v[0], ttype: v[1]};
});
const pcodes = [...this.pcodes].map((v) => {
return {name: v[0], pc: v[1].jsonEmit()};
});
return {...super.jsonEmit(), isbuiltin: true, enclosingtype: this.enclosingtype, implkeyname: this.implkeyname, binds: binds, pcodes: pcodes};
}
}
class ICPPConstDecl
{
readonly gkey: MIRGlobalKey;
readonly optenumname: [MIRResolvedTypeKey, string] | undefined;
readonly storageOffset: number;
readonly valueInvoke: MIRInvokeKey;
readonly ctype: MIRResolvedTypeKey;
constructor(gkey: MIRGlobalKey, optenumname: [MIRResolvedTypeKey, string] | undefined, storageOffset: number, valueInvoke: MIRInvokeKey, ctype: MIRResolvedTypeKey) {
this.gkey = gkey;
this.optenumname = optenumname;
this.storageOffset = storageOffset;
this.valueInvoke = valueInvoke;
this.ctype = ctype;
}
jsonEmit(): object {
return { storageOffset: this.storageOffset, valueInvoke: this.valueInvoke, ctype: this.ctype };
}
}
class ICPPAssembly
{
cbuffsize: number = 0;
cmask: RefMask = "";
readonly typenames: MIRResolvedTypeKey[];
readonly propertynames: string[];
readonly fields: MIRFieldDecl[];
readonly srcCode: { fname: string, contents: string }[];
invokenames: Set<MIRInvokeKey>;
vinvokenames: Set<MIRVirtualMethodKey>;
vtable: {oftype: MIRResolvedTypeKey, vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]}[] = [];
subtypes: Map<MIRResolvedTypeKey, Set<MIRResolvedTypeKey>> = new Map<MIRResolvedTypeKey, Set<MIRResolvedTypeKey>>();
typedecls: ICPPLayoutInfo[] = [];
invdecls: ICPPInvokeDecl[] = [];
litdecls: { offset: number, storage: ICPPTypeSizeInfo, value: string }[] = [];
constdecls: ICPPConstDecl[] = [];
constructor(typenames: MIRResolvedTypeKey[], propertynames: string[], fields: MIRFieldDecl[], srcCode: { fname: string, contents: string }[], invokenames: MIRInvokeKey[], vinvokenames: MIRVirtualMethodKey[]) {
this.typenames = typenames;
this.propertynames = propertynames;
this.fields = fields;
this.srcCode = srcCode;
this.invokenames = new Set<MIRInvokeKey>(invokenames);
this.vinvokenames = new Set<MIRVirtualMethodKey>(vinvokenames);
}
private generateBoxedTypeName(tkey: MIRResolvedTypeKey): string {
return tkey + "@boxed";
}
private processStringOfEntityDecl(edecl: MIRStringOfInternalEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
return {
ptag: ICPPParseTag.StringOfTag,
tkey: icpptype.tkey,
name: edecl.tkey
};
}
private processDataStringStringOfEntityDecl(edecl: MIRDataStringInternalEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
return {
ptag: ICPPParseTag.DataStringTag,
tkey: icpptype.tkey,
name: edecl.tkey
};
}
private processDataBufferStringOfEntityDecl(edecl: MIRDataBufferInternalEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
return {
ptag: ICPPParseTag.DataBufferTag,
tkey: icpptype.tkey,
name: edecl.tkey
};
}
private processConstructableEntityDecl(edecl: MIRConstructableEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
return {
ptag: ICPPParseTag.EntityDeclOfTag,
tkey: icpptype.tkey,
name: edecl.tkey,
oftype: edecl.fromtype
};
}
private processEnumEntityDecl(edecl: MIREnumEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
const enumnames = edecl.enums.map((en) => edecl.tkey + "::" + en);
return {
ptag: ICPPParseTag.EnumTag,
tkey: icpptype.tkey,
name: edecl.tkey,
enumnames: enumnames
};
}
private processConstructableInternalEntityDecl(edecl: MIRConstructableInternalEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
if(icpptype.layout === ICPPLayoutCategory.Ref) {
return {
ptag: ICPPParseTag.EntityConstructableRefTag,
tkey: icpptype.tkey,
name: edecl.tkey,
allocinfo: icpptype.allocinfo.jemit(),
oftype: edecl.fromtype
};
}
else {
return {
ptag: ICPPParseTag.EntityConstructableStructTag,
tkey: icpptype.tkey,
name: edecl.tkey,
allocinfo: icpptype.allocinfo.jemit(),
oftype: edecl.fromtype,
norefs: icpptype.canScalarStackAllocate(),
boxedtype: icpptype.needsBoxableType() ? this.generateBoxedTypeName(icpptype.tkey) : null
};
}
}
private processPrimitiveListEntityDecl(edecl: MIRPrimitiveListEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
return {
ptag: ICPPParseTag.ListTag,
tkey: icpptype.tkey,
name: edecl.tkey,
etype: edecl.getTypeT().typeID
};
}
private processPrimitiveStackEntityDecl(edecl: MIRPrimitiveStackEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
assert(false, "MIRPrimitiveStackEntityTypeDecl");
return {};
}
private processPrimitiveQueueEntityDecl(edecl: MIRPrimitiveQueueEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
assert(false, "MIRPrimitiveQueueEntityTypeDecl");
return {};
}
private processPrimitiveSetEntityDecl(edecl: MIRPrimitiveSetEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
assert(false, "MIRPrimitiveSetEntityTypeDecl");
return {};
}
private processPrimitiveMapEntityDecl(edecl: MIRPrimitiveMapEntityTypeDecl, icpptype: ICPPLayoutInfo): object {
return {
ptag: ICPPParseTag.ListTag,
tkey: icpptype.tkey,
name: edecl.tkey,
ktype: edecl.getTypeK(),
vtype: edecl.getTypeV(),
etype: edecl.tupentrytype
};
}
private processPartialVector4EntityDecl(edecl: MIRPrimitiveInternalEntityTypeDecl, icpptype: ICPPCollectionInternalsLayoutInfo): object {
const etype = edecl.terms.get("T") as MIRType;
return {
ptag: ICPPParseTag.PartialVector4Tag,
tkey: edecl.tkey,
name: edecl.tkey,
heapsize: icpptype.allocinfo.heapsize,
heapmask: icpptype.allocinfo.heapmask,
etype: etype.typeID,
esize: icpptype.xinfo[0].size
};
}
private processPartialVector8EntityDecl(edecl: MIRPrimitiveInternalEntityTypeDecl, icpptype: ICPPCollectionInternalsLayoutInfo): object {
return {
ptag: ICPPParseTag.PartialVector4Tag,
tkey: edecl.tkey,
name: edecl.tkey,
heapsize: icpptype.allocinfo.heapsize,
heapmask: icpptype.allocinfo.heapmask,
etype: icpptype.xinfo[0].type,
esize: icpptype.xinfo[0].size
};
}
private processListTreeEntityDecl(edecl: MIRPrimitiveInternalEntityTypeDecl, icpptype: ICPPCollectionInternalsLayoutInfo): object {
return {
ptag: ICPPParseTag.ListTreeTag,
tkey: edecl.tkey,
name: edecl.tkey,
etype: icpptype.xinfo[0].type,
};
}
private processMapTreeEntityDecl(edecl: MIRPrimitiveInternalEntityTypeDecl, icpptype: ICPPCollectionInternalsLayoutInfo): object {
return {
ptag: ICPPParseTag.MapTreeTag,
tkey: edecl.tkey,
name: edecl.tkey,
heapsize: icpptype.allocinfo.heapsize,
heapmask: icpptype.allocinfo.heapmask,
ktype: icpptype.xinfo[0].type,
vtype: icpptype.xinfo[1].type,
koffset: icpptype.xinfo[0].offset,
voffset: icpptype.xinfo[1].offset
};
}
private processEntityDecl(edcl: MIRObjectEntityTypeDecl, icpplayout: ICPPEntityLayoutInfo): object {
const vtbl = this.vtable.find((vte) => vte.oftype === edcl.tkey) as {oftype: MIRResolvedTypeKey, vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]};
if(icpplayout.layout === ICPPLayoutCategory.Ref) {
return {
ptag: ICPPParseTag.EntityObjectRefTag,
tkey: edcl.tkey,
allocinfo: icpplayout.allocinfo.jemit(),
name: edcl.tkey,
vtable: vtbl || null,
fieldnames: icpplayout.fieldnames,
fieldtypes: icpplayout.fieldtypes,
fieldoffsets: icpplayout.fieldoffsets
};
}
else {
return {
ptag: ICPPParseTag.EntityObjectStructTag,
tkey: edcl.tkey,
allocinfo: icpplayout.allocinfo.jemit(),
name: edcl.tkey,
vtable: vtbl || null,
norefs: icpplayout.canScalarStackAllocate(),
boxedtype: icpplayout.needsBoxableType() ? this.generateBoxedTypeName(edcl.tkey) : null,
fieldnames: icpplayout.fieldnames,
fieldtypes: icpplayout.fieldtypes,
fieldoffsets: icpplayout.fieldoffsets
};
}
}
private processConceptDecl(cdcl: MIRConceptTypeDecl, icpplayout: ICPPLayoutInfo, subtypes: MIRResolvedTypeKey[]): object {
if(icpplayout.layout === ICPPLayoutCategory.UnionRef) {
return {
ptag: ICPPParseTag.RefUnionTag,
tkey: cdcl.tkey,
name: cdcl.tkey,
subtypes: subtypes
};
}
else if (icpplayout.layout === ICPPLayoutCategory.UnionInline) {
return {
ptag: ICPPParseTag.InlineUnionTag,
tkey: cdcl.tkey,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.tkey,
subtypes: subtypes
};
}
else {
return {
ptag: ICPPParseTag.UniversalUnionTag,
tkey: cdcl.tkey,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.tkey,
subtypes: subtypes
};
}
}
private processTupleDecl(cdcl: MIRTupleType, icpplayout: ICPPTupleLayoutInfo): object {
const vtbl = this.vtable.find((vte) => vte.oftype === cdcl.typeID) as {oftype: MIRResolvedTypeKey, vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]};
if(icpplayout.layout === ICPPLayoutCategory.Ref) {
return {
ptag: ICPPParseTag.TupleRefTag,
tkey: cdcl.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.typeID,
vtable: vtbl || null,
maxIndex: icpplayout.maxIndex,
ttypes: icpplayout.ttypes,
idxoffsets: icpplayout.idxoffsets
};
}
else {
return {
ptag: ICPPParseTag.TupleStructTag,
tkey: cdcl.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.typeID,
vtable: vtbl || null,
norefs: icpplayout.canScalarStackAllocate(),
boxedtype: icpplayout.needsBoxableType() ? this.generateBoxedTypeName(cdcl.typeID) : null,
maxIndex: icpplayout.maxIndex,
ttypes: icpplayout.ttypes,
idxoffsets: icpplayout.idxoffsets
};
}
}
private processRecordDecl(cdcl: MIRRecordType, icpplayout: ICPPRecordLayoutInfo): object {
const vtbl = this.vtable.find((vte) => vte.oftype === cdcl.typeID) as {oftype: MIRResolvedTypeKey, vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]};
if(icpplayout.layout === ICPPLayoutCategory.Ref) {
return {
ptag: ICPPParseTag.RecordRefTag,
tkey: cdcl.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.typeID,
vtable: vtbl || null,
propertynames: icpplayout.propertynames,
propertytypes: icpplayout.propertytypes,
propertyoffsets: icpplayout.propertyoffsets
};
}
else {
return {
ptag: ICPPParseTag.RecordStructTag,
tkey: cdcl.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.typeID,
vtable: vtbl || null,
norefs: icpplayout.canScalarStackAllocate(),
boxedtype: icpplayout.needsBoxableType() ? this.generateBoxedTypeName(cdcl.typeID) : null,
propertynames: icpplayout.propertynames,
propertytypes: icpplayout.propertytypes,
propertyoffsets: icpplayout.propertyoffsets
};
}
}
private processEphemeralListDecl(cdcl: MIREphemeralListType, icpplayout: ICPPEphemeralListLayoutInfo): object {
return {
ptag: ICPPParseTag.EphemeralListTag,
tkey: cdcl.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: cdcl.typeID,
norefs: icpplayout.canScalarStackAllocate(),
etypes: icpplayout.etypes,
idxoffsets: icpplayout.eoffsets
};
}
private processUnionDecl(ud: MIRType, icpplayout: ICPPLayoutInfo, subtypes: MIRResolvedTypeKey[]): object {
if(icpplayout.layout === ICPPLayoutCategory.UnionRef) {
return {
ptag: ICPPParseTag.RefUnionTag,
tkey: ud.typeID,
name: ud.typeID,
subtypes: subtypes
};
}
else if (icpplayout.layout === ICPPLayoutCategory.UnionInline) {
return {
ptag: ICPPParseTag.InlineUnionTag,
tkey: ud.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: ud.typeID,
subtypes: subtypes
};
}
else {
return {
ptag: ICPPParseTag.UniversalUnionTag,
tkey: ud.typeID,
allocinfo: icpplayout.allocinfo.jemit(),
name: ud.typeID,
subtypes: subtypes
};
}
}
jsonEmit(assembly: MIRAssembly): object {
const entitydecls = [...assembly.entityDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((edcl) => {
const icpplayout = this.typedecls.find((dd) => dd.tkey === edcl.tkey) as ICPPLayoutInfo;
if (edcl.attributes.includes("__stringof_type")) {
return this.processStringOfEntityDecl(edcl as MIRStringOfInternalEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__datastring_type")) {
return this.processDataStringStringOfEntityDecl(edcl as MIRDataStringInternalEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__databuffer_type")) {
return this.processDataBufferStringOfEntityDecl(edcl as MIRDataBufferInternalEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__typedprimitive")) {
return this.processConstructableEntityDecl(edcl as MIRConstructableEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__enum_type")) {
return this.processEnumEntityDecl(edcl as MIREnumEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__ok_type")) {
return this.processConstructableInternalEntityDecl(edcl as MIRConstructableInternalEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__err_type")) {
return this.processConstructableInternalEntityDecl(edcl as MIRConstructableInternalEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__something_type")) {
return this.processConstructableInternalEntityDecl(edcl as MIRConstructableInternalEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__list_type")) {
return this.processPrimitiveListEntityDecl(edcl as MIRPrimitiveListEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__stack_type")) {
return this.processPrimitiveStackEntityDecl(edcl as MIRPrimitiveStackEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__queue_type")) {
return this.processPrimitiveQueueEntityDecl(edcl as MIRPrimitiveQueueEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__set_type")) {
return this.processPrimitiveSetEntityDecl(edcl as MIRPrimitiveSetEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__map_type")) {
return this.processPrimitiveMapEntityDecl(edcl as MIRPrimitiveMapEntityTypeDecl, icpplayout);
}
else if (edcl.attributes.includes("__partial_vector4_type")) {
return this.processPartialVector4EntityDecl(edcl as MIRPrimitiveInternalEntityTypeDecl, icpplayout as ICPPCollectionInternalsLayoutInfo);
}
else if (edcl.attributes.includes("__partial_vector8_type")) {
return this.processPartialVector8EntityDecl(edcl as MIRPrimitiveInternalEntityTypeDecl, icpplayout as ICPPCollectionInternalsLayoutInfo);
}
else if (edcl.attributes.includes("__list_tree_type")) {
return this.processListTreeEntityDecl(edcl as MIRPrimitiveInternalEntityTypeDecl, icpplayout as ICPPCollectionInternalsLayoutInfo);
}
else if (edcl.attributes.includes("__map_tree_type")) {
return this.processMapTreeEntityDecl(edcl as MIRPrimitiveInternalEntityTypeDecl, icpplayout as ICPPCollectionInternalsLayoutInfo);
}
else if (edcl instanceof MIRObjectEntityTypeDecl) {
return this.processEntityDecl(edcl, icpplayout as ICPPEntityLayoutInfo);
}
else {
return undefined;
}
}).filter((icppt) => icppt !== undefined);
const conceptdecls = [...assembly.conceptDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((tdcl) => {
const icpplayout = this.typedecls.find((dd) => dd.tkey === tdcl.tkey) as ICPPLayoutInfo;
const ctype = assembly.typeMap.get(tdcl.tkey) as MIRType;
const subtypes = [...assembly.typeMap].filter((tt) => assembly.subtypeOf(tt[1], ctype)).map((subt) => subt[0]);
return this.processConceptDecl(tdcl, icpplayout, subtypes);
});
const tupledecls = [...assembly.tupleDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((tdcl) => {
const icpplayout = this.typedecls.find((dd) => dd.tkey === tdcl.typeID) as ICPPLayoutInfo;
return this.processTupleDecl(tdcl, icpplayout as ICPPTupleLayoutInfo);
});
const recorddecls = [...assembly.recordDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((rdcl) => {
const icpplayout = this.typedecls.find((dd) => dd.tkey === rdcl.typeID) as ICPPLayoutInfo;
return this.processRecordDecl(rdcl, icpplayout as ICPPRecordLayoutInfo);
});
const elistdecls = [...assembly.ephemeralListDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((eldcl) => {
const icpplayout = this.typedecls.find((dd) => dd.tkey === eldcl.typeID) as ICPPLayoutInfo;
return this.processEphemeralListDecl(eldcl, icpplayout as ICPPEphemeralListLayoutInfo);
});
const uniondecls = [...assembly.typeMap].filter((td) => td[1].options.length > 1).sort((a, b) => a[0].localeCompare(b[0])).map((td) => td[1]).map((ud) => {
const icpplayout = this.typedecls.find((dd) => dd.tkey === ud.typeID) as ICPPLayoutInfo;
const subtypes = [...assembly.typeMap].filter((tt) => assembly.subtypeOf(tt[1], ud)).map((subt) => subt[0]);
return this.processUnionDecl(ud, icpplayout, subtypes);
});
const boxedtypes = [...assembly.typeMap]
.filter((td) => {
const icppinfo = (this.typedecls.find((dd) => dd.tkey === td[0]) as ICPPLayoutInfo);
return icppinfo.needsBoxableType();
})
.sort((a, b) => a[0].localeCompare(b[0])).map((td) => td[1])
.map((ud) => {
return {
ptag: ICPPParseTag.BoxedStructTag,
tkey: this.generateBoxedTypeName(ud.typeID),
name: this.generateBoxedTypeName(ud.typeID),
oftype: ud.typeID
}
});
const lflavors = [...assembly.entityDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((edcl) => {
if (edcl.attributes.includes("__list_type")) {
const ldcl = edcl as MIRPrimitiveListEntityTypeDecl;
return {
ltype: ldcl.tkey,
entrytype: ldcl.getTypeT().typeID,
pv4type: `PartialVector4<${ldcl.getTypeT().typeID}>`,
pv8type: `PartialVector8<${ldcl.getTypeT().typeID}>`,
treetype: `ListTree<${ldcl.getTypeT().typeID}>`
};
}
else {
return undefined;
}
}).filter((icppt) => icppt !== undefined);
const mflavors = [...assembly.entityDecls].sort((a, b) => a[0].localeCompare(b[0])).map((dclp) => dclp[1]).map((edcl) => {
if (edcl.attributes.includes("__map_type")) {
const mdcl = edcl as MIRPrimitiveMapEntityTypeDecl;
return {
ltype: mdcl.tkey,
keytype: mdcl.getTypeK().typeID,
valuetype: mdcl.getTypeV().typeID,
tupletype: mdcl.tupentrytype,
treetype: `MapTree<${mdcl.getTypeK().typeID}, ${mdcl.getTypeV().typeID}>`
};
}
else {
return undefined;
}
}).filter((icppt) => icppt !== undefined);
const validators = [...assembly.validatorRegexs].sort((a, b) => a[0].localeCompare(b[0])).map((vdcl) => {
return {
vtype: vdcl[0],
regex: vdcl[1].jemit()
};
});
const regexes = assembly.literalRegexs.sort((a, b) => a.restr.localeCompare(b.restr)).map((redcl) => {
return redcl.jemit();
});
return {
src: this.srcCode,
cmask: this.cmask,
cbuffsize: this.cbuffsize,
typenames: this.typenames.sort(),
propertynames: this.propertynames.sort(),
fieldnames: this.fields.map((ff) => ff.fkey).sort(),
fielddecls: this.fields.sort((a, b) => a.fkey.localeCompare(b.fkey)).map((ff) => {
return {
fkey: ff.fkey,
fname: ff.fname,
declaredType: ff.declaredType,
isOptional: ff.isOptional
}
}),
invokenames: [...this.invokenames].sort(),
vinvokenames: [...this.vinvokenames].sort(),
vtable: this.vtable.sort((a, b) => a.oftype.localeCompare(b.oftype)),
typedecls: [...entitydecls, ...conceptdecls, ...tupledecls, ...recorddecls, ...elistdecls, ...uniondecls],
boxeddecls: boxedtypes,
listflavors: lflavors,
mapflavors: mflavors,
invdecls: this.invdecls.sort((a, b) => a.ikey.localeCompare(b.ikey)).map((inv) => inv.jsonEmit()),
litdecls: this.litdecls.sort((a, b) => a.value.localeCompare(b.value)).map((lv) => {
return {offset: lv.offset, storage: lv.storage.tkey, value: lv.value};
}),
validators: validators,
regexes: regexes,
constdecls: this.constdecls.map((cd) => cd.jsonEmit())
};
}
}
export {
TranspilerOptions, SourceInfo, ICPP_WORD_SIZE, UNIVERSAL_CONTENT_SIZE, UNIVERSAL_TOTAL_SIZE, UNIVERSAL_MASK,
ICPPTypeSizeInfo, RefMask,
ICPPLayoutCategory, ICPPLayoutInfo, ICPPLayoutInfoFixed, ICPPTupleLayoutInfo, ICPPRecordLayoutInfo, ICPPEntityLayoutInfo, ICPPCollectionInternalsLayoutInfo, ICPPEphemeralListLayoutInfo,
ICPPLayoutInlineUnion, ICPPLayoutRefUnion, ICPPLayoutUniversalUnion,
ICPPInvokeDecl, ICPPFunctionParameter, ICPPPCode, ICPPInvokeBodyDecl, ICPPInvokePrimitiveDecl,
ICPPConstDecl,
ICPPAssembly
}; | the_stack |
export abstract class TemporalField {
/** Checks if this field is supported by the temporal object. */
abstract isSupportedBy(temporal: TemporalAccessor): boolean;
/** Checks if this field represents a component of a date. */
abstract isDateBased(): boolean;
/** Checks if this field represents a component of a time. */
abstract isTimeBased(): boolean;
/** Gets the unit that the field is measured in. */
abstract baseUnit(): TemporalUnit;
/** Gets the range that the field is bound by. */
abstract rangeUnit(): TemporalUnit;
/** Gets the range of valid values for the field. */
abstract range(): ValueRange;
/**
* Get the range of valid values for this field using the temporal object to
* refine the result.
*/
abstract rangeRefinedBy(temporal: TemporalAccessor): ValueRange;
/** Gets the value of this field from the specified temporal object. */
abstract getFrom(temporal: TemporalAccessor): number;
/** Returns a copy of the specified temporal object with the value of this field set. */
abstract adjustInto<R extends Temporal>(temporal: R, newValue: number): R;
abstract name(): string;
abstract displayName(/* TODO: locale */): string;
abstract equals(other: any): boolean;
}
/**
* A unit of date-time, such as Days or Hours.
*
* Measurement of time is built on units, such as years, months, days, hours, minutes and seconds.
* Implementations of this interface represent those units.
*
* An instance of this interface represents the unit itself, rather than an amount of the unit.
* See `Period` for a class that represents an amount in terms of the common units.
*
* The most commonly used units are defined in `ChronoUnit`. Further units are supplied in
* `IsoFields`. Units can also be written by application code by implementing this interface.
*/
export abstract class TemporalUnit {
/** Returns a copy of the specified temporal object with the specified period added. */
abstract addTo<T extends Temporal>(temporal: T, amount: number): T;
/**
* Calculates the period in terms of this unit between two temporal objects of the same type.
*
* Returns the period between temporal1 and temporal2 in terms of this unit; a positive number
* if `temporal2` is later than `temporal1`, negative if earlier.
*/
abstract between(temporal1: Temporal, temporal2: Temporal): number;
/** Gets the duration of this unit, which may be an estimate. */
abstract duration(): Duration;
/** Checks if this unit is date-based. */
abstract isDateBased(): boolean;
/** Checks if the duration of the unit is an estimate. */
abstract isDurationEstimated(): boolean;
/** Checks if this unit is supported by the specified temporal object. */
abstract isSupportedBy(temporal: Temporal): boolean;
/** Checks if this unit is time-based. */
abstract isTimeBased(): boolean;
}
/**
* The range of valid values for a date-time field.
*
* All TemporalField instances have a valid range of values. For example, the ISO day-of-month
* runs from 1 to somewhere between 28 and 31. This class captures that valid range.
*
* It is important to be aware of the limitations of this class. Only the minimum and maximum
* values are provided. It is possible for there to be invalid values within the outer range.
* For example, a weird field may have valid values of 1, 2, 4, 6, 7, thus have a range of '1 - 7',
* despite that fact that values 3 and 5 are invalid.
*
* Instances of this class are not tied to a specific field.
*/
export class ValueRange {
static of(min: number, max: number): ValueRange;
static of(min: number, maxSmallest: number, maxLargest: number): ValueRange;
static of(minSmallest: number, minLargest: number, maxSmallest: number, maxLargest: number): ValueRange;
private constructor();
checkValidValue(value: number, field: TemporalField): number;
checkValidIntValue(value: number, field: TemporalField): number;
equals(other: any): boolean;
hashCode(): number;
isFixed(): boolean;
isIntValue(): boolean;
isValidIntValue(value: number): boolean;
isValidValue(value: number): boolean;
largestMinimum(): number;
maximum(): number;
minimum(): number;
smallestMaximum(): number;
toString(): string;
}
/**
* Framework-level class defining an amount of time, such as "6 hours", "8 days" or
* "2 years and 3 months".
*
* This is the base class type for amounts of time. An amount is distinct from a date or
* time-of-day in that it is not tied to any specific point on the time-line.
*
* The amount can be thought of as a `Map` of `TemporalUnit` to `number`, exposed via
* `units()` and `get()`. A simple case might have a single unit-value pair, such
* as "6 hours". A more complex case may have multiple unit-value pairs, such as "7 years,
* 3 months and 5 days".
*
* There are two common implementations. `Period` is a date-based implementation,
* storing years, months and days. `Duration` is a time-based implementation, storing
* seconds and nanoseconds, but providing some access using other duration based units such
* as minutes, hours and fixed 24-hour days.
*
* This class is a framework-level class that should not be widely used in application code.
* Instead, applications should create and pass around instances of concrete types, such as
* `Period` and `Duration`.
*/
export abstract class TemporalAmount {
/**
* This adds to the specified temporal object using the logic encapsulated in the
* implementing class.
*
* There are two equivalent ways of using this method. The first is to invoke this method
* directly. The second is to use `Temporal.plus(TemporalAmount)`:
*
* ```
* // these two lines are equivalent, but the second approach is recommended
* dateTime = amount.addTo(dateTime);
* dateTime = dateTime.plus(amount);
* ```
*
* It is recommended to use the second approach, `plus(TemporalAmount)`, as it is a lot
* clearer to read in code.
*/
abstract addTo<T extends Temporal>(temporal: T): T;
/** Gets the amount associated with the specified unit. */
abstract get(unit: TemporalUnit): number;
/** Gets the list of units, from largest to smallest, that fully define this amount. */
abstract units(): TemporalUnit[];
/**
* This substract to the specified temporal object using the logic encapsulated in the
* implementing class.
*
* There are two equivalent ways of using this method. The first is to invoke this method
* directly. The second is to use `Temporal.minus(TemporalAmount)`:
* ```
* // these two lines are equivalent, but the second approach is recommended
* dateTime = amount.substractFrom(dateTime);
* dateTime = dateTime.minus(amount);
* ```
*
* It is recommended to use the second approach, `minus(TemporalAmount)`, as it is a lot
* clearer to read in code.
*/
abstract subtractFrom<T extends Temporal>(temporal: T): T;
}
/**
* Framework-level interface defining read-only access to a temporal object, such as a date, time,
* offset or some combination of these.
*
* This is the base interface type for date, time and offset objects. It is implemented by those
* classes that can provide information as fields or queries.
*
* Most date and time information can be represented as a number. These are modeled using
* `TemporalField` with the number held using a long to handle large values. Year, month and
* day-of-month are simple examples of fields, but they also include instant and offsets. See
* `ChronoField` for the standard set of fields.
*
* Two pieces of date/time information cannot be represented by numbers, the chronology and the
* time-zone. These can be accessed via queries using the static methods defined on
* `TemporalQueries`.
*
* A sub-interface, `Temporal`, extends this definition to one that also supports adjustment and
* manipulation on more complete temporal objects.
*
* This interface is a framework-level interface that should not be widely used in application code.
* Instead, applications should create and pass around instances of concrete types, such as
* `LocalDate`. There are many reasons for this, part of which is that implementations of this
* interface may be in calendar systems other than ISO. See `ChronoLocalDate` for a fuller
* discussion of the issues.
*/
export abstract class TemporalAccessor {
/**
* Gets the value of the specified field as an integer number.
*
* This queries the date-time for the value for the specified field. The returned value will
* always be within the valid range of values for the field. If the date-time cannot return
* the value, because the field is unsupported or for some other reason, an exception will
* be thrown.
*/
get(field: TemporalField): number;
/**
* Queries this date-time.
*
* This queries this date-time using the specified query strategy object.
*
* Queries are a key tool for extracting information from date-times. They exists to
* externalize the process of querying, permitting different approaches, as per the strategy
* design pattern. Examples might be a query that checks if the date is the day before
* February 29th in a leap year, or calculates the number of days to your next birthday.
*
* The most common query implementations are method references, such as `LocalDate::FROM` and
* `ZoneId::FROM`. Further implementations are on `TemporalQueries`. Queries may also be
* defined by applications.
*/
query<R>(query: TemporalQuery<R>): R | null;
/**
* Gets the range of valid values for the specified field.
*
* All fields can be expressed as an integer number. This method returns an object that
* describes the valid range for that value. The value of this temporal object is used to
* enhance the accuracy of the returned range. If the date-time cannot return the range,
* because the field is unsupported or for some other reason, an exception will be thrown.
*
* Note that the result only describes the minimum and maximum valid values and it is
* important not to read too much into them. For example, there could be values within the
* range that are invalid for the field.
*/
range(field: TemporalField): ValueRange;
abstract getLong(field: TemporalField): number;
/**
* Checks if the specified field is supported.
*
* This checks if the date-time can be queried for the specified field. If false, then
* calling the `range` and `get` methods will throw an exception.
*/
abstract isSupported(field: TemporalField): boolean;
}
/**
* Framework-level interface defining read-write access to a temporal object, such as a date, time,
* offset or some combination of these.
*
* This is the base interface type for date, time and offset objects that are complete enough to be
* manipulated using plus and minus. It is implemented by those classes that can provide and
* manipulate information as fields or queries. See `TemporalAccessor` for the read-only version of
* this interface.
*
* Most date and time information can be represented as a number. These are modeled using
* `TemporalField` with the number held using a long to handle large values. Year, month and
* day-of-month are simple examples of fields, but they also include instant and offsets. See
* `ChronoField` for the standard set of fields.
*
* Two pieces of date/time information cannot be represented by numbers, the chronology and the
* time-zone. These can be accessed via queries using the static methods defined on
* `TemporalQueries`.
*
* This interface is a framework-level interface that should not be widely used in application code.
* Instead, applications should create and pass around instances of concrete types, such as
* `LocalDate`. There are many reasons for this, part of which is that implementations of this
* interface may be in calendar systems other than ISO. See `ChronoLocalDate` for a fuller
* discussion of the issues.
*/
export abstract class Temporal extends TemporalAccessor {
minus(amountToSubtract: number, unit: TemporalUnit): Temporal;
/**
* Returns an object of the same type as this object with an amount subtracted.
*
* This adjusts this temporal, subtracting according to the rules of the specified amount.
* The amount is typically a `Period` but may be any other type implementing `TemporalAmount`,
* such as `Duration`.
*
* Some example code indicating how and why this method is used:
* ```
* date = date.minus(period); // subtract a Period instance
* date = date.minus(duration); // subtract a Duration instance
* date = date.minus(workingDays(6)); // example user-written workingDays method
* ```
*
* Note that calling plus followed by minus is not guaranteed to return the same date-time.
*/
minus(amount: TemporalAmount): Temporal;
plus(amountToAdd: number, unit: TemporalUnit): Temporal;
/**
* Returns an object of the same type as this object with an amount added.
*
* This adjusts this temporal, adding according to the rules of the specified amount. The
* amount is typically a `Period` but may be any other type implementing `TemporalAmount`,
* such as `Duration`.
*
* Some example code indicating how and why this method is used:
* ```
* date = date.plus(period); // add a Period instance
* date = date.plus(duration); // add a Duration instance
* date = date.plus(workingDays(6)); // example user-written workingDays method
* ```
*
* Note that calling plus followed by minus is not guaranteed to return the same date-time.
*/
plus(amount: TemporalAmount): Temporal;
/**
* Returns an adjusted object of the same type as this object with the adjustment made.
*
* This adjusts this date-time according to the rules of the specified adjuster. A simple
* adjuster might simply set the one of the fields, such as the year field. A more complex
* adjuster might set the date to the last day of the month. A selection of common adjustments
* is provided in `TemporalAdjusters`. These include finding the "last day of the month" and
* "next Wednesday". The adjuster is responsible for handling special cases, such as the
* varying lengths of month and leap years.
*
* Some example code indicating how and why this method is used:
* ```
* date = date.with(Month.JULY); // most key classes implement TemporalAdjuster
* date = date.with(lastDayOfMonth()); // static import from TemporalAdjusters
* date = date.with(next(WEDNESDAY)); // static import from TemporalAdjusters and DayOfWeek
* ```
*/
with(adjuster: TemporalAdjuster): Temporal;
/**
* Returns an object of the same type as this object with the specified field altered.
*
* This returns a new object based on this one with the value for the specified field changed.
* For example, on a `LocalDate`, this could be used to set the year, month or day-of-month.
* The returned object will have the same observable type as this object.
*
* In some cases, changing a field is not fully defined. For example, if the target object is
* a date representing the 31st January, then changing the month to February would be unclear.
* In cases like this, the field is responsible for resolving the result. Typically it will
* choose the previous valid date, which would be the last valid day of February in this
* example.
*/
with(field: TemporalField, newValue: number): Temporal;
abstract isSupported(field: TemporalField): boolean;
/**
* Checks if the specified unit is supported.
*
* This checks if the date-time can be queried for the specified unit. If false, then calling
* the plus and minus methods will throw an exception.
*/
abstract isSupported(unit: TemporalUnit): boolean;
/**
* Calculates the period between this temporal and another temporal in terms of the
* specified unit.
*
* This calculates the period between two temporals in terms of a single unit. The start
* and end points are this and the specified temporal. The result will be negative if the
* end is before the start. For example, the period in hours between two temporal objects
* can be calculated using `startTime.until(endTime, HOURS)`.
*
* The calculation returns a whole number, representing the number of complete units between
* the two temporals. For example, the period in hours between the times 11:30 and 13:29 will
* only be one hour as it is one minute short of two hours.
*
* There are two equivalent ways of using this method. The first is to invoke this method
* directly. The second is to use `TemporalUnit.between(Temporal, Temporal)`:
* ```
* // these two lines are equivalent
* between = thisUnit.between(start, end);
* between = start.until(end, thisUnit);
* ```
*
* The choice should be made based on which makes the code more readable.
*
* For example, this method allows the number of days between two dates to be calculated:
* ```
* const daysBetween = DAYS.between(start, end);
* // or alternatively
* const daysBetween = start.until(end, DAYS);
* ```
*/
abstract until(endTemporal: Temporal, unit: TemporalUnit): number;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): Temporal;
protected _minusAmount(amount: TemporalAmount): Temporal;
protected _plusAmount(amount: TemporalAmount): Temporal;
protected _withAdjuster(adjuster: TemporalAdjuster): Temporal;
protected abstract _plusUnit(amountToAdd: number, unit: TemporalUnit): Temporal;
protected abstract _withField(field: TemporalField, newValue: number): Temporal;
}
/**
* Strategy for adjusting a temporal object.
*
* Adjusters are a key tool for modifying temporal objects. They exist to externalize the process
* of adjustment, permitting different approaches, as per the strategy design pattern. Examples
* might be an adjuster that sets the date avoiding weekends, or one that sets the date to the
* last day of the month.
*
* There are two equivalent ways of using a `TemporalAdjuster`. The first is to invoke the method
* on this interface directly. The second is to use `Temporal.with(TemporalAdjuster)`:
*
* ```
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisAdjuster.adjustInto(temporal);
* temporal = temporal.with(thisAdjuster);
* ```
*
* It is recommended to use the second approach, `with(TemporalAdjuster)`, as it is a lot clearer
* to read in code.
*
* See `TemporalAdjusters` for a standard set of adjusters, including finding the last day of
* the month. Adjusters may also be defined by applications.
*/
export abstract class TemporalAdjuster {
abstract adjustInto(temporal: Temporal): Temporal;
}
export abstract class TemporalQuery<R> {
abstract queryFrom(temporal: TemporalAccessor): R;
}
/**
A standard set of fields.
*
* This set of fields provide field-based access to manipulate a date, time or date-time.
* The standard set of fields can be extended by implementing {@link TemporalField}.
*/
export class ChronoField extends TemporalField {
/**
* This represents concept of the count of
* days within the period of a week where the weeks are aligned to the start of the month.
* This field is typically used with `ALIGNED_WEEK_OF_MONTH`.
*/
static ALIGNED_DAY_OF_WEEK_IN_MONTH: ChronoField;
/**
* This represents concept of the count of days
* within the period of a week where the weeks are aligned to the start of the year.
* This field is typically used with `ALIGNED_WEEK_OF_YEAR`.
*/
static ALIGNED_DAY_OF_WEEK_IN_YEAR: ChronoField;
/**
* This represents concept of the count of weeks within
* the period of a month where the weeks are aligned to the start of the month. This field
* is typically used with `ALIGNED_DAY_OF_WEEK_IN_MONTH`.
*/
static ALIGNED_WEEK_OF_MONTH: ChronoField;
/**
* his represents concept of the count of weeks within
* the period of a year where the weeks are aligned to the start of the year. This field
* is typically used with `ALIGNED_DAY_OF_WEEK_IN_YEAR`.
*/
static ALIGNED_WEEK_OF_YEAR: ChronoField;
/**
* This counts the AM/PM within the day, from 0 (AM) to 1 (PM).
*/
static AMPM_OF_DAY: ChronoField;
/**
* This counts the hour within the AM/PM, from 1 to 12.
* This is the hour that would be observed on a standard 12-hour analog wall clock.
*/
static CLOCK_HOUR_OF_AMPM: ChronoField;
/**
* This counts the hour within the AM/PM, from 1 to 24.
* This is the hour that would be observed on a 24-hour analog wall clock.
*/
static CLOCK_HOUR_OF_DAY: ChronoField;
/**
* This represents the concept of the day within the month.
* In the default ISO calendar system, this has values from 1 to 31 in most months.
* April, June, September, November have days from 1 to 30, while February has days from
* 1 to 28, or 29 in a leap year.
*/
static DAY_OF_MONTH: ChronoField;
/**
* This represents the standard concept of the day of the week.
* In the default ISO calendar system, this has values from Monday (1) to Sunday (7).
* The {@link DayOfWeek} class can be used to interpret the result.
*/
static DAY_OF_WEEK: ChronoField;
/**
* This represents the concept of the day within the year.
* In the default ISO calendar system, this has values from 1 to 365 in standard years and
* 1 to 366 in leap years.
*/
static DAY_OF_YEAR: ChronoField;
/**
* This field is the sequential count of days where
* 1970-01-01 (ISO) is zero. Note that this uses the local time-line, ignoring offset and
* time-zone.
*/
static EPOCH_DAY: ChronoField;
/**
* This represents the concept of the era, which is the largest
* division of the time-line. This field is typically used with `YEAR_OF_ERA`.
*
* In the default ISO calendar system, there are two eras defined, 'BCE' and 'CE'. The era
* 'CE' is the one currently in use and year-of-era runs from 1 to the maximum value.
* The era 'BCE' is the previous era, and the year-of-era runs backwards.
*/
static ERA: ChronoField;
/**
* This counts the hour within the AM/PM, from 0 to 11.
* This is the hour that would be observed on a standard 12-hour digital clock.
*/
static HOUR_OF_AMPM: ChronoField;
/**
* This counts the hour within the day, from 0 to 23. This is
* the hour that would be observed on a standard 24-hour digital clock.
*/
static HOUR_OF_DAY: ChronoField;
/**
* This represents the concept of the sequential count of
* seconds where `1970-01-01T00:00Z` (ISO) is zero. This field may be used with `NANO_OF_DAY`
* to represent the fraction of the day.
*
* An Instant represents an instantaneous point on the time-line. On their own they have
* no elements which allow a local date-time to be obtained. Only when paired with an offset
* or time-zone can the local date or time be found. This field allows the seconds part of
* the instant to be queried.
*/
static INSTANT_SECONDS: ChronoField;
/**
* This counts the microsecond within the day, from `0` to
* `(24 * 60 * 60 * 1_000_000) - 1`.
*
* This field is used to represent the micro-of-day handling any fraction of the second.
* Implementations of {@link TemporalAccessor} should provide a value for this field if they
* can return a value for `SECOND_OF_DAY` filling unknown precision with zero.
*
* When this field is used for setting a value, it should behave in the same way as
* setting `NANO_OF_DAY` with the value multiplied by 1,000.
*/
static MICRO_OF_DAY: ChronoField;
/**
* This counts the microsecond within the second, from 0 to 999,999.
*
* This field is used to represent the micro-of-second handling any fraction of the second.
* Implementations of {@link TemporalAccessor} should provide a value for this field if they
* can return a value for `SECOND_OF_MINUTE`, `SECOND_OF_DAY` or `INSTANT_SECONDS` filling
* unknown precision with zero.
*/
static MICRO_OF_SECOND: ChronoField;
/**
* This counts the millisecond within the day, from 0 to
* `(24 * 60 * 60 * 1,000) - 1`.
*
* This field is used to represent the milli-of-day handling any fraction of the second.
* Implementations of {@link TemporalAccessor} should provide a value for this field if they
* can return a value for `SECOND_OF_DAY` filling unknown precision with zero.
*
* When this field is used for setting a value, it should behave in the same way as
* setting `NANO_OF_DAY` with the value multiplied by 1,000,000.
*/
static MILLI_OF_DAY: ChronoField;
/**
* This counts the millisecond within the second, from 0 to
* 999.
*
* This field is used to represent the milli-of-second handling any fraction of the second.
* Implementations of {@link TemporalAccessor} should provide a value for this field if they can
* return a value for `SECOND_OF_MINUTE`, `SECOND_OF_DAY` or `INSTANT_SECONDS` filling unknown
* precision with zero.
*
* When this field is used for setting a value, it should behave in the same way as
* setting `NANO_OF_SECOND` with the value multiplied by 1,000,000.
*/
static MILLI_OF_SECOND: ChronoField;
/**
* This counts the minute within the day, from 0 to `(24 * 60) - 1`.
*/
static MINUTE_OF_DAY: ChronoField;
/**
* This counts the minute within the hour, from 0 to 59.
*/
static MINUTE_OF_HOUR: ChronoField;
/**
* The month-of-year, such as March. This represents the concept
* of the month within the year. In the default ISO calendar system, this has values from
* January (1) to December (12).
*/
static MONTH_OF_YEAR: ChronoField;
/**
* This counts the nanosecond within the day, from 0 to
* `(24 * 60 * 60 * 1,000,000,000) - 1`.
*
* This field is used to represent the nano-of-day handling any fraction of the second.
* Implementations of {@link TemporalAccessor} should provide a value for this field if they
* can return a value for `SECOND_OF_DAY` filling unknown precision with zero.
*/
static NANO_OF_DAY: ChronoField;
/**
* This counts the nanosecond within the second, from 0
* to 999,999,999.
*
* This field is used to represent the nano-of-second handling any fraction of the second.
* Implementations of {@link TemporalAccessor} should provide a value for this field if they
* can return a value for `SECOND_OF_MINUTE`, `SECOND_OF_DAY` or `INSTANT_SECONDS` filling
* unknown precision with zero.
*
* When this field is used for setting a value, it should set as much precision as the
* object stores, using integer division to remove excess precision. For example, if the
* {@link TemporalAccessor} stores time to millisecond precision, then the nano-of-second must
* be divided by 1,000,000 before replacing the milli-of-second.
*/
static NANO_OF_SECOND: ChronoField;
/**
* This represents the concept of the offset in seconds of
* local time from UTC/Greenwich.
*
* A {@link ZoneOffset} represents the period of time that local time differs from
* UTC/Greenwich. This is usually a fixed number of hours and minutes. It is equivalent to
* the total amount of the offset in seconds. For example, during the winter Paris has an
* offset of +01:00, which is 3600 seconds.
*/
static OFFSET_SECONDS: ChronoField;
/**
* The proleptic-month, which counts months sequentially
* from year 0.
*
* The first month in year zero has the value zero. The value increase for later months
* and decrease for earlier ones. Note that this uses the local time-line, ignoring offset
* and time-zone.
*/
static PROLEPTIC_MONTH: ChronoField;
/**
* This counts the second within the day, from 0 to
* (24 * 60 * 60) - 1.
*/
static SECOND_OF_DAY: ChronoField;
/**
* This counts the second within the minute, from 0 to 59.
*/
static SECOND_OF_MINUTE: ChronoField;
/**
* The proleptic year, such as 2012. This represents the concept of
* the year, counting sequentially and using negative numbers. The proleptic year is not
* interpreted in terms of the era.
*
* The standard mental model for a date is based on three concepts - year, month and day.
* These map onto the `YEAR`, `MONTH_OF_YEAR` and `DAY_OF_MONTH` fields. Note that there is no
* reference to eras. The full model for a date requires four concepts - era, year, month and
* day. These map onto the `ERA`, `YEAR_OF_ERA`, `MONTH_OF_YEAR` and `DAY_OF_MONTH` fields.
* Whether this field or `YEAR_OF_ERA` is used depends on which mental model is being used.
*/
static YEAR: ChronoField;
/**
* This represents the concept of the year within the era. This
* field is typically used with `ERA`. The standard mental model for a date is based on three
* concepts - year, month and day. These map onto the `YEAR`, `MONTH_OF_YEAR` and
* `DAY_OF_MONTH` fields. Note that there is no reference to eras. The full model for a date
* requires four concepts - era, year, month and day. These map onto the `ERA`, `YEAR_OF_ERA`,
* `MONTH_OF_YEAR` and `DAY_OF_MONTH` fields. Whether this field or `YEAR` is used depends on
* which mental model is being used.
*
* In the default ISO calendar system, there are two eras defined, 'BCE' and 'CE'.
* The era 'CE' is the one currently in use and year-of-era runs from 1 to the maximum value.
* The era 'BCE' is the previous era, and the year-of-era runs backwards.
*
* For example, subtracting a year each time yield the following:
* - year-proleptic 2 = 'CE' year-of-era 2
* - year-proleptic 1 = 'CE' year-of-era 1
* - year-proleptic 0 = 'BCE' year-of-era 1
* - year-proleptic -1 = 'BCE' year-of-era 2
*
* Note that the ISO-8601 standard does not actually define eras. Note also that the
* ISO eras do not align with the well-known AD/BC eras due to the change between the Julian
* and Gregorian calendar systems.
*/
static YEAR_OF_ERA: ChronoField;
private constructor();
isSupportedBy(temporal: TemporalAccessor): boolean;
baseUnit(): TemporalUnit;
/** Checks that the specified value is valid for this field. */
checkValidValue(value: number): number;
/**
* Checks that the specified value is valid for this field and
* is within the range of a safe integer.
*/
checkValidIntValue(value: number): number;
displayName(): string;
equals(other: any): boolean;
getFrom(temporal: TemporalAccessor): number;
isDateBased(): boolean;
isTimeBased(): boolean;
name(): string;
range(): ValueRange;
rangeRefinedBy(temporal: TemporalAccessor): ValueRange;
rangeUnit(): TemporalUnit;
adjustInto<R extends Temporal>(temporal: R, newValue: number): R;
toString(): string;
}
/**
* A standard set of date periods units.
*
* This set of units provide unit-based access to manipulate a date, time or date-time.
* The standard set of units can be extended by implementing TemporalUnit.
*/
export class ChronoUnit extends TemporalUnit {
/**
* Unit that represents the concept of a nanosecond, the smallest supported unit
* of time. For the ISO calendar system, it is equal to the 1,000,000,000th part of the second unit.
*/
static NANOS: ChronoUnit;
/**
* Unit that represents the concept of a microsecond. For the ISO calendar
* system, it is equal to the 1,000,000th part of the second unit.
*/
static MICROS: ChronoUnit;
/**
* Unit that represents the concept of a millisecond. For the ISO calendar
* system, it is equal to the 1000th part of the second unit.
*/
static MILLIS: ChronoUnit;
/**
* Unit that represents the concept of a second. For the ISO calendar system,
* it is equal to the second in the SI system of units, except around a leap-second.
*/
static SECONDS: ChronoUnit;
/**
* Unit that represents the concept of a minute. For the ISO calendar system,
* it is equal to 60 seconds.
*/
static MINUTES: ChronoUnit;
/**
* Unit that represents the concept of an hour. For the ISO calendar system,
* it is equal to 60 minutes.
*/
static HOURS: ChronoUnit;
/**
* Unit that represents the concept of half a day, as used in AM/PM. For
* the ISO calendar system, it is equal to 12 hours.
*/
static HALF_DAYS: ChronoUnit;
/**
* Unit that represents the concept of a day. For the ISO calendar system, it
* is the standard day from midnight to midnight. The estimated duration of a day is 24 Hours.
*/
static DAYS: ChronoUnit;
/**
* Unit that represents the concept of a week. For the ISO calendar system,
* it is equal to 7 Days.
*/
static WEEKS: ChronoUnit;
/**
* Unit that represents the concept of a month. For the ISO calendar system,
* the length of the month varies by month-of-year. The estimated duration of a month is
* one twelfth of 365.2425 Days.
*/
static MONTHS: ChronoUnit;
/**
* Unit that represents the concept of a year. For the ISO calendar system, it
* is equal to 12 months. The estimated duration of a year is 365.2425 Days.
*/
static YEARS: ChronoUnit;
/**
* Unit that represents the concept of a decade. For the ISO calendar system,
* it is equal to 10 years.
*/
static DECADES: ChronoUnit;
/**
* Unit that represents the concept of a century. For the ISO calendar
* system, it is equal to 100 years.
*/
static CENTURIES: ChronoUnit;
/**
* Unit that represents the concept of a millennium. For the ISO calendar
* system, it is equal to 1,000 years.
*/
static MILLENNIA: ChronoUnit;
/**
* Unit that represents the concept of an era. The ISO calendar system doesn't
* have eras thus it is impossible to add an era to a date or date-time. The estimated duration
* of the era is artificially defined as 1,000,000,000 Years.
*/
static ERAS: ChronoUnit;
/**
* Artificial unit that represents the concept of forever. This is primarily
* used with {@link TemporalField} to represent unbounded fields such as the year or era. The
* estimated duration of the era is artificially defined as the largest duration supported by
* {@link Duration}.
*/
static FOREVER: ChronoUnit;
private constructor();
addTo<T extends Temporal>(temporal: T, amount: number): T;
between(temporal1: Temporal, temporal2: Temporal): number;
/**
* Compares this ChronoUnit to the specified {@link TemporalUnit}.
* The comparison is based on the total length of the durations.
*/
compareTo(other: TemporalUnit): number;
duration(): Duration;
isDateBased(): boolean;
isDurationEstimated(): boolean;
isSupportedBy(temporal: Temporal): boolean;
isTimeBased(): boolean;
toString(): string;
}
/**
* Fields and units specific to the ISO-8601 calendar system,
* including quarter-of-year and week-based-year.
*/
export namespace IsoFields {
/**
* This field allows the day-of-quarter value to be queried and set. The day-of-quarter has
* values from 1 to 90 in Q1 of a standard year, from 1 to 91 in Q1 of a leap year, from
* 1 to 91 in Q2 and from 1 to 92 in Q3 and Q4.
*
* The day-of-quarter can only be calculated if the day-of-year, month-of-year and year are available.
*
* When setting this field, the value is allowed to be partially lenient, taking any value from
* 1 to 92. If the quarter has less than 92 days, then day 92, and potentially day 91, is in
* the following quarter.
*/
export const DAY_OF_QUARTER: TemporalField;
/**
* This field allows the quarter-of-year value to be queried and set. The quarter-of-year has
* values from 1 to 4.
*
* The day-of-quarter can only be calculated if the month-of-year is available.
*/
export const QUARTER_OF_YEAR: TemporalField;
/**
* The field that represents the week-of-week-based-year.
*/
export const WEEK_OF_WEEK_BASED_YEAR: TemporalField;
/**
* The field that represents the week-based-year.
*/
export const WEEK_BASED_YEAR: TemporalField;
/**
* The unit that represents week-based-years for the purpose of addition and subtraction.
*
* This allows a number of week-based-years to be added to, or subtracted from, a date.
* The unit is equal to either 52 or 53 weeks. The estimated duration of a week-based-year is
* the same as that of a standard ISO year at 365.2425 Days.
*
* The rules for addition add the number of week-based-years to the existing value for the
* week-based-year field. If the resulting week-based-year only has 52 weeks, then the date
* will be in week 1 of the following week-based-year.
*/
export const WEEK_BASED_YEARS: TemporalUnit;
/**
* Unit that represents the concept of a quarter-year. For the ISO calendar system, it is equal
* to 3 months. The estimated duration of a quarter-year is one quarter of 365.2425 days.
*/
export const QUARTER_YEARS: TemporalUnit;
}
export namespace TemporalAdjusters {
/**
* Returns the day-of-week in month adjuster, which returns a new date in the same month with
* the ordinal day-of-week. This is used for expressions like the 'second Tuesday in March'.
*
* The ISO calendar system behaves as follows:
* - The input 2011-12-15 for (1,TUESDAY) will return 2011-12-06.
* - The input 2011-12-15 for (2,TUESDAY) will return 2011-12-13.
* - The input 2011-12-15 for (3,TUESDAY) will return 2011-12-20.
* - The input 2011-12-15 for (4,TUESDAY) will return 2011-12-27.
* - The input 2011-12-15 for (5,TUESDAY) will return 2012-01-03.
* - The input 2011-12-15 for (-1,TUESDAY) will return 2011-12-27 (last in month).
* - The input 2011-12-15 for (-4,TUESDAY) will return 2011-12-06 (3 weeks before last in month).
* - The input 2011-12-15 for (-5,TUESDAY) will return 2011-11-29 (4 weeks before last in month).
* - The input 2011-12-15 for (0,TUESDAY) will return 2011-11-29 (last in previous month).
*
* For a positive or zero ordinal, the algorithm is equivalent to finding the first day-of-week
* that matches within the month and then adding a number of weeks to it. For a negative
* ordinal, the algorithm is equivalent to finding the last day-of-week that matches within the
* month and then subtracting a number of weeks to it. The ordinal number of weeks is not
* validated and is interpreted leniently according to this algorithm. This definition means
* that an ordinal of zero finds the last matching day-of-week in the previous month.
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK`
* and `DAY_OF_MONTH` fields and the `DAYS` unit, and assumes a seven day week.
*/
function dayOfWeekInMonth(ordinal: number, dayOfWeek: DayOfWeek): TemporalAdjuster;
/**
* Returns the "first day of month" adjuster, which returns a new date set to the first day
* of the current month.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 will return 2011-01-01.
* - The input 2011-02-15 will return 2011-02-01.
*
* The behavior is suitable for use with most calendar systems. It is equivalent to:
* ```
* temporal.with(DAY_OF_MONTH, 1);
* ```
*/
function firstDayOfMonth(): TemporalAdjuster;
/**
* Returns the "first day of next month" adjuster, which returns a new date set to the first
* day of the next month.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 will return 2011-02-01.
* - The input 2011-02-15 will return 2011-03-01.
*
* The behavior is suitable for use with most calendar systems. It is equivalent to:
* ```
* temporal.with(DAY_OF_MONTH, 1).plus(1, MONTHS);
* ```
*/
function firstDayOfNextMonth(): TemporalAdjuster;
/**
* Returns the "first day of next year" adjuster, which returns a new date set to the first
* day of the next year.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 will return 2012-01-01.
*
* The behavior is suitable for use with most calendar systems. It is equivalent to:
* ```
* temporal.with(DAY_OF_YEAR, 1).plus(1, YEARS);
* ```
*/
function firstDayOfNextYear(): TemporalAdjuster;
/**
* Returns the "first day of year" adjuster, which returns a new date set to the first day
* of the current year.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 will return 2011-01-01.
* - The input 2011-02-15 will return 2011-01-01.
*
* The behavior is suitable for use with most calendar systems. It is equivalent to:
* ```
* temporal.with(DAY_OF_YEAR, 1);
* ```
*/
function firstDayOfYear(): TemporalAdjuster;
/**
* Returns the first in month adjuster, which returns a new date in the same month with the
* first matching day-of-week. This is used for expressions like 'first Tuesday in March'.
*
* The ISO calendar system behaves as follows:
* - The input 2011-12-15 for (MONDAY) will return 2011-12-05.
* - The input 2011-12-15 for (FRIDAY) will return 2011-12-02.
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK`
* and `DAY_OF_MONTH` fields and the `DAYS` unit, and assumes a seven day week.
*/
function firstInMonth(dayOfWeek: DayOfWeek): TemporalAdjuster;
/**
* Returns the "last day of month" adjuster, which returns a new date set to the last day of
* the current month.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 will return 2011-01-31.
* - The input 2011-02-15 will return 2011-02-28.
* - The input 2012-02-15 will return 2012-02-29 (leap year).
* - The input 2011-04-15 will return 2011-04-30.
*
* The behavior is suitable for use with most calendar systems. It is equivalent to:
* ```
* const lastDay = temporal.range(DAY_OF_MONTH).getMaximum();
* temporal.with(DAY_OF_MONTH, lastDay);
* ```
*/
function lastDayOfMonth(): TemporalAdjuster;
/**
* Returns the "last day of year" adjuster, which returns a new date set to the last day of
* the current year.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 will return 2011-12-31.
* - The input 2011-02-15 will return 2011-12-31.
*
* The behavior is suitable for use with most calendar systems. It is equivalent to:
* ```
* const lastDay = temporal.range(DAY_OF_YEAR).getMaximum();
* temporal.with(DAY_OF_YEAR, lastDay);
* ```
*/
function lastDayOfYear(): TemporalAdjuster;
/**
* Returns the last in month adjuster, which returns a new date in the same month with the
* last matching day-of-week. This is used for expressions like 'last Tuesday in March'.
*
* The ISO calendar system behaves as follows:
* - The input 2011-12-15 for (MONDAY) will return 2011-12-26.
* - The input 2011-12-15 for (FRIDAY) will return 2011-12-30.
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK`
* and `DAY_OF_MONTH` fields and the `DAYS` unit, and assumes a seven day week.
*/
function lastInMonth(dayOfWeek: DayOfWeek): TemporalAdjuster;
/**
* Returns the next day-of-week adjuster, which adjusts the date to the first occurrence of
* the specified day-of-week after the date being adjusted.
*
* - The ISO calendar system behaves as follows:
* - The input 2011-01-15 (a Saturday) for parameter (MONDAY) will return 2011-01-17 (two
* days later).
* - The input 2011-01-15 (a Saturday) for parameter (WEDNESDAY) will return 2011-01-19 (four
* days later).
* - The input 2011-01-15 (a Saturday) for parameter (SATURDAY) will return 2011-01-22 (seven
* days later).
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK`
* field and the `DAYS` unit, and assumes a seven day week.
*/
function next(dayOfWeek: DayOfWeek): TemporalAdjuster;
/**
* Returns the next-or-same day-of-week adjuster, which adjusts the date to the first
* occurrence of the specified day-of-week after the date being adjusted unless it is already
* on that day in which case the same object is returned.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 (a Saturday) for parameter (MONDAY) will return 2011-01-17 (two
* days later).
* - The input 2011-01-15 (a Saturday) for parameter (WEDNESDAY) will return 2011-01-19 (four
* days later).
* - The input 2011-01-15 (a Saturday) for parameter (SATURDAY) will return 2011-01-15 (same
* as input).
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK`
* field and the `DAYS` unit, and assumes a seven day week.
*/
function nextOrSame(dayOfWeek: DayOfWeek): TemporalAdjuster;
/**
* Returns the previous day-of-week adjuster, which adjusts the date to the first occurrence
* of the specified day-of-week before the date being adjusted.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 (a Saturday) for parameter (MONDAY) will return 2011-01-10 (five
* days earlier).
* - The input 2011-01-15 (a Saturday) for parameter (WEDNESDAY) will return 2011-01-12 (three
* days earlier).
* - The input 2011-01-15 (a Saturday) for parameter (SATURDAY) will return 2011-01-08 (seven
* days earlier).
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK` field
* and the `DAYS` unit, and assumes a seven day week.
*/
function previous(dayOfWeek: DayOfWeek): TemporalAdjuster;
/**
* Returns the previous-or-same day-of-week adjuster, which adjusts the date to the first
* occurrence of the specified day-of-week before the date being adjusted unless it is already
* on that day in which case the same object is returned.
*
* The ISO calendar system behaves as follows:
* - The input 2011-01-15 (a Saturday) for parameter (MONDAY) will return 2011-01-10 (five
* days earlier).
* - The input 2011-01-15 (a Saturday) for parameter (WEDNESDAY) will return 2011-01-12 (three
* days earlier).
* - The input 2011-01-15 (a Saturday) for parameter (SATURDAY) will return 2011-01-15 (same
* as input).
*
* The behavior is suitable for use with most calendar systems. It uses the `DAY_OF_WEEK`
* field and the `DAYS` unit, and assumes a seven day week.
*/
function previousOrSame(dayOfWeek: DayOfWeek): TemporalAdjuster;
}
export namespace TemporalQueries {
function chronology(): TemporalQuery<Chronology | null>;
function localDate(): TemporalQuery<LocalDate | null>;
function localTime(): TemporalQuery<LocalTime | null>;
function offset(): TemporalQuery<ZoneOffset | null>;
function precision(): TemporalQuery<TemporalUnit | null>;
function zone(): TemporalQuery<ZoneId | null>;
function zoneId(): TemporalQuery<ZoneId | null>;
}
// ----------------------------------------------------------------------------
// MAIN
// ----------------------------------------------------------------------------
export abstract class Clock {
static fixed(fixedInstant: Instant, zoneId: ZoneId): Clock;
static offset(baseClock: Clock, offsetDuration: Duration): Clock;
static system(zone: ZoneId): Clock;
static systemDefaultZone(): Clock;
static systemUTC(): Clock;
abstract equals(other: any): boolean;
abstract instant(): Instant;
abstract millis(): number;
abstract withZone(zone: ZoneId): Clock;
abstract zone(): ZoneId;
}
export class Duration extends TemporalAmount {
static ZERO: Duration;
static between(startInclusive: Temporal, endExclusive: Temporal): Duration;
static from(amount: TemporalAmount): Duration;
static of(amount: number, unit: TemporalUnit): Duration;
static ofDays(days: number): Duration;
static ofHours(hours: number): Duration;
static ofMillis(millis: number): Duration;
static ofMinutes(minutes: number): Duration;
static ofNanos(nanos: number): Duration;
static ofSeconds(seconds: number, nanoAdjustment?: number): Duration;
static parse(text: string): Duration;
private constructor();
abs(): Duration;
addTo<T extends Temporal>(temporal: T): T;
compareTo(otherDuration: Duration): number;
dividedBy(divisor: number): Duration;
equals(other: any): boolean;
get(unit: TemporalUnit): number;
isNegative(): boolean;
isZero(): boolean;
minus(amount: number, unit: TemporalUnit): Duration;
minus(duration: Duration): Duration;
minusDays(daysToSubtract: number): Duration;
minusHours(hoursToSubtract: number): Duration;
minusMillis(millisToSubtract: number): Duration;
minusMinutes(minutesToSubtract: number): Duration;
minusNanos(nanosToSubtract: number): Duration;
minusSeconds(secondsToSubtract: number): Duration;
multipliedBy(multiplicand: number): Duration;
nano(): number;
negated(): Duration;
plus(amount: number, unit: TemporalUnit): Duration;
plus(duration: Duration): Duration;
plusDays(daysToAdd: number): Duration;
plusHours(hoursToAdd: number): Duration;
plusMillis(millisToAdd: number): Duration;
plusMinutes(minutesToAdd: number): Duration;
plusNanos(nanosToAdd: number): Duration;
plusSeconds(secondsToAdd: number): Duration;
plusSecondsNanos(secondsToAdd: number, nanosToAdd: number): Duration;
seconds(): number;
subtractFrom<T extends Temporal>(temporal: T): T;
toDays(): number;
toHours(): number;
toJSON(): string;
toMillis(): number;
toMinutes(): number;
toNanos(): number;
toString(): string;
units(): TemporalUnit[];
withNanos(nanoOfSecond: number): Duration;
withSeconds(seconds: number): Duration;
}
export class Instant extends Temporal implements TemporalAdjuster {
static EPOCH: Instant;
static MIN: Instant;
static MAX: Instant;
static MIN_SECONDS: Instant;
static MAX_SECONDS: Instant;
static FROM: TemporalQuery<Instant>;
static from(temporal: TemporalAccessor): Instant;
static now(clock?: Clock): Instant;
static ofEpochMilli(epochMilli: number): Instant;
static ofEpochSecond(epochSecond: number, nanoAdjustment?: number): Instant;
static parse(text: string): Instant;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atOffset(offset: ZoneOffset): OffsetDateTime;
atZone(zone: ZoneId): ZonedDateTime;
compareTo(otherInstant: Instant): number;
epochSecond(): number;
equals(other: any): boolean;
getLong(field: TemporalField): number;
hashCode(): number;
isAfter(otherInstant: Instant): boolean;
isBefore(otherInstant: Instant): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
minus(amountToSubtract: number, unit: TemporalUnit): Instant;
minus(amount: TemporalAmount): Instant;
minusMillis(millisToSubtract: number): Instant;
minusNanos(nanosToSubtract: number): Instant;
minusSeconds(secondsToSubtract: number): Instant;
nano(): number;
plus(amountToAdd: number, unit: TemporalUnit): Instant;
plus(amount: TemporalAmount): Instant;
plusMillis(millisToAdd: number): Instant;
plusNanos(nanosToAdd: number): Instant;
plusSeconds(secondsToAdd: number): Instant;
toEpochMilli(): number;
toJSON(): string;
toString(): string;
truncatedTo(unit: TemporalUnit): Instant;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): Instant;
with(field: TemporalField, newValue: number): Instant;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): Instant;
protected _minusAmount(amount: TemporalAmount): Instant;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): Instant;
protected _plusAmount(amount: TemporalAmount): Instant;
protected _withAdjuster(adjuster: TemporalAdjuster): Instant;
protected _withField(field: TemporalField, newValue: number): Instant;
}
export class LocalDate extends ChronoLocalDate implements TemporalAdjuster {
static MIN: LocalDate;
static MAX: LocalDate;
static EPOCH_0: LocalDate;
static FROM: TemporalQuery<LocalDate>;
static from(temporal: TemporalAccessor): LocalDate;
static now(clockOrZone?: Clock | ZoneId): LocalDate;
static of(year: number, month: Month | number, dayOfMonth: number): LocalDate;
static ofEpochDay(epochDay: number): LocalDate;
static ofInstant(instant: Instant, zoneId?: ZoneId): LocalDate;
static ofYearDay(year: number, dayOfYear: number): LocalDate;
static parse(text: string, formatter?: DateTimeFormatter): LocalDate;
private constructor();
atStartOfDay(): LocalDateTime;
atStartOfDay(zone: ZoneId): ZonedDateTime;
atTime(hour: number, minute: number, second?: number, nanoOfSecond?: number): LocalDateTime;
atTime(time: LocalTime): LocalDateTime;
atTime(time: OffsetTime): OffsetDateTime;
chronology(): Chronology;
compareTo(other: LocalDate): number;
dayOfMonth(): number;
dayOfWeek(): DayOfWeek;
dayOfYear(): number;
equals(other: any): boolean;
getLong(field: TemporalField): number;
hashCode(): number;
isAfter(other: LocalDate): boolean;
isBefore(other: LocalDate): boolean;
isEqual(other: LocalDate): boolean;
isLeapYear(): boolean;
isoWeekOfWeekyear(): number;
isoWeekyear(): number;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
lengthOfMonth(): number;
lengthOfYear(): number;
minus(amountToSubtract: number, unit: TemporalUnit): LocalDate;
minus(amount: TemporalAmount): LocalDate;
minusDays(daysToSubtract: number): LocalDate;
minusMonths(monthsToSubtract: number): LocalDate;
minusWeeks(weeksToSubtract: number): LocalDate;
minusYears(yearsToSubtract: number): LocalDate;
month(): Month;
monthValue(): number;
plus(amountToAdd: number, unit: TemporalUnit): LocalDate;
plus(amount: TemporalAmount): LocalDate;
plusDays(daysToAdd: number): LocalDate;
plusMonths(monthsToAdd: number): LocalDate;
plusWeeks(weeksToAdd: number): LocalDate;
plusYears(yearsToAdd: number): LocalDate;
toEpochDay(): number;
toJSON(): string;
toString(): string;
until(endDate: TemporalAccessor): Period;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): LocalDate;
with(field: TemporalField, newValue: number): LocalDate;
withDayOfMonth(dayOfMonth: number): LocalDate;
withDayOfYear(dayOfYear: number): LocalDate;
withMonth(month: Month | number): LocalDate;
withYear(year: number): LocalDate;
year(): number;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): LocalDate;
protected _minusAmount(amount: TemporalAmount): LocalDate;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): LocalDate;
protected _plusAmount(amount: TemporalAmount): LocalDate;
protected _withAdjuster(adjuster: TemporalAdjuster): LocalDate;
protected _withField(field: TemporalField, newValue: number): LocalDate;
}
export class LocalDateTime extends ChronoLocalDateTime implements TemporalAdjuster {
static MIN: LocalDateTime;
static MAX: LocalDateTime;
static FROM: TemporalQuery<LocalDateTime>;
static from(temporal: TemporalAccessor): LocalDateTime;
static now(clockOrZone?: Clock | ZoneId): LocalDateTime;
static of(date: LocalDate, time: LocalTime): LocalDateTime;
static of(year: number, month: Month | number, dayOfMonth: number, hour?: number, minute?: number, second?: number, nanoSecond?: number): LocalDateTime;
static ofEpochSecond(epochSecond: number, nanoOfSecond: number, offset: ZoneOffset): LocalDateTime;
static ofEpochSecond(epochSecond: number, offset: ZoneOffset): LocalDateTime;
static ofInstant(instant: Instant, zoneId?: ZoneId): LocalDateTime;
static parse(text: string, formatter?: DateTimeFormatter): LocalDateTime;
private constructor();
atOffset(offset: ZoneOffset): OffsetDateTime;
atZone(zone: ZoneId): ZonedDateTime;
compareTo(other: LocalDateTime): number;
dayOfMonth(): number;
dayOfWeek(): DayOfWeek;
dayOfYear(): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
getLong(field: TemporalField): number;
hashCode(): number;
hour(): number;
isAfter(other: LocalDateTime): boolean;
isBefore(other: LocalDateTime): boolean;
isEqual(other: LocalDateTime): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
minus(amountToSubtract: number, unit: TemporalUnit): LocalDateTime;
minus(amount: TemporalAmount): LocalDateTime;
minusDays(days: number): LocalDateTime;
minusHours(hours: number): LocalDateTime;
minusMinutes(minutes: number): LocalDateTime;
minusMonths(months: number): LocalDateTime;
minusNanos(nanos: number): LocalDateTime;
minusSeconds(seconds: number): LocalDateTime;
minusWeeks(weeks: number): LocalDateTime;
minusYears(years: number): LocalDateTime;
minute(): number;
month(): Month;
monthValue(): number;
nano(): number;
plus(amountToAdd: number, unit: TemporalUnit): LocalDateTime;
plus(amount: TemporalAmount): LocalDateTime;
plusDays(days: number): LocalDateTime;
plusHours(hours: number): LocalDateTime;
plusMinutes(minutes: number): LocalDateTime;
plusMonths(months: number): LocalDateTime;
plusNanos(nanos: number): LocalDateTime;
plusSeconds(seconds: number): LocalDateTime;
plusWeeks(weeks: number): LocalDateTime;
plusYears(years: number): LocalDateTime;
second(): number;
toJSON(): string;
toLocalDate(): LocalDate;
toLocalTime(): LocalTime;
toString(): string;
truncatedTo(unit: TemporalUnit): LocalDateTime;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): LocalDateTime;
with(field: TemporalField, newValue: number): LocalDateTime;
withDayOfMonth(dayOfMonth: number): LocalDateTime;
withDayOfYear(dayOfYear: number): LocalDateTime;
withHour(hour: number): LocalDateTime;
withMinute(minute: number): LocalDateTime;
withMonth(month: number | Month): LocalDateTime;
withNano(nanoOfSecond: number): LocalDateTime;
withSecond(second: number): LocalDateTime;
withYear(year: number): LocalDateTime;
year(): number;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): LocalDateTime;
protected _minusAmount(amount: TemporalAmount): LocalDateTime;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): LocalDateTime;
protected _plusAmount(amount: TemporalAmount): LocalDateTime;
protected _withAdjuster(adjuster: TemporalAdjuster): LocalDateTime;
protected _withField(field: TemporalField, newValue: number): LocalDateTime;
}
export class LocalTime extends Temporal implements TemporalAdjuster {
static MIN: LocalTime;
static MAX: LocalTime;
static MIDNIGHT: LocalTime;
static NOON: LocalTime;
static HOURS_PER_DAY: number;
static MINUTES_PER_HOUR: number;
static MINUTES_PER_DAY: number;
static SECONDS_PER_MINUTE: number;
static SECONDS_PER_HOUR: number;
static SECONDS_PER_DAY: number;
static MILLIS_PER_DAY: number;
static MICROS_PER_DAY: number;
static NANOS_PER_SECOND: number;
static NANOS_PER_MINUTE: number;
static NANOS_PER_HOUR: number;
static NANOS_PER_DAY: number;
static FROM: TemporalQuery<LocalTime>;
static from(temporal: TemporalAccessor): LocalTime;
static now(clockOrZone?: Clock | ZoneId): LocalTime;
static of(hour?: number, minute?: number, second?: number, nanoOfSecond?: number): LocalTime;
static ofInstant(instant: Instant, zone?: ZoneId): LocalTime;
static ofNanoOfDay(nanoOfDay: number): LocalTime;
static ofSecondOfDay(secondOfDay?: number, nanoOfSecond?: number): LocalTime;
static parse(text: String, formatter?: DateTimeFormatter): LocalTime;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atDate(date: LocalDate): LocalDateTime;
atOffset(offset: ZoneOffset): OffsetTime;
compareTo(other: LocalTime): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
getLong(field: ChronoField): number;
hashCode(): number;
hour(): number;
isAfter(other: LocalTime): boolean;
isBefore(other: LocalTime): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
minus(amountToSubtract: number, unit: TemporalUnit): LocalTime;
minus(amount: TemporalAmount): LocalTime;
minusHours(hoursToSubtract: number): LocalTime;
minusMinutes(minutesToSubtract: number): LocalTime;
minusNanos(nanosToSubtract: number): LocalTime;
minusSeconds(secondsToSubtract: number): LocalTime;
minute(): number;
nano(): number;
plus(amountToAdd: number, unit: TemporalUnit): LocalTime;
plus(amount: TemporalAmount): LocalTime;
plusHours(hoursToAdd: number): LocalTime;
plusMinutes(minutesToAdd: number): LocalTime;
plusNanos(nanosToAdd: number): LocalTime;
plusSeconds(secondstoAdd: number): LocalTime;
second(): number;
toJSON(): string;
toNanoOfDay(): number;
toSecondOfDay(): number;
toString(): string;
toString(): string;
truncatedTo(unit: ChronoUnit): LocalTime;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): LocalTime;
with(field: TemporalField, newValue: number): LocalTime;
withHour(hour: number): LocalTime;
withMinute(minute: number): LocalTime;
withNano(nanoOfSecond: number): LocalTime;
withSecond(second: number): LocalTime;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): LocalTime;
protected _minusAmount(amount: TemporalAmount): LocalTime;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): LocalTime;
protected _plusAmount(amount: TemporalAmount): LocalTime;
protected _withAdjuster(adjuster: TemporalAdjuster): LocalTime;
protected _withField(field: TemporalField, newValue: number): LocalTime;
}
export class MonthDay extends TemporalAccessor implements TemporalAdjuster {
static FROM: TemporalQuery<MonthDay>;
static from(temporal: TemporalAccessor): MonthDay;
static now(zoneIdOrClock?: ZoneId | Clock): MonthDay;
static of(month: Month | number, dayOfMonth: number): MonthDay;
static parse(text: string, formatter?: DateTimeFormatter): MonthDay;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atYear(year: number): LocalDate;
compareTo(other: MonthDay): number;
dayOfMonth(): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
getLong(field: TemporalField): number;
isAfter(other: MonthDay): boolean;
isBefore(other: MonthDay): boolean;
isSupported(field: TemporalField): boolean;
isValidYear(year: number): boolean;
month(): Month;
monthValue(): number;
toJSON(): string;
toString(): string;
with(month: Month): MonthDay;
withDayOfMonth(dayOfMonth: number): MonthDay;
withMonth(month: number): MonthDay;
}
export class Period extends TemporalAmount {
static ZERO: Period;
static between(startDate: LocalDate, endDate: LocalDate): Period;
static from(amount: TemporalAmount): Period;
static of(years: number, months: number, days: number): Period;
static ofDays(days: number): Period;
static ofMonths(months: number): Period;
static ofWeeks(weeks: number): Period;
static ofYears(years: number): Period;
static parse(text: string): Period;
private constructor();
addTo<T extends Temporal>(temporal: T): T;
chronology(): IsoChronology;
days(): number;
equals(other: any): boolean;
get(unit: TemporalUnit): number;
hashCode(): number;
isNegative(): boolean;
isZero(): boolean;
minus(amountToSubtract: TemporalAmount): Period;
minusDays(daysToSubtract: number): Period;
minusMonths(monthsToSubtract: number): Period;
minusYears(yearsToSubtract: number): Period;
months(): number;
multipliedBy(scalar: number): Period;
negated(): Period;
normalized(): Period;
plus(amountToAdd: TemporalAmount): Period;
plusDays(daysToAdd: number): Period;
plusMonths(monthsToAdd: number): Period;
plusYears(yearsToAdd: number): Period;
subtractFrom<T extends Temporal>(temporal: T): T;
toJSON(): string;
toString(): string;
toTotalMonths(): number;
units(): TemporalUnit[];
withDays(days: number): Period;
withMonths(months: number): Period;
withYears(years: number): Period;
years(): number;
}
export class Year extends Temporal implements TemporalAdjuster {
static MIN_VALUE: number;
static MAX_VALUE: number;
static FROM: TemporalQuery<Year>;
static from(temporal: TemporalAccessor): Year;
static isLeap(year: number): boolean;
static now(zoneIdOrClock?: ZoneId | Clock): Year;
static of(isoYear: number): Year;
static parse(text: string, formatter?: DateTimeFormatter): Year;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atDay(dayOfYear: number): LocalDate;
atMonth(month: Month | number): YearMonth;
atMonthDay(monthDay: MonthDay): LocalDate;
compareTo(other: Year): number;
equals(other: any): boolean;
getLong(field: TemporalField): number;
isAfter(other: Year): boolean;
isBefore(other: Year): boolean;
isLeap(): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
isValidMonthDay(monthDay: MonthDay): boolean;
length(): number;
minus(amountToSubtract: number, unit: TemporalUnit): Year;
minus(amount: TemporalAmount): Year;
minusYears(yearsToSubtract: number): Year;
plus(amountToAdd: number, unit: TemporalUnit): Year;
plus(amount: TemporalAmount): Year;
plusYears(yearsToAdd: number): Year;
toJSON(): string;
toString(): string;
until(endExclusive: Temporal, unit: TemporalUnit): number;
value(): number;
with(adjuster: TemporalAdjuster): Year;
with(field: TemporalField, newValue: number): Year;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): Year;
protected _minusAmount(amount: TemporalAmount): Year;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): Year;
protected _plusAmount(amount: TemporalAmount): Year;
protected _withAdjuster(adjuster: TemporalAdjuster): Year;
protected _withField(field: TemporalField, newValue: number): Year;
}
export class YearMonth extends Temporal implements TemporalAdjuster {
static FROM: TemporalQuery<YearMonth>;
static from(temporal: TemporalAccessor): YearMonth;
static now(zoneIdOrClock?: ZoneId | Clock): YearMonth;
static of(year: number, monthOrNumber: Month | number): YearMonth;
static parse(text: string, formatter?: DateTimeFormatter): YearMonth;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atDay(dayOfMonth: number): LocalDate;
atEndOfMonth(): LocalDate;
compareTo(other: YearMonth): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
getLong(field: TemporalField): number;
isAfter(other: YearMonth): boolean;
isBefore(other: YearMonth): boolean;
isLeapYear(): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
isValidDay(): boolean;
lengthOfMonth(): number;
lengthOfYear(): number;
minus(amountToSubtract: number, unit: TemporalUnit): YearMonth;
minus(amount: TemporalAmount): YearMonth;
minusMonths(monthsToSubtract: number): YearMonth;
minusYears(yearsToSubtract: number): YearMonth;
month(): Month;
monthValue(): number;
plus(amountToAdd: number, unit: TemporalUnit): YearMonth;
plus(amount: TemporalAmount): YearMonth;
plusMonths(monthsToAdd: number): YearMonth;
plusYears(yearsToAdd: number): YearMonth;
toJSON(): string;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): YearMonth;
with(field: TemporalField, newValue: number): YearMonth;
withMonth(month: number): YearMonth;
withYear(year: number): YearMonth;
year(): number;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): YearMonth;
protected _minusAmount(amount: TemporalAmount): YearMonth;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): YearMonth;
protected _plusAmount(amount: TemporalAmount): YearMonth;
protected _withAdjuster(adjuster: TemporalAdjuster): YearMonth;
protected _withField(field: TemporalField, newValue: number): YearMonth;
}
/**
* A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as
* `2007-12-03T10:15:30+01:00`.
*
* `OffsetDateTime` is an immutable representation of a date-time with an offset. This class stores
* all date and time fields, to a precision of nanoseconds, as well as the offset from
* UTC/Greenwich. For example, the value "2nd October 2007 at 13:45:30.123456789 +02:00" can be
* stored in an `OffsetDateTime`.
*
* `OffsetDateTime`, `ZonedDateTime` and `Instant` all store an instant on the time-line to
* nanosecond precision. `Instant` is the simplest, simply representing the instant. `OffsetDateTime`
* adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained.
* `ZonedDateTime` adds full time-zone rules.
*
* It is intended that `ZonedDateTime` or `Instant` is used to model data in simpler applications. This
* class may be used when modeling date-time concepts in more detail, or when communicating to a
* database or in a network protocol.
*
* This is a value-based class; use of identity-sensitive operations (including reference equality
* (`==`), identity hash code, or synchronization) on instances of `OffsetDateTime` may have
* unpredictable results and should be avoided. The `equals` method should be used for comparisons.
*/
export class OffsetDateTime extends Temporal implements TemporalAdjuster {
static MIN: OffsetDateTime;
static MAX: OffsetDateTime;
static FROM: TemporalQuery<OffsetDateTime>;
static from(temporal: TemporalAccessor): OffsetDateTime
static now(clockOrZone?: Clock | ZoneId): OffsetDateTime;
static of(dateTime: LocalDateTime, offset: ZoneOffset): OffsetDateTime;
static of(date: LocalDate, time: LocalTime, offset: ZoneOffset): OffsetDateTime;
static of(year: number, month: number, day: number, hour: number, minute: number, second: number, nanoOfSecond: number, offset: ZoneOffset): OffsetDateTime;
static ofInstant(instant: Instant, zone: ZoneId): OffsetDateTime;
static parse(text: string, formatter?: DateTimeFormatter): OffsetDateTime;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atZoneSameInstant(zone: ZoneId): ZonedDateTime;
atZoneSimilarLocal(zone: ZoneId): ZonedDateTime;
compareTo(other: OffsetDateTime): number;
dayOfMonth(): number;
dayOfWeek(): DayOfWeek;
dayOfYear(): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
getLong(field: TemporalField): number;
hashCode(): number;
hour(): number;
isAfter(other: OffsetDateTime): boolean;
isBefore(other: OffsetDateTime): boolean;
isEqual(other: OffsetDateTime): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
minus(amountToSubtract: number, unit: TemporalUnit): OffsetDateTime;
minus(amount: TemporalAmount): OffsetDateTime;
minusDays(days: number): OffsetDateTime;
minusHours(hours: number): OffsetDateTime;
minusMinutes(minutes: number): OffsetDateTime;
minusMonths(months: number): OffsetDateTime;
minusNanos(nanos: number): OffsetDateTime;
minusSeconds(seconds: number): OffsetDateTime;
minusWeeks(weeks: number): OffsetDateTime;
minusYears(years: number): OffsetDateTime;
minute(): number;
month(): Month;
monthValue(): number;
nano(): number;
offset(): ZoneOffset;
plus(amountToAdd: number, unit: TemporalUnit): OffsetDateTime;
plus(amount: TemporalAmount): OffsetDateTime;
plusDays(days: number): OffsetDateTime;
plusHours(hours: number): OffsetDateTime;
plusMinutes(minutes: number): OffsetDateTime;
plusMonths(months: number): OffsetDateTime;
plusNanos(nanos: number): OffsetDateTime;
plusSeconds(seconds: number): OffsetDateTime;
plusWeeks(weeks: number): OffsetDateTime;
plusYears(years: number): OffsetDateTime;
second(): number;
toEpochSecond(): number;
toInstant(): Instant;
toJSON(): string;
toLocalDate(): LocalDate;
toLocalDateTime(): LocalDateTime;
toLocalTime(): LocalTime;
toOffsetTime(): OffsetTime;
toString(): string;
truncatedTo(unit: TemporalUnit): OffsetDateTime;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): OffsetDateTime;
with(field: TemporalField, newValue: number): OffsetDateTime;
withDayOfMonth(dayOfMonth: number): OffsetDateTime;
withDayOfYear(dayOfYear: number): OffsetDateTime;
withHour(hour: number): OffsetDateTime;
withMinute(minute: number): OffsetDateTime;
withMonth(month: number): OffsetDateTime;
withNano(nanoOfSecond: number): OffsetDateTime;
withOffsetSameInstant(offset: ZoneOffset): OffsetDateTime;
withOffsetSameLocal(offset: ZoneOffset): OffsetDateTime;
withSecond(second: number): OffsetDateTime;
withYear(year: number): OffsetDateTime;
year(): number;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): OffsetDateTime;
protected _minusAmount(amount: TemporalAmount): OffsetDateTime;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): OffsetDateTime;
protected _plusAmount(amount: TemporalAmount): OffsetDateTime;
protected _withAdjuster(adjuster: TemporalAdjuster): OffsetDateTime;
protected _withField(field: TemporalField, newValue: number): OffsetDateTime;
}
/**
* A time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as `10:15:30+01:00`.
*
* `OffsetTime` is an immutable date-time object that represents a time, often viewed as
* hour-minute-second-offset. This class stores all time fields, to a precision of nanoseconds, as
* well as a zone offset. For example, the value "13:45:30.123456789+02:00" can be stored in an
* `OffsetTime`.
*
* This is a value-based class; use of identity-sensitive operations (including reference equality
* (`==`), identity hash code, or synchronization) on instances of `OffsetTime` may have
* unpredictable results and should be avoided. The `equals` method should be used for comparisons.
*/
export class OffsetTime extends Temporal implements TemporalAdjuster {
static MIN: OffsetTime;
static MAX: OffsetTime;
static FROM: TemporalQuery<OffsetTime>;
static from(temporal: TemporalAccessor): OffsetTime
static now(clockOrZone?: Clock | ZoneId): OffsetTime;
static of(time: LocalTime, offset: ZoneOffset): OffsetTime;
static of(hour: number, minute: number, second: number, nanoOfSecond: number, offset: ZoneOffset): OffsetTime;
static ofInstant(instant: Instant, zone: ZoneId): OffsetTime;
static parse(text: string, formatter?: DateTimeFormatter): OffsetTime;
private constructor();
adjustInto(temporal: Temporal): Temporal;
atDate(date: LocalDate): OffsetDateTime;
compareTo(other: OffsetTime): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
getLong(field: TemporalField): number;
hashCode(): number;
hour(): number;
isAfter(other: OffsetTime): boolean;
isBefore(other: OffsetTime): boolean;
isEqual(other: OffsetTime): boolean;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
minus(amountToSubtract: number, unit: TemporalUnit): OffsetTime;
minus(amount: TemporalAmount): OffsetTime;
minusHours(hours: number): OffsetTime;
minusMinutes(minutes: number): OffsetTime;
minusNanos(nanos: number): OffsetTime;
minusSeconds(seconds: number): OffsetTime;
minute(): number;
nano(): number;
offset(): ZoneOffset;
plus(amountToAdd: number, unit: TemporalUnit): OffsetTime;
plus(amount: TemporalAmount): OffsetTime;
plusHours(hours: number): OffsetTime;
plusMinutes(minutes: number): OffsetTime;
plusNanos(nanos: number): OffsetTime;
plusSeconds(seconds: number): OffsetTime;
second(): number;
toEpochSecond(date: LocalDate): number;
toJSON(): string;
toLocalTime(): LocalTime;
toString(): string;
truncatedTo(unit: TemporalUnit): OffsetTime;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): OffsetTime;
with(field: TemporalField, newValue: number): OffsetTime;
withHour(hour: number): OffsetTime;
withMinute(minute: number): OffsetTime;
withNano(nanoOfSecond: number): OffsetTime;
withOffsetSameInstant(offset: ZoneOffset): OffsetTime;
withOffsetSameLocal(offset: ZoneOffset): OffsetTime;
withSecond(second: number): OffsetTime;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): OffsetTime;
protected _minusAmount(amount: TemporalAmount): OffsetTime;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): OffsetTime;
protected _plusAmount(amount: TemporalAmount): OffsetTime;
protected _withAdjuster(adjuster: TemporalAdjuster): OffsetTime;
protected _withField(field: TemporalField, newValue: number): OffsetTime;
}
/**
* A date-time with a time-zone in the ISO-8601 calendar system, such as
* `2007-12-23T10:15:30+01:00 Europe/Paris`.
*
* `ZonedDateTime` is an immutable representation of a date-time with a time-zone. This class
* stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone
* offset used to handle ambiguous local date-times. For example, the value "2nd October 2007 at
* 13:45.30.123456789 +02:00 in the Europe/Paris time-zone" can be stored in a `ZonedDateTime`.
*
* This class handles conversion from the local time-line of `LocalDateTime` to the instant
* time-line of `Instant`. The difference between the two time-lines is the offset from
* UTC/Greenwich, represented by a `ZoneOffset`.
*
* Converting between the two time-lines involves calculating the offset using the rules accessed
* from the `ZoneId`. Obtaining the offset for an instant is simple, as there is exactly one valid
* offset for each instant. By contrast, obtaining the offset for a local date-time is not
* straightforward. There are three cases:
* - Normal, with one valid offset. For the vast majority of the year, the normal case applies,
* where there is a single valid offset for the local date-time.
* - Gap, with zero valid offsets. This is when clocks jump forward typically due to the spring
* daylight savings change from "winter" to "summer". In a gap there are local date-time values
* with no valid offset.
* - Overlap, with two valid offsets. This is when clocks are set back typically due to the autumn
* daylight savings change from "summer" to "winter". In an overlap there are local date-time
* values with two valid offsets.
*
* Any method that converts directly or implicitly from a local date-time to an instant by
* obtaining the offset has the potential to be complicated.
*
* For Gaps, the general strategy is that if the local date-time falls in the middle of a Gap,
* then the resulting zoned date-time will have a local date-time shifted forwards by the length
* of the Gap, resulting in a date-time in the later offset, typically "summer" time.
*
* For Overlaps, the general strategy is that if the local date-time falls in the middle of an
* Overlap, then the previous offset will be retained. If there is no previous offset, or the
* previous offset is invalid, then the earlier offset is used, typically "summer" time. Two
* additional methods, `withEarlierOffsetAtOverlap()` and `withLaterOffsetAtOverlap()`, help
* manage the case of an overlap.
*/
export class ZonedDateTime extends ChronoZonedDateTime {
static FROM: TemporalQuery<ZonedDateTime>;
static from(temporal: TemporalAccessor): ZonedDateTime;
static now(clockOrZone?: Clock | ZoneId): ZonedDateTime;
static of(localDateTime: LocalDateTime, zone: ZoneId): ZonedDateTime;
static of(date: LocalDate, time: LocalTime, zone: ZoneId): ZonedDateTime;
static of(year: number, month: number, dayOfMonth: number, hour: number, minute: number, second: number, nanoOfSecond: number, zone: ZoneId): ZonedDateTime;
/**
* Obtains an instance of ZonedDateTime from an Instant.
*
* This creates a zoned date-time with the same instant as that specified. Calling
* `ChronoZonedDateTime.toInstant()` will return an instant equal to the one used here.
*
* Converting an instant to a zoned date-time is simple as there is only one valid offset for
* each instant.
*/
static ofInstant(instant: Instant, zone: ZoneId): ZonedDateTime;
/**
* Obtains an instance of `ZonedDateTime` from the instant formed by combining the local
* date-time and offset.
*
* This creates a zoned date-time by combining the `LocalDateTime` and `ZoneOffset`. This
* combination uniquely specifies an instant without ambiguity.
*
* Converting an instant to a zoned date-time is simple as there is only one valid offset for
* each instant. If the valid offset is different to the offset specified, the the date-time
* and offset of the zoned date-time will differ from those specified.
*
* If the `ZoneId` to be used is a `ZoneOffset`, this method is equivalent to
* `of(LocalDateTime, ZoneId)`.
*/
static ofInstant(localDateTime: LocalDateTime, offset: ZoneOffset, zone: ZoneId): ZonedDateTime;
/**
* Obtains an instance of `ZonedDateTime` from a local date-time using the preferred offset
* if possible.
*
* The local date-time is resolved to a single instant on the time-line. This is achieved by
* finding a valid offset from UTC/Greenwich for the local date-time as defined by the rules
* of the zone ID.
*
* In most cases, there is only one valid offset for a local date-time. In the case of an
* overlap, where clocks are set back, there are two valid offsets. If the preferred offset
* is one of the valid offsets then it is used. Otherwise the earlier valid offset is used,
* typically corresponding to "summer".
*
* In the case of a gap, where clocks jump forward, there is no valid offset. Instead, the
* local date-time is adjusted to be later by the length of the gap. For a typical one hour
* daylight savings change, the local date-time will be moved one hour later into the offset
* typically corresponding to "summer".
*/
static ofLocal(localDateTime: LocalDateTime, zone: ZoneId, preferredOffset?: ZoneOffset | null): ZonedDateTime;
/**
* Obtains an instance of `ZonedDateTime` strictly validating the combination of local
* date-time, offset and zone ID.
*
* This creates a zoned date-time ensuring that the offset is valid for the local date-time
* according to the rules of the specified zone. If the offset is invalid, an exception is
* thrown.
*/
static ofStrict(localDateTime: LocalDateTime, offset: ZoneOffset, zone: ZoneId): ZonedDateTime;
static parse(text: string, formatter?: DateTimeFormatter): ZonedDateTime;
private constructor();
dayOfMonth(): number;
dayOfWeek(): DayOfWeek;
dayOfYear(): number;
equals(other: any): boolean;
getLong(field: TemporalField): number;
hashCode(): number;
hour(): number;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
minus(amountToSubtract: number, unit: TemporalUnit): ZonedDateTime;
minus(amount: TemporalAmount): ZonedDateTime;
minusDays(days: number): ZonedDateTime;
minusHours(hours: number): ZonedDateTime;
minusMinutes(minutes: number): ZonedDateTime;
minusMonths(months: number): ZonedDateTime;
minusNanos(nanos: number): ZonedDateTime;
minusSeconds(seconds: number): ZonedDateTime;
minusWeeks(weeks: number): ZonedDateTime;
minusYears(years: number): ZonedDateTime;
minute(): number;
month(): Month;
monthValue(): number;
nano(): number;
offset(): ZoneOffset;
plus(amountToAdd: number, unit: TemporalUnit): ZonedDateTime;
plus(amount: TemporalAmount): ZonedDateTime;
plusDays(days: number): ZonedDateTime;
plusHours(hours: number): ZonedDateTime;
plusMinutes(minutes: number): ZonedDateTime;
plusMonths(months: number): ZonedDateTime;
plusNanos(nanos: number): ZonedDateTime;
plusSeconds(seconds: number): ZonedDateTime;
plusWeeks(weeks: number): ZonedDateTime;
plusYears(years: number): ZonedDateTime;
range(field: TemporalField): ValueRange;
second(): number;
toJSON(): string;
toLocalDate(): LocalDate;
toLocalDateTime(): LocalDateTime;
toLocalTime(): LocalTime;
toOffsetDateTime(): OffsetDateTime;
toString(): string;
truncatedTo(unit: TemporalUnit): ZonedDateTime;
until(endExclusive: Temporal, unit: TemporalUnit): number;
with(adjuster: TemporalAdjuster): ZonedDateTime;
with(field: TemporalField, newValue: number): ZonedDateTime;
withDayOfMonth(dayOfMonth: number): ZonedDateTime;
withDayOfYear(dayOfYear: number): ZonedDateTime;
/**
* Returns a copy of this date-time changing the zone offset to the earlier of the two valid
* offsets at a local time-line overlap.
*
* This method only has any effect when the local time-line overlaps, such as at an autumn
* daylight savings cutover. In this scenario, there are two valid offsets for the local
* date-time. Calling this method will return a zoned date-time with the earlier of the two
* selected.
*
* If this method is called when it is not an overlap, `this` is returned.
*/
withEarlierOffsetAtOverlap(): ZonedDateTime;
/**
* Returns a copy of this date-time with the zone ID set to the offset.
*
* This returns a zoned date-time where the zone ID is the same as `offset()`. The local
* date-time, offset and instant of the result will be the same as in this date-time.
*
* Setting the date-time to a fixed single offset means that any future calculations, such as
* addition or subtraction, have no complex edge cases due to time-zone rules. This might also
* be useful when sending a zoned date-time across a network, as most protocols, such as
* ISO-8601, only handle offsets, and not region-based zone IDs.
*/
withFixedOffsetZone(): ZonedDateTime;
withHour(hour: number): ZonedDateTime;
/**
* Returns a copy of this date-time changing the zone offset to the later of the two valid
* offsets at a local time-line overlap.
*
* This method only has any effect when the local time-line overlaps, such as at an autumn
* daylight savings cutover. In this scenario, there are two valid offsets for the local
* date-time. Calling this method will return a zoned date-time with the later of the two
* selected.
*
* If this method is called when it is not an overlap, `this` is returned.
*/
withLaterOffsetAtOverlap(): ZonedDateTime;
withMinute(minute: number): ZonedDateTime;
withMonth(month: number): ZonedDateTime;
withNano(nanoOfSecond: number): ZonedDateTime;
withSecond(second: number): ZonedDateTime;
withYear(year: number): ZonedDateTime;
/**
* Returns a copy of this date-time with a different time-zone, retaining the instant.
*
* This method changes the time-zone and retains the instant. This normally results in a
* change to the local date-time.
*
* This method is based on retaining the same instant, thus gaps and overlaps in the local
* time-line have no effect on the result.
*
* To change the offset while keeping the local time, use `withZoneSameLocal(ZoneId)`.
*/
withZoneSameInstant(zone: ZoneId): ZonedDateTime;
/**
* Returns a copy of this date-time with a different time-zone, retaining the local date-time
* if possible.
*
* This method changes the time-zone and retains the local date-time. The local date-time is
* only changed if it is invalid for the new zone, determined using the same approach as
* `ofLocal(LocalDateTime, ZoneId, ZoneOffset)`.
*
* To change the zone and adjust the local date-time, use `withZoneSameInstant(ZoneId)`.
*/
withZoneSameLocal(zone: ZoneId): ZonedDateTime;
year(): number;
zone(): ZoneId;
protected _minusUnit(amountToSubtract: number, unit: TemporalUnit): ZonedDateTime;
protected _minusAmount(amount: TemporalAmount): ZonedDateTime;
protected _plusUnit(amountToAdd: number, unit: TemporalUnit): ZonedDateTime;
protected _plusAmount(amount: TemporalAmount): ZonedDateTime;
protected _withAdjuster(adjuster: TemporalAdjuster): ZonedDateTime;
protected _withField(field: TemporalField, newValue: number): ZonedDateTime;
}
export abstract class ZoneId {
static SYSTEM: ZoneId;
static UTC: ZoneId;
static systemDefault(): ZoneId;
static of(zoneId: string): ZoneId;
static ofOffset(prefix: string, offset: ZoneOffset): ZoneId;
static from(temporal: TemporalAccessor): ZoneId;
static getAvailableZoneIds(): string[];
equals(other: any): boolean;
hashCode(): number;
abstract id(): string;
normalized(): ZoneId;
abstract rules(): ZoneRules;
toJSON(): string;
toString(): string;
}
export class ZoneOffset extends ZoneId implements TemporalAdjuster {
static MAX_SECONDS: ZoneOffset;
static UTC: ZoneOffset;
static MIN: ZoneOffset;
static MAX: ZoneOffset;
static of(offsetId: string): ZoneOffset;
static ofHours(hours: number): ZoneOffset;
static ofHoursMinutes(hours: number, minutes: number): ZoneOffset;
static ofHoursMinutesSeconds(hours: number, minutes: number, seconds: number): ZoneOffset;
static ofTotalMinutes(totalMinutes: number): ZoneOffset;
static ofTotalSeconds(totalSeconds: number): ZoneOffset;
private constructor();
adjustInto(temporal: Temporal): Temporal;
compareTo(other: ZoneOffset): number;
equals(other: any): boolean;
get(field: TemporalField): number;
getLong(field: TemporalField): number;
hashCode(): number;
id(): string;
rules(): ZoneRules;
toString(): string;
totalSeconds(): number;
}
export class ZoneRegion extends ZoneId {
static ofId(zoneId: string): ZoneId;
private constructor();
id(): string;
rules(): ZoneRules;
}
export class DayOfWeek extends TemporalAccessor implements TemporalAdjuster {
static MONDAY: DayOfWeek;
static TUESDAY: DayOfWeek;
static WEDNESDAY: DayOfWeek;
static THURSDAY: DayOfWeek;
static FRIDAY: DayOfWeek;
static SATURDAY: DayOfWeek;
static SUNDAY: DayOfWeek;
static FROM: TemporalQuery<DayOfWeek>;
static from(temporal: TemporalAccessor): DayOfWeek;
static of(dayOfWeek: number): DayOfWeek;
static valueOf(name: string): DayOfWeek;
static values(): DayOfWeek[];
private constructor();
adjustInto(temporal: Temporal): Temporal;
compareTo(other: DayOfWeek): number;
equals(other: any): boolean;
getLong(field: TemporalField): number;
isSupported(field: TemporalField): boolean;
minus(days: number): DayOfWeek;
name(): string;
ordinal(): number;
plus(days: number): DayOfWeek;
toJSON(): string;
toString(): string;
value(): number;
}
export class Month extends TemporalAccessor implements TemporalAdjuster {
static JANUARY: Month;
static FEBRUARY: Month;
static MARCH: Month;
static APRIL: Month;
static MAY: Month;
static JUNE: Month;
static JULY: Month;
static AUGUST: Month;
static SEPTEMBER: Month;
static OCTOBER: Month;
static NOVEMBER: Month;
static DECEMBER: Month;
static from(temporal: TemporalAccessor): Month;
static of(month: number): Month;
static valueOf(name: string): Month;
static values(): Month[];
private constructor();
adjustInto(temporal: Temporal): Temporal;
compareTo(other: Month): number;
equals(other: any): boolean;
firstDayOfYear(leapYear: boolean): number;
firstMonthOfQuarter(): Month;
getLong(field: TemporalField): number;
isSupported(field: TemporalField): boolean;
length(leapYear: boolean): number;
maxLength(): number;
minLength(): number;
minus(months: number): Month;
name(): string;
ordinal(): number;
plus(months: number): Month;
toJSON(): string;
toString(): string;
value(): number;
}
// ----------------------------------------------------------------------------
// FORMAT
// ----------------------------------------------------------------------------
export class DateTimeFormatter {
static ISO_LOCAL_DATE: DateTimeFormatter;
static ISO_LOCAL_TIME: DateTimeFormatter;
static ISO_LOCAL_DATE_TIME: DateTimeFormatter;
static ISO_INSTANT: DateTimeFormatter;
static ISO_OFFSET_DATE_TIME: DateTimeFormatter;
static ISO_OFFSET_TIME: DateTimeFormatter;
static ISO_ZONED_DATE_TIME: DateTimeFormatter;
static ofPattern(pattern: string): DateTimeFormatter;
static parsedExcessDays(): TemporalQuery<Period>;
static parsedLeapSecond(): TemporalQuery<boolean>;
private constructor();
chronology(): Chronology | null;
decimalStyle(): DecimalStyle;
format(temporal: TemporalAccessor): string;
parse(text: string): TemporalAccessor;
parse<T>(text: string, query: TemporalQuery<T>): T;
parseUnresolved(text: string, position: ParsePosition): TemporalAccessor;
toString(): string;
withChronology(chrono: Chronology): DateTimeFormatter;
withResolverStyle(resolverStyle: ResolverStyle): DateTimeFormatter;
}
export class DateTimeFormatterBuilder {
constructor();
append(formatter: DateTimeFormatter): DateTimeFormatterBuilder;
appendFraction(field: TemporalField, minWidth: number, maxWidth: number, decimalPoint: boolean): DateTimeFormatterBuilder;
appendInstant(fractionalDigits: number): DateTimeFormatterBuilder;
appendLiteral(literal: any): DateTimeFormatterBuilder;
appendOffset(pattern: string, noOffsetText: string): DateTimeFormatterBuilder;
appendOffsetId(): DateTimeFormatterBuilder;
appendPattern(pattern: string): DateTimeFormatterBuilder;
appendValue(field: TemporalField, width?: number, maxWidth?: number, signStyle?: SignStyle): DateTimeFormatterBuilder;
appendValueReduced(field: TemporalField, width: number, maxWidth: number, base: ChronoLocalDate | number): DateTimeFormatterBuilder;
appendZoneId(): DateTimeFormatterBuilder;
optionalEnd(): DateTimeFormatterBuilder;
optionalStart(): DateTimeFormatterBuilder;
padNext(): DateTimeFormatterBuilder;
parseCaseInsensitive(): DateTimeFormatterBuilder;
parseCaseSensitive(): DateTimeFormatterBuilder;
parseLenient(): DateTimeFormatterBuilder;
parseStrict(): DateTimeFormatterBuilder;
toFormatter(resolverStyle?: ResolverStyle): DateTimeFormatter;
}
export class DecimalStyle {
private constructor();
decimalSeparator(): string;
equals(other: any): boolean;
hashCode(): any;
negativeSign(): string;
positiveSign(): string;
toString(): string;
zeroDigit(): string;
}
export class ResolverStyle {
static STRICT: ResolverStyle;
static SMART: ResolverStyle;
static LENIENT: ResolverStyle;
private constructor();
equals(other: any): boolean;
toJSON(): string;
toString(): string;
}
export class SignStyle {
static NORMAL: SignStyle;
static NEVER: SignStyle;
static ALWAYS: SignStyle;
static EXCEEDS_PAD: SignStyle;
static NOT_NEGATIVE: SignStyle;
private constructor();
equals(other: any): boolean;
toJSON(): string;
toString(): string;
}
export class TextStyle {
static FULL: TextStyle;
static FULL_STANDALONE: TextStyle;
static SHORT: TextStyle;
static SHORT_STANDALONE: TextStyle;
static NARROW: TextStyle;
static NARROW_STANDALONE: TextStyle;
private constructor();
asNormal(): TextStyle;
asStandalone(): TextStyle;
isStandalone(): boolean;
equals(other: any): boolean;
toJSON(): string;
toString(): string;
}
export class ParsePosition {
constructor(index: number);
getIndex(): number;
setIndex(index: number): void;
getErrorIndex(): number;
setErrorIndex(errorIndex: number): void;
}
// ----------------------------------------------------------------------------
// ZONE
// ----------------------------------------------------------------------------
export class ZoneOffsetTransition {
static of(transition: LocalDateTime, offsetBefore: ZoneOffset, offsetAfter: ZoneOffset): ZoneOffsetTransition;
private constructor();
compareTo(transition: ZoneOffsetTransition): number;
dateTimeAfter(): LocalDateTime;
dateTimeBefore(): LocalDateTime;
duration(): Duration;
durationSeconds(): number;
equals(other: any): boolean;
hashCode(): number;
instant(): Instant;
isGap(): boolean;
isOverlap(): boolean;
isValidOffset(offset: ZoneOffset): boolean;
offsetAfter(): ZoneOffset;
offsetBefore(): ZoneOffset;
toEpochSecond(): number;
toString(): string;
validOffsets(): ZoneOffset[];
}
export interface ZoneOffsetTransitionRule {
// TODO: Not implemented yet
}
export abstract class ZoneRules {
static of(offest: ZoneOffset): ZoneRules;
/**
* Gets the offset applicable at the specified instant in these rules.
*
* The mapping from an instant to an offset is simple, there is only one valid offset
* for each instant. This method returns that offset.
*/
offset(instant: Instant): ZoneOffset;
/**
* Gets a suitable offset for the specified local date-time in these rules.
*
* The mapping from a local date-time to an offset is not straightforward. There are
* three cases:
* - Normal, with one valid offset. For the vast majority of the year, the normal case
* applies, where there is a single valid offset for the local date-time.
* - Gap, with zero valid offsets. This is when clocks jump forward typically due to the
* spring daylight savings change from "winter" to "summer". In a gap there are local
* date-time values with no valid offset.
* - Overlap, with two valid offsets. This is when clocks are set back typically due to
* the autumn daylight savings change from "summer" to "winter". In an overlap there are
* local date-time values with two valid offsets.
*
* Thus, for any given local date-time there can be zero, one or two valid offsets. This
* method returns the single offset in the Normal case, and in the Gap or Overlap case it
* returns the offset before the transition.
*
* Since, in the case of Gap and Overlap, the offset returned is a "best" value, rather
* than the "correct" value, it should be treated with care. Applications that care about
* the correct offset should use a combination of this method, `getValidOffsets` and
* `getTransition`.
*/
offset(localDateTime: LocalDateTime): ZoneOffset;
toJSON(): string;
abstract daylightSavings(instant: Instant): Duration;
abstract isDaylightSavings(instant: Instant): boolean;
abstract isFixedOffset(): boolean;
/**
* Checks if the offset date-time is valid for these rules.
*
* To be valid, the local date-time must not be in a gap and the offset must match the
* valid offsets.
*/
abstract isValidOffset(localDateTime: LocalDateTime, offset: ZoneOffset): boolean;
abstract nextTransition(instant: Instant): ZoneOffsetTransition;
abstract offsetOfEpochMilli(epochMilli: number): ZoneOffset;
abstract offsetOfInstant(instant: Instant): ZoneOffset;
abstract offsetOfLocalDateTime(localDateTime: LocalDateTime): ZoneOffset;
abstract previousTransition(instant: Instant): ZoneOffsetTransition;
abstract standardOffset(instant: Instant): ZoneOffset;
abstract toString(): string;
/**
* Gets the offset transition applicable at the specified local date-time in these rules.
*
* The mapping from a local date-time to an offset is not straightforward. There are
* three cases:
* - Normal, with one valid offset. For the vast majority of the year, the normal case
* applies, where there is a single valid offset for the local date-time.
* - Gap, with zero valid offsets. This is when clocks jump forward typically due to the
* spring daylight savings change from "winter" to "summer". In a gap there are local
* date-time values with no valid offset.
* - Overlap, with two valid offsets. This is when clocks are set back typically due to
* the autumn daylight savings change from "summer" to "winter". In an overlap there are
* local date-time values with two valid offsets.
*
* A transition is used to model the cases of a Gap or Overlap. The Normal case will return
* `null`.
*
* There are various ways to handle the conversion from a `LocalDateTime`. One technique,
* using this method, would be:
* ```
* const trans = rules.transition(localDT);
* if (trans === null) {
* // Gap or Overlap: determine what to do from transition
* } else {
* // Normal case: only one valid offset
* zoneOffset = rules.offset(localDT);
* }
* ```
*
* @returns the offset transition, `null` if the local date-time is not in transition.
*/
abstract transition(localDateTime: LocalDateTime): ZoneOffsetTransition;
abstract transitionRules(): ZoneOffsetTransitionRule[];
abstract transitions(): ZoneOffsetTransition[];
/**
* Gets the offset applicable at the specified local date-time in these rules.
*
* The mapping from a local date-time to an offset is not straightforward. There are
* three cases:
* - Normal, with one valid offset. For the vast majority of the year, the normal case
* applies, where there is a single valid offset for the local date-time.
* - Gap, with zero valid offsets. This is when clocks jump forward typically due to the
* spring daylight savings change from "winter" to "summer". In a gap there are local
* date-time values with no valid offset.
* - Overlap, with two valid offsets. This is when clocks are set back typically due to
* the autumn daylight savings change from "summer" to "winter". In an overlap there are
* local date-time values with two valid offsets.
*
* Thus, for any given local date-time there can be zero, one or two valid offsets. This
* method returns that list of valid offsets, which is a list of size 0, 1 or 2. In the
* case where there are two offsets, the earlier offset is returned at index 0 and the
* later offset at index 1.
*
* There are various ways to handle the conversion from a `LocalDateTime`. One technique,
* using this method, would be:
* ```
* const validOffsets = rules.getOffset(localDT);
* if (validOffsets.length === 1) {
* // Normal case: only one valid offset
* zoneOffset = validOffsets[0];
* } else {
* // Gap or Overlap: determine what to do from transition
* const trans = rules.transition(localDT);
* }
* ```
*
* In theory, it is possible for there to be more than two valid offsets. This would happen
* if clocks to be put back more than once in quick succession. This has never happened in
* the history of time-zones and thus has no special handling. However, if it were to
* happen, then the list would return more than 2 entries.
*/
abstract validOffsets(localDateTime: LocalDateTime): ZoneOffset[];
}
export class ZoneRulesProvider {
static getRules(zoneId: string): ZoneRules;
static getAvailableZoneIds(): string[];
}
// ----------------------------------------------------------------------------
// CHRONO
// ----------------------------------------------------------------------------
// TODO: js-joda doesn't have Chronology yet. Methods like `LocalDate.chronology()`
// actually return an `IsoChronology` so Chronology is an alias type of that class
// for now. Change this if Chronology is added.
export type Chronology = IsoChronology;
export abstract class IsoChronology {
static isLeapYear(prolepticYear: number): boolean;
private constructor();
equals(other: any): boolean;
resolveDate(fieldValues: any, resolverStyle: any): any;
toString(): string;
}
export abstract class ChronoLocalDate extends Temporal implements TemporalAdjuster {
adjustInto(temporal: Temporal): Temporal;
format(formatter: DateTimeFormatter): string;
isSupported(fieldOrUnit: TemporalField | TemporalUnit): boolean;
}
export abstract class ChronoLocalDateTime extends Temporal implements TemporalAdjuster {
adjustInto(temporal: Temporal): Temporal;
chronology(): Chronology;
toEpochSecond(offset: ZoneOffset): number;
toInstant(offset: ZoneOffset): Instant;
}
export abstract class ChronoZonedDateTime extends Temporal {
compareTo(other: ChronoZonedDateTime): number;
equals(other: any): boolean;
format(formatter: DateTimeFormatter): string;
isAfter(other: ChronoZonedDateTime): boolean;
isBefore(other: ChronoZonedDateTime): boolean;
isEqual(other: ChronoZonedDateTime): boolean;
toEpochSecond(): number;
toInstant(): Instant;
}
// ----------------------------------------------------------------------------
// SUPPORT
// ----------------------------------------------------------------------------
export function nativeJs(date: Date | any, zone?: ZoneId): TemporalAccessor;
export function convert(
temporal: LocalDate | LocalDateTime | ZonedDateTime | Instant,
zone?: ZoneId,
): {
toDate: () => Date;
toEpochMilli: () => number;
};
export function use(plugin: Function): any;
// ----------------------------------------------------------------------------
// EXCEPTIONS
// ----------------------------------------------------------------------------
export class DateTimeException extends Error {
constructor(message?: string, cause?: Error);
}
export class UnsupportedTemporalTypeException extends DateTimeException { }
export class DateTimeParseException extends Error {
constructor(message?: string, text?: string, index?: number, cause?: Error);
parsedString(): string;
errorIndex(): number;
}
export class ArithmeticException extends Error { }
export class IllegalArgumentException extends Error { }
export class IllegalStateException extends Error { }
export class NullPointerException extends Error { }
export const __esModule: true;
export as namespace JSJoda; | the_stack |
import React, {
useCallback, useMemo, useRef, useState, useEffect,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
UncontrolledButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem, Modal, ModalHeader, ModalBody, ModalFooter,
} from 'reactstrap';
import { ISelectableAll, ISelectableAndIndeterminatable } from '~/client/interfaces/selectable-all';
import AppContainer from '~/client/services/AppContainer';
import { toastSuccess, toastError } from '~/client/util/apiNotification';
import { apiv3Post } from '~/client/util/apiv3-client';
import { V5ConversionErrCode } from '~/interfaces/errors/v5-conversion-error';
import { V5MigrationStatus } from '~/interfaces/page-listing-results';
import { IFormattedSearchResult } from '~/interfaces/search';
import { PageMigrationErrorData, SocketEventName } from '~/interfaces/websocket';
import { useCurrentUser } from '~/stores/context';
import {
ILegacyPrivatePage, usePrivateLegacyPagesMigrationModal,
} from '~/stores/modal';
import { useSWRxV5MigrationStatus } from '~/stores/page-listing';
import {
useSWRxSearch,
} from '~/stores/search';
import { useGlobalSocket } from '~/stores/websocket';
import { MenuItemType } from './Common/Dropdown/PageItemControl';
import PaginationWrapper from './PaginationWrapper';
import { PrivateLegacyPagesMigrationModal } from './PrivateLegacyPagesMigrationModal';
import { OperateAllControl } from './SearchPage/OperateAllControl';
import SearchControl from './SearchPage/SearchControl';
import { IReturnSelectedPageIds, SearchPageBase, usePageDeleteModalForBulkDeletion } from './SearchPage2/SearchPageBase';
// TODO: replace with "customize:showPageLimitationS"
const INITIAL_PAGING_SIZE = 20;
const initQ = '/';
/**
* SearchResultListHead
*/
type SearchResultListHeadProps = {
searchResult: IFormattedSearchResult,
offset: number,
pagingSize: number,
onPagingSizeChanged: (size: number) => void,
migrationStatus?: V5MigrationStatus,
}
const SearchResultListHead = React.memo((props: SearchResultListHeadProps): JSX.Element => {
const { t } = useTranslation();
const {
searchResult, offset, pagingSize,
onPagingSizeChanged, migrationStatus,
} = props;
if (migrationStatus == null) {
return (
<div className="mw-0 flex-grow-1 flex-basis-0 m-5 text-muted text-center">
<i className="fa fa-2x fa-spinner fa-pulse mr-1"></i>
</div>
);
}
const { took, total, hitsCount } = searchResult.meta;
const leftNum = offset + 1;
const rightNum = offset + hitsCount;
const isSuccess = migrationStatus.migratablePagesCount === 0;
if (isSuccess) {
return (
<div className="card border-success mt-3">
<div className="card-body">
<h2 className="card-title text-success">{t('private_legacy_pages.nopages_title')}</h2>
<p className="card-text">
{t('private_legacy_pages.nopages_desc1')}<br />
{/* eslint-disable-next-line react/no-danger */}
<span dangerouslySetInnerHTML={{ __html: t('private_legacy_pages.detail_info') }}></span>
</p>
</div>
</div>
);
}
return (
<>
<div className="form-inline d-flex align-items-center justify-content-between">
<div className="text-nowrap">
{t('search_result.result_meta')}
<span className="ml-3">{`${leftNum}-${rightNum}`} / {total}</span>
{ took != null && (
<span className="ml-3 text-muted">({took}ms)</span>
) }
</div>
<div className="input-group flex-nowrap search-result-select-group ml-auto d-md-flex d-none">
<div className="input-group-prepend">
<label className="input-group-text text-muted" htmlFor="inputGroupSelect01">{t('search_result.number_of_list_to_display')}</label>
</div>
<select
defaultValue={pagingSize}
className="custom-select"
id="inputGroupSelect01"
onChange={e => onPagingSizeChanged(Number(e.target.value))}
>
{[20, 50, 100, 200].map((limit) => {
return <option key={limit} value={limit}>{limit} {t('search_result.page_number_unit')}</option>;
})}
</select>
</div>
</div>
<div className="card border-warning mt-3">
<div className="card-body">
<h2 className="card-title text-warning">{t('private_legacy_pages.alert_title')}</h2>
<p className="card-text">
{t('private_legacy_pages.alert_desc1', { delete_all_selected_page: t('search_result.delete_all_selected_page') })}<br />
{/* eslint-disable-next-line react/no-danger */}
<span dangerouslySetInnerHTML={{ __html: t('private_legacy_pages.detail_info') }}></span>
</p>
</div>
</div>
</>
);
});
/*
* ConvertByPathModal
*/
type ConvertByPathModalProps = {
isOpen: boolean,
close?: () => void,
onSubmit?: (convertPath: string) => Promise<void> | void,
}
const ConvertByPathModal = React.memo((props: ConvertByPathModalProps): JSX.Element => {
const { t } = useTranslation();
const [currentInput, setInput] = useState<string>('');
const [checked, setChecked] = useState<boolean>(false);
useEffect(() => {
setChecked(false);
}, [props.isOpen]);
return (
<Modal size="lg" isOpen={props.isOpen} toggle={props.close} className="grw-create-page">
<ModalHeader tag="h4" toggle={props.close} className="bg-primary text-light">
{ t('private_legacy_pages.by_path_modal.title') }
</ModalHeader>
<ModalBody>
<p>{t('private_legacy_pages.by_path_modal.description')}</p>
<input type="text" className="form-control" placeholder="/" value={currentInput} onChange={e => setInput(e.target.value)} />
<div className="alert alert-danger mt-3" role="alert">
{ t('private_legacy_pages.by_path_modal.alert') }
</div>
</ModalBody>
<ModalFooter>
<div className="form-check">
<input
className="form-check-input"
type="checkbox"
id="understoodCheckbox"
onChange={e => setChecked(e.target.checked)}
/>
<label className="form-check-label" htmlFor="understoodCheckbox">{ t('private_legacy_pages.by_path_modal.checkbox_label') }</label>
</div>
<button
type="button"
className="btn btn-primary"
disabled={!checked}
onClick={() => props.onSubmit?.(currentInput)}
>
<i className="icon-fw icon-refresh" aria-hidden="true"></i>
{ t('private_legacy_pages.by_path_modal.button_label') }
</button>
</ModalFooter>
</Modal>
);
});
/**
* LegacyPage
*/
type Props = {
appContainer: AppContainer,
}
const PrivateLegacyPages = (props: Props): JSX.Element => {
const { t } = useTranslation();
const { data: currentUser } = useCurrentUser();
const isAdmin = currentUser?.admin;
const {
appContainer,
} = props;
const [keyword, setKeyword] = useState<string>(initQ);
const [offset, setOffset] = useState<number>(0);
const [limit, setLimit] = useState<number>(INITIAL_PAGING_SIZE);
const [isOpenConvertModal, setOpenConvertModal] = useState<boolean>(false);
const [isControlEnabled, setControlEnabled] = useState(false);
const selectAllControlRef = useRef<ISelectableAndIndeterminatable|null>(null);
const searchPageBaseRef = useRef<ISelectableAll & IReturnSelectedPageIds|null>(null);
const { data, conditions, mutate } = useSWRxSearch(keyword, 'PrivateLegacyPages', {
offset,
limit,
includeUserPages: true,
includeTrashPages: false,
});
const { data: migrationStatus, mutate: mutateMigrationStatus } = useSWRxV5MigrationStatus();
const searchInvokedHandler = useCallback((_keyword: string) => {
mutateMigrationStatus();
setKeyword(_keyword);
setOffset(0);
}, []);
const { open: openModal, close: closeModal } = usePrivateLegacyPagesMigrationModal();
const { data: socket } = useGlobalSocket();
useEffect(() => {
socket?.on(SocketEventName.PageMigrationSuccess, () => {
toastSuccess(t('private_legacy_pages.toaster.page_migration_succeeded'));
});
socket?.on(SocketEventName.PageMigrationError, (data?: PageMigrationErrorData) => {
if (data == null || data.paths.length === 0) {
toastError(t('private_legacy_pages.toaster.page_migration_failed'));
}
else {
const errorPaths = data.paths.length > 3
? `${data.paths.slice(0, 3).join(', ')}...`
: data.paths.join(', ');
toastError(t('private_legacy_pages.toaster.page_migration_failed_with_paths', { paths: errorPaths }));
}
});
return () => {
socket?.off(SocketEventName.PageMigrationSuccess);
socket?.off(SocketEventName.PageMigrationError);
};
}, [socket]);
const selectAllCheckboxChangedHandler = useCallback((isChecked: boolean) => {
const instance = searchPageBaseRef.current;
if (instance == null) {
return;
}
if (isChecked) {
instance.selectAll();
setControlEnabled(true);
}
else {
instance.deselectAll();
setControlEnabled(false);
}
}, []);
const selectedPagesByCheckboxesChangedHandler = useCallback((selectedCount: number, totalCount: number) => {
const instance = selectAllControlRef.current;
if (instance == null) {
return;
}
if (selectedCount === 0) {
instance.deselect();
setControlEnabled(false);
}
else if (selectedCount === totalCount) {
instance.select();
setControlEnabled(true);
}
else {
instance.setIndeterminate();
setControlEnabled(true);
}
}, []);
// for bulk deletion
const deleteAllButtonClickedHandler = usePageDeleteModalForBulkDeletion(data, searchPageBaseRef, () => mutate());
const convertMenuItemClickedHandler = useCallback(() => {
if (data == null) {
return;
}
const instance = searchPageBaseRef.current;
if (instance == null || instance.getSelectedPageIds == null) {
return;
}
const selectedPageIds = instance.getSelectedPageIds();
if (selectedPageIds.size === 0) {
return;
}
const selectedPages = data.data
.filter(pageWithMeta => selectedPageIds.has(pageWithMeta.data._id))
.map(pageWithMeta => ({ pageId: pageWithMeta.data._id, path: pageWithMeta.data.path } as ILegacyPrivatePage));
openModal(
selectedPages,
() => {
toastSuccess(t('Successfully requested'));
closeModal();
mutateMigrationStatus();
mutate();
},
);
}, [data, mutate, openModal, closeModal, mutateMigrationStatus]);
const pagingSizeChangedHandler = useCallback((pagingSize: number) => {
setOffset(0);
setLimit(pagingSize);
mutate();
}, [mutate]);
const pagingNumberChangedHandler = useCallback((activePage: number) => {
setOffset((activePage - 1) * limit);
mutate();
}, [limit, mutate]);
const openConvertModalHandler = useCallback(() => {
if (!isAdmin) { return }
setOpenConvertModal(true);
}, [isAdmin]);
const hitsCount = data?.meta.hitsCount;
const renderOpenModalButton = useCallback(() => {
return (
<div className="d-flex pl-md-2">
<button type="button" className="btn btn-light" onClick={() => openConvertModalHandler()}>
{t('private_legacy_pages.input_path_to_convert')}
</button>
</div>
);
}, [t, openConvertModalHandler]);
const searchControlAllAction = useMemo(() => {
const isCheckboxDisabled = hitsCount === 0;
return (
<div className="search-control d-flex align-items-center">
<div className="d-flex pl-md-2">
<OperateAllControl
ref={selectAllControlRef}
isCheckboxDisabled={isCheckboxDisabled}
onCheckboxChanged={selectAllCheckboxChangedHandler}
>
<UncontrolledButtonDropdown>
<DropdownToggle caret color="outline-primary" disabled={!isControlEnabled}>
{t('private_legacy_pages.bulk_operation')}
</DropdownToggle>
<DropdownMenu>
<DropdownItem onClick={convertMenuItemClickedHandler}>
<i className="icon-fw icon-refresh"></i>
{t('private_legacy_pages.convert_all_selected_pages')}
</DropdownItem>
<DropdownItem onClick={deleteAllButtonClickedHandler}>
<span className="text-danger">
<i className="icon-fw icon-trash"></i>
{t('search_result.delete_all_selected_page')}
</span>
</DropdownItem>
</DropdownMenu>
</UncontrolledButtonDropdown>
</OperateAllControl>
</div>
{isAdmin && renderOpenModalButton()}
</div>
);
}, [convertMenuItemClickedHandler, deleteAllButtonClickedHandler, hitsCount, isControlEnabled, selectAllCheckboxChangedHandler, t]);
const searchControl = useMemo(() => {
return (
<SearchControl
isSearchServiceReachable
isEnableSort={false}
isEnableFilter={false}
initialSearchConditions={{ keyword: initQ, limit: INITIAL_PAGING_SIZE }}
onSearchInvoked={searchInvokedHandler}
allControl={searchControlAllAction}
/>
);
}, [searchInvokedHandler, searchControlAllAction]);
const searchResultListHead = useMemo(() => {
if (data == null) {
return <></>;
}
return (
<SearchResultListHead
searchResult={data}
offset={offset}
pagingSize={limit}
onPagingSizeChanged={pagingSizeChangedHandler}
migrationStatus={migrationStatus}
/>
);
}, [data, limit, offset, pagingSizeChangedHandler, migrationStatus]);
const searchPager = useMemo(() => {
// when pager is not needed
if (data == null || data.meta.hitsCount === data.meta.total) {
return <></>;
}
const { total } = data.meta;
const { offset, limit } = conditions;
return (
<PaginationWrapper
activePage={Math.floor(offset / limit) + 1}
totalItemsCount={total}
pagingLimit={limit}
changePage={pagingNumberChangedHandler}
/>
);
}, [conditions, data, pagingNumberChangedHandler]);
return (
<>
<SearchPageBase
ref={searchPageBaseRef}
appContainer={appContainer}
pages={data?.data}
onSelectedPagesByCheckboxesChanged={selectedPagesByCheckboxesChangedHandler}
forceHideMenuItems={[MenuItemType.BOOKMARK, MenuItemType.RENAME, MenuItemType.DUPLICATE, MenuItemType.REVERT, MenuItemType.PATH_RECOVERY]}
// Components
searchControl={searchControl}
searchResultListHead={searchResultListHead}
searchPager={searchPager}
/>
<PrivateLegacyPagesMigrationModal />
<ConvertByPathModal
isOpen={isOpenConvertModal}
close={() => setOpenConvertModal(false)}
onSubmit={async(convertPath: string) => {
try {
await apiv3Post<void>('/pages/convert-pages-by-path', {
convertPath,
});
toastSuccess(t('private_legacy_pages.by_path_modal.success'));
setOpenConvertModal(false);
}
catch (errs) {
if (errs.length === 1) {
switch (errs[0].code) {
case V5ConversionErrCode.GRANT_INVALID:
toastError(t('private_legacy_pages.by_path_modal.error_grant_invalid'));
break;
case V5ConversionErrCode.PAGE_NOT_FOUND:
toastError(t('private_legacy_pages.by_path_modal.error_page_not_found'));
break;
case V5ConversionErrCode.DUPLICATE_PAGES_FOUND:
toastError(t('private_legacy_pages.by_path_modal.error_duplicate_pages_found'));
break;
default:
toastError(t('private_legacy_pages.by_path_modal.error'));
}
}
else {
toastError(t('private_legacy_pages.by_path_modal.error'));
}
}
}}
/>
</>
);
};
export default PrivateLegacyPages; | the_stack |
import './ng_dev_mode';
import { QueryList } from '../linker';
import { Sanitizer } from '../sanitization/security';
import { StyleSanitizeFn } from '../sanitization/style_sanitizer';
import { LContainer } from './interfaces/container';
import { ComponentDefInternal, ComponentQuery, ComponentTemplate, DirectiveDefInternal, DirectiveDefListOrFactory, InitialStylingFlags, PipeDefListOrFactory, RenderFlags } from './interfaces/definition';
import { LInjector } from './interfaces/injector';
import { LContainerNode, LElementNode, LNode, LProjectionNode, LTextNode, LViewNode, TAttributes, TContainerNode, TElementNode, TNode, TNodeType } from './interfaces/node';
import { CssSelectorList } from './interfaces/projection';
import { LQueries } from './interfaces/query';
import { RComment, RElement, RText, Renderer3, RendererFactory3 } from './interfaces/renderer';
import { CurrentMatchesList, LViewData, LViewFlags, RootContext, TView } from './interfaces/view';
/**
* Directive (D) sets a property on all component instances using this constant as a key and the
* component's host node (LElement) as the value. This is used in methods like detectChanges to
* facilitate jumping from an instance to the host node.
*/
export declare const NG_HOST_SYMBOL = "__ngHostLNode__";
/**
* Function used to sanitize the value before writing it into the renderer.
*/
export declare type SanitizerFn = (value: any) => string;
/**
* Token set in currentMatches while dependencies are being resolved.
*
* If we visit a directive that has a value set to CIRCULAR, we know we've
* already seen it, and thus have a circular dependency.
*/
export declare const CIRCULAR = "__CIRCULAR__";
export declare function getRenderer(): Renderer3;
export declare function getCurrentSanitizer(): Sanitizer | null;
export declare function getViewData(): LViewData;
export declare function getPreviousOrParentNode(): LNode;
/**
* Query instructions can ask for "current queries" in 2 different cases:
* - when creating view queries (at the root of a component view, before any node is created - in
* this case currentQueries points to view queries)
* - when creating content queries (inb this previousOrParentNode points to a node on which we
* create content queries).
*/
export declare function getCurrentQueries(QueryType: {
new (): LQueries;
}): LQueries;
export declare function getCreationMode(): boolean;
/**
* Swap the current state with a new state.
*
* For performance reasons we store the state in the top level of the module.
* This way we minimize the number of properties to read. Whenever a new view
* is entered we have to store the state for later, and when the view is
* exited the state has to be restored
*
* @param newView New state to become active
* @param host Element to which the View is a child of
* @returns the previous state;
*/
export declare function enterView(newView: LViewData, host: LElementNode | LViewNode | null): LViewData;
/**
* Used in lieu of enterView to make it clear when we are exiting a child view. This makes
* the direction of traversal (up or down the view tree) a bit clearer.
*
* @param newView New state to become active
* @param creationOnly An optional boolean to indicate that the view was processed in creation mode
* only, i.e. the first update will be done later. Only possible for dynamically created views.
*/
export declare function leaveView(newView: LViewData, creationOnly?: boolean): void;
/** Sets the host bindings for the current view. */
export declare function setHostBindings(bindings: number[] | null): void;
export declare function executeInitAndContentHooks(): void;
export declare function createLViewData<T>(renderer: Renderer3, tView: TView, context: T | null, flags: LViewFlags, sanitizer?: Sanitizer | null): LViewData;
/**
* Creation of LNode object is extracted to a separate function so we always create LNode object
* with the same shape
* (same properties assigned in the same order).
*/
export declare function createLNodeObject(type: TNodeType, currentView: LViewData, parent: LNode | null, native: RText | RElement | RComment | null, state: any, queries: LQueries | null): LElementNode & LTextNode & LViewNode & LContainerNode & LProjectionNode;
/**
* A common way of creating the LNode to make sure that all of them have same shape to
* keep the execution code monomorphic and fast.
*
* @param index The index at which the LNode should be saved (null if view, since they are not
* saved).
* @param type The type of LNode to create
* @param native The native element for this LNode, if applicable
* @param name The tag name of the associated native element, if applicable
* @param attrs Any attrs for the native element, if applicable
* @param data Any data that should be saved on the LNode
*/
export declare function createLNode(index: number, type: TNodeType.Element, native: RElement | RText | null, name: string | null, attrs: TAttributes | null, lViewData?: LViewData | null): LElementNode;
export declare function createLNode(index: number, type: TNodeType.View, native: null, name: null, attrs: null, lViewData: LViewData): LViewNode;
export declare function createLNode(index: number, type: TNodeType.Container, native: RComment, name: string | null, attrs: TAttributes | null, lContainer: LContainer): LContainerNode;
export declare function createLNode(index: number, type: TNodeType.Projection, native: null, name: null, attrs: TAttributes | null, lProjection: null): LProjectionNode;
/**
* Resets the application state.
*/
export declare function resetApplicationState(): void;
/**
*
* @param hostNode Existing node to render into.
* @param template Template function with the instructions.
* @param context to pass into the template.
* @param providedRendererFactory renderer factory to use
* @param host The host element node to use
* @param directives Directive defs that should be used for matching
* @param pipes Pipe defs that should be used for matching
*/
export declare function renderTemplate<T>(hostNode: RElement, template: ComponentTemplate<T>, context: T, providedRendererFactory: RendererFactory3, host: LElementNode | null, directives?: DirectiveDefListOrFactory | null, pipes?: PipeDefListOrFactory | null, sanitizer?: Sanitizer | null): LElementNode;
/**
* Used for creating the LViewNode of a dynamic embedded view,
* either through ViewContainerRef.createEmbeddedView() or TemplateRef.createEmbeddedView().
* Such lViewNode will then be renderer with renderEmbeddedTemplate() (see below).
*/
export declare function createEmbeddedViewNode<T>(tView: TView, context: T, renderer: Renderer3, queries?: LQueries | null): LViewNode;
/**
* Used for rendering embedded views (e.g. dynamically created views)
*
* Dynamically created views must store/retrieve their TViews differently from component views
* because their template functions are nested in the template functions of their hosts, creating
* closures. If their host template happens to be an embedded template in a loop (e.g. ngFor inside
* an ngFor), the nesting would mean we'd have multiple instances of the template function, so we
* can't store TViews in the template function itself (as we do for comps). Instead, we store the
* TView for dynamically created views on their host TNode, which only has one instance.
*/
export declare function renderEmbeddedTemplate<T>(viewNode: LViewNode | LElementNode, tView: TView, context: T, rf: RenderFlags): LViewNode | LElementNode;
export declare function renderComponentOrTemplate<T>(node: LElementNode, hostView: LViewData, componentOrContext: T, template?: ComponentTemplate<T>): void;
export declare function namespaceSVG(): void;
export declare function namespaceMathML(): void;
export declare function namespaceHTML(): void;
/**
* Creates an empty element using {@link elementStart} and {@link elementEnd}
*
* @param index Index of the element in the data array
* @param name Name of the DOM Node
* @param attrs Statically bound set of attributes to be written into the DOM element on creation.
* @param localRefs A set of local reference bindings on the element.
*/
export declare function element(index: number, name: string, attrs?: TAttributes | null, localRefs?: string[] | null): void;
/**
* Create DOM element. The instruction must later be followed by `elementEnd()` call.
*
* @param index Index of the element in the LViewData array
* @param name Name of the DOM Node
* @param attrs Statically bound set of attributes to be written into the DOM element on creation.
* @param localRefs A set of local reference bindings on the element.
*
* Attributes and localRefs are passed as an array of strings where elements with an even index
* hold an attribute name and elements with an odd index hold an attribute value, ex.:
* ['id', 'warning5', 'class', 'alert']
*/
export declare function elementStart(index: number, name: string, attrs?: TAttributes | null, localRefs?: string[] | null): RElement;
/**
* Creates a native element from a tag name, using a renderer.
* @param name the tag name
* @param overriddenRenderer Optional A renderer to override the default one
* @returns the element created
*/
export declare function elementCreate(name: string, overriddenRenderer?: Renderer3): RElement;
export declare function resolveDirective(def: DirectiveDefInternal<any>, valueIndex: number, matches: CurrentMatchesList, tView: TView): any;
/** Sets the context for a ChangeDetectorRef to the given instance. */
export declare function initChangeDetectorIfExisting(injector: LInjector | null, instance: any, view: LViewData): void;
export declare function isComponent(tNode: TNode): boolean;
/**
* Creates a TView instance
*
* @param viewIndex The viewBlockId for inline views, or -1 if it's a component/dynamic
* @param directives Registry of directives for this view
* @param pipes Registry of pipes for this view
*/
export declare function createTView(viewIndex: number, template: ComponentTemplate<any> | null, directives: DirectiveDefListOrFactory | null, pipes: PipeDefListOrFactory | null, viewQuery: ComponentQuery<any> | null): TView;
export declare function createError(text: string, token: any): Error;
/**
* Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
*
* @param elementOrSelector Render element or CSS selector to locate the element.
*/
export declare function locateHostElement(factory: RendererFactory3, elementOrSelector: RElement | string): RElement | null;
/**
* Creates the host LNode.
*
* @param rNode Render host element.
* @param def ComponentDef
*
* @returns LElementNode created
*/
export declare function hostElement(tag: string, rNode: RElement | null, def: ComponentDefInternal<any>, sanitizer?: Sanitizer | null): LElementNode;
/**
* Adds an event listener to the current node.
*
* If an output exists on one of the node's directives, it also subscribes to the output
* and saves the subscription for later cleanup.
*
* @param eventName Name of the event
* @param listenerFn The function to be called when event emits
* @param useCapture Whether or not to use capture in event listener.
*/
export declare function listener(eventName: string, listenerFn: (e?: any) => any, useCapture?: boolean): void;
/**
* Saves context for this cleanup function in LView.cleanupInstances.
*
* On the first template pass, saves in TView:
* - Cleanup function
* - Index of context we just saved in LView.cleanupInstances
*/
export declare function storeCleanupWithContext(view: LViewData | null, context: any, cleanupFn: Function): void;
/**
* Saves the cleanup function itself in LView.cleanupInstances.
*
* This is necessary for functions that are wrapped with their contexts, like in renderer2
* listeners.
*
* On the first template pass, the index of the cleanup function is saved in TView.
*/
export declare function storeCleanupFn(view: LViewData, cleanupFn: Function): void;
/** Mark the end of the element. */
export declare function elementEnd(): void;
/**
* Updates the value of removes an attribute on an Element.
*
* @param number index The index of the element in the data array
* @param name name The name of the attribute.
* @param value value The attribute is removed when value is `null` or `undefined`.
* Otherwise the attribute value is set to the stringified value.
* @param sanitizer An optional function used to sanitize the value.
*/
export declare function elementAttribute(index: number, name: string, value: any, sanitizer?: SanitizerFn): void;
/**
* Update a property on an Element.
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new @Inputs don't have to be re-compiled.
*
* @param index The index of the element to update in the data array
* @param propName Name of property. Because it is going to DOM, this is not subject to
* renaming as part of minification.
* @param value New value to write.
* @param sanitizer An optional function used to sanitize the value.
*/
export declare function elementProperty<T>(index: number, propName: string, value: T | NO_CHANGE, sanitizer?: SanitizerFn): void;
/**
* Constructs a TNode object from the arguments.
*
* @param type The type of the node
* @param adjustedIndex The index of the TNode in TView.data, adjusted for HEADER_OFFSET
* @param tagName The tag name of the node
* @param attrs The attributes defined on this node
* @param parent The parent of this node
* @param tViews Any TViews attached to this node
* @returns the TNode object
*/
export declare function createTNode(type: TNodeType, adjustedIndex: number, tagName: string | null, attrs: TAttributes | null, parent: TElementNode | TContainerNode | null, tViews: TView[] | null): TNode;
/**
* Add or remove a class in a `classList` on a DOM element.
*
* This instruction is meant to handle the [class.foo]="exp" case
*
* @param index The index of the element to update in the data array
* @param className Name of class to toggle. Because it is going to DOM, this is not subject to
* renaming as part of minification.
* @param value A value indicating if a given class should be added or removed.
*/
export declare function elementClassProp<T>(index: number, stylingIndex: number, value: T | NO_CHANGE): void;
/**
* Assign any inline style values to the element during creation mode.
*
* This instruction is meant to be called during creation mode to apply all styling
* (e.g. `style="..."`) values to the element. This is also where the provided index
* value is allocated for the styling details for its corresponding element (the element
* index is the previous index value from this one).
*
* (Note this function calls `elementStylingApply` immediately when called.)
*
*
* @param index Index value which will be allocated to store styling data for the element.
* (Note that this is not the element index, but rather an index value allocated
* specifically for element styling--the index must be the next index after the element
* index.)
* @param classDeclarations A key/value array of CSS classes that will be registered on the element.
* Each individual style will be used on the element as long as it is not overridden
* by any classes placed on the element by multiple (`[class]`) or singular (`[class.named]`)
* bindings. If a class binding changes its value to a falsy value then the matching initial
* class value that are passed in here will be applied to the element (if matched).
* @param styleDeclarations A key/value array of CSS styles that will be registered on the element.
* Each individual style will be used on the element as long as it is not overridden
* by any styles placed on the element by multiple (`[style]`) or singular (`[style.prop]`)
* bindings. If a style binding changes its value to null then the initial styling
* values that are passed in here will be applied to the element (if matched).
* @param styleSanitizer An optional sanitizer function that will be used (if provided)
* to sanitize the any CSS property values that are applied to the element (during rendering).
*/
export declare function elementStyling<T>(classDeclarations?: (string | boolean | InitialStylingFlags)[] | null, styleDeclarations?: (string | boolean | InitialStylingFlags)[] | null, styleSanitizer?: StyleSanitizeFn | null): void;
/**
* Apply all styling values to the element which have been queued by any styling instructions.
*
* This instruction is meant to be run once one or more `elementStyle` and/or `elementStyleProp`
* have been issued against the element. This function will also determine if any styles have
* changed and will then skip the operation if there is nothing new to render.
*
* Once called then all queued styles will be flushed.
*
* @param index Index of the element's styling storage that will be rendered.
* (Note that this is not the element index, but rather an index value allocated
* specifically for element styling--the index must be the next index after the element
* index.)
*/
export declare function elementStylingApply<T>(index: number): void;
/**
* Queue a given style to be rendered on an Element.
*
* If the style value is `null` then it will be removed from the element
* (or assigned a different value depending if there are any styles placed
* on the element with `elementStyle` or any styles that are present
* from when the element was created (with `elementStyling`).
*
* (Note that the styling instruction will not be applied until `elementStylingApply` is called.)
*
* @param index Index of the element's styling storage to change in the data array.
* (Note that this is not the element index, but rather an index value allocated
* specifically for element styling--the index must be the next index after the element
* index.)
* @param styleIndex Index of the style property on this element. (Monotonically increasing.)
* @param styleName Name of property. Because it is going to DOM this is not subject to
* renaming as part of minification.
* @param value New value to write (null to remove).
* @param suffix Optional suffix. Used with scalar values to add unit such as `px`.
* Note that when a suffix is provided then the underlying sanitizer will
* be ignored.
*/
export declare function elementStyleProp<T>(index: number, styleIndex: number, value: T | null, suffix?: string): void;
/**
* Queue a key/value map of styles to be rendered on an Element.
*
* This instruction is meant to handle the `[style]="exp"` usage. When styles are applied to
* the Element they will then be placed with respect to any styles set with `elementStyleProp`.
* If any styles are set to `null` then they will be removed from the element (unless the same
* style properties have been assigned to the element during creation using `elementStyling`).
*
* (Note that the styling instruction will not be applied until `elementStylingApply` is called.)
*
* @param index Index of the element's styling storage to change in the data array.
* (Note that this is not the element index, but rather an index value allocated
* specifically for element styling--the index must be the next index after the element
* index.)
* @param classes A key/value style map of CSS classes that will be added to the given element.
* Any missing classes (that have already been applied to the element beforehand) will be
* removed (unset) from the element's list of CSS classes.
* @param styles A key/value style map of the styles that will be applied to the given element.
* Any missing styles (that have already been applied to the element beforehand) will be
* removed (unset) from the element's styling.
*/
export declare function elementStylingMap<T>(index: number, classes: {
[key: string]: any;
} | string | null, styles?: {
[styleName: string]: any;
} | null): void;
/**
* Create static text node
*
* @param index Index of the node in the data array
* @param value Value to write. This value will be stringified.
*/
export declare function text(index: number, value?: any): void;
/**
* Create text node with binding
* Bindings should be handled externally with the proper interpolation(1-8) method
*
* @param index Index of the node in the data array.
* @param value Stringified value to write.
*/
export declare function textBinding<T>(index: number, value: T | NO_CHANGE): void;
/**
* Create a directive and their associated content queries.
*
* NOTE: directives can be created in order other than the index order. They can also
* be retrieved before they are created in which case the value will be null.
*
* @param directive The directive instance.
* @param directiveDef DirectiveDef object which contains information about the template.
*/
export declare function directiveCreate<T>(directiveDefIdx: number, directive: T, directiveDef: DirectiveDefInternal<T> | ComponentDefInternal<T>): T;
/**
* A lighter version of directiveCreate() that is used for the root component
*
* This version does not contain features that we don't already support at root in
* current Angular. Example: local refs and inputs on root component.
*/
export declare function baseDirectiveCreate<T>(index: number, directive: T, directiveDef: DirectiveDefInternal<T> | ComponentDefInternal<T>): T;
/**
* Creates a LContainer, either from a container instruction, or for a ViewContainerRef.
*
* @param parentLNode the LNode in which the container's content will be rendered
* @param currentView The parent view of the LContainer
* @param isForViewContainerRef Optional a flag indicating the ViewContainerRef case
* @returns LContainer
*/
export declare function createLContainer(parentLNode: LNode, currentView: LViewData, isForViewContainerRef?: boolean): LContainer;
/**
* Creates an LContainerNode.
*
* Only `LViewNodes` can go into `LContainerNodes`.
*
* @param index The index of the container in the data array
* @param template Optional inline template
* @param tagName The name of the container element, if applicable
* @param attrs The attrs attached to the container, if applicable
* @param localRefs A set of local reference bindings on the element.
*/
export declare function container(index: number, template?: ComponentTemplate<any>, tagName?: string | null, attrs?: TAttributes, localRefs?: string[] | null): void;
/**
* Sets a container up to receive views.
*
* @param index The index of the container in the data array
*/
export declare function containerRefreshStart(index: number): void;
/**
* Marks the end of the LContainerNode.
*
* Marking the end of LContainerNode is the time when to child Views get inserted or removed.
*/
export declare function containerRefreshEnd(): void;
/**
* Marks the start of an embedded view.
*
* @param viewBlockId The ID of this view
* @return boolean Whether or not this view is in creation mode
*/
export declare function embeddedViewStart(viewBlockId: number): RenderFlags;
/** Marks the end of an embedded view. */
export declare function embeddedViewEnd(): void;
/**
* Refreshes components by entering the component view and processing its bindings, queries, etc.
*
* @param directiveIndex Directive index in LViewData[DIRECTIVES]
* @param adjustedElementIndex Element index in LViewData[] (adjusted for HEADER_OFFSET)
*/
export declare function componentRefresh<T>(directiveIndex: number, adjustedElementIndex: number): void;
/** Returns a boolean for whether the view is attached */
export declare function viewAttached(view: LViewData): boolean;
/**
* Instruction to distribute projectable nodes among <ng-content> occurrences in a given template.
* It takes all the selectors from the entire component's template and decides where
* each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is
* backed by a selector).
*
* This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text,
* un-parsed form.
*
* The parsed form is needed for efficient matching of a node against a given CSS selector.
* The un-parsed, textual form is needed for support of the ngProjectAs attribute.
*
* Having a CSS selector in 2 different formats is not ideal, but alternatives have even more
* drawbacks:
* - having only a textual form would require runtime parsing of CSS selectors;
* - we can't have only a parsed as we can't re-construct textual form from it (as entered by a
* template author).
*
* @param selectors A collection of parsed CSS selectors
* @param rawSelectors A collection of CSS selectors in the raw, un-parsed form
*/
export declare function projectionDef(selectors?: CssSelectorList[], textSelectors?: string[]): void;
/**
* Inserts previously re-distributed projected nodes. This instruction must be preceded by a call
* to the projectionDef instruction.
*
* @param nodeIndex
* @param selectorIndex:
* - 0 when the selector is `*` (or unspecified as this is the default value),
* - 1 based index of the selector from the {@link projectionDef}
*/
export declare function projection(nodeIndex: number, selectorIndex?: number, attrs?: string[]): void;
/**
* Adds LViewData or LContainer to the end of the current view tree.
*
* This structure will be used to traverse through nested views to remove listeners
* and call onDestroy callbacks.
*
* @param currentView The view where LViewData or LContainer should be added
* @param adjustedHostIndex Index of the view's host node in LViewData[], adjusted for header
* @param state The LViewData or LContainer to add to the view tree
* @returns The state passed in
*/
export declare function addToViewTree<T extends LViewData | LContainer>(currentView: LViewData, adjustedHostIndex: number, state: T): T;
/** If node is an OnPush component, marks its LViewData dirty. */
export declare function markDirtyIfOnPush(node: LElementNode): void;
/**
* Wraps an event listener so its host view and its ancestor views will be marked dirty
* whenever the event fires. Necessary to support OnPush components.
*/
export declare function wrapListenerWithDirtyLogic(view: LViewData, listenerFn: (e?: any) => any): (e: Event) => any;
/**
* Wraps an event listener so its host view and its ancestor views will be marked dirty
* whenever the event fires. Also wraps with preventDefault behavior.
*/
export declare function wrapListenerWithDirtyAndDefault(view: LViewData, listenerFn: (e?: any) => any): EventListener;
/** Marks current view and all ancestors dirty */
export declare function markViewDirty(view: LViewData): void;
/**
* Used to schedule change detection on the whole application.
*
* Unlike `tick`, `scheduleTick` coalesces multiple calls into one change detection run.
* It is usually called indirectly by calling `markDirty` when the view needs to be
* re-rendered.
*
* Typically `scheduleTick` uses `requestAnimationFrame` to coalesce multiple
* `scheduleTick` requests. The scheduling function can be overridden in
* `renderComponent`'s `scheduler` option.
*/
export declare function scheduleTick<T>(rootContext: RootContext): void;
/**
* Used to perform change detection on the whole application.
*
* This is equivalent to `detectChanges`, but invoked on root component. Additionally, `tick`
* executes lifecycle hooks and conditionally checks components based on their
* `ChangeDetectionStrategy` and dirtiness.
*
* The preferred way to trigger change detection is to call `markDirty`. `markDirty` internally
* schedules `tick` using a scheduler in order to coalesce multiple `markDirty` calls into a
* single change detection run. By default, the scheduler is `requestAnimationFrame`, but can
* be changed when calling `renderComponent` and providing the `scheduler` option.
*/
export declare function tick<T>(component: T): void;
/**
* Retrieve the root view from any component by walking the parent `LViewData` until
* reaching the root `LViewData`.
*
* @param component any component
*/
export declare function getRootView(component: any): LViewData;
/**
* Synchronously perform change detection on a component (and possibly its sub-components).
*
* This function triggers change detection in a synchronous way on a component. There should
* be very little reason to call this function directly since a preferred way to do change
* detection is to {@link markDirty} the component and wait for the scheduler to call this method
* at some future point in time. This is because a single user action often results in many
* components being invalidated and calling change detection on each component synchronously
* would be inefficient. It is better to wait until all components are marked as dirty and
* then perform single change detection across all of the components
*
* @param component The component which the change detection should be performed on.
*/
export declare function detectChanges<T>(component: T): void;
/**
* Checks the change detector and its children, and throws if any changes are detected.
*
* This is used in development mode to verify that running change detection doesn't
* introduce other changes.
*/
export declare function checkNoChanges<T>(component: T): void;
/** Checks the view of the component provided. Does not gate on dirty checks or execute doCheck. */
export declare function detectChangesInternal<T>(hostView: LViewData, hostNode: LElementNode, component: T): void;
/**
* Mark the component as dirty (needing change detection).
*
* Marking a component dirty will schedule a change detection on this
* component at some point in the future. Marking an already dirty
* component as dirty is a noop. Only one outstanding change detection
* can be scheduled per component tree. (Two components bootstrapped with
* separate `renderComponent` will have separate schedulers)
*
* When the root component is bootstrapped with `renderComponent`, a scheduler
* can be provided.
*
* @param component Component to mark as dirty.
*/
export declare function markDirty<T>(component: T): void;
export interface NO_CHANGE {
brand: 'NO_CHANGE';
}
/** A special value which designates that a value has not changed. */
export declare const NO_CHANGE: NO_CHANGE;
/**
* Creates a single value binding.
*
* @param value Value to diff
*/
export declare function bind<T>(value: T): T | NO_CHANGE;
/**
* Reserves slots for pure functions (`pureFunctionX` instructions)
*
* Bindings for pure functions are stored after the LNodes in the data array but before the binding.
*
* ----------------------------------------------------------------------------
* | LNodes ... | pure function bindings | regular bindings / interpolations |
* ----------------------------------------------------------------------------
* ^
* TView.bindingStartIndex
*
* Pure function instructions are given an offset from TView.bindingStartIndex.
* Subtracting the offset from TView.bindingStartIndex gives the first index where the bindings
* are stored.
*
* NOTE: reserveSlots instructions are only ever allowed at the very end of the creation block
*/
export declare function reserveSlots(numSlots: number): void;
/**
* Sets up the binding index before executing any `pureFunctionX` instructions.
*
* The index must be restored after the pure function is executed
*
* {@link reserveSlots}
*/
export declare function moveBindingIndexToReservedSlot(offset: number): number;
/**
* Restores the binding index to the given value.
*
* This function is typically used to restore the index after a `pureFunctionX` has
* been executed.
*/
export declare function restoreBindingIndex(index: number): void;
/**
* Create interpolation bindings with a variable number of expressions.
*
* If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
* Those are faster because there is no need to create an array of expressions and iterate over it.
*
* `values`:
* - has static text at even indexes,
* - has evaluated expressions at odd indexes.
*
* Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
*/
export declare function interpolationV(values: any[]): string | NO_CHANGE;
/**
* Creates an interpolation binding with 1 expression.
*
* @param prefix static value used for concatenation only.
* @param v0 value checked for change.
* @param suffix static value used for concatenation only.
*/
export declare function interpolation1(prefix: string, v0: any, suffix: string): string | NO_CHANGE;
/** Creates an interpolation binding with 2 expressions. */
export declare function interpolation2(prefix: string, v0: any, i0: string, v1: any, suffix: string): string | NO_CHANGE;
/** Creates an interpolation binding with 3 expressions. */
export declare function interpolation3(prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, suffix: string): string | NO_CHANGE;
/** Create an interpolation binding with 4 expressions. */
export declare function interpolation4(prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, suffix: string): string | NO_CHANGE;
/** Creates an interpolation binding with 5 expressions. */
export declare function interpolation5(prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, suffix: string): string | NO_CHANGE;
/** Creates an interpolation binding with 6 expressions. */
export declare function interpolation6(prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, suffix: string): string | NO_CHANGE;
/** Creates an interpolation binding with 7 expressions. */
export declare function interpolation7(prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, suffix: string): string | NO_CHANGE;
/** Creates an interpolation binding with 8 expressions. */
export declare function interpolation8(prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, i6: string, v7: any, suffix: string): string | NO_CHANGE;
/** Store a value in the `data` at a given `index`. */
export declare function store<T>(index: number, value: T): void;
/** Retrieves a value from the `directives` array. */
export declare function loadDirective<T>(index: number): T;
export declare function loadQueryList<T>(queryListIdx: number): QueryList<T>;
/** Retrieves a value from current `viewData`. */
export declare function load<T>(index: number): T;
export declare function loadElement(index: number): LElementNode;
/** Gets the current binding value and increments the binding index. */
export declare function consumeBinding(): any;
/** Updates binding if changed, then returns whether it was updated. */
export declare function bindingUpdated(value: any): boolean;
/** Updates binding if changed, then returns the latest value. */
export declare function checkAndUpdateBinding(value: any): any;
/** Updates 2 bindings if changed, then returns whether either was updated. */
export declare function bindingUpdated2(exp1: any, exp2: any): boolean;
/** Updates 4 bindings if changed, then returns whether any was updated. */
export declare function bindingUpdated4(exp1: any, exp2: any, exp3: any, exp4: any): boolean;
export declare function getTView(): TView;
/**
* Registers a QueryList, associated with a content query, for later refresh (part of a view
* refresh).
*/
export declare function registerContentQuery<Q>(queryList: QueryList<Q>): void;
export declare function assertPreviousIsParent(): void;
/**
* On the first template pass, the reserved slots should be set `NO_CHANGE`.
*
* If not, they might not have been actually reserved.
*/
export declare function assertReservedSlotInitialized(slotOffset: number, numSlots: number): void;
export declare function _getComponentHostLElementNode<T>(component: T): LElementNode;
export declare const CLEAN_PROMISE: Promise<null>;
export declare const ROOT_DIRECTIVE_INDICES: number[]; | the_stack |
import { FocusMonitor } from '@angular/cdk/a11y';
import { ESCAPE } from '@angular/cdk/keycodes';
import { OverlayContainer } from '@angular/cdk/overlay';
import { Component, ElementRef, NgModule, ViewChild } from '@angular/core';
import { async, ComponentFixture, fakeAsync, flush, flushMicrotasks, TestBed, tick } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { dispatchKeyboardEvent, fastTestSetup, patchElementFocus } from '../../../../test/helpers';
import { TooltipDirective, TooltipPosition } from './tooltip.directive';
import { TooltipModule } from './tooltip.module';
describe('browser.ui.tooltip', () => {
let fixture: ComponentFixture<TestTooltipComponent>;
let component: TestTooltipComponent;
let overlayContainer: OverlayContainer;
let overlayContainerElement: HTMLElement;
let focusMonitor: FocusMonitor;
fastTestSetup();
beforeAll(async () => {
await TestBed
.configureTestingModule({
imports: [TestTooltipModule],
})
.compileComponents();
});
beforeEach(() => {
overlayContainer = TestBed.get(OverlayContainer);
overlayContainerElement = overlayContainer.getContainerElement();
focusMonitor = TestBed.get(FocusMonitor);
fixture = TestBed.createComponent(TestTooltipComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
overlayContainer.ngOnDestroy();
});
it('should show and hide the tooltip.', fakeAsync(() => {
component.tooltip.show();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(true);
fixture.detectChanges();
// wait till animation has finished
tick(500);
expect(overlayContainerElement.textContent).toContain(component.message);
// After hide called, a timeout delay is created that will to hide the tooltip.
const tooltipDelay = 1000;
component.tooltip.hide(tooltipDelay);
expect(component.tooltip.isTooltipVisible()).toBe(true);
// After the tooltip delay elapses, expect that the tooltip is not visible.
tick(tooltipDelay);
fixture.detectChanges();
expect(component.tooltip.isTooltipVisible()).toBe(false);
// On animation complete, should expect that the tooltip has been detached.
flushMicrotasks();
}));
it('should show with delay', fakeAsync(() => {
const tooltipDelay = 1000;
component.tooltip.show(tooltipDelay);
expect(component.tooltip.isTooltipVisible()).toBe(false);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('');
tick(tooltipDelay);
expect(component.tooltip.isTooltipVisible()).toBe(true);
expect(overlayContainerElement.textContent).toContain(component.message);
}));
it('should not show if disabled', fakeAsync(() => {
// Test that disabling the tooltip will not set the tooltip visible
component.tooltip.disabled = true;
component.tooltip.show();
fixture.detectChanges();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(false);
// Test to make sure setting disabled to false will show the tooltip
// Sanity check to make sure everything was correct before (detectChanges, tick)
component.tooltip.disabled = false;
component.tooltip.show();
fixture.detectChanges();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(true);
}));
it('should hide if disabled while visible', fakeAsync(() => {
// Display the tooltip with a timeout before hiding.
component.tooltip.hideDelay = 1000;
component.tooltip.show();
fixture.detectChanges();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(true);
// Set tooltip to be disabled and verify that the tooltip hides.
component.tooltip.disabled = true;
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(false);
}));
it('should hide if the message is cleared while the tooltip is open', fakeAsync(() => {
component.tooltip.show();
fixture.detectChanges();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(true);
fixture.componentInstance.message = '';
fixture.detectChanges();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(false);
}));
it('should not show if hide is called before delay finishes', async(() => {
const tooltipDelay = 1000;
component.tooltip.show(tooltipDelay);
expect(component.tooltip.isTooltipVisible()).toBe(false);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('');
component.tooltip.hide();
fixture.whenStable().then(() => {
expect(component.tooltip.isTooltipVisible()).toBe(false);
});
}));
it('should not show tooltip if message is not present or empty', () => {
component.tooltip.message = undefined;
fixture.detectChanges();
component.tooltip.show();
component.tooltip.message = null;
fixture.detectChanges();
component.tooltip.show();
component.tooltip.message = '';
fixture.detectChanges();
component.tooltip.show();
component.tooltip.message = ' ';
fixture.detectChanges();
component.tooltip.show();
});
it('should be able to modify the tooltip message', fakeAsync(() => {
component.tooltip.show();
tick(500);
expect(component.tooltip._tooltipInstance._visibility).toBe('visible');
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain(component.message);
const newMessage = 'new tooltip message';
component.tooltip.message = newMessage;
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain(newMessage);
}));
it('should be removed after parent destroyed', fakeAsync(() => {
component.tooltip.show();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(true);
fixture.destroy();
expect(overlayContainerElement.childNodes.length).toBe(0);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should hide when clicking away', fakeAsync(() => {
component.tooltip.show();
tick(500);
fixture.detectChanges();
tick(500);
expect(component.tooltip.isTooltipVisible()).toBe(true);
expect(overlayContainerElement.textContent).toContain(component.message);
document.body.click();
tick(500);
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(component.tooltip.isTooltipVisible()).toBe(false);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should not hide immediately if a click fires while animating', fakeAsync(() => {
component.tooltip.show();
tick(0);
fixture.detectChanges();
document.body.click();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toContain(component.message);
}));
it('should not throw when pressing ESCAPE', fakeAsync(() => {
expect(() => {
dispatchKeyboardEvent(component.button.nativeElement, 'keydown', ESCAPE);
fixture.detectChanges();
}).not.toThrow();
// Flush due to the additional tick that is necessary for the FocusMonitor.
flush();
}));
it('should not show the tooltip on progammatic focus', fakeAsync(() => {
patchElementFocus(component.button.nativeElement);
focusMonitor.focusVia(component.button.nativeElement, 'program');
tick(500);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.Tooltip')).toBeNull();
}));
it('should not show the tooltip on mouse focus', fakeAsync(() => {
patchElementFocus(component.button.nativeElement);
focusMonitor.focusVia(component.button.nativeElement, 'mouse');
tick(500);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.Tooltip')).toBeNull();
}));
it('should set a fallback origin position by inverting the main origin position', () => {
component.tooltip.position = 'left';
expect(component.tooltip._getOrigin().main.originX).toBe('start');
expect(component.tooltip._getOrigin().fallback.originX).toBe('end');
component.tooltip.position = 'right';
expect(component.tooltip._getOrigin().main.originX).toBe('end');
expect(component.tooltip._getOrigin().fallback.originX).toBe('start');
component.tooltip.position = 'above';
expect(component.tooltip._getOrigin().main.originY).toBe('top');
expect(component.tooltip._getOrigin().fallback.originY).toBe('bottom');
component.tooltip.position = 'below';
expect(component.tooltip._getOrigin().main.originY).toBe('bottom');
expect(component.tooltip._getOrigin().fallback.originY).toBe('top');
});
it('should set a fallback overlay position by inverting the main overlay position', () => {
component.tooltip.position = 'left';
expect(component.tooltip._getOverlayPosition().main.overlayX).toBe('end');
expect(component.tooltip._getOverlayPosition().fallback.overlayX).toBe('start');
component.tooltip.position = 'right';
expect(component.tooltip._getOverlayPosition().main.overlayX).toBe('start');
expect(component.tooltip._getOverlayPosition().fallback.overlayX).toBe('end');
component.tooltip.position = 'above';
expect(component.tooltip._getOverlayPosition().main.overlayY).toBe('bottom');
expect(component.tooltip._getOverlayPosition().fallback.overlayY).toBe('top');
component.tooltip.position = 'below';
expect(component.tooltip._getOverlayPosition().main.overlayY).toBe('top');
expect(component.tooltip._getOverlayPosition().fallback.overlayY).toBe('bottom');
});
});
@Component({
template: `
<button #button [gdTooltip]="message" [gdTooltipPosition]="position">
Button
</button>
`,
})
class TestTooltipComponent {
position: TooltipPosition = 'below';
message = 'initial message';
@ViewChild(TooltipDirective) tooltip: TooltipDirective;
@ViewChild('button') button: ElementRef<HTMLButtonElement>;
}
@NgModule({
imports: [
TooltipModule,
NoopAnimationsModule,
],
declarations: [
TestTooltipComponent,
],
exports: [
TestTooltipComponent,
],
})
class TestTooltipModule {
} | the_stack |
import { RangeNavigator } from '../../../src/range-navigator/index';
import { AreaSeries } from '../../../src/chart/index';
import { createElement, remove } from '@syncfusion/ej2-base';
import { DataManager, Query } from '@syncfusion/ej2-data';
import '../../../node_modules/es6-promise/dist/es6-promise';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
RangeNavigator.Inject(AreaSeries);
/**
* Spec for range navigator
*/
let value: number = 0;
let point: object;
let data: object[] = [];
let dateTime: object[] = [];
for (let j: number = 0; j < 100; j++) {
value += (Math.random() * 10 - 5);
point = { x: j, y: value, y1: value + 10 };
data.push(point);
}
describe('Range navigator', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('with default case', () => {
let element: Element;
let range: RangeNavigator;
let rangeElement: Element = createElement('div', { id: 'container' });
let axisLabel: Element;
let dataManager: DataManager = new DataManager({
url: 'http://mvc.syncfusion.com/Services/Northwnd.svc/Tasks/'
});
let query: Query = new Query().take(5).where('Estimate', 'lessThan', 3, false);
beforeAll(() => {
document.body.appendChild(rangeElement);
range = new RangeNavigator({
dataSource: data, xName: 'x', yName: 'y', value: [20, 30]
});
range.appendTo('#container');
});
afterAll((): void => {
range.destroy();
rangeElement.remove();
});
it('empty options control class names', () => {
element = document.getElementById('container');
expect(element.classList.contains('e-control')).toBe(true);
expect(element.classList.contains('e-rangenavigator')).toBe(true);
});
it('checking with numeric lightweight', () => {
let container: Element = document.getElementById('container_svg');
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#FF4081');
expect(container.getAttribute('height')).toEqual('50');
expect(range != null).toBe(true);
});
it('checking with fabric theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#007897');
done();
};
range.theme = 'Fabric';
range.refresh();
});
it('checking with Bootstrap4 theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#FFD939');
done();
};
range.theme = 'Bootstrap4';
range.refresh();
});
it('checking with bootstrap theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#428BCA');
done();
};
range.theme = 'Bootstrap';
range.refresh();
});
it('checking with highContrast theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#FFD939');
done();
};
range.theme = 'HighContrastLight';
range.refresh();
});
it('checking with tailwind theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#4F46E5');
done();
};
range.theme = 'Tailwind';
range.refresh();
});
it('checking with tailwind dark theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('#22D3EE');
done();
};
range.theme = 'TailwindDark';
range.refresh();
});
it('checking with custom width', (done: Function) => {
range.loaded = (args: Object): void => {
let container: Element = document.getElementById('container_svg');
expect(container.getAttribute('width')).toEqual('200');
expect(range != null).toBe(true);
done();
};
range.theme = 'Material';
range.width = '200';
range.refresh();
});
it('checking with numeric axis with minimum only', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_0');
expect(element.textContent).toEqual('10');
expect(range != null).toBe(true);
done();
};
range.series = [{ dataSource: data, xName: 'x', yName: 'y', type: 'Line' }];
range.minimum = 10;
range.height = '';
range.width = '';
range.refresh();
});
it('checking with numeric axis with maximum only', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabels');
expect(element.childNodes[0].lastChild.textContent).toEqual('1000');
done();
};
range.minimum = null;
range.maximum = 1000;
range.refresh();
});
it('checking with numeric axis with interval only', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_0');
expect(element.textContent).toEqual('0');
element = document.getElementById('container_AxisLabel_1');
expect(element.textContent).toEqual('50');
done();
};
range.minimum = null;
range.interval = 50;
range.maximum = 1000;
range.refresh();
});
it('checking with numeric axis with range', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_0');
expect(element.textContent).toEqual('20');
element = document.getElementById('container_AxisLabel_1');
expect(element.textContent).toEqual('40');
done();
};
range.minimum = 20;
range.interval = 20;
range.maximum = 100;
range.refresh();
});
it('checking with label position inside', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_0');
expect(element.getAttribute('y') === '102').toBe(true);
done();
};
range.labelPosition = 'Inside';
range.refresh();
});
it('checking with label position outside', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_0');
expect(element.getAttribute('y') === '111' || element.getAttribute('y') === '111.25').toBe(true);
done();
};
range.labelPosition = 'Outside';
range.refresh();
});
it('checking with interval', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_0');
expect(element.textContent).toEqual('20');
element = document.getElementById('container_AxisLabel_1');
expect(element.textContent).toEqual('25');
done();
};
range.interval = 5;
range.refresh();
});
it('checking with custom label format', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_AxisLabel_1');
expect(element.textContent.indexOf('K') > -1).toBe(true);
done();
};
range.labelFormat = '{value}K';
range.refresh();
});
it('checking with area series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_Series_0');
expect(element.getAttribute('fill')).toBe('#00bdae');
expect(element.getAttribute('stroke-width')).toBe('2');
done();
};
range.series = [{ dataSource: data, xName: 'x', yName: 'y', type: 'Area' }];
range.refresh();
});
it('checking with line series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_Series_0');
expect(element.getAttribute('fill')).toBe('none');
expect(element.getAttribute('stroke-width')).toBe('1');
expect(element.getAttribute('stroke')).toBe('#00bdae');
done();
};
range.series[0].type = 'Line';
range.refresh();
});
it('checking with multiple series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_chart');
expect(element.childElementCount).toEqual(2);
done();
};
range.minimum = 10;
range.maximum = 50;
range.series = [{ dataSource: data, xName: 'x', yName: 'y' },
{ dataSource: data, xName: 'x', yName: 'y1' }];
range.refresh();
});
it('checking with combination series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_chart');
expect(element.childElementCount).toEqual(2);
element = document.getElementById('container_Series_0');
expect(element.getAttribute('fill')).toBe('none');
expect(element.getAttribute('stroke-width')).toBe('1');
expect(element.getAttribute('stroke')).toBe('#00bdae');
element = document.getElementById('container_Series_1');
expect(element.getAttribute('fill')).toBe('#404041');
done();
};
range.series = [{ dataSource: data, xName: 'x', yName: 'y' },
{ dataSource: data, xName: 'x', yName: 'y1', type: 'Area' }];
range.refresh();
});
it('checking with fabric theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('transparent');
done();
};
range.theme = 'Fabric';
range.refresh();
});
it('checking with bootstrap theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('transparent');
done();
};
range.theme = 'Bootstrap';
range.refresh();
});
it('checking with highcontrast theme', (done: Function) => {
range.loaded = (args: Object) => {
let selectedElement: Element = document.getElementById('container_SelectedArea');
expect(selectedElement.getAttribute('fill')).toEqual('transparent');
done();
};
range.theme = 'HighContrastLight';
range.refresh();
});
it('checking with area series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_Series_0');
expect(element.getAttribute('fill')).toBe('#00bdae');
expect(element.getAttribute('stroke-width')).toBe('2');
done();
};
range.theme = 'Material';
range.series[0].type = 'Area';
range.refresh();
});
it('checking with line series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_Series_0');
expect(element.getAttribute('fill')).toBe('none');
expect(element.getAttribute('stroke-width')).toBe('1');
expect(element.getAttribute('stroke')).toBe('#00bdae');
done();
};
range.series[0].type = 'Line';
range.refresh();
});
it('checking with multiple series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_chart');
expect(element.childElementCount).toEqual(2);
done();
};
range.minimum = 10;
range.maximum = 50;
range.series = [{ dataSource: data, xName: 'x', yName: 'y' },
{ dataSource: data, xName: 'x', yName: 'y1' }];
range.refresh();
});
it('checking with combination series', (done: Function) => {
range.loaded = (args: Object): void => {
element = document.getElementById('container_chart');
expect(element.childElementCount).toEqual(2);
element = document.getElementById('container_Series_0');
expect(element.getAttribute('fill')).toBe('none');
expect(element.getAttribute('stroke-width')).toBe('1');
expect(element.getAttribute('stroke')).toBe('#00bdae');
element = document.getElementById('container_Series_1');
expect(element.getAttribute('fill')).toBe('#404041');
done();
};
range.value = [20, 50];
range.series = [{ dataSource: data, xName: 'x', yName: 'y' },
{ dataSource: data, xName: 'x', yName: 'y1', type: 'Area' }];
range.refresh();
});
it('checking with remote date lightweight', () => {
range.loaded = (args: object): void => {
element = document.getElementById('container_chart');
// expect(element.childElementCount).toEqual(0);
// done();
};
range.dataSource = dataManager;
range.xName = 'Id';
range.yName = 'Estimate';
range.query = query
range.series = [];
range.refresh();
});
it('checking with remote date lightweight', () => {
range.loaded = (args: object): void => {
element = document.getElementById('container_chart');
// expect(element.childElementCount).toEqual(1);
// done();
};
range.series = [{
dataSource: dataManager, xName: 'Id', yName: 'Estimate',
query: query
}];
range.getPersistData();
range.refresh();
});
it('checking with margin', () => {
range.loaded = (args: Object): void => {
let container: Element = document.getElementById('containerSeriesGroup0');
// expect(
// container.getAttribute('transform') === 'translate(21.5,10)' ||
// container.getAttribute('transform') === 'translate(21,10)'
// ).toBe(true);
// done();
};
range.margin = { top: 10, left: 10, right: 10, bottom: 10 };
range.refresh();
});
it('checking materialdark', () => {
range.loaded = (args: Object): void => {
let container: Element = document.getElementById('containerSeriesGroup0');
// expect(
// container.getAttribute('transform') === 'translate(21.5,10)' ||
// container.getAttribute('transform') === 'translate(21,10)'
// ).toBe(true);
// done();
};
range.theme = 'MaterialDark';
range.refresh();
});
it('checking fabricdark', () => {
range.loaded = (args: Object): void => {
let container: Element = document.getElementById('containerSeriesGroup0');
// expect(
// container.getAttribute('transform') === 'translate(21.5,10)' ||
// container.getAttribute('transform') === 'translate(21,10)'
// ).toBe(true);
// done();
};
range.theme = 'FabricDark';
range.refresh();
});
it('checking Bootstrapdark', () => {
range.loaded = (args: Object): void => {
let container: Element = document.getElementById('containerSeriesGroup0');
// expect(
// container.getAttribute('transform') === 'translate(21.5,10)' ||
// container.getAttribute('transform') === 'translate(21,10)'
// ).toBe(true);
// done();
};
range.theme = 'BootstrapDark';
range.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
import { describe, it, expect, run } from 'https://deno.land/x/tincan@0.2.2/mod.ts'
import { App } from '../../app.ts'
import { BindToSuperDeno, InitAppAndTest } from '../util.ts'
import { renderFile as eta } from 'https://deno.land/x/eta@v1.12.3/mod.ts'
import { EtaConfig } from 'https://deno.land/x/eta@v1.12.3/config.ts'
import * as path from 'https://deno.land/std@0.106.0/path/mod.ts'
import { readFile as readFileCb } from 'https://deno.land/std@0.106.0/node/fs.ts'
import { promisify } from 'https://deno.land/std@0.106.0/node/util.ts'
const readFile = promisify(readFileCb)
describe('App constructor', () => {
it('app.locals are get and set', () => {
const app = new App()
app.locals.hello = 'world'
expect(app.locals.hello).toBe('world')
})
it('Custom noMatchHandler works', async () => {
const { fetch } = InitAppAndTest(
(_req, _res, next) => {
next()
},
undefined,
{
noMatchHandler: (req) => {
req.respond({
status: 404,
body: `Oopsie! Page ${req.url} is lost.`
})
}
}
)
await fetch.get('/').expect(404, 'Oopsie! Page / is lost.')
})
it('Custom onError works', async () => {
const app = new App({
onError: (err, req) => {
req.respond({
status: 500,
body: `Ouch, ${err} hurt me on ${req.url} page.`
})
}
})
app.use((_req, _res, next) => next('you'))
const fetch = BindToSuperDeno(app)
await fetch.get('/').expect(500, 'Ouch, you hurt me on / page.')
})
})
describe('Template engines', () => {
it('Works with eta out of the box', async () => {
const app = new App<EtaConfig>({
onError: (err) => console.log(err)
})
const pwd = Deno.cwd()
Deno.chdir(path.resolve(pwd, 'tests/fixtures'))
app.engine('eta', eta)
app.use((_, res) => {
res.render('index.eta', {
name: 'Eta'
})
Deno.chdir(pwd)
})
const fetch = BindToSuperDeno(app)
await fetch.get('/').expect(200, 'Hello from Eta')
})
it('can render without data passed', async () => {
const pwd = Deno.cwd()
Deno.chdir(path.resolve(pwd, 'tests/fixtures'))
const app = new App<EtaConfig>()
app.engine('eta', eta)
app.use((_, res) => {
res.render('empty.eta')
Deno.chdir(pwd)
})
const request = BindToSuperDeno(app)
await request.get('/').expect('Hello World')
})
})
describe('Routing', () => {
it('should respond on matched route', async () => {
const { fetch } = InitAppAndTest((_req, res) => void res.send('Hello world'), '/route')
await fetch.get('/route').expect(200, 'Hello world')
})
it('should match wares containing base path', async () => {
const app = new App()
app.use('/abc', (_req, res) => void res.send('Hello world'))
const fetch = BindToSuperDeno(app)
await fetch.get('/abc/def').expect(200, 'Hello world')
})
it('"*" should catch all undefined routes', async () => {
const app = new App()
app
.get('/route', (_req, res) => void res.send('A different route'))
.all('*', (_req, res) => void res.send('Hello world'))
const fetch = BindToSuperDeno(app)
await fetch.get('/test').expect(200, 'Hello world')
})
it('should throw 404 on no routes', async () => {
await BindToSuperDeno(new App()).get('/').expect(404)
})
})
describe('app.route(path)', () => {
it('app.route works properly', async () => {
const app = new App()
app.route('/').get((req, res) => res.end(req.url))
await BindToSuperDeno(app).get('/').expect(200)
})
it('app.route supports chaining route methods', async () => {
const app = new App()
app.route('/').get((req, res) => res.end(req.url))
await BindToSuperDeno(app).get('/').expect(200)
})
it('app.route supports chaining route methods', async () => {
const app = new App()
app
.route('/')
.get((_, res) => res.send('GET request'))
.post((_, res) => res.send('POST request'))
await BindToSuperDeno(app).post('/').expect(200, 'POST request')
})
})
describe('app.use(args)', () => {
it('should chain middleware', () => {
const app = new App()
app.use((_req, _res, next) => next()).use((_req, _res, next) => next())
expect(app.middleware.length).toBe(2)
})
it('req and res inherit properties from previous middlewares', async () => {
const app = new App()
app
.use((_req, res, next) => {
res.locals.hello = 'world'
next()
})
.get('/', (_, res) => {
res.send(res.locals)
})
const fetch = BindToSuperDeno(app)
await fetch.get('/').expect(200, '{\n "hello": "world"\n}')
})
it('should flatten the array of wares', async () => {
const app = new App()
let counter = 1
app.use('/abc', [(_1, _2, next) => counter++ && next(), (_1, _2, next) => counter++ && next()], (_req, res) => {
expect(counter).toBe(3)
res.send('Hello World')
})
const fetch = BindToSuperDeno(app)
await fetch.get('/abc').expect(200, 'Hello World')
})
})
describe('next(err?)', () => {
it('next function skips current middleware', async () => {
const app = new App()
app.locals['log'] = 'test'
app
.use((req, _res, next) => {
app.locals['log'] = req.url
next()
})
.use((_req, res) => void res.json({ ...app.locals }))
await BindToSuperDeno(app).get('/').expect(200, '{\n "log": "/"\n}')
})
it('next function handles errors', async () => {
const app = new App()
app.use((req, res, next) => {
if (req.url === '/broken') {
next('Your appearance destroyed this world.')
} else {
res.send('Welcome back')
}
})
await BindToSuperDeno(app).get('/broken').expect(500, 'Your appearance destroyed this world.')
})
it("next function sends error message if it's not an HTTP status code or string", async () => {
const app = new App()
app.use((req, res, next) => {
if (req.url === '/broken') {
next(new Error('Your appearance destroyed this world.'))
} else {
res.send('Welcome back')
}
})
await BindToSuperDeno(app).get('/broken').expect(500, 'Your appearance destroyed this world.')
})
it('errors in async wares do not destroy the app', async () => {
const app = new App()
app.use(async (_req, _res) => {
throw await `bruh`
})
await BindToSuperDeno(app).get('/').expect(500, 'bruh')
})
it('errors in sync wares do not destroy the app', async () => {
const app = new App()
app.use((_req, _res) => {
throw `bruh`
})
await BindToSuperDeno(app).get('/').expect(500, 'bruh')
})
})
describe('HTTP methods', () => {
it('app.get handles get request', async () => {
const app = new App()
app.get('/', (req, res) => void res.send(req.method))
await BindToSuperDeno(app).get('/').expect(200, 'GET')
})
it('app.post handles post request', async () => {
const { fetch } = InitAppAndTest((req, res) => void res.send(req.method), '/', {}, 'post')
await fetch.post('/').expect(200, 'POST')
})
it('app.put handles put request', async () => {
const { fetch } = InitAppAndTest((req, res) => void res.send(req.method), '/', {}, 'put')
await fetch.put('/').expect(200, 'PUT')
})
it('app.patch handles patch request', async () => {
const { fetch } = InitAppAndTest((req, res) => void res.send(req.method), '/', {}, 'patch')
await fetch.patch('/').expect(200, 'PATCH')
})
it('app.head handles head request', async () => {
const app = new App()
app.head('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.head('/').expect(200)
})
it('app.delete handles delete request', async () => {
const app = new App()
app.delete('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.delete('/').expect(200, 'DELETE')
})
it('app.checkout handles checkout request', async () => {
const app = new App()
app.checkout('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.checkout('/').expect(200, 'CHECKOUT')
})
it('app.copy handles copy request', async () => {
const app = new App()
app.copy('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.copy('/').expect(200, 'COPY')
})
it('app.lock handles lock request', async () => {
const app = new App()
app.lock('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.lock('/').expect(200, 'LOCK')
})
it('app.merge handles merge request', async () => {
const app = new App()
app.merge('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.merge('/').expect(200, 'MERGE')
})
it('app.mkactivity handles mkactivity request', async () => {
const app = new App()
app.mkactivity('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.mkactivity('/').expect(200, 'MKACTIVITY')
})
it('app.mkcol handles mkcol request', async () => {
const app = new App()
app.mkcol('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.mkcol('/').expect(200, 'MKCOL')
})
it('app.move handles move request', async () => {
const app = new App()
app.move('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.move('/').expect(200, 'MOVE')
})
it('app.search handles search request', async () => {
const app = new App()
app.search('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.search('/').expect(200, 'SEARCH')
})
it('app.notify handles notify request', async () => {
const app = new App()
app.notify('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.notify('/').expect(200, 'NOTIFY')
})
it('app.purge handles purge request', async () => {
const app = new App()
app.purge('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.purge('/').expect(200, 'PURGE')
})
it('app.report handles report request', async () => {
const app = new App()
app.report('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.report('/').expect(200, 'REPORT')
})
it('app.subscribe handles subscribe request', async () => {
const app = new App()
app.subscribe('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.subscribe('/').expect(200, 'SUBSCRIBE')
})
it('app.unsubscribe handles unsubscribe request', async () => {
const app = new App()
app.unsubscribe('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.unsubscribe('/').expect(200, 'UNSUBSCRIBE')
})
/* it('app.trace handles trace request', async () => {
const app = new App()
app.trace('/', (req, res) => void res.send(req.method))
const fetch = BindToSuperDeno(app)
await fetch.trace('/').expect(200, 'TRACE')
})
*/ it('HEAD request works when any of the method handlers are defined', async () => {
const app = new App()
app.get('/', (_, res) => res.send('It works'))
const fetch = BindToSuperDeno(app)
await fetch.head('/').expect(200)
})
it('HEAD request does not work for undefined handlers', async () => {
const app = new App()
app.get('/', (_, res) => res.send('It works'))
const fetch = BindToSuperDeno(app)
await fetch.head('/hello').expect(404)
})
})
describe('Route handlers', () => {
it('router accepts array of middlewares', async () => {
const app = new App()
app.use('/', [
(req, _, n) => {
// @ts-ignore
req.parsedBody = 'hello'
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += ' '
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += 'world'
n()
},
(req, res) => {
res.send(req.parsedBody)
}
])
const request = BindToSuperDeno(app)
await request.get('/').expect(200, 'hello world')
})
it('router accepts path as array of middlewares', async () => {
const app = new App()
app.use([
(req, _, n) => {
// @ts-ignore
req.parsedBody = 'hello'
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += ' '
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += 'world'
n()
},
(req, res) => {
res.send(req.parsedBody)
}
])
const request = BindToSuperDeno(app)
await request.get('/').expect(200, 'hello world')
})
it('router accepts list of middlewares', async () => {
const app = new App()
app.use(
(req, _, n) => {
// @ts-ignore
req.parsedBody = 'hello'
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += ' '
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += 'world'
n()
},
(req, res) => {
res.send(req.parsedBody)
}
)
const request = BindToSuperDeno(app)
await request.get('/').expect(200, 'hello world')
})
it('router accepts array of wares', async () => {
const app = new App()
app.get('/', [
(req, _, n) => {
// @ts-ignore
req.parsedBody = 'hello'
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += ' '
n()
},
(req, _, n) => {
// @ts-ignore
req.parsedBody += 'world'
n()
},
(req, res) => {
res.send(req.parsedBody)
}
])
const request = BindToSuperDeno(app)
await request.get('/').expect(200, 'hello world')
})
it('router methods do not match loosely', async () => {
const app = new App()
app.get('/route', (_, res) => res.send('found'))
const request = BindToSuperDeno(app)
await request.get('/route/subroute').expect(404)
})
it('req and res inherit properties from previous middlewares', async () => {
const app = new App()
app
.use((req, _res, next) => {
req.parsedBody = { hello: 'world' }
next()
})
.use((req, res) => {
res.json(req.parsedBody)
})
const request = BindToSuperDeno(app)
await request.get('/').expect(200, { hello: 'world' })
})
it('req and res inherit properties from previous middlewares asynchronously', async () => {
const app = new App()
const dec = new TextDecoder()
app
.use(async (req, _res, next) => {
const file = await readFile(`${Deno.cwd()}/tests/fixtures/test.txt`)
// @ts-ignore
req.parsedBody = dec.decode(file)
next()
})
.use((req, res) => {
res.send(req.parsedBody)
})
const request = BindToSuperDeno(app)
await request.get('/').expect(200, 'Hello World')
})
})
describe('Subapps', () => {
it('sub-app mounts on a specific path', () => {
const app = new App()
const subApp = new App()
app.use('/subapp', subApp)
expect(subApp.mountpath).toBe('/subapp')
})
it('sub-app mounts on root', async () => {
const app = new App()
const subApp = new App()
subApp.use((_, res) => void res.send('Hello World!'))
app.use(subApp)
const request = BindToSuperDeno(app)
await request.get('/').expect(200, 'Hello World!')
})
it('sub-app handles its own path', async () => {
const app = new App()
const subApp = new App()
subApp.use((_, res) => void res.send('Hello World!'))
app.use('/subapp', subApp)
const request = BindToSuperDeno(app)
await request.get('/subapp').expect(200, 'Hello World!')
})
it('sub-app paths get prefixed with the mount path', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (_, res) => res.send(`Hello from ${subApp.mountpath}`))
app.use('/subapp', subApp)
const request = BindToSuperDeno(app)
await request.get('/subapp/route').expect(200, 'Hello from /subapp')
})
/* it('req.originalUrl does not change', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (req, res) =>
res.send({
origUrl: req.originalUrl,
url: req.url,
path: req.path
})
)
app.use('/subapp', subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/subapp/route').expect(200, {
origUrl: '/subapp/route',
url: '/route',
path: '/route'
})
}) */
it('lets other wares handle the URL if subapp doesnt have that path', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (_, res) => res.send(subApp.mountpath))
app.use('/test', subApp)
app.use('/test3', (req, res) => res.send(req.url))
const request = BindToSuperDeno(app)
await request.get('/test/route').expect(200, '/test')
})
it('should mount app on a specified path', () => {
const app = new App()
const subapp = new App()
app.use('/subapp', subapp)
expect(subapp.mountpath).toBe('/subapp')
})
it('should mount on "/" if path is not specified', () => {
const app = new App()
const subapp = new App()
app.use(subapp)
expect(subapp.mountpath).toBe('/')
})
it('app.parent should reference to the app it was mounted on', () => {
const app = new App()
const subapp = new App()
app.use(subapp)
expect(subapp.parent).toBe(app)
})
it('app.path() should return the mountpath', () => {
const app = new App()
const subapp = new App()
app.use('/subapp', subapp)
expect(subapp.path()).toBe('/subapp')
})
it('app.path() should nest mountpaths', () => {
const app = new App()
const subapp = new App()
const subsubapp = new App()
subapp.use('/admin', subsubapp)
app.use('/blog', subapp)
expect(subsubapp.path()).toBe('/blog/admin')
})
it('middlewares of a subapp should preserve the path', () => {
const app = new App()
const subapp = new App()
subapp.use('/path', (_req, _res) => void 0)
app.use('/subapp', subapp)
expect(subapp.middleware[0].path).toBe('/path')
})
it('matches when mounted on params', async () => {
const app = new App()
const subApp = new App()
subApp.get('/', (_, res) => res.send('hit'))
app.use('/users/:userID', subApp)
const request = BindToSuperDeno(app)
await request.get('/users/123/').expect(200, 'hit')
})
it('matches when mounted on params and on custom subapp route', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (_, res) => res.send('hit'))
app.use('/users/:userID', subApp)
const request = BindToSuperDeno(app)
await request.get('/users/123/route').expect(200, 'hit')
})
})
describe('App settings', () => {
describe('xPoweredBy', () => {
it('is enabled by default', () => {
const app = new App()
expect(app.settings.xPoweredBy).toBe(true)
})
it('should set X-Powered-By to "tinyhttp"', async () => {
const { fetch } = InitAppAndTest((_req, res) => void res.send('hi'))
await fetch.get('/').expect('X-Powered-By', 'tinyhttp')
})
/* it('when disabled should not send anything', async () => {
const app = new App({ settings: { xPoweredBy: false } })
app.use((_req, res) => void res.send('hi'))
const request = BindToSuperDeno(app)
await request.get('/').expect('X-Powered-By', null)
}) */
})
describe('bindAppToReqRes', () => {
it('references the current app instance in req.app and res.app', async () => {
const app = new App({
settings: {
bindAppToReqRes: true
}
})
app.locals['hello'] = 'world'
app.use((req, res) => {
expect(req.app).toBeInstanceOf(App)
expect(res.app).toBeInstanceOf(App)
expect(req.app.locals['hello']).toBe('world')
expect(res.app.locals['hello']).toBe('world')
res.end()
})
const request = BindToSuperDeno(app)
await request.get('/').expect(200)
})
})
describe('enableReqRoute', () => {
it('attach current fn to req.route when enabled', async () => {
const app = new App({ settings: { enableReqRoute: true } })
app.use((req, res) => {
expect(req.route).toEqual(app.middleware[0])
res.end()
})
const request = BindToSuperDeno(app)
await request.get('/').expect(200)
})
})
})
run() | the_stack |
declare const BrowserAPI: BrowserAPI;
interface Window {
MutationObserver: typeof MutationObserver;
WebkitMutationObserver: typeof MutationObserver;
Image: any;
}
function getMeta(name: string) {
const e = document.querySelector(`link[rel="${name}"]`);
return e ? e.getAttribute('href') : null;
}
(() => {
window.dispatchEvent(new CustomEvent(browserAPI.runtime.id + '-install'));
document.addEventListener('stylishInstallChrome', onClick);
document.addEventListener('stylishUpdateChrome', onClick);
onDOMready().then(() => {
window.postMessage({
direction: 'from-content-script',
message: 'StylishInstalled',
}, '*');
});
let gotBody = false;
const mutationObserver = (window.MutationObserver || window.WebkitMutationObserver);
new mutationObserver(observeDOM).observe(document.documentElement, {
childList: true,
subtree: true,
});
observeDOM();
let lastEvent: {
type: string;
detail?: any;
};
function observeDOM() {
if (!gotBody) {
if (!document.body) return;
gotBody = true;
document.title = document.title.replace(/^(\d+)&\w+=/, '#$1: ');
const url = getMeta('stylish-id-url') || location.href;
browserAPI.runtime.sendMessage({
type: 'getStyles',
data: {
url
}
}).then(checkUpdatability);
}
if (document.getElementById('install_button')) {
onDOMready().then(() => {
requestAnimationFrame(() => {
sendEvent(lastEvent);
});
});
}
}
/* since we are using "stylish-code-chrome" meta key on all browsers and
US.o does not provide "advanced settings" on this url if browser is not Chrome,
we need to fix this URL using "stylish-update-url" meta key
*/
function getStyleURL() {
const textUrl = getMeta('stylish-update-url') || '';
const jsonUrl = getMeta('stylish-code-chrome') ||
textUrl.replace(/styles\/(\d+)\/[^?]*/, 'styles/chrome/$1.json');
const paramsMissing = jsonUrl.indexOf('?') === -1
&& textUrl.indexOf('?') !== -1;
return jsonUrl + (paramsMissing ? textUrl.replace(/^[^?]+/, '') : '');
}
function checkUpdatability([installedStyle]: {
node: CRM.StylesheetNode;
state: 'installed'|'updatable';
}[]) {
const updateURL = installedStyle &&
installedStyle.node.nodeInfo.source !== 'local' &&
installedStyle.node.nodeInfo.source.updateURL;
document.dispatchEvent(new CustomEvent('stylusFixBuggyUSOsettings', {
detail: updateURL
}));
if (!installedStyle) {
sendEvent({type: 'styleCanBeInstalledChrome'});
return;
}
sendEvent({
type: installedStyle.state === 'updatable' ?
'styleCanBeUpdatedChrome' : 'styleAlreadyInstalledChrome',
detail: {
updateUrl: updateURL
},
});
}
function sendEvent(event: {
type: string;
detail?: any;
}) {
lastEvent = event;
let {type, detail = null} = event;
detail = {detail};
onDOMready().then(() => {
document.dispatchEvent(new CustomEvent(type, detail));
});
}
let processing: boolean;
function onClick(event: MouseEvent & {
type: string;
}) {
if (processing) {
return;
}
processing = true;
(event.type.indexOf('Update') !== -1 ? onUpdate() : onInstall()).then(done, done);
function done() {
setTimeout(() => {
processing = false;
});
}
}
async function onInstall() {
await saveStyleCode('styleInstall')
return await getResource(getMeta('stylish-install-ping-url-chrome'));
}
function onUpdate() {
return new Promise((resolve, reject) => {
const url = getMeta('stylish-id-url') || location.href;
browserAPI.runtime.sendMessage({
type: 'getStyles',
data: {
url
}
}).then(([style]: {
node: CRM.StylesheetNode;
state: 'installed'|'updatable';
}[]) => {
saveStyleCode('styleUpdate', {
id: style.node.id
}).then(() => {
resolve(null);
}, (err) => {
reject(err);
});
});
});
}
async function saveStyleCode(message: string, addProps: {
id?: CRM.NodeId<CRM.StylesheetNode>;
} = {}) {
const isNew = message === 'styleInstall'
enableUpdateButton(false);
if (isNew) {
await browserAPI.runtime.sendMessage({
type: 'styleInstall',
data: {
downloadURL: location.href,
type: 'userstyles.org',
code: await getResource(getStyleURL()),
author: document.querySelector('#style_author a') ?
document.querySelector('#style_author a').innerText : 'anonymous'
}
});
sendEvent({
type: 'styleInstalledChrome',
detail: {}
});
} else {
await browserAPI.runtime.sendMessage({
type: 'updateStylesheet',
data: {
nodeId: addProps.id
}
});
}
function enableUpdateButton(state: boolean) {
const important = (s: string) => s.replace(/;/g, '!important;');
const button = document.getElementById('update_style_button');
if (button) {
button.style.cssText = state ? '' : important('pointer-events: none; opacity: .35;');
const icon = button.querySelector('img[src*=".svg"]');
if (icon) {
icon.style.cssText = state ? '' : important('transition: transform 5s; transform: rotate(0);');
if (state) {
setTimeout(() => (icon.style.cssText += important('transform: rotate(10turn);')));
}
}
}
}
}
function onDOMready() {
if (document.readyState !== 'loading') {
return Promise.resolve();
}
return new Promise(resolve => {
document.addEventListener('DOMContentLoaded', function _() {
document.removeEventListener('DOMContentLoaded', _);
resolve(null);
});
});
}
function getResource(url: string): Promise<string> {
return new Promise((resolve) => {
if (!url) {
resolve(null);
return;
}
if (url.indexOf("#") == 0) {
resolve(document.getElementById(url.substring(1)).innerText);
return;
}
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status >= 400) {
resolve(null);
} else {
resolve(xhr.responseText);
}
}
};
if (url.length > 2000) {
const parts = url.split("?");
xhr.open("POST", parts[0], true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(parts[1]);
} else {
xhr.open("GET", url, true);
xhr.send();
}
});
}
})();
// run in page context
document.documentElement.appendChild(document.createElement('script')).text = `(${
(EXTENSION_ORIGIN: string, isChrome: boolean) => {
document.currentScript.remove();
// spoof Stylish extension presence in Chrome
if (isChrome) {
const originalImg = window.Image;
class FakeImage {
constructor(width: number, height: number) {
const img = new originalImg(width, height);
let loaded: {
[url: string]: boolean;
} = {};
window.setInterval(() => {
if (img.src && !loaded[img.src] && /^chrome-extension:/i.test(img.src)) {
loaded[img.src] = true;
setTimeout(() => typeof img.onload === 'function' && img.onload());
}
}, 125);
return img;
}
}
window.Image = FakeImage;
}
// spoof USO referrer for style search in the popup
if (window !== top && location.pathname === '/') {
window.addEventListener('message', ({data, origin}) => {
if (!data || !data.xhr || origin !== EXTENSION_ORIGIN) {
return;
}
const xhr = new XMLHttpRequest();
xhr.onloadend = xhr.onerror = () => {
window.stop();
top.postMessage({
id: data.xhr.id,
status: xhr.status,
// [being overcautious] a string response is used instead of relying on responseType=json
// because it was invoked in a web page context so another extension may have incorrectly spoofed it
response: xhr.response,
}, EXTENSION_ORIGIN);
};
xhr.open('GET', data.xhr.url);
xhr.send();
});
}
// USO bug workaround: use the actual style settings in API response
let settings: any;
const originalResponseJson = Response.prototype.json;
document.addEventListener('stylusFixBuggyUSOsettings', function _({detail}: {detail: string}) {
document.removeEventListener('stylusFixBuggyUSOsettings', _ as any);
if (isChrome &&
parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) >= 52) {
settings = /\?/.test(detail) &&
new URLSearchParams(new URL(detail).search);
} else {
settings = /\?/.test(detail) &&
new URLSearchParams(new URL(detail).search.replace(/^\?/, ''));
}
if (!settings) {
Response.prototype.json = originalResponseJson;
}
} as any);
Response.prototype.json = function (...args: any[]) {
return originalResponseJson.call(this, ...args).then((json: {
style_settings?: any;
}) => {
if (!settings || typeof ((json || {}).style_settings || {}).every !== 'function') {
return json;
}
Response.prototype.json = originalResponseJson;
const images: [any, any][] = [];
for (const jsonSetting of json.style_settings) {
let value = settings.get('ik-' + jsonSetting.install_key);
if (!value
|| !jsonSetting.style_setting_options
|| !jsonSetting.style_setting_options[0]) {
continue;
}
if (value.startsWith('ik-')) {
value = value.replace(/^ik-/, '');
let item = null;
for (let i = 0; i < jsonSetting.style_setting_options.length; i++) {
if (jsonSetting.style_setting_options[i].default) {
item = jsonSetting.style_setting_options[i];
break;
}
}
const defaultItem = item;
if (!defaultItem || defaultItem.install_key !== value) {
if (defaultItem) {
defaultItem.default = false;
}
jsonSetting.style_setting_options.filter((item: any) => {
if (item.install_key === value) {
item.default = true;
return true;
}
return false;
}).length > 0;
}
} else if (jsonSetting.setting_type === 'image') {
jsonSetting.style_setting_options.some((item: any) => {
if (item.default) {
item.default = false;
return true;
}
return false;
}).length > 0;
images.push([jsonSetting.install_key, value]);
} else {
const item = jsonSetting.style_setting_options[0];
if (item.value !== value && item.install_key === 'placeholder') {
item.value = value;
}
}
}
if (images.length) {
new MutationObserver((_, observer) => {
if (!document.getElementById('style-settings')) {
return;
}
observer.disconnect();
for (const [name, url] of images) {
const elRadio = document.querySelector(`input[name="ik-${name}"][value="user-url"]`);
const elUrl = elRadio && document.getElementById(elRadio.id.replace('url-choice', 'user-url')) as
HTMLInputElement;
if (elUrl) {
elUrl.value = url;
}
}
}).observe(document, {childList: true, subtree: true});
}
return json;
});
};
}
})('${browserAPI.runtime.getURL('').slice(0, -1)}', ${BrowserAPI.getBrowser() === 'chrome'})`;
if (location.search.indexOf('category=') !== -1) {
document.addEventListener('DOMContentLoaded', function _() {
document.removeEventListener('DOMContentLoaded', _);
new MutationObserver((_, observer) => {
if (!document.getElementById('pagination')) {
return;
}
observer.disconnect();
const category = '&' + location.search.match(/category=[^&]+/)[0];
const links = document.querySelectorAll('#pagination a[href*="page="]:not([href*="category="])') as
any as HTMLAnchorElement[];
for (let i = 0; i < links.length; i++) {
links[i].href += category;
}
}).observe(document, {childList: true, subtree: true});
});
} | the_stack |
import {
registerCommand,
DefaultCommands,
CommandConditions,
openUrlInTarget
} from "./registry/command";
import {
IMapViewer,
ActiveMapTool,
RefreshMode,
ReduxDispatch,
getInitialView,
getRuntimeMap,
getCurrentView,
ITargetedCommand,
IConfigurationReducerState,
DEFAULT_MODAL_SIZE
} from "./common";
import { tr } from "../api/i18n";
import { DefaultComponentNames } from "../api/registry/component";
import {
SPRITE_SELECT,
SPRITE_PAN,
SPRITE_ZOOM_IN,
SPRITE_ZOOM_IN_FIXED,
SPRITE_ZOOM_OUT_FIXED,
SPRITE_PAN_WEST,
SPRITE_PAN_EAST,
SPRITE_PAN_NORTH,
SPRITE_PAN_SOUTH,
SPRITE_ABOUT,
SPRITE_HELP,
SPRITE_MEASURE,
SPRITE_INITIAL_CENTER,
SPRITE_ZOOM_FULL,
SPRITE_VIEW_BACK,
SPRITE_ICON_REFRESHMAP,
SPRITE_VIEW_FORWARD,
SPRITE_GEOLOCATION,
SPRITE_INVOKE_SCRIPT,
SPRITE_COORDINATE_TRACKER,
SPRITE_LAYER_ADD,
SPRITE_PRINT
} from "../constants/assets";
import { setCurrentView, setActiveTool, previousView, nextView } from '../actions/map';
import { showModalComponent, showModalUrl } from '../actions/modal';
import { refresh } from '../actions/legend';
import { setTaskPaneVisibility, setLegendVisibility, setSelectionPanelVisibility } from '../actions/template';
import React from "react";
import ReactDOM from "react-dom";
function panMap(dispatch: ReduxDispatch, viewer: IMapViewer, value: "right" | "left" | "up" | "down") {
const settings: any = {
"right": [2, 1],
"left": [0, 1],
"down": [0, 1],
"up": [0, 3]
};
const view = viewer.getCurrentView();
const current_center = [view.x, view.y];
const currentExtent = viewer.getCurrentExtent();
let newPos: number[];
const direction = settings[value];
if (value == "right" || value == "left") {
newPos = [
currentExtent[direction[0]],
current_center[direction[1]]
];
} else {
newPos = [
current_center[direction[0]],
currentExtent[direction[1]]
];
}
dispatch(setCurrentView({ x: newPos[0], y: newPos[1], scale: view.scale }));
}
export function buildTargetedCommand(config: Readonly<IConfigurationReducerState>, parameters: any): ITargetedCommand {
const cmdTarget = (parameters || {}).Target;
const cmdDef: ITargetedCommand = {
target: cmdTarget || "NewWindow"
};
if (config.capabilities.hasTaskPane && cmdTarget == "TaskPane") {
cmdDef.target = "TaskPane";
}
if (cmdTarget == "SpecifiedFrame") {
cmdDef.target = cmdTarget;
cmdDef.targetFrame = (parameters || {}).TargetFrame;
}
return cmdDef;
}
/**
* Registers the default set of commands into the command registry. This is automatically called by the default viewer
* bundle. If creating your own viewer bundle, be sure to call this function in your entry point, or individually register
* the commands you want to make available in your custom viewer bundle
*
* @export
*/
export function initDefaultCommands() {
//Select Tool
registerCommand(DefaultCommands.Select, {
iconClass: SPRITE_SELECT,
selected: (state) => {
return state.activeTool === ActiveMapTool.Select;
},
enabled: () => true,
invoke: (dispatch) => {
return dispatch(setActiveTool(ActiveMapTool.Select));
}
});
//Pan Tool
registerCommand(DefaultCommands.Pan, {
iconClass: SPRITE_PAN,
selected: (state) => {
return state.activeTool === ActiveMapTool.Pan;
},
enabled: () => true,
invoke: (dispatch) => {
return dispatch(setActiveTool(ActiveMapTool.Pan));
}
});
//Zoom Tool
registerCommand(DefaultCommands.Zoom, {
iconClass: SPRITE_ZOOM_IN,
selected: (state) => {
return state.activeTool === ActiveMapTool.Zoom;
},
enabled: () => true,
invoke: (dispatch) => {
return dispatch(setActiveTool(ActiveMapTool.Zoom));
}
});
//Zoom in
registerCommand(DefaultCommands.ZoomIn, {
iconClass: SPRITE_ZOOM_IN_FIXED,
selected: () => false,
enabled: () => true,
invoke: (_dispatch, _getState, viewer) => {
if (viewer) {
viewer.zoomDelta(1);
}
}
});
//Zoom Out
registerCommand(DefaultCommands.ZoomOut, {
iconClass: SPRITE_ZOOM_OUT_FIXED,
selected: () => false,
enabled: () => true,
invoke: (_dispatch, _getState, viewer) => {
if (viewer) {
viewer.zoomDelta(-1);
}
}
});
//Pan Left
registerCommand(DefaultCommands.PanLeft, {
iconClass: SPRITE_PAN_WEST,
selected: () => false,
enabled: () => true,
invoke: (dispatch, _getState, viewer) => {
if (viewer) {
panMap(dispatch, viewer, "left");
}
}
});
//Pan Right
registerCommand(DefaultCommands.PanRight, {
iconClass: SPRITE_PAN_EAST,
selected: () => false,
enabled: () => true,
invoke: (dispatch, _getState, viewer) => {
if (viewer) {
panMap(dispatch, viewer, "right");
}
}
});
//Pan Up
registerCommand(DefaultCommands.PanUp, {
iconClass: SPRITE_PAN_NORTH,
selected: () => false,
enabled: () => true,
invoke: (dispatch, _getState, viewer) => {
if (viewer) {
panMap(dispatch, viewer, "up");
}
}
});
//Pan Down
registerCommand(DefaultCommands.PanDown, {
iconClass: SPRITE_PAN_SOUTH,
selected: () => false,
enabled: () => true,
invoke: (dispatch, _getState, viewer) => {
if (viewer) {
panMap(dispatch, viewer, "down");
}
}
});
//About
registerCommand(DefaultCommands.About, {
iconClass: SPRITE_ABOUT,
selected: () => false,
enabled: () => true,
invoke: (dispatch, getState) => {
dispatch(showModalComponent({
modal: {
title: tr("ABOUT", getState().config.locale),
backdrop: true,
size: DEFAULT_MODAL_SIZE
},
name: DefaultComponentNames.About,
component: DefaultComponentNames.About
}));
}
});
//Help
registerCommand(DefaultCommands.Help, {
iconClass: SPRITE_HELP,
selected: () => false,
enabled: () => true,
invoke: (dispatch, getState) => {
dispatch(showModalUrl({
modal: {
title: tr("HELP", getState().config.locale),
backdrop: true,
size: DEFAULT_MODAL_SIZE
},
name: DefaultCommands.Help,
url: "help/index.html"
}));
}
});
//Measure
registerCommand(DefaultCommands.Measure, {
iconClass: SPRITE_MEASURE,
selected: () => false,
enabled: () => true,
invoke: (dispatch, getState, _viewer, parameters) => {
const config = getState().config;
const url = "component://Measure";
const cmdDef = buildTargetedCommand(config, parameters);
openUrlInTarget(DefaultCommands.Measure, cmdDef, config.capabilities.hasTaskPane, dispatch, url, tr("MEASURE", config.locale));
}
});
//Initial Center and scale
registerCommand(DefaultCommands.RestoreView, {
iconClass: SPRITE_INITIAL_CENTER,
selected: () => false,
enabled: () => true,
invoke: (_dispatch, getState, viewer) => {
if (viewer) {
const view = getInitialView(getState());
if (view != null) {
viewer.zoomToView(view.x, view.y, view.scale);
} else {
viewer.initialView();
}
}
}
})
//Zoom Extents
registerCommand(DefaultCommands.ZoomExtents, {
iconClass: SPRITE_ZOOM_FULL,
selected: () => false,
enabled: () => true,
invoke: (_dispatch, _getState, viewer) => {
if (viewer) {
viewer.initialView();
}
}
});
//Refresh Map
registerCommand(DefaultCommands.RefreshMap, {
iconClass: SPRITE_ICON_REFRESHMAP,
selected: () => false,
enabled: CommandConditions.isNotBusy,
invoke: (dispatch, _getState, viewer) => {
if (viewer) {
viewer.refreshMap(RefreshMode.LayersOnly | RefreshMode.SelectionOnly);
dispatch(refresh());
}
}
});
//Previous View
registerCommand(DefaultCommands.PreviousView, {
iconClass: SPRITE_VIEW_BACK,
selected: () => false,
enabled: CommandConditions.hasPreviousView,
invoke: (dispatch, getState) => {
const mapName = getState().config.activeMapName;
if (mapName) {
dispatch(previousView(mapName));
}
}
});
//Next View
registerCommand(DefaultCommands.NextView, {
iconClass: SPRITE_VIEW_FORWARD,
selected: () => false,
enabled: CommandConditions.hasNextView,
invoke: (dispatch, getState) => {
const mapName = getState().config.activeMapName;
if (mapName) {
dispatch(nextView(mapName));
}
}
});
//Geolocation
registerCommand(DefaultCommands.Geolocation, {
iconClass: SPRITE_GEOLOCATION,
selected: () => false,
enabled: CommandConditions.isNotBusy,
invoke: (_dispatch, getState, viewer, parameters) => {
const state = getState();
const view = getCurrentView(state);
const rtMap = getRuntimeMap(state);
const locale = state.config.locale;
if (viewer && view && rtMap) {
const fact = viewer.getOLFactory();
const geoOptions: Partial<PositionOptions> = {};
let zoomScale = view.scale;
if (parameters.ZoomLevel) {
zoomScale = parseInt(parameters.ZoomLevel, 10);
}
if (parameters.EnableHighAccuracy) {
geoOptions.enableHighAccuracy = (parameters.EnableHighAccuracy == "true");
}
if (parameters.Timeout) {
geoOptions.timeout = parseInt(parameters.Timeout, 10);
}
if (parameters.MaximumAge) {
geoOptions.maximumAge = parseInt(parameters.MaximumAge, 10);
}
navigator.geolocation.getCurrentPosition(pos => {
const proj = viewer.getProjection();
const txCoord = fact.transformCoordinateFromLonLat([pos.coords.longitude, pos.coords.latitude], proj);
const testCoord = fact.transformCoordinateFromLonLat([pos.coords.longitude, pos.coords.latitude], `EPSG:${rtMap.CoordinateSystem.EpsgCode}`);
viewer.zoomToView(txCoord[0], txCoord[1], zoomScale);
const extents: [number, number, number, number] = [
rtMap.Extents.LowerLeftCoordinate.X,
rtMap.Extents.LowerLeftCoordinate.Y,
rtMap.Extents.UpperRightCoordinate.X,
rtMap.Extents.UpperRightCoordinate.Y
];
if (fact.extentContainsXY(extents, testCoord[0], testCoord[1])) {
viewer.toastSuccess("geolocation", tr("GEOLOCATION_SUCCESS", locale));
//getTopToaster().show({ icon: "geolocation", message: tr("GEOLOCATION_SUCCESS", locale), intent: Intent.SUCCESS });
} else {
viewer.toastWarning("warning-sign", tr("GEOLOCATION_WARN_OUTSIDE_MAP", locale));
//getTopToaster().show({ icon: "warning-sign", message: tr("GEOLOCATION_WARN_OUTSIDE_MAP", locale), intent: Intent.WARNING });
}
}, err => {
viewer.toastError("error", tr("GEOLOCATION_ERROR", locale, { message: err.message, code: err.code }));
//getTopToaster().show({ icon: "error", message: tr("GEOLOCATION_ERROR", locale, { message: err.message, code: err.code }), intent: Intent.DANGER });
}, geoOptions);
}
}
});
//Coordinate Tracker
registerCommand(DefaultCommands.CoordinateTracker, {
iconClass: SPRITE_COORDINATE_TRACKER,
selected: () => false,
enabled: () => true,
invoke: (dispatch, getState, _viewer, parameters) => {
const config = getState().config;
const url = `component://CoordinateTracker?${(parameters.Projection || []).map((p: string) => "projections=" + p).join("&")}`;
const cmdDef = buildTargetedCommand(config, parameters);
openUrlInTarget(DefaultCommands.CoordinateTracker, cmdDef, config.capabilities.hasTaskPane, dispatch, url, tr("COORDTRACKER", config.locale));
}
});
//External Layer Manager
registerCommand(DefaultCommands.AddManageLayers, {
iconClass: SPRITE_LAYER_ADD,
selected: () => false,
enabled: () => true,
invoke: (dispatch, getState, _viewer, parameters) => {
const config = getState().config;
const url = `component://${DefaultComponentNames.AddManageLayers}`;
const cmdDef = buildTargetedCommand(config, parameters);
openUrlInTarget(DefaultCommands.AddManageLayers, cmdDef, config.capabilities.hasTaskPane, dispatch, url, tr("ADD_MANAGE_LAYERS", config.locale));
}
});
//Print
registerCommand(DefaultCommands.Print, {
iconClass: SPRITE_PRINT,
selected: () => false,
enabled: () => true,
invoke: (_dispatch, _getState, viewer, _parameters) => {
viewer?.exportImage({
callback: (image) => {
const el = React.createElement("img", { src: image });
const printWindow = window.open();
if (printWindow) {
// Open and immediately close the document. This works around a problem in Firefox that is
// captured here: https://bugzilla.mozilla.org/show_bug.cgi?id=667227.
// Essentially, when we first create an iframe, it has no document loaded and asynchronously
// starts a load of "about:blank". If we access the document object and start manipulating it
// before that async load completes, a new document will be automatically created. But then
// when the async load completes, the original, automatically-created document gets unloaded
// and the new "about:blank" gets swapped in. End result: everything we add to the DOM before
// the async load complete gets lost and Firefox ends up printing a blank page.
// Explicitly opening and then closing a new document _seems_ to avoid this.
printWindow.document.open();
printWindow.document.close();
printWindow.document.head.innerHTML = `
<meta charset="UTF-8">
<title>Print View</title>
`;
printWindow.document.body.innerHTML = '<div id="print"></div>';
ReactDOM.render(el, printWindow.document.getElementById("print"));
}
}
});
}
});
//Fusion template helper commands
/*
registerCommand("showOverview", {
icon: "images/icons/invoke-script",
selected: () => false,
enabled: CommandConditions.isNotBusy,
invoke: (dispatch, getState, viewer, parameters) => {
}
});
*/
registerCommand("showTaskPane", {
iconClass: SPRITE_INVOKE_SCRIPT,
selected: () => false,
enabled: CommandConditions.isNotBusy,
invoke: (dispatch, _getState) => {
dispatch(setTaskPaneVisibility(true));
}
});
registerCommand("showLegend", {
iconClass: SPRITE_INVOKE_SCRIPT,
selected: () => false,
enabled: CommandConditions.isNotBusy,
invoke: (dispatch, _getState) => {
dispatch(setLegendVisibility(true));
}
});
registerCommand("showSelectionPanel", {
iconClass: SPRITE_INVOKE_SCRIPT,
selected: () => false,
enabled: CommandConditions.isNotBusy,
invoke: (dispatch, _getState) => {
dispatch(setSelectionPanelVisibility(true));
}
});
} | the_stack |
import {
$BuiltinFunction,
$Function,
$OrdinaryCreateFromConstructor,
} from '../types/function.js';
import {
Realm,
ExecutionContext,
} from '../realm.js';
import {
$AnyNonEmpty,
$AnyNonEmptyNonError,
CompletionType,
} from '../types/_shared.js';
import {
$Undefined,
} from '../types/undefined.js';
import {
$Object,
} from '../types/object.js';
import {
$String,
} from '../types/string.js';
import {
$StringExoticObject,
} from '../exotics/string.js';
import {
$FunctionPrototype,
} from './function.js';
import {
$List
} from '../types/list.js';
// http://www.ecma-international.org/ecma-262/#sec-object-constructor
// #region 19.1.1 The Object Constructor
export class $ObjectConstructor extends $BuiltinFunction<'%Object%'> {
// http://www.ecma-international.org/ecma-262/#sec-object.prototype
// 19.1.2.19 Object.prototype
public get $prototype(): $ObjectPrototype {
return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $ObjectPrototype;
}
public set $prototype(value: $ObjectPrototype) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false);
}
// http://www.ecma-international.org/ecma-262/#sec-object.assign
// 19.1.2.1 Object.assign ( target , ... sources )
public get $assign(): $Object_assign {
return this.getProperty(this.realm['[[Intrinsics]]'].$assign)['[[Value]]'] as $Object_assign;
}
public set $assign(value: $Object_assign) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$assign, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.create
// 19.1.2.2 Object.create ( O , Properties )
public get $create(): $Object_create {
return this.getProperty(this.realm['[[Intrinsics]]'].$create)['[[Value]]'] as $Object_create;
}
public set $create(value: $Object_create) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$create, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.defineproperties
// 19.1.2.3 Object.defineProperties ( O , Properties )
public get $defineProperties(): $Object_defineProperties {
return this.getProperty(this.realm['[[Intrinsics]]'].$defineProperties)['[[Value]]'] as $Object_defineProperties;
}
public set $defineProperties(value: $Object_defineProperties) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$defineProperties, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.defineproperty
// 19.1.2.4 Object.defineProperty ( O , P , Attributes )
public get $defineProperty(): $Object_defineProperty {
return this.getProperty(this.realm['[[Intrinsics]]'].$defineProperty)['[[Value]]'] as $Object_defineProperty;
}
public set $defineProperty(value: $Object_defineProperty) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$defineProperty, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.entries
// 19.1.2.5 Object.entries ( O )
public get $entries(): $Object_entries {
return this.getProperty(this.realm['[[Intrinsics]]'].$entries)['[[Value]]'] as $Object_entries;
}
public set $entries(value: $Object_entries) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$entries, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.freeze
// 19.1.2.6 Object.freeze ( O )
public get $freeze(): $Object_freeze {
return this.getProperty(this.realm['[[Intrinsics]]'].$freeze)['[[Value]]'] as $Object_freeze;
}
public set $freeze(value: $Object_freeze) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$freeze, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.fromentries
// 19.1.2.7 Object.fromEntries ( iterable )
public get $fromEntries(): $Object_fromEntries {
return this.getProperty(this.realm['[[Intrinsics]]'].$fromEntries)['[[Value]]'] as $Object_fromEntries;
}
public set $fromEntries(value: $Object_fromEntries) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$fromEntries, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertydescriptor
// 19.1.2.8 Object.getOwnPropertyDescriptor ( O , P )
public get $getOwnPropertyDescriptor(): $Object_getOwnPropertyDescriptor {
return this.getProperty(this.realm['[[Intrinsics]]'].$getOwnPropertyDescriptor)['[[Value]]'] as $Object_getOwnPropertyDescriptor;
}
public set $getOwnPropertyDescriptor(value: $Object_getOwnPropertyDescriptor) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$getOwnPropertyDescriptor, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertydescriptors
// 19.1.2.9 Object.getOwnPropertyDescriptors ( O )
public get $getOwnPropertyDescriptors(): $Object_getOwnPropertyDescriptors {
return this.getProperty(this.realm['[[Intrinsics]]'].$getOwnPropertyDescriptors)['[[Value]]'] as $Object_getOwnPropertyDescriptors;
}
public set $getOwnPropertyDescriptors(value: $Object_getOwnPropertyDescriptors) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$getOwnPropertyDescriptors, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertynames
// 19.1.2.10 Object.getOwnPropertyNames ( O )
public get $getOwnPropertyNames(): $Object_getOwnPropertyNames {
return this.getProperty(this.realm['[[Intrinsics]]'].$getOwnPropertyNames)['[[Value]]'] as $Object_getOwnPropertyNames;
}
public set $getOwnPropertyNames(value: $Object_getOwnPropertyNames) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$getOwnPropertyNames, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertysymbols
// 19.1.2.11 Object.getOwnPropertySymbols ( O )
public get $getOwnPropertySymbols(): $Object_getOwnPropertySymbols {
return this.getProperty(this.realm['[[Intrinsics]]'].$getOwnPropertySymbols)['[[Value]]'] as $Object_getOwnPropertySymbols;
}
public set $getOwnPropertySymbols(value: $Object_getOwnPropertySymbols) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$getOwnPropertySymbols, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.getprototypeof
// 19.1.2.12 Object.getPrototypeOf ( O )
public get $getPrototypeOf(): $Object_getPrototypeOf {
return this.getProperty(this.realm['[[Intrinsics]]'].$getPrototypeOf)['[[Value]]'] as $Object_getPrototypeOf;
}
public set $getPrototypeOf(value: $Object_getPrototypeOf) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$getPrototypeOf, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.is
// 19.1.2.13 Object.is ( value1 , value2 )
public get $is(): $Object_is {
return this.getProperty(this.realm['[[Intrinsics]]'].$is)['[[Value]]'] as $Object_is;
}
public set $is(value: $Object_is) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$is, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.isextensible
// 19.1.2.14 Object.isExtensible ( O )
public get $isExtensible(): $Object_isExtensible {
return this.getProperty(this.realm['[[Intrinsics]]'].$isExtensible)['[[Value]]'] as $Object_isExtensible;
}
public set $isExtensible(value: $Object_isExtensible) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$isExtensible, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.isfrozen
// 19.1.2.15 Object.isFrozen ( O )
public get $isFrozen(): $Object_isFrozen {
return this.getProperty(this.realm['[[Intrinsics]]'].$isFrozen)['[[Value]]'] as $Object_isFrozen;
}
public set $isFrozen(value: $Object_isFrozen) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$isFrozen, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.issealed
// 19.1.2.16 Object.isSealed ( O )
public get $isSealed(): $Object_isSealed {
return this.getProperty(this.realm['[[Intrinsics]]'].$isSealed)['[[Value]]'] as $Object_isSealed;
}
public set $isSealed(value: $Object_isSealed) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$isSealed, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.keys
// 19.1.2.17 Object.keys ( O )
public get $keys(): $Object_keys {
return this.getProperty(this.realm['[[Intrinsics]]'].$keys)['[[Value]]'] as $Object_keys;
}
public set $keys(value: $Object_keys) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$keys, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.preventextensions
// 19.1.2.18 Object.preventExtensions ( O )
public get $preventExtensions(): $Object_preventExtensions {
return this.getProperty(this.realm['[[Intrinsics]]'].$preventExtensions)['[[Value]]'] as $Object_preventExtensions;
}
public set $preventExtensions(value: $Object_preventExtensions) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$preventExtensions, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.seal
// 19.1.2.20 Object.seal ( O )
public get $seal(): $Object_seal {
return this.getProperty(this.realm['[[Intrinsics]]'].$seal)['[[Value]]'] as $Object_seal;
}
public set $seal(value: $Object_seal) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$seal, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.setprototypeof
// 19.1.2.21 Object.setPrototypeOf ( O , proto )
public get $setPrototypeOf(): $Object_setPrototypeOf {
return this.getProperty(this.realm['[[Intrinsics]]'].$setPrototypeOf)['[[Value]]'] as $Object_setPrototypeOf;
}
public set $setPrototypeOf(value: $Object_setPrototypeOf) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$setPrototypeOf, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.values
// 19.1.2.22 Object.values ( O )
public get $values(): $Object_values {
return this.getProperty(this.realm['[[Intrinsics]]'].$values)['[[Value]]'] as $Object_values;
}
public set $values(value: $Object_values) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$values, value);
}
public constructor(
realm: Realm,
functionPrototype: $FunctionPrototype,
) {
super(realm, '%Object%', functionPrototype);
}
// http://www.ecma-international.org/ecma-262/#sec-object-value
// 19.1.1.1 Object ( [ value ] )
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[value]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. If NewTarget is neither undefined nor the active function, then
if (!NewTarget.isUndefined && NewTarget !== this) {
// 1. a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%ObjectPrototype%").
return $OrdinaryCreateFromConstructor(ctx, NewTarget, '%ObjectPrototype%');
}
// 2. If value is null, undefined or not supplied, return ObjectCreate(%ObjectPrototype%).
if (value === void 0 || value.isNil) {
return $Object.ObjectCreate(ctx, 'Object', intrinsics['%ObjectPrototype%']);
}
// 3. Return ! ToObject(value).
return value.ToObject(ctx);
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.assign
// 19.1.2.1 Object.assign ( target , ... sources )
export class $Object_assign extends $BuiltinFunction<'Object.assign'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.assign', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let to be ? ToObject(target).
// 2. If only one argument was passed, return to.
// 3. Let sources be the List of argument values starting with the second argument.
// 4. For each element nextSource of sources, in ascending index order, do
// 4. a. If nextSource is neither undefined nor null, then
// 4. a. i. Let from be ! ToObject(nextSource).
// 4. a. ii. Let keys be ? from.[[OwnPropertyKeys]]().
// 4. a. iii. For each element nextKey of keys in List order, do
// 4. a. iii. 1. Let desc be ? from.[[GetOwnProperty]](nextKey).
// 4. a. iii. 2. If desc is not undefined and desc.[[Enumerable]] is true, then
// 4. a. iii. 2. a. Let propValue be ? Get(from, nextKey).
// 4. a. iii. 2. b. Perform ? Set(to, nextKey, propValue, true).
// 5. Return to.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.create
// 19.1.2.2 Object.create ( O , Properties )
export class $Object_create extends $BuiltinFunction<'Object.create'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.create', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is neither Object nor Null, throw a TypeError exception.
// 2. Let obj be ObjectCreate(O).
// 3. If Properties is not undefined, then
// 3. a. Return ? ObjectDefineProperties(obj, Properties).
// 4. Return obj.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.defineproperties
// 19.1.2.3 Object.defineProperties ( O , Properties )
export class $Object_defineProperties extends $BuiltinFunction<'Object.defineProperties'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.defineProperties', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Return ? ObjectDefineProperties(O, Properties).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-objectdefineproperties
// 19.1.2.3.1 Runtime Semantics: ObjectDefineProperties ( O , Properties )
export function $ObjectDefineProperties(
ctx: ExecutionContext,
O: any,
Properties: any,
): any {
// 1. If Type(O) is not Object, throw a TypeError exception.
// 2. Let props be ? ToObject(Properties).
// 3. Let keys be ? props.[[OwnPropertyKeys]]().
// 4. Let descriptors be a new empty List.
// 5. For each element nextKey of keys in List order, do
// 5. a. Let propDesc be ? props.[[GetOwnProperty]](nextKey).
// 5. b. If propDesc is not undefined and propDesc.[[Enumerable]] is true, then
// 5. b. i. Let descObj be ? Get(props, nextKey).
// 5. b. ii. Let desc be ? ToPropertyDescriptor(descObj).
// 5. b. iii. Append the pair (a two element List) consisting of nextKey and desc to the end of descriptors.
// 6. For each pair from descriptors in list order, do
// 6. a. Let P be the first element of pair.
// 6. b. Let desc be the second element of pair.
// 6. c. Perform ? DefinePropertyOrThrow(O, P, desc).
// 7. Return O.
throw new Error('Method not implemented.');
}
// http://www.ecma-international.org/ecma-262/#sec-object.defineproperty
// 19.1.2.4 Object.defineProperty ( O , P , Attributes )
export class $Object_defineProperty extends $BuiltinFunction<'Object.defineProperty'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.defineProperty', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, throw a TypeError exception.
// 2. Let key be ? ToPropertyKey(P).
// 3. Let desc be ? ToPropertyDescriptor(Attributes).
// 4. Perform ? DefinePropertyOrThrow(O, key, desc).
// 5. Return O.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.entries
// 19.1.2.5 Object.entries ( O )
export class $Object_entries extends $BuiltinFunction<'Object.entries'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.entries', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let obj be ? ToObject(O).
// 2. Let nameList be ? EnumerableOwnPropertyNames(obj, "key+value").
// 3. Return CreateArrayFromList(nameList).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.freeze
// 19.1.2.6 Object.freeze ( O )
export class $Object_freeze extends $BuiltinFunction<'Object.freeze'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.freeze', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, return O.
// 2. Let status be ? SetIntegrityLevel(O, "frozen").
// 3. If status is false, throw a TypeError exception.
// 4. Return O.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.fromentries
// 19.1.2.7 Object.fromEntries ( iterable )
export class $Object_fromEntries extends $BuiltinFunction<'Object.fromEntries'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.fromEntries', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Perform ? RequireObjectCoercible(iterable).
// 2. Let obj be ObjectCreate(%ObjectPrototype%).
// 3. Assert: obj is an extensible ordinary object with no own properties.
// 4. Let stepsDefine be the algorithm steps defined in CreateDataPropertyOnObject Functions.
// 5. Let adder be CreateBuiltinFunction(stepsDefine, « »).
// 6. Return ? AddEntriesFromIterable(obj, iterable, adder).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-create-data-property-on-object-functions
// 19.1.2.7.1 CreateDataPropertyOnObject Functions
export class $CreateDataPropertyOnObject extends $BuiltinFunction<'CreateDataPropertyOnObject'> {
public constructor(
realm: Realm,
) {
const intrinsics = realm['[[Intrinsics]]'];
super(realm, 'CreateDataPropertyOnObject', intrinsics['%FunctionPrototype%']);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let O be the this value.
// 2. Assert: Type(O) is Object.
// 3. Assert: O is an extensible ordinary object.
// 4. Let propertyKey be ? ToPropertyKey(key).
// 5. Perform ! CreateDataPropertyOrThrow(O, propertyKey, value).
// 6. Return undefined.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertydescriptor
// 19.1.2.8 Object.getOwnPropertyDescriptor ( O , P )
export class $Object_getOwnPropertyDescriptor extends $BuiltinFunction<'Object.getOwnPropertyDescriptor'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.getOwnPropertyDescriptor', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let obj be ? ToObject(O).
// 2. Let key be ? ToPropertyKey(P).
// 3. Let desc be ? obj.[[GetOwnProperty]](key).
// 4. Return FromPropertyDescriptor(desc).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertydescriptors
// 19.1.2.9 Object.getOwnPropertyDescriptors ( O )
export class $Object_getOwnPropertyDescriptors extends $BuiltinFunction<'Object.getOwnPropertyDescriptors'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.getOwnPropertyDescriptors', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let obj be ? ToObject(O).
// 2. Let ownKeys be ? obj.[[OwnPropertyKeys]]().
// 3. Let descriptors be ! ObjectCreate(%ObjectPrototype%).
// 4. For each element key of ownKeys in List order, do
// 4. a. Let desc be ? obj.[[GetOwnProperty]](key).
// 4. b. Let descriptor be ! FromPropertyDescriptor(desc).
// 4. c. If descriptor is not undefined, perform ! CreateDataProperty(descriptors, key, descriptor).
// 5. Return descriptors.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertynames
// 19.1.2.10 Object.getOwnPropertyNames ( O )
export class $Object_getOwnPropertyNames extends $BuiltinFunction<'Object.getOwnPropertyNames'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.getOwnPropertyNames', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Return ? GetOwnPropertyKeys(O, String).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.getownpropertysymbols
// 19.1.2.11 Object.getOwnPropertySymbols ( O )
export class $Object_getOwnPropertySymbols extends $BuiltinFunction<'Object.getOwnPropertySymbols'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.getOwnPropertySymbols', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Return ? GetOwnPropertyKeys(O, Symbol).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-getownpropertykeys
// 19.1.2.11.1 Runtime Semantics: GetOwnPropertyKeys ( O , type )
export function $GetOwnPropertyKeys(
ctx: ExecutionContext,
O: any,
type: any,
): any {
// 1. Let obj be ? ToObject(O).
// 2. Let keys be ? obj.[[OwnPropertyKeys]]().
// 3. Let nameList be a new empty List.
// 4. For each element nextKey of keys in List order, do
// 4. a. If Type(nextKey) is type, then
// 4. a. i. Append nextKey as the last element of nameList.
// 5. Return CreateArrayFromList(nameList).
throw new Error('Method not implemented.');
}
// http://www.ecma-international.org/ecma-262/#sec-object.getprototypeof
// 19.1.2.12 Object.getPrototypeOf ( O )
export class $Object_getPrototypeOf extends $BuiltinFunction<'Object.getPrototypeOf'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.getPrototypeOf', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let obj be ? ToObject(O).
// 2. Return ? obj.[[GetPrototypeOf]]().
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.is
// 19.1.2.13 Object.is ( value1 , value2 )
export class $Object_is extends $BuiltinFunction<'Object.is'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.is', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Return SameValue(value1, value2).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.isextensible
// 19.1.2.14 Object.isExtensible ( O )
export class $Object_isExtensible extends $BuiltinFunction<'Object.isExtensible'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.isExtensible', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, return false.
// 2. Return ? IsExtensible(O).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.isfrozen
// 19.1.2.15 Object.isFrozen ( O )
export class $Object_isFrozen extends $BuiltinFunction<'Object.isFrozen'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.isFrozen', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, return true.
// 2. Return ? TestIntegrityLevel(O, "frozen").
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.issealed
// 19.1.2.16 Object.isSealed ( O )
export class $Object_isSealed extends $BuiltinFunction<'Object.isSealed'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.isSealed', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, return true.
// 2. Return ? TestIntegrityLevel(O, "sealed").
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.keys
// 19.1.2.17 Object.keys ( O )
export class $Object_keys extends $BuiltinFunction<'Object.keys'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.keys', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let obj be ? ToObject(O).
// 2. Let nameList be ? EnumerableOwnPropertyNames(obj, "key").
// 3. Return CreateArrayFromList(nameList).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.preventextensions
// 19.1.2.18 Object.preventExtensions ( O )
export class $Object_preventExtensions extends $BuiltinFunction<'Object.preventExtensions'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.preventExtensions', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, return O.
// 2. Let status be ? O.[[PreventExtensions]]().
// 3. If status is false, throw a TypeError exception.
// 4. Return O.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.seal
// 19.1.2.20 Object.seal ( O )
export class $Object_seal extends $BuiltinFunction<'Object.seal'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.seal', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. If Type(O) is not Object, return O.
// 2. Let status be ? SetIntegrityLevel(O, "sealed").
// 3. If status is false, throw a TypeError exception.
// 4. Return O.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.setprototypeof
// 19.1.2.21 Object.setPrototypeOf ( O , proto )
export class $Object_setPrototypeOf extends $BuiltinFunction<'Object.setPrototypeOf'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.setPrototypeOf', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Set O to ? RequireObjectCoercible(O).
// 2. If Type(proto) is neither Object nor Null, throw a TypeError exception.
// 3. If Type(O) is not Object, return O.
// 4. Let status be ? O.[[SetPrototypeOf]](proto).
// 5. If status is false, throw a TypeError exception.
// 6. Return O.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.values
// 19.1.2.22 Object.values ( O )
export class $Object_values extends $BuiltinFunction<'Object.values'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.values', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[O]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
if (O === void 0) {
O = intrinsics.undefined;
}
// 1. Let obj be ? ToObject(O).
// 2. Let nameList be ? EnumerableOwnPropertyNames(obj, "value").
// 3. Return CreateArrayFromList(nameList).
throw new Error('Method not implemented.');
}
}
// #endregion
// http://www.ecma-international.org/ecma-262/#sec-properties-of-the-object-prototype-object
// #region 19.1.3 Properties of the Object Prototype Object
export class $ObjectPrototype extends $Object<'%ObjectPrototype%'> {
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.constructor
// 19.1.3.1 Object.prototype.constructor
public get $constructor(): $ObjectConstructor {
return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $ObjectConstructor;
}
public set $constructor(value: $ObjectConstructor) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.hasownproperty
// 19.1.3.2 Object.prototype.hasOwnProperty ( V )
public get $hasOwnProperty(): $ObjectPrototype_hasOwnProperty {
return this.getProperty(this.realm['[[Intrinsics]]'].$hasOwnProperty)['[[Value]]'] as $ObjectPrototype_hasOwnProperty;
}
public set $hasOwnProperty(value: $ObjectPrototype_hasOwnProperty) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$hasOwnProperty, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.isprototypeof
// 19.1.3.3 Object.prototype.isPrototypeOf ( V )
public get $isPrototypeOf(): $ObjectPrototype_isPrototypeOf {
return this.getProperty(this.realm['[[Intrinsics]]'].$isPrototypeOf)['[[Value]]'] as $ObjectPrototype_isPrototypeOf;
}
public set $isPrototypeOf(value: $ObjectPrototype_isPrototypeOf) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$isPrototypeOf, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.propertyisenumerable
// 19.1.3.4 Object.prototype.propertyIsEnumerable ( V )
public get $propertyIsEnumerable(): $ObjectPrototype_propertyIsEnumerable {
return this.getProperty(this.realm['[[Intrinsics]]'].$propertyIsEnumerable)['[[Value]]'] as $ObjectPrototype_propertyIsEnumerable;
}
public set $propertyIsEnumerable(value: $ObjectPrototype_propertyIsEnumerable) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$propertyIsEnumerable, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.tolocalestring
// 19.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )
public get $toLocaleString(): $ObjectPrototype_toLocaleString {
return this.getProperty(this.realm['[[Intrinsics]]'].$toLocaleString)['[[Value]]'] as $ObjectPrototype_toLocaleString;
}
public set $toLocaleString(value: $ObjectPrototype_toLocaleString) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$toLocaleString, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.tostring
// 19.1.3.6 Object.prototype.toString ( )
public get $toString(): $ObjProto_toString {
return this.getProperty(this.realm['[[Intrinsics]]'].$toString)['[[Value]]'] as $ObjProto_toString;
}
public set $toString(value: $ObjProto_toString) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$toString, value);
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.valueof
// 19.1.3.7 Object.prototype.valueOf ( )
public get $valueOf(): $ObjProto_valueOf {
return this.getProperty(this.realm['[[Intrinsics]]'].$valueOf)['[[Value]]'] as $ObjProto_valueOf;
}
public set $valueOf(value: $ObjProto_valueOf) {
this.setDataProperty(this.realm['[[Intrinsics]]'].$valueOf, value);
}
public constructor(
realm: Realm,
) {
const intrinsics = realm['[[Intrinsics]]'];
super(realm, '%ObjectPrototype%', intrinsics.null, CompletionType.normal, intrinsics.empty);
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.hasownproperty
// 19.1.3.2 Object.prototype.hasOwnProperty ( V )
export class $ObjectPrototype_hasOwnProperty extends $BuiltinFunction<'Object.prototype.hasOwnProperty'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.prototype.hasOwnProperty', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let P be ? ToPropertyKey(V).
// 2. Let O be ? ToObject(this value).
// 3. Return ? HasOwnProperty(O, P).
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.isprototypeof
// 19.1.3.3 Object.prototype.isPrototypeOf ( V )
export class $ObjectPrototype_isPrototypeOf extends $BuiltinFunction<'Object.prototype.isPrototypeOf'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.prototype.isPrototypeOf', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. If Type(V) is not Object, return false.
// 2. Let O be ? ToObject(this value).
// 3. Repeat,
// 3. a. Set V to ? V.[[GetPrototypeOf]]().
// 3. b. If V is null, return false.
// 3. c. If SameValue(O, V) is true, return true.
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.propertyisenumerable
// 19.1.3.4 Object.prototype.propertyIsEnumerable ( V )
export class $ObjectPrototype_propertyIsEnumerable extends $BuiltinFunction<'Object.prototype.propertyIsEnumerable'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.prototype.propertyIsEnumerable', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let P be ? ToPropertyKey(V).
// 2. Let O be ? ToObject(this value).
// 3. Let desc be ? O.[[GetOwnProperty]](P).
// 4. If desc is undefined, return false.
// 5. Return desc.[[Enumerable]].
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.tolocalestring
// 19.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )
export class $ObjectPrototype_toLocaleString extends $BuiltinFunction<'Object.prototype.toLocaleString'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.prototype.toLocaleString', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let O be the this value.
// 2. Return ? Invoke(O, "toString").
throw new Error('Method not implemented.');
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.tostring
// 19.1.3.6 Object.prototype.toString ( )
export class $ObjProto_toString extends $BuiltinFunction<'Object.prototype.toString'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, 'Object.prototype.toString', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. If the this value is undefined, return "[object Undefined]".
if (thisArgument.isUndefined) {
return new $String(realm, '[object Undefined]');
}
// 2. If the this value is null, return "[object Null]".
if (thisArgument.isNull) {
return new $String(realm, '[object Null]');
}
// 3. Let O be ! ToObject(this value).
const O = thisArgument.ToObject(ctx);
const tag = O['[[Get]]'](ctx, intrinsics['@@toStringTag'], O);
if (tag.isAbrupt) { return tag; }
if (tag.isString) {
return new $String(realm, `[object ${tag['[[Value]]']}]`);
}
// 4. Let isArray be ? IsArray(O).
// 5. If isArray is true, let builtinTag be "Array".
if (O.isArray) {
// TODO: implement IsArray semantics for proxy with null handler (which throws type error)
return new $String(realm, `[object Array]`);
}
// 6. Else if O is a String exotic object, let builtinTag be "String".
if (O instanceof $StringExoticObject) {
return new $String(realm, `[object String]`);
}
// 7. Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
if ('[[ParameterMap]]' in O) {
return new $String(realm, `[object Arguments]`);
}
// 8. Else if O has a [[Call]] internal method, let builtinTag be "Function".
if ('[[Call]]' in O) {
return new $String(realm, `[object Function]`);
}
// 9. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
if ('[[ErrorData]]' in O) {
return new $String(realm, `[object Error]`);
}
// 10. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
if ('[[BooleanData]]' in O) {
return new $String(realm, `[object Boolean]`);
}
// 11. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
if ('[[NumberData]]' in O) {
return new $String(realm, `[object Number]`);
}
// 12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
if ('[[DateValue]]' in O) {
return new $String(realm, `[object Date]`);
}
// 13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
if ('[[RegExpMatcher]]' in O) {
return new $String(realm, `[object RegExp]`);
}
// 14. Else, let builtinTag be "Object".
return new $String(realm, `[object Object]`);
// 15. Let tag be ? Get(O, @@toStringTag).
// 16. If Type(tag) is not String, set tag to builtinTag.
// 17. Return the string-concatenation of "[object ", tag, and "]".
}
}
// http://www.ecma-international.org/ecma-262/#sec-object.prototype.valueof
// 19.1.3.7 Object.prototype.valueOf ( )
export class $ObjProto_valueOf extends $BuiltinFunction<'%ObjProto_valueOf%'> {
public constructor(
realm: Realm,
proto: $FunctionPrototype,
) {
super(realm, '%ObjProto_valueOf%', proto);
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Return ? ToObject(this value).
throw new Error('Method not implemented.');
}
}
// #endregion | the_stack |
import assert from "assert";
import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials";
import { LotusClient } from '../../src/providers/LotusClient';
import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector';
import { WsJsonRpcConnector } from '../../src/connectors/WsJsonRpcConnector';
const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN });
const wsConnector = new WsJsonRpcConnector({ url: 'ws://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN });
describe("State", function () {
const blocksWithMessages: any = [];
it("get blocks with messages [http]", async function() {
const con = new LotusClient(httpConnector);
const res: any = await con.chain.getTipSetByHeight(30);
let parentCid = res.Blocks[0].Parents[0];
let crtBlock = res.Cids[0];
while (parentCid) {
let block: any = undefined;
try {
block = await con.chain.getBlock(parentCid);
} catch(e) {};
if (block){
const messages = await con.chain.getBlockMessages(parentCid);
if (messages.BlsMessages.length > 0) blocksWithMessages.push (crtBlock);
crtBlock = parentCid;
parentCid = block.Parents? block.Parents[0] : null;
} else {
parentCid = undefined;
}
}
});
it("should get block parent receipts [http]", async function() {
const con = new LotusClient(httpConnector);
const receipts = await con.chain.getParentReceipts(blocksWithMessages[0]);
assert.strictEqual(typeof receipts[0].GasUsed, "number", "invalid receipts");
});
it("should get block parent receipts [ws]", async function() {
const provider = new LotusClient(wsConnector);
const receipts = await provider.chain.getParentReceipts(blocksWithMessages[0]);
assert.strictEqual(typeof receipts[0].GasUsed, "number", "invalid receipts");
await provider.release();
});
it("should get block parent messages [http]", async function() {
const con = new LotusClient(httpConnector);
const messages = await con.chain.getParentMessages(blocksWithMessages[0]);
assert.strictEqual(typeof messages[0].Message.Nonce, "number", "invalid message");
});
it("should get block parent messages [ws]", async function() {
const provider = new LotusClient(wsConnector);
const messages = await provider.chain.getParentMessages(blocksWithMessages[0]);
assert.strictEqual(typeof messages[0].Message.Nonce, "number", "invalid message");
await provider.release();
});
it("should run the given message", async function() {
const provider = new LotusClient(httpConnector);
const messages = await provider.state.listMessages({
To: 't01000'
});
const message = await provider.chain.getMessage(messages[0])
const result = await provider.state.stateCall(message);
const valid = !!result.ExecutionTrace && !!result.Msg && !!result.MsgRct;
assert.strictEqual(valid, true, "failed to run message");
});
it("should get actor [http]", async function() {
const con = new LotusClient(httpConnector);
const actor = await con.state.getActor('t01000');
assert.strictEqual( typeof actor.Balance === 'string', true, "invalid actor");
});
it("should get state [http]", async function() {
const con = new LotusClient(httpConnector);
const state = await con.state.readState('t01000');
assert.strictEqual(JSON.stringify(Object.keys(state)), JSON.stringify(['Balance', 'State']), 'invalid state');
});
it("should list messages [http]", async function () {
const con = new LotusClient(httpConnector);
const messages = await con.state.listMessages({
To: 't01000'
});
assert.strictEqual(Array.isArray(messages) && messages.length > 0, true, 'invalid list of messages');
});
it("should get network name [http]", async function () {
const con = new LotusClient(httpConnector);
const network = await con.state.networkName();
assert.strictEqual(typeof network === 'string', true, 'invalid network name');
});
it("should get miner sectors info [http]", async function () {
const con = new LotusClient(httpConnector);
const sectors = await con.state.minerSectors('t01000');
const valid = sectors.reduce((acc, sector) => acc === false ? acc : typeof sector.SectorNumber === 'number', true);
assert.strictEqual(valid, true, 'invalid sectors info');
});
it("should get miner active sectors info [http]", async function () {
const con = new LotusClient(httpConnector);
const sectors = await con.state.minerActiveSectors('t01000');
const valid = sectors.reduce((acc, sector) => acc === false ? acc : typeof sector.SectorNumber === 'number', true);
assert.strictEqual(valid, true, 'invalid active sectors info');
});
it("should get miner proving deadline", async function () {
const con = new LotusClient(httpConnector);
const provingDeadline = await con.state.minerProvingDeadline('t01000');
assert.strictEqual(typeof provingDeadline.Index === 'number', true, 'invalid miner proving deadline');
});
it("should get miner power", async function () {
const con = new LotusClient(httpConnector);
const power = await con.state.minerPower('t01000');
assert.strictEqual(typeof power.MinerPower.RawBytePower === 'string', true, 'invalid miner power');
});
it("should get miner info", async function () {
const con = new LotusClient(httpConnector);
const minerInfo = await con.state.minerInfo('t01000');
assert.strictEqual(typeof minerInfo.Owner === 'string', true, 'invalid miner info');
});
it("should get miner deadlines", async function () {
const con = new LotusClient(httpConnector);
const minerDeadlines = await con.state.minerDeadlines('t01000');
const valid = minerDeadlines.reduce((acc, deadline) => acc === false ? false : Array.isArray(deadline.PostSubmissions), true);
assert.strictEqual(valid, true, 'invalid miner deadlines');
});
it("should get miner partitions", async function () {
const con = new LotusClient(httpConnector);
const minerPartitions = await con.state.minerPartitions('t01000', 0);
const valid = minerPartitions.reduce((acc, partition) => acc === false ? false : Array.isArray(partition.AllSectors), true);
assert.strictEqual(valid, true, 'invalid miner partitions');
});
it("should get the faulty sectors of a miner", async function () {
const con = new LotusClient(httpConnector);
const minerFaults = await con.state.minerFaults('t01000');
assert.strictEqual(minerFaults === null || Array.isArray(minerFaults), true, 'invalid miner faulty sectors');
});
// TODO: test on hold. The method has a bug
// it("should get all faulty sectors", async function () {
// const con = new LotusClient(httpConnector);
// const minerFaults = await con.allMinerFaults(182);
// });
it("should get the recovering sectors of a miner", async function () {
const con = new LotusClient(httpConnector);
const recoveries = await con.state.minerRecoveries('t01000');
assert.strictEqual(recoveries === null || Array.isArray(recoveries), true, 'invalid miner recovering sectors');
});
it("should get the precommit deposit for the specified miner's sector", async function () {
const con = new LotusClient(httpConnector);
const deposit = await con.state.minerPreCommitDepositForPower('t01000', {
SealProof: 1,
SectorNumber: 1,
SealedCID: {
"/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4"
},
SealRandEpoch: 10101,
DealIDs: null,
Expiration: 10101,
ReplaceCapacity: true,
ReplaceSectorDeadline: 42,
ReplaceSectorPartition: 42,
ReplaceSectorNumber: 9
});
assert.strictEqual(typeof deposit === 'string', true, "invalid precommit deposit for the specified miner's sector");
});
it("should get the initial pledge collateral for the specified miner's sector", async function () {
const con = new LotusClient(httpConnector);
const collateral = await con.state.minerInitialPledgeCollateral('t01000', {
SealProof: 1,
SectorNumber: 1,
SealedCID: {
"/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4"
},
SealRandEpoch: 10101,
DealIDs: null,
Expiration: 10101,
ReplaceCapacity: true,
ReplaceSectorDeadline: 42,
ReplaceSectorPartition: 42,
ReplaceSectorNumber: 9
});
assert.strictEqual(typeof collateral === 'string', true, "invalid pledge collateral for the specified miner's sector");
});
it("should get the miner's balance that can be withdrawn or spent", async function () {
const con = new LotusClient(httpConnector);
const balance = await con.state.minerAvailableBalance('t01000');
assert.strictEqual(typeof balance === 'string', true, "invalid miner's balance that can be withdrawn or spent");
});
// TODO: It throws an error: precommit not found
// it("should get the PreCommit info for the specified miner's sector", async function () {
// const con = new LotusClient(httpConnector);
// const preCommitInfo = await con.state.sectorPreCommitInfo('t01000', 0);
// });
it("should return info for the specified miner's sector", async function() {
const con = new LotusClient(httpConnector);
const info = await con.state.sectorGetInfo('t01000', 0);
assert.strictEqual(info.SectorNumber === 0, true, "invalid info for the specified miner's sector");
});
it("should get epoch at which given sector will expire", async function() {
const con = new LotusClient(httpConnector);
const expiration = await con.state.sectorExpiration('t01000', 0);
assert.strictEqual(typeof expiration.OnTime === 'number', true, "invalid epoch at which given sector will expire");
});
it("should get deadline/partition with the specified sector", async function() {
const con = new LotusClient(httpConnector);
const partition = await con.state.sectorPartition('t01000', 0);
assert.strictEqual(typeof partition.Partition === 'number', true, "invalid deadline/partition with the specified sector");
});
it("should search for message and return its receipt and the tipset where it was executed", async function() {
const con = new LotusClient(httpConnector);
const messages = await con.state.listMessages({
To: 't01000',
});
const receipt = await con.state.searchMsg(messages[0]);
assert.strictEqual(typeof receipt.Height === 'number', true, "invalid height for searched messages");
});
it("should wait for message", async function() {
this.timeout(10000);
const con = new LotusClient(httpConnector);
const messages = await con.state.listMessages({
To: 't01000',
});
const lookup = await con.state.waitMsg(messages[0], 10);
assert.strictEqual(typeof lookup.Height === 'number', true, "invalid lookup info for waited messages");
});
it("should wait message limited", async function() {
this.timeout(10000);
const con = new LotusClient(httpConnector);
const messages = await con.state.listMessages({
To: 't01000'
});
const lookup = await con.state.waitMsgLimited(messages[0], 10, 10000000);
assert.strictEqual(typeof lookup.Height === 'number', true, "invalid lookup info for limited waited messages");
});
it("should list miners", async function() {
const con = new LotusClient(httpConnector);
const miners = await con.state.listMiners();
assert.strictEqual(Array.isArray(miners), true, "invalid list of miners");
});
it("should list actors", async function() {
const con = new LotusClient(httpConnector);
const actors = await con.state.listActors();
assert.strictEqual(Array.isArray(actors), true, "invalid list of actors");
});
it("should get market balance", async function() {
const con = new LotusClient(httpConnector);
const marketBalance = await con.state.marketBalance('t01000');
assert.strictEqual(typeof marketBalance.Escrow === 'string', true, "invalid market balance");
});
/*
disabled temporarily: Error: locked funds not found
it("should get market participants", async function() {
const con = new LotusClient(httpConnector);
const marketBalance = await con.marketParticipants();
assert.strictEqual(typeof marketBalance === 'object', true, "invalid market participants");
});
*/
it("should get market deals", async function() {
const con = new LotusClient(httpConnector);
const marketDeals = await con.state.marketDeals();
let valid = typeof marketDeals === 'object';
const keys = Object.keys(marketDeals);
if (valid && keys.length > 0) {
valid = typeof marketDeals[keys[0]].Proposal.PieceSize === 'number';
}
assert.strictEqual(valid, true, "invalid market deals");
});
it("should get information about the storage deal", async function() {
const con = new LotusClient(httpConnector);
const marketDeal = await con.state.marketStorageDeal(0);
assert.strictEqual(!!marketDeal.Proposal.PieceCID, true, "invalid information about the storage deal");
});
it("should get the ID address of the given address", async function() {
const con = new LotusClient(httpConnector);
const id = await con.state.lookupId('t01000');
assert.strictEqual(typeof id === 'string', true, "invalid ID address");
});
it("should get the public key address of the given ID address", async function() {
const con = new LotusClient(httpConnector);
const key = await con.state.accountKey('t01002');
assert.strictEqual(typeof key === 'string', true, "public key address of the given ID address");
});
// TODO: Fix error: "failed to load hamt node: cbor input had wrong number of fields" and add assertion
// it("should return all the actors whose states change", async function() {
// const con = new LotusClient(httpConnector);
// const tipSet = await con.getTipSetByHeight(1);
// const tipSet2 = await con.getTipSetByHeight(30);
// const actors = await con.changedActors(tipSet.Cids[0], tipSet2.Cids[0]);
// });
it("should return the message receipt for the given message", async function() {
const con = new LotusClient(httpConnector);
const messages = await con.state.listMessages({
To: 't01000'
});
const receipt = await con.state.getReceipt(messages[0]);
assert.strictEqual(typeof receipt.ExitCode === 'number', true, "invalid message receipt");
});
it("should return the number of sectors in a miner's sector set", async function() {
const con = new LotusClient(httpConnector);
const sectors = await con.state.minerSectorCount('t01000');
assert.strictEqual(typeof sectors.Active === 'number', true, "invalid number of sectors");
});
it("should apply the messages", async function() {
const con = new LotusClient(httpConnector);
const messages = await con.state.listMessages({
To: 't01000'
});
const message = await con.chain.getMessage(messages[0]);
const state = await con.state.compute(10, [message]);
assert.strictEqual(!!state.Root['/'], true, "invalid state after compute");
});
it("should return the data cap for the given address", async function() {
const con = new LotusClient(httpConnector);
const status = await con.state.verifiedClientStatus('t01000');
assert.strictEqual(status === null || typeof status === 'string', true, "invalid data cap");
});
it("should return min and max collateral a storage provider can issue", async function() {
const con = new LotusClient(httpConnector);
const collateralBounds = await con.state.dealProviderCollateralBounds(Math.pow(1024, 2), true);
const valid = typeof collateralBounds.Min === 'string' && typeof collateralBounds.Max === 'string'
assert.strictEqual(valid, true, "invalid collateral a storage provider can issue");
});
it("the circulating supply of Filecoin at the given tipset", async function() {
const con = new LotusClient(httpConnector);
const supply = await con.state.circulatingSupply();
const valid = Object
.keys(supply)
.reduce((acc, key) => acc === false ? acc : typeof key === 'string', true);
assert.strictEqual(valid, true, "invalid circulating supply of Filecoin");
});
it("the vm circulating supply of Filecoin at the given tipset", async function() {
const con = new LotusClient(httpConnector);
const supply = await con.state.vmCirculatingSupply();
const valid = Object
.keys(supply)
.reduce((acc, key) => acc === false ? acc : typeof key === 'string', true);
assert.strictEqual(valid, true, "invalid vm circulating supply of Filecoin");
});
it("should return the data cap for the verifier address [http]", async function() {
const con = new LotusClient(httpConnector);
const status = await con.state.verifierStatus('t01000');
assert.strictEqual(status === null || typeof status === 'string', true, "invalid data cap");
});
it("should return the data cap for the verifier address [ws]", async function() {
const con = new LotusClient(wsConnector);
const status = await con.state.verifierStatus('t01000');
assert.strictEqual(status === null || typeof status === 'string', true, "invalid data cap");
await con.release();
});
it("should return the network version [http]", async function() {
const con = new LotusClient(httpConnector);
const version = await con.state.networkVersion();
assert.strictEqual(typeof version === 'number', true, "invalid network version");
});
it("should return the network version [ws]", async function() {
const con = new LotusClient(wsConnector);
const version = await con.state.networkVersion()
assert.strictEqual(typeof version === 'number', true, "invalid network version");
await con.release();
});
it("should return the address of the Verified Registry's root key [http]", async function() {
const con = new LotusClient(httpConnector);
const address = await con.state.verifiedRegistryRootKey();
assert.strictEqual(typeof address === 'string', true, "invalid address");
});
it("should return the address of the Verified Registry's root key [ws]", async function() {
const con = new LotusClient(wsConnector);
const address = await con.state.verifiedRegistryRootKey()
assert.strictEqual(typeof address === 'string', true, "invalid address");
await con.release();
});
}); | the_stack |
import {
Listbox,
ListboxButton,
ListboxLabel,
ListboxOption,
ListboxOptions,
} from ".";
import { suppressConsoleLogs } from "$lib/test-utils/suppress-console-logs";
import { act, render } from "@testing-library/svelte";
import {
assertActiveElement,
assertActiveListboxOption,
assertListbox,
assertListboxButton,
assertListboxButtonLinkedWithListbox,
assertListboxButtonLinkedWithListboxLabel,
assertListboxLabel,
assertListboxLabelLinkedWithListbox,
assertListboxOption,
assertNoActiveListboxOption,
assertNoSelectedListboxOption,
getByText,
getListbox,
getListboxButton,
getListboxButtons,
getListboxes,
getListboxLabel,
getListboxOptions,
ListboxState,
} from "$lib/test-utils/accessibility-assertions";
import {
click,
focus,
Keys,
MouseButton,
mouseLeave,
mouseMove,
press,
shift,
type,
word,
} from "$lib/test-utils/interactions";
import { Transition } from "../transitions";
import TransitionDebug from "$lib/components/disclosure/_TransitionDebug.svelte";
import svelte from "svelte-inline-compile";
import { writable } from "svelte/store";
let mockId = 0;
jest.mock('../../hooks/use-id', () => {
return {
useId: jest.fn(() => ++mockId),
}
})
beforeEach(() => mockId = 0)
beforeAll(() => {
// jest.spyOn(window, 'requestAnimationFrame').mockImplementation(setImmediate as any)
// jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(clearImmediate as any)
})
afterAll(() => jest.restoreAllMocks())
function nextFrame() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
resolve();
});
});
});
}
describe('safeguards', () => {
it.each([
['ListboxButton', ListboxButton],
['ListboxLabel', ListboxLabel],
['ListboxOptions', ListboxOptions],
['ListboxOption', ListboxOption],
])(
'should error when we are using a <%s /> without a parent <Listbox />',
suppressConsoleLogs((name, Component) => {
expect(() => render(Component)).toThrowError(
`<${name} /> is missing a parent <Listbox /> component.`
)
})
)
it(
'should be possible to render a Listbox without crashing',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
})
describe('Rendering', () => {
describe('Listbox', () => {
it(
'should render a Listbox using slot props',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} let:open>
<ListboxButton>Trigger</ListboxButton>
{#if open}
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
{/if}
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.Visible })
})
)
it(
'should be possible to disable a Listbox',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} disabled={true}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await press(Keys.Enter, getListboxButton())
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
})
describe('ListboxLabel', () => {
it(
'should be possible to render a ListboxLabel using slot props',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxLabel let:open let:disabled>{JSON.stringify({ open, disabled })}</ListboxLabel>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a"> Option A </ListboxOption>
<ListboxOption value="b"> Option B </ListboxOption>
<ListboxOption value="c"> Option C </ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-2' },
})
assertListboxLabel({
attributes: { id: 'headlessui-listbox-label-1' },
textContent: JSON.stringify({ open: false, disabled: false }),
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxLabel({
attributes: { id: 'headlessui-listbox-label-1' },
textContent: JSON.stringify({ open: true, disabled: false }),
})
assertListbox({ state: ListboxState.Visible })
assertListboxLabelLinkedWithListbox()
assertListboxButtonLinkedWithListboxLabel()
})
)
it(
'should be possible to render a ListboxLabel with slot props and an `as` prop',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxLabel as="p" let:open let:disabled>{JSON.stringify({ open, disabled })}</ListboxLabel>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxLabel({
attributes: { id: 'headlessui-listbox-label-1' },
textContent: JSON.stringify({ open: false, disabled: false }),
tag: 'p',
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxLabel({
attributes: { id: 'headlessui-listbox-label-1' },
textContent: JSON.stringify({ open: true, disabled: false }),
tag: 'p',
})
assertListbox({ state: ListboxState.Visible })
})
)
});
describe("ListboxButton", () => {
it(
'should render a ListboxButton with slot props',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton let:open let:disabled>{JSON.stringify({ open, disabled})}</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A </ListboxOption>
<ListboxOption value="b">Option B </ListboxOption>
<ListboxOption value="c">Option C </ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
textContent: JSON.stringify({ open: false, disabled: false }),
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-button-1' },
textContent: JSON.stringify({ open: true, disabled: false }),
})
assertListbox({ state: ListboxState.Visible })
})
)
it(
'should be possible to render a ListboxButton using slot props and an `as` prop',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton as="div" role="button" let:open let:disabled>
{JSON.stringify({ open, disabled })}
</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
textContent: JSON.stringify({ open: false, disabled: false }),
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-button-1' },
textContent: JSON.stringify({ open: true, disabled: false }),
})
assertListbox({ state: ListboxState.Visible })
})
)
it(
'should be possible to render a ListboxButton and a ListboxLabel and see them linked together',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxLabel>Label</ListboxLabel>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// TODO: Needed to make it similar to vue test implementation?
// await new Promise(requestAnimationFrame)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-2' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
assertListboxButtonLinkedWithListboxLabel()
})
)
describe('`type` attribute', () => {
it('should set the `type` to "button" by default', async () => {
render(svelte`
<Listbox value={null} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
</Listbox>
`);
expect(getListboxButton()).toHaveAttribute('type', 'button')
})
it('should not set the `type` to "button" if it already contains a `type`', async () => {
render(svelte`
<Listbox value={null} on:change={console.log}>
<ListboxButton type="submit">Trigger</ListboxButton>
</Listbox>
`);
expect(getListboxButton()).toHaveAttribute('type', 'submit')
})
it('should not set the type if the "as" prop is not a "button"', async () => {
render(svelte`
<Listbox value={null} on:change={console.log}>
<ListboxButton as="div">Trigger</ListboxButton>
</Listbox>
`);
expect(getListboxButton()).not.toHaveAttribute('type')
})
})
})
describe('ListboxOptions', () => {
it(
'should render ListboxOptions with slot props',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions let:open>
<ListboxOption value="a">{JSON.stringify({ open })}</ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({
state: ListboxState.Visible,
textContent: JSON.stringify({ open: true }),
})
assertActiveElement(getListbox())
})
)
it('should be possible to always render the ListboxOptions if we provide it a `static` prop', () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions static={true}>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Let's verify that the Listbox is already there
expect(getListbox()).not.toBe(null)
})
it('should be possible to use a different render strategy for the ListboxOptions', async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions unmount={false}>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListbox({ state: ListboxState.InvisibleHidden })
// Let's open the Listbox, to see if it is not hidden anymore
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
})
})
describe('ListboxOption', () => {
it(
'should render a ListboxOption with slot props',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" let:active let:selected let:disabled>
{JSON.stringify({ active, selected, disabled })}
</ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({
state: ListboxState.Visible,
textContent: JSON.stringify({ active: false, selected: false, disabled: false }),
})
})
)
it('should guarantee the listbox option order after a few unmounts', async () => {
let showFirst = writable(false);
render(svelte`
<Listbox value={undefined}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
{#if $showFirst}
<ListboxOption value="a">Option A</ListboxOption>
{/if}
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`)
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open Listbox
await click(getListboxButton())
let options = getListboxOptions()
expect(options).toHaveLength(2)
options.forEach(option => assertListboxOption(option))
// Make the first option active
await press(Keys.ArrowDown)
// Verify that the first listbox option is active
assertActiveListboxOption(options[0])
// Now add a new option dynamically
await act(() => showFirst.set(true));
// New option should be treated correctly
options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
// Focused option should now be second
assertActiveListboxOption(options[1])
// We should be able to go to the first option
await press(Keys.Home)
assertActiveListboxOption(options[0])
// And the last one
await press(Keys.End)
assertActiveListboxOption(options[2])
})
})
})
describe('Rendering composition', () => {
it(
'should be possible to conditionally render classNames (aka class can be a function?!)',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" class={(bag) => JSON.stringify(bag)}>Option A</ListboxOption>
<ListboxOption value="b" class={(bag) => JSON.stringify(bag)} disabled>Option B</ListboxOption>
<ListboxOption value="c" class="no-special-treatment">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open Listbox
await click(getListboxButton())
let options = getListboxOptions()
// Verify correct classNames
expect('' + options[0].classList).toEqual(
JSON.stringify({ active: false, selected: false, disabled: false })
)
expect('' + options[1].classList).toEqual(
JSON.stringify({ active: false, selected: false, disabled: true })
)
expect('' + options[2].classList).toEqual('no-special-treatment')
// Double check that nothing is active
assertNoActiveListboxOption(getListbox())
// Make the first option active
await press(Keys.ArrowDown)
// Verify the classNames
expect('' + options[0].classList).toEqual(
JSON.stringify({ active: true, selected: false, disabled: false })
)
expect('' + options[1].classList).toEqual(
JSON.stringify({ active: false, selected: false, disabled: true })
)
expect('' + options[2].classList).toEqual('no-special-treatment')
// Double check that the first option is the active one
assertActiveListboxOption(options[0])
// Let's go down, this should go to the third option since the second option is disabled!
await press(Keys.ArrowDown)
// Verify the classNames
expect('' + options[0].classList).toEqual(
JSON.stringify({ active: false, selected: false, disabled: false })
)
expect('' + options[1].classList).toEqual(
JSON.stringify({ active: false, selected: false, disabled: true })
)
expect('' + options[2].classList).toEqual('no-special-treatment')
// Double check that the last option is the active one
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to swap the Listbox option with a button for example',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" as="button">Option A</ListboxOption>
<ListboxOption value="b" as="button">Option B</ListboxOption>
<ListboxOption value="c" as="button">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open Listbox
await click(getListboxButton())
// Verify options are buttons now
getListboxOptions().forEach(option => assertListboxOption(option, { tag: 'button' }))
})
)
})
describe('Composition', () => {
it(
'should be possible to wrap the ListboxOptions with a Transition component',
suppressConsoleLogs(async () => {
let orderFn = jest.fn()
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<TransitionDebug name="Listbox" fn={orderFn} />
<Transition>
<TransitionDebug name="Transition" fn={orderFn} />
<ListboxOptions>
<ListboxOption as="button" value="a">
<TransitionDebug name="ListboxOption" fn={orderFn} />
Option A
</ListboxOption>
</ListboxOptions>
</Transition>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
await click(getListboxButton())
assertListboxButton({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({
state: ListboxState.Visible,
textContent: "Option A",
})
await click(getListboxButton())
// Wait for all transitions to finish
await nextFrame()
// Verify that we tracked the `mounts` and `unmounts` in the correct order
expect(orderFn.mock.calls).toEqual([
['Mounting - Listbox'],
['Mounting - Transition'],
['Mounting - ListboxOption'],
['Unmounting - Transition'],
['Unmounting - ListboxOption'],
])
})
)
})
describe('Keyboard interactions', () => {
describe('`Enter` key', () => {
it(
'should be possible to open the listbox with Enter',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option, { selected: false }))
// Verify that the first listbox option is active
assertActiveListboxOption(options[0])
assertNoSelectedListboxOption()
})
)
it(
'should not be possible to open the listbox with Enter when the button is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} disabled={true}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Try to open the listbox
await press(Keys.Enter)
// Verify it is still closed
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be possible to open the listbox with Enter, and focus the selected option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value="b" on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should be possible to open the listbox with Enter, and focus the selected option (when using the `hidden` render strategy)',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value="b" on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions unmount={false}>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleHidden,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleHidden })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
let options = getListboxOptions()
// Hover over Option A
await mouseMove(options[0])
// Verify that Option A is active
assertActiveListboxOption(options[0])
// Verify that Option B is still selected
assertListboxOption(options[1], { selected: true })
// Close/Hide the listbox
await press(Keys.Escape)
// Re-open the listbox
await click(getListboxButton())
// Verify we have listbox options
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should be possible to open the listbox with Enter, and focus the selected option (with a list of objects)',
suppressConsoleLogs(async () => {
let myOptions = [
{ id: 'a', name: 'Option A' },
{ id: 'b', name: 'Option B' },
{ id: 'c', name: 'Option C' },
]
render(svelte`
<Listbox value={myOptions[1]} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value={myOptions[0]}>Option A</ListboxOption>
<ListboxOption value={myOptions[1]}>Option B</ListboxOption>
<ListboxOption value={myOptions[2]}>Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should have no active listbox option when there are no listbox options at all',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions />
</Listbox>
`);
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
assertNoActiveListboxOption()
})
)
it(
'should focus the first non disabled listbox option when opening with Enter',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
let options = getListboxOptions()
// Verify that the first non-disabled listbox option is active
assertActiveListboxOption(options[1])
})
)
it(
'should focus the first non disabled listbox option when opening with Enter (jump over multiple disabled ones)',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
let options = getListboxOptions()
// Verify that the first non-disabled listbox option is active
assertActiveListboxOption(options[2])
})
)
it(
'should have no active listbox option upon Enter key press, when there are no non-disabled listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
assertNoActiveListboxOption()
})
)
it(
'should be possible to close the listbox with Enter when there is no active listboxoption',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open listbox
await click(getListboxButton())
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
// Close listbox
await press(Keys.Enter)
// Verify it is closed
assertListboxButton({ state: ListboxState.InvisibleUnmounted })
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Verify the button is focused again
assertActiveElement(getListboxButton())
})
)
it(
'should be possible to close the listbox with Enter and choose the active listbox option',
suppressConsoleLogs(async () => {
let handleChange = jest.fn()
let value = writable();
render(svelte`
<Listbox value={$value} on:change={(e) => { value.set(e.detail); handleChange(e.detail) } }>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open listbox
await click(getListboxButton())
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
// Activate the first listbox option
let options = getListboxOptions()
await mouseMove(options[0])
// Choose option, and close listbox
await press(Keys.Enter)
// Verify it is closed
assertListboxButton({ state: ListboxState.InvisibleUnmounted })
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Verify we got the change event
expect(handleChange).toHaveBeenCalledTimes(1)
expect(handleChange).toHaveBeenCalledWith('a')
// Verify the button is focused again
assertActiveElement(getListboxButton())
// Open listbox again
await click(getListboxButton())
// Verify the active option is the previously selected one
assertActiveListboxOption(getListboxOptions()[0])
})
)
})
describe('`Space` key', () => {
it(
'should be possible to open the listbox with Space',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[0])
})
)
it(
'should not be possible to open the listbox with Space when the button is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} disabled>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Try to open the listbox
await press(Keys.Space)
// Verify it is still closed
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be possible to open the listbox with Space, and focus the selected option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value="b" on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should have no active listbox option when there are no listbox options at all',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions />
</Listbox>
`);
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
assertNoActiveListboxOption()
})
)
it(
'should focus the first non disabled listbox option when opening with Space',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
let options = getListboxOptions()
// Verify that the first non-disabled listbox option is active
assertActiveListboxOption(options[1])
})
)
it(
'should focus the first non disabled listbox option when opening with Space (jump over multiple disabled ones)',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
let options = getListboxOptions()
// Verify that the first non-disabled listbox option is active
assertActiveListboxOption(options[2])
})
)
it(
'should have no active listbox option upon Space key press, when there are no non-disabled listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
assertNoActiveListboxOption()
})
)
it(
'should be possible to close the listbox with Space and choose the active listbox option',
suppressConsoleLogs(async () => {
let handleChange = jest.fn()
let value = writable();
render(svelte`
<Listbox value={$value} on:change={(e) => { value.set(e.detail); handleChange(e.detail) } }>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open listbox
await click(getListboxButton())
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
// Activate the first listbox option
let options = getListboxOptions()
await mouseMove(options[0])
// Choose option, and close listbox
await press(Keys.Space)
// Verify it is closed
assertListboxButton({ state: ListboxState.InvisibleUnmounted })
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Verify we got the change event
expect(handleChange).toHaveBeenCalledTimes(1)
expect(handleChange).toHaveBeenCalledWith('a')
// Verify the button is focused again
assertActiveElement(getListboxButton())
// Open listbox again
await click(getListboxButton())
// Verify the active option is the previously selected one
assertActiveListboxOption(getListboxOptions()[0])
})
)
})
describe('`Escape` key', () => {
it(
'should be possible to close an open listbox with Escape',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Space)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Close listbox
await press(Keys.Escape)
// Verify it is closed
assertListboxButton({ state: ListboxState.InvisibleUnmounted })
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Verify the button is focused again
assertActiveElement(getListboxButton())
})
)
})
describe('`Tab` key', () => {
it(
'should focus trap when we use Tab',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[0])
// Try to tab
await press(Keys.Tab)
// Verify it is still open
assertListboxButton({ state: ListboxState.Visible })
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
})
)
it(
'should focus trap when we use Shift+Tab',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[0])
// Try to Shift+Tab
await press(shift(Keys.Tab))
// Verify it is still open
assertListboxButton({ state: ListboxState.Visible })
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
})
)
})
describe('`ArrowDown` key', () => {
it(
'should be possible to open the listbox with ArrowDown',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowDown)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
// Verify that the first listbox option is active
assertActiveListboxOption(options[0])
})
)
it(
'should not be possible to open the listbox with ArrowDown when the button is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} disabled>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Try to open the listbox
await press(Keys.ArrowDown)
// Verify it is still closed
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be possible to open the listbox with ArrowDown, and focus the selected option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value="b" on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowDown)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should have no active listbox option when there are no listbox options at all',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions />
</Listbox>
`);
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowDown)
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
assertNoActiveListboxOption()
})
)
it(
'should be possible to use ArrowDown to navigate the listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[0])
// We should be able to go down once
await press(Keys.ArrowDown)
assertActiveListboxOption(options[1])
// We should be able to go down again
await press(Keys.ArrowDown)
assertActiveListboxOption(options[2])
// We should NOT be able to go down again (because last option). Current implementation won't go around.
await press(Keys.ArrowDown)
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use ArrowDown to navigate the listbox options and skip the first disabled one',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[1])
// We should be able to go down once
await press(Keys.ArrowDown)
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use ArrowDown to navigate the listbox options and jump to the first non-disabled one',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[2])
})
)
})
describe('`ArrowRight` key', () => {
it(
'should be possible to use ArrowRight to navigate the listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} horizontal>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[0])
// We should be able to go right once
await press(Keys.ArrowRight)
assertActiveListboxOption(options[1])
// We should be able to go right again
await press(Keys.ArrowRight)
assertActiveListboxOption(options[2])
// We should NOT be able to go right again (because last option). Current implementation won't go around.
await press(Keys.ArrowRight)
assertActiveListboxOption(options[2])
})
)
})
describe('`ArrowUp` key', () => {
it(
'should be possible to open the listbox with ArrowUp and the last option should be active',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
// ! ALERT: The LAST option should now be active
assertActiveListboxOption(options[2])
})
)
it(
'should not be possible to open the listbox with ArrowUp and the last option should be active when the button is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} disabled>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Try to open the listbox
await press(Keys.ArrowUp)
// Verify it is still closed
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be possible to open the listbox with ArrowUp, and focus the selected option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value="b" on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should have no active listbox option when there are no listbox options at all',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions />
</Listbox>
`);
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
assertNoActiveListboxOption()
})
)
it(
'should be possible to use ArrowUp to navigate the listbox options and jump to the first non-disabled one',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[0])
})
)
it(
'should not be possible to navigate up or down if there is only a single non-disabled option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[2])
// We should not be able to go up (because those are disabled)
await press(Keys.ArrowUp)
assertActiveListboxOption(options[2])
// We should not be able to go down (because this is the last option)
await press(Keys.ArrowDown)
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use ArrowUp to navigate the listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[2])
// We should be able to go down once
await press(Keys.ArrowUp)
assertActiveListboxOption(options[1])
// We should be able to go down again
await press(Keys.ArrowUp)
assertActiveListboxOption(options[0])
// We should NOT be able to go up again (because first option). Current implementation won't go around.
await press(Keys.ArrowUp)
assertActiveListboxOption(options[0])
})
)
})
describe('`ArrowLeft` key', () => {
it(
'should be possible to use ArrowLeft to navigate the listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} horizontal>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
orientation: 'horizontal',
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
assertActiveListboxOption(options[2])
// We should be able to go left once
await press(Keys.ArrowLeft)
assertActiveListboxOption(options[1])
// We should be able to go left again
await press(Keys.ArrowLeft)
assertActiveListboxOption(options[0])
// We should NOT be able to go left again (because first option). Current implementation won't go around.
await press(Keys.ArrowLeft)
assertActiveListboxOption(options[0])
})
)
})
describe('`End` key', () => {
it(
'should be possible to use the End key to go to the last listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
let options = getListboxOptions()
// We should be on the first option
assertActiveListboxOption(options[0])
// We should be able to go to the last option
await press(Keys.End)
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use the End key to go to the last non disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
let options = getListboxOptions()
// We should be on the first option
assertActiveListboxOption(options[0])
// We should be able to go to the last non-disabled option
await press(Keys.End)
assertActiveListboxOption(options[1])
})
)
it(
'should be possible to use the End key to go to the first listbox option if that is the only non-disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.End)
let options = getListboxOptions()
assertActiveListboxOption(options[0])
})
)
it(
'should have no active listbox option upon End key press, when there are no non-disabled listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.End)
assertNoActiveListboxOption()
})
)
})
describe('`PageDown` key', () => {
it(
'should be possible to use the PageDown key to go to the last listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
let options = getListboxOptions()
// We should be on the first option
assertActiveListboxOption(options[0])
// We should be able to go to the last option
await press(Keys.PageDown)
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use the PageDown key to go to the last non disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.Enter)
let options = getListboxOptions()
// We should be on the first option
assertActiveListboxOption(options[0])
// We should be able to go to the last non-disabled option
await press(Keys.PageDown)
assertActiveListboxOption(options[1])
})
)
it(
'should be possible to use the PageDown key to go to the first listbox option if that is the only non-disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.PageDown)
let options = getListboxOptions()
assertActiveListboxOption(options[0])
})
)
it(
'should have no active listbox option upon PageDown key press, when there are no non-disabled listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.PageDown)
assertNoActiveListboxOption()
})
)
})
describe('`Home` key', () => {
it(
'should be possible to use the Home key to go to the first listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
let options = getListboxOptions()
// We should be on the last option
assertActiveListboxOption(options[2])
// We should be able to go to the first option
await press(Keys.Home)
assertActiveListboxOption(options[0])
})
)
it(
'should be possible to use the Home key to go to the first non disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
<ListboxOption value="d">Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.Home)
let options = getListboxOptions()
// We should be on the first non-disabled option
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use the Home key to go to the last listbox option if that is the only non-disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d">Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.Home)
let options = getListboxOptions()
assertActiveListboxOption(options[3])
})
)
it(
'should have no active listbox option upon Home key press, when there are no non-disabled listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.Home)
assertNoActiveListboxOption()
})
)
})
describe('`PageUp` key', () => {
it(
'should be possible to use the PageUp key to go to the first listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
let options = getListboxOptions()
// We should be on the last option
assertActiveListboxOption(options[2])
// We should be able to go to the first option
await press(Keys.PageUp)
assertActiveListboxOption(options[0])
})
)
it(
'should be possible to use the PageUp key to go to the first non disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
<ListboxOption value="d">Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.PageUp)
let options = getListboxOptions()
// We should be on the first non-disabled option
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to use the PageUp key to go to the last listbox option if that is the only non-disabled listbox option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d">Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.PageUp)
let options = getListboxOptions()
assertActiveListboxOption(options[3])
})
)
it(
'should have no active listbox option upon PageUp key press, when there are no non-disabled listbox options',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a" disabled>Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c" disabled>Option C</ListboxOption>
<ListboxOption value="d" disabled>Option D</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// We opened via click, we don't have an active option
assertNoActiveListboxOption()
// We should not be able to go to the end
await press(Keys.PageUp)
assertNoActiveListboxOption()
})
)
})
describe('`Any` key aka search', () => {
it(
'should be possible to type a full word that has a perfect match',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="alice">alice</ListboxOption>
<ListboxOption value="bob">bob</ListboxOption>
<ListboxOption value="charlie">charlie</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// We should be able to go to the second option
await type(word('bob'))
assertActiveListboxOption(options[1])
// We should be able to go to the first option
await type(word('alice'))
assertActiveListboxOption(options[0])
// We should be able to go to the last option
await type(word('charlie'))
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to type a partial of a word',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="alice">alice</ListboxOption>
<ListboxOption value="bob">bob</ListboxOption>
<ListboxOption value="charlie">charlie</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
let options = getListboxOptions()
// We should be on the last option
assertActiveListboxOption(options[2])
// We should be able to go to the second option
await type(word('bo'))
assertActiveListboxOption(options[1])
// We should be able to go to the first option
await type(word('ali'))
assertActiveListboxOption(options[0])
// We should be able to go to the last option
await type(word('char'))
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to type words with spaces',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">value a</ListboxOption>
<ListboxOption value="b">value b</ListboxOption>
<ListboxOption value="c">value c</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
let options = getListboxOptions()
// We should be on the last option
assertActiveListboxOption(options[2])
// We should be able to go to the second option
await type(word('value b'))
assertActiveListboxOption(options[1])
// We should be able to go to the first option
await type(word('value a'))
assertActiveListboxOption(options[0])
// We should be able to go to the last option
await type(word('value c'))
assertActiveListboxOption(options[2])
})
)
it(
'should not be possible to search for a disabled option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="alice">alice</ListboxOption>
<ListboxOption value="bob" disabled>bob</ListboxOption>
<ListboxOption value="charlie">charlie</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
let options = getListboxOptions()
// We should be on the last option
assertActiveListboxOption(options[2])
// We should not be able to go to the disabled option
await type(word('bo'))
// We should still be on the last option
assertActiveListboxOption(options[2])
})
)
it(
'should be possible to search for a word (case insensitive)',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="alice">alice</ListboxOption>
<ListboxOption value="bob">bob</ListboxOption>
<ListboxOption value="charlie">charlie</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Focus the button
getListboxButton()?.focus()
// Open listbox
await press(Keys.ArrowUp)
let options = getListboxOptions()
// We should be on the last option
assertActiveListboxOption(options[2])
// Search for bob in a different casing
await type(word('BO'))
// We should be on `bob`
assertActiveListboxOption(options[1])
})
)
it(
'should be possible to search for the next occurence',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">alice</ListboxOption>
<ListboxOption value="b">bob</ListboxOption>
<ListboxOption value="c">charlie</ListboxOption>
<ListboxOption value="d">bob</ListboxOption>
</ListboxOptions>
</Listbox>
`)
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// Search for bob
await type(word('b'))
// We should be on the first `bob`
assertActiveListboxOption(options[1])
// Search for bob again
await type(word('b'))
// We should be on the second `bob`
assertActiveListboxOption(options[3])
// Search for bob once again
await type(word('b'))
// We should be back on the first `bob`
assertActiveListboxOption(options[1])
})
)
})
})
describe('Mouse interactions', () => {
it(
'should focus the ListboxButton when we click the ListboxLabel',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxLabel>Label</ListboxLabel>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Ensure the button is not focused yet
assertActiveElement(document.body)
// Focus the label
await click(getListboxLabel())
// Ensure that the actual button is focused instead
assertActiveElement(getListboxButton())
})
)
it(
'should not focus the ListboxButton when we right click the ListboxLabel',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxLabel>Label</ListboxLabel>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Ensure the button is not focused yet
assertActiveElement(document.body)
// Focus the label
await click(getListboxLabel(), MouseButton.Right)
// Ensure that the body is still active
assertActiveElement(document.body)
})
)
it(
'should be possible to open the listbox on click',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open listbox
await click(getListboxButton())
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach(option => assertListboxOption(option))
})
)
it(
'should not be possible to open the listbox on right click',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Try to open the listbox
await click(getListboxButton(), MouseButton.Right)
// Verify it is still closed
assertListboxButton({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should not be possible to open the listbox on click when the button is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log} disabled>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Try to open the listbox
await click(getListboxButton())
// Verify it is still closed
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be possible to open the listbox on click, and focus the selected option',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value="b" on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
assertListboxButton({
state: ListboxState.InvisibleUnmounted,
attributes: { id: 'headlessui-listbox-button-1' },
})
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Open listbox
await click(getListboxButton())
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
assertListbox({
state: ListboxState.Visible,
attributes: { id: 'headlessui-listbox-options-2' },
})
assertActiveElement(getListbox())
assertListboxButtonLinkedWithListbox()
// Verify we have listbox options
let options = getListboxOptions()
expect(options).toHaveLength(3)
options.forEach((option, i) => assertListboxOption(option, { selected: i === 1 }))
// Verify that the second listbox option is active (because it is already selected)
assertActiveListboxOption(options[1])
})
)
it(
'should be possible to close a listbox on click',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
// Verify it is visible
assertListboxButton({ state: ListboxState.Visible })
// Click to close
await click(getListboxButton())
// Verify it is closed
assertListboxButton({ state: ListboxState.InvisibleUnmounted })
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be a no-op when we click outside of a closed listbox',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Verify that the window is closed
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Click something that is not related to the listbox
await click(document.body)
// Should still be closed
assertListbox({ state: ListboxState.InvisibleUnmounted })
})
)
it(
'should be possible to click outside of the listbox which should close the listbox',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
// Click something that is not related to the listbox
await click(document.body)
// Should be closed now
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Verify the button is focused again
assertActiveElement(getListboxButton())
})
)
it(
'should be possible to click outside of the listbox on another listbox button which should close the current listbox and open the new listbox',
suppressConsoleLogs(async () => {
render(svelte`
<div>
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
</div>
`)
let [button1, button2] = getListboxButtons()
// Click the first listbox button
await click(button1)
expect(getListboxes()).toHaveLength(1) // Only 1 listbox should be visible
// Ensure the open listbox is linked to the first button
assertListboxButtonLinkedWithListbox(button1, getListbox())
// Click the second listbox button
await click(button2)
expect(getListboxes()).toHaveLength(1) // Only 1 listbox should be visible
// Ensure the open listbox is linked to the second button
assertListboxButtonLinkedWithListbox(button2, getListbox())
})
)
it(
'should be possible to click outside of the listbox which should close the listbox (even if we press the listbox button)',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
// Click the listbox button again
await click(getListboxButton())
// Should be closed now
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Verify the button is focused again
assertActiveElement(getListboxButton())
})
)
// TODO: This test looks like it's for React-specific behavior (for some reason)
it.skip(
'should be possible to click outside of the listbox, on an element which is within a focusable element, which closes the listbox',
suppressConsoleLogs(async () => {
let focusFn = jest.fn()
render(svelte`
<div>
<Listbox value={undefined} on:change={console.log}>
<ListboxButton on:focus={focusFn}>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
<button id="btn">
<span>Next</span>
</button>
</div>
`)
// Click the listbox button
await click(getListboxButton())
// Ensure the listbox is open
assertListbox({ state: ListboxState.Visible })
// Click the span inside the button
await click(getByText('Next'))
// Ensure the listbox is closed
assertListbox({ state: ListboxState.InvisibleUnmounted })
// Ensure the outside button is focused
assertActiveElement(document.getElementById('btn'))
// Ensure that the focus button only got focus once (first click)
expect(focusFn).toHaveBeenCalledTimes(1)
})
)
it(
'should be possible to hover an option and make it active',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// We should be able to go to the second option
await mouseMove(options[1])
assertActiveListboxOption(options[1])
// We should be able to go to the first option
await mouseMove(options[0])
assertActiveListboxOption(options[0])
// We should be able to go to the last option
await mouseMove(options[2])
assertActiveListboxOption(options[2])
})
)
it(
'should make a listbox option active when you move the mouse over it',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// We should be able to go to the second option
await mouseMove(options[1])
assertActiveListboxOption(options[1])
})
)
it(
'should be a no-op when we move the mouse and the listbox option is already active',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// We should be able to go to the second option
await mouseMove(options[1])
assertActiveListboxOption(options[1])
await mouseMove(options[1])
// Nothing should be changed
assertActiveListboxOption(options[1])
})
)
it(
'should be a no-op when we move the mouse and the listbox option is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
await mouseMove(options[1])
assertNoActiveListboxOption()
})
)
it(
'should not be possible to hover an option that is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// Try to hover over option 1, which is disabled
await mouseMove(options[1])
// We should not have an active option now
assertNoActiveListboxOption()
})
)
it(
'should be possible to mouse leave an option and make it inactive',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// We should be able to go to the second option
await mouseMove(options[1])
assertActiveListboxOption(options[1])
await mouseLeave(options[1])
assertNoActiveListboxOption()
// We should be able to go to the first option
await mouseMove(options[0])
assertActiveListboxOption(options[0])
await mouseLeave(options[0])
assertNoActiveListboxOption()
// We should be able to go to the last option
await mouseMove(options[2])
assertActiveListboxOption(options[2])
await mouseLeave(options[2])
assertNoActiveListboxOption()
})
)
it(
'should be possible to mouse leave a disabled option and be a no-op',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
let options = getListboxOptions()
// Try to hover over option 1, which is disabled
await mouseMove(options[1])
assertNoActiveListboxOption()
await mouseLeave(options[1])
assertNoActiveListboxOption()
})
)
it(
'should be possible to click a listbox option, which closes the listbox',
suppressConsoleLogs(async () => {
let handleChange = jest.fn()
let value = writable();
render(svelte`
<Listbox value={$value} on:change={(e) => { value.set(e.detail); handleChange(e.detail) } }>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
let options = getListboxOptions()
// We should be able to click the first option
await click(options[1])
assertListbox({ state: ListboxState.InvisibleUnmounted })
expect(handleChange).toHaveBeenCalledTimes(1)
expect(handleChange).toHaveBeenCalledWith('b')
// Verify the button is focused again
assertActiveElement(getListboxButton())
// Open listbox again
await click(getListboxButton())
// Verify the active option is the previously selected one
assertActiveListboxOption(getListboxOptions()[1])
})
)
it(
'should be possible to click a disabled listbox option, which is a no-op',
suppressConsoleLogs(async () => {
let handleChange = jest.fn()
let value = writable();
render(svelte`
<Listbox value={$value} on:change={(e) => { value.set(e.detail); handleChange(e.detail) } }>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
let options = getListboxOptions()
// We should be able to click the first option
await click(options[1])
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
expect(handleChange).toHaveBeenCalledTimes(0)
// Close the listbox
await click(getListboxButton())
// Open listbox again
await click(getListboxButton())
// Verify the active option is non existing
assertNoActiveListboxOption()
})
)
it(
'should be possible focus a listbox option, so that it becomes active',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b">Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
let options = getListboxOptions()
// Verify that nothing is active yet
assertNoActiveListboxOption()
// We should be able to focus the first option
await focus(options[1])
assertActiveListboxOption(options[1])
})
)
it(
'should not be possible to focus a listbox option which is disabled',
suppressConsoleLogs(async () => {
render(svelte`
<Listbox value={undefined} on:change={console.log}>
<ListboxButton>Trigger</ListboxButton>
<ListboxOptions>
<ListboxOption value="a">Option A</ListboxOption>
<ListboxOption value="b" disabled>Option B</ListboxOption>
<ListboxOption value="c">Option C</ListboxOption>
</ListboxOptions>
</Listbox>
`);
// Open listbox
await click(getListboxButton())
assertListbox({ state: ListboxState.Visible })
assertActiveElement(getListbox())
let options = getListboxOptions()
// We should not be able to focus the first option
await focus(options[1])
assertNoActiveListboxOption()
})
)
}) | the_stack |
import Nibbles from './Nibbles';
import NodeBase from './NodeBase';
import { BranchNode, BranchKeys } from './BranchNode';
import ExtensionNode from './ExtensionNode';
import LeafNode from './LeafNode';
import ProofData from './ProofData';
import assert = require('assert');
import ethUtil = require('ethereumjs-util');
import rlp = require('rlp');
import crypto = require('crypto');
const FuzzyProofGenerator = {
/** Generates a proof data. */
generateByPattern(
pattern: string,
pathMaxLength: number = 32,
valueMaxLength: number = 32,
): ProofData {
assert(pathMaxLength >= 1);
assert(valueMaxLength >= 1);
this.assertPatternValidity(pattern);
const pathMinLength: number = Math.ceil(pattern.length / 2);
assert(pathMaxLength >= pathMinLength);
const pathLength: number = pathMinLength + Math.floor(
Math.random() * (pathMaxLength - pathMinLength + 1),
);
assert(pathLength <= pathMaxLength);
assert(pathLength >= pathMinLength);
const path: Buffer = crypto.randomBytes(pathLength);
const valueLength = 1 + Math.floor(Math.random() * valueMaxLength);
assert(valueLength <= valueMaxLength);
assert(valueLength >= 1);
const value: Buffer = crypto.randomBytes(valueLength);
return this.generate(pattern, path, value);
},
/** Generates a proof data. */
generate(pattern: string, path: Buffer, value: Buffer): ProofData {
this.assertPatternValidity(pattern);
const endingWithBranchNode: boolean = (pattern[pattern.length - 1] === 'b');
const nibblePath: Buffer = Nibbles.toNibbles(path);
Nibbles.assertNibbleArray(nibblePath);
// If a pattern ends with a branch node, that branch node is not going
// to contain any nibble from the pattern and only value.
assert(nibblePath.length >= pattern.length - (endingWithBranchNode ? 1 : 0));
const rlpValue: Buffer = rlp.encode(value);
const valueHash: Buffer = ethUtil.keccak256(value);
const rlpValuehash: Buffer = ethUtil.keccak256(rlpValue);
const pathData: Buffer[] = this.generateRandomPathData(
(endingWithBranchNode ? pattern.substring(0, pattern.length - 1) : pattern),
nibblePath,
);
// If a pattern ends with a branch node, that branch node is not going
// to contain any nibble from the pattern and only value. That's why
// during generation of path sections according to the pattern ending
// branch node is not counted and we add an empty Buffer representing
// ending branch node path section.
if (endingWithBranchNode) {
pathData.push(Buffer.from([]));
}
const branchesKeysData: BranchKeys[] = this.generateRandomBranchesKeysData(
pattern.split('b').length - 1,
);
const nodes: NodeBase[] = this.createNodes(
pattern,
value,
pathData,
branchesKeysData,
);
assert(nodes.length === pattern.length);
const rlpParentNodesArray: Buffer[][] = [];
nodes.forEach((n): void => {
rlpParentNodesArray.push(n.raw());
});
const proofData = {
pattern,
value: (endingWithBranchNode ? rlpValuehash : valueHash),
encodedPath: path,
rlpParentNodes: rlp.encode(rlpParentNodesArray),
root: nodes[0].hash(),
};
return proofData;
},
/** Asserts a pattern validity by traversing through state machine. */
assertPatternValidity(pattern: string): void {
if (pattern.length === 0) {
throw new Error('The pattern is empty.');
}
switch (pattern[0]) {
case 'b': {
this.processBranch(pattern, 1);
break;
}
case 'e': {
this.processExtension(pattern, 1);
break;
}
case 'l': {
this.processLeaf(pattern, 1);
break;
}
default: {
throw new Error(`An unexpected symbol (${pattern[0]}) in the pattern.`);
}
}
},
processLeaf(pattern: string, index: number): void {
if (index !== pattern.length) {
throw new Error('Pattern does not end with leaf node.');
}
},
processBranch(pattern: string, index: number): void {
if (index === pattern.length) {
if (pattern.length === 1 || pattern[index - 2] !== 'b') {
// The verification library we are using in our project would accept
// as a valid proof only a path ending with double 'b' (putting aside
// an ending leaf node, as it's always allowed).
throw new Error('Pattern can end with double branch node only.');
}
return;
}
switch (pattern[index]) {
case 'b': {
this.processBranch(pattern, index + 1);
break;
}
case 'e': {
this.processExtension(pattern, index + 1);
break;
}
case 'l': {
this.processLeaf(pattern, index + 1);
break;
}
default: {
throw new Error(`An unexpected symbol (${pattern[index]}) in the pattern.`);
}
}
},
processExtension(pattern: string, index: number): void {
if (pattern.length === index) {
throw new Error('Pattern ends with an extension node.');
}
switch (pattern[index]) {
case 'b': {
this.processBranch(pattern, index + 1);
break;
}
case 'e': {
throw new Error('Pattern contains two consecutive extension nodes.');
}
case 'l': {
throw new Error('Pattern contains a leaf node after an extension node.');
}
default: {
throw new Error(`An unexpected symbol (${pattern[index]}) in the pattern.`);
}
}
},
/**
* Divides a path into a random consecutive sections according to the
* specified pattern.
*/
generateRandomPathData(
pattern: string,
nibblePath: Buffer,
): Buffer[] {
assert(pattern.length > 0);
assert(nibblePath.length >= pattern.length);
// "numberCount" variable below is the count of extension and leaf nodes
// in the pattern.
const numberCount: number = pattern.length
- (pattern.split('b').length - 1);
// Each node in the pattern is going to use at least one nibble.
// Hence, we are calculating nibbles' amount, left after subtracting
// nibbles path's length from pattern's length.
// Variable is named "sum", as in the next step, we will randomly choose
// numbers ("numberCount" is the count of numbers) that sum up to "sum".
const sum: number = nibblePath.length - pattern.length;
// Generates non-negative numbers that sum up to "sum".
const randomNumbers: number[] = this.generateRandomNumbers(sum, numberCount);
// Numbers generated above, were non-negative numbers (includes 0)
// that sum up to "sum", which was calculated by taking out pattern length.
const pathSectionsLengths: number[] = randomNumbers.map(x => x + 1);
const pathData = this.generatePathData(
pattern,
nibblePath,
pathSectionsLengths,
);
return pathData;
},
/**
* Divides a path into a consecutive sections according to the
* specified pattern and lengths parameter.
*/
generatePathData(
pattern: string,
nibblePath: Buffer,
pathSectionsLengths: number[],
): Buffer[] {
assert(pattern.length !== 0);
assert(nibblePath.length >= pattern.length);
const pathData: Buffer[] = [];
let pathSectionsIndex = 0;
let nibblePathIndex = 0;
for (let i = 0; i < pattern.length; i += 1) {
assert(nibblePathIndex < nibblePath.length);
switch (pattern[i]) {
case 'b': {
pathData.push(nibblePath.slice(nibblePathIndex, nibblePathIndex + 1));
nibblePathIndex += 1;
break;
}
case 'e':
case 'l': {
assert(pathSectionsIndex < pathSectionsLengths.length);
pathData.push(
nibblePath.slice(
nibblePathIndex,
nibblePathIndex + pathSectionsLengths[pathSectionsIndex],
),
);
nibblePathIndex += (pathSectionsLengths[pathSectionsIndex]);
pathSectionsIndex += 1;
break;
}
default: {
throw new Error(`An unexpected symbol (${pattern[0]}) in the pattern.`);
}
}
}
assert(nibblePathIndex === nibblePath.length);
assert(pathSectionsIndex === pathSectionsLengths.length);
assert.deepEqual(
pathData.reduce((acc: Buffer, val: Buffer): Buffer => Buffer.concat([acc, val])),
nibblePath,
);
return pathData;
},
/**
* Generates random non-negative numbers that sum to the specified value.
*
* @remarks:
* See: https://math.stackexchange.com/questions/1276206/method-of-generating-random-numbers-that-sum-to-100-is-this-truly-random
* See: https://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29
*/
generateRandomNumbers(sum: number, numberCount: number): number[] {
assert(sum >= 0);
assert(numberCount >= 0);
if (numberCount === 0) {
return [];
}
if (numberCount === 1) {
return [sum];
}
const lowerBoundInclusive = 1;
const upperBoundInclusive = sum + numberCount - 1;
const pickedRandoms: number[] = [];
for (let i = 0; i < numberCount - 1; i += 1) {
let x = -1;
do {
x = lowerBoundInclusive + Math.floor(Math.random() * upperBoundInclusive);
} while (pickedRandoms.includes(x));
pickedRandoms.push(x);
}
assert(pickedRandoms.length === numberCount - 1);
pickedRandoms.forEach(
(el: number): void => assert(el >= lowerBoundInclusive && el <= upperBoundInclusive),
);
pickedRandoms.sort((a: number, b: number): number => a - b);
const generatedRandoms: number[] = [];
generatedRandoms.push(pickedRandoms[0] - 1);
for (let i = 1; i < numberCount - 1; i += 1) {
generatedRandoms.push(pickedRandoms[i] - pickedRandoms[i - 1] - 1);
}
generatedRandoms.push(upperBoundInclusive - pickedRandoms[pickedRandoms.length - 1]);
generatedRandoms.forEach(
(el: number): void => assert(el >= 0),
);
assert(generatedRandoms.length === numberCount);
assert(generatedRandoms.reduce((a, b): number => a + b) === sum);
return generatedRandoms;
},
/**
* Generates an array of branch nodes with random values for keys.
*
* @param branchNodeAmount An amount of branch nodes to generate data for.
*/
generateRandomBranchesKeysData(branchNodeAmount: number): BranchKeys[] {
assert(branchNodeAmount >= 0);
const branchesKeysData: BranchKeys[] = [];
for (let i = 0; i < branchNodeAmount; i += 1) {
branchesKeysData.push(this.generateRandomBranchKeysData());
}
return branchesKeysData;
},
/**
* Generates a branch node with random values for keys.
* First, function generates random number between 0 and 16 (max amount of
* keys for a branch node). Afterwards, generates a random index for each
* key and random value to be stored in that index.
*/
generateRandomBranchKeysData(): Buffer[] {
const branchKeysData: Buffer[] = new Array<Buffer>(16);
branchKeysData.fill(Buffer.from([]));
const amount: number = Math.floor(Math.random() * 16);
assert(amount >= 0 && amount < 16);
const indexes: number[] = [];
for (let i = 0; i < amount; i += 1) {
let x = -1;
do {
x = Math.floor(Math.random() * 16);
assert(x >= 0 && x < 16);
} while (indexes.includes(x));
indexes.push(x);
}
assert(indexes.length === amount);
for (let i = 0; i < indexes.length; i += 1) {
assert(indexes[i] >= 0 && indexes[i] < 16);
branchKeysData[indexes[i]] = this.generateRandomKeccak256();
}
return branchKeysData;
},
/**
* Creates nodes.
*
* Creates nodes bottom up by passing a previous node hash up by stack.
*
* @param pattern A pattern for a path.
* @param value A value to store in an ending node (either leaf or branch node).
* @param nibblePathData A buffer array containing the path segment for each node.
* @param branchKeysData A buffer array containing the keys for each branch node.
*/
createNodes(
pattern: string,
value: Buffer,
nibblePathData: Buffer[],
branchKeysData: BranchKeys[],
): NodeBase[] {
assert(pattern.length !== 0);
assert(value.length !== 0);
assert(nibblePathData.length !== 0);
assert(pattern.length === nibblePathData.length);
this.assertPatternValidity(pattern);
const nodes: NodeBase[] = [];
let previousNodeHash: Buffer = Buffer.from([]);
let branchKeysDataIndex = 0;
for (let i: number = pattern.length - 1; i >= 0; i -= 1) {
switch (pattern[i]) {
case 'l': {
assert(i === pattern.length - 1);
assert(previousNodeHash.length === 0);
assert(nibblePathData[i].length >= 1);
const ln = new LeafNode(nibblePathData[i], value);
previousNodeHash = ln.hash();
nodes.push(ln);
break;
}
case 'e': {
assert(previousNodeHash.length !== 0);
assert(nibblePathData[i].length >= 1);
const en = new ExtensionNode(nibblePathData[i], previousNodeHash);
previousNodeHash = en.hash();
nodes.push(en);
break;
}
case 'b': {
assert(branchKeysDataIndex < branchKeysData.length);
if (i === pattern.length - 1) {
assert(nibblePathData[i].length === 0);
const bn = new BranchNode(branchKeysData[branchKeysDataIndex], value);
branchKeysDataIndex += 1;
previousNodeHash = bn.hash();
nodes.push(bn);
} else {
assert(nibblePathData[i].length === 1);
assert(nibblePathData[i][0] >= 0 && nibblePathData[i][0] <= 15);
const bks: Buffer[] = branchKeysData[branchKeysDataIndex];
bks[nibblePathData[i][0]] = previousNodeHash;
const bn = new BranchNode(bks, Buffer.alloc(0));
branchKeysDataIndex += 1;
previousNodeHash = bn.hash();
nodes.push(bn);
}
break;
}
default: {
throw new Error(`An unexpected symbol (${pattern[0]}) in the pattern.`);
}
}
}
assert(branchKeysDataIndex === branchKeysData.length);
nodes.reverse();
return nodes;
},
/** Generates random keccak256 value. */
generateRandomKeccak256(): Buffer {
return ethUtil.keccak256(
crypto.randomBytes(256),
);
},
};
export { FuzzyProofGenerator as default }; | the_stack |
import { mapSchema } from "../MappedSchema";
import { graphql, GraphQLString } from "graphql";
import { OperationType } from "../operation-types";
import { types } from "../universal";
describe("Adhoc operations", () => {
test("custom operation without args", async () => {
// @snippet:start AdhocOperation_withoutArgs
const customOperation = {
operationType: OperationType.Query,
name: "printHello",
fieldConfig: {
type: GraphQLString,
description: "Prints hello",
resolve: () => {
return "hello";
},
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
const result = await graphql(
schema,
`
query {
printHello
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"printHello": "hello",
},
}
`);
});
test("custom operations with args", async () => {
// @snippet:start AdhocOperation_withArgs
const customOperation = {
operationType: OperationType.Query,
name: "printGreeting",
fieldConfig: {
type: GraphQLString,
args: {
name: {
type: GraphQLString,
},
},
description: "Prints hello",
resolve: (_obj: any, args: { name: string }) => {
return `hello ${args.name}`;
},
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
const result = await graphql(
schema,
`
query {
printGreeting(name: "Lorefnon")
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"printGreeting": "hello Lorefnon",
},
}
`);
});
test("custom operations with args and default values", async () => {
// @snippet:start AdhocOperation_withDefaultArgs
const customOperation = {
operationType: OperationType.Query,
name: "printGreeting",
fieldConfig: {
type: GraphQLString,
args: {
name: {
type: GraphQLString,
defaultValue: "Lorefnon",
},
},
description: "Prints hello",
resolve: (_obj: any, args: { name: string }) => {
return `hello ${args.name}`;
},
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
const result = await graphql(
schema,
`
query {
greetSpecific: printGreeting(name: "John")
greetDefault: printGreeting
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"greetDefault": "hello Lorefnon",
"greetSpecific": "hello John",
},
}
`);
});
test("Custom query operation with types specified through io-ts", async () => {
// @snippet:start AdhocQueryOperation_iots
const OrderDetailTypeSpec = types.object("OrderDetail", {
orderId: types.number,
purchasedAt: types.isoDate,
purchasedBy: types.array(
types.object("OrderDetailPurchaser", {
customerId: types.number,
name: types.string,
}),
),
});
type OrderDetail = typeof OrderDetailTypeSpec["Type"];
const customOperation = {
operationType: OperationType.Query,
name: "orderDetails",
fieldConfig: {
type: OrderDetailTypeSpec.graphQLOutputType,
args: {
orderId: {
type: types.number.graphQLInputType,
},
},
description: "Prints hello",
resolve: (_parent: any, args: { orderId: number }): OrderDetail => ({
orderId: args.orderId,
purchasedAt: new Date("2020-01-01"),
purchasedBy: [
{
customerId: 1,
name: "John Doe",
},
{
customerId: 2,
name: "Jane Doe",
},
],
}),
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
// @snippet:start AdhocQueryOperation_iots_schema_introspection_query
const introspectionResult = await graphql(
schema,
`
query {
__schema {
types {
name
fields {
name
type {
name
}
}
}
}
}
`,
);
// @snippet:end
// @snippet:start AdhocQueryOperation_iots_schema_introspection_query_result
expect(introspectionResult).toMatchInlineSnapshot(`
Object {
"data": Object {
"__schema": Object {
"types": Array [
Object {
"fields": Array [
Object {
"name": "orderDetails",
"type": Object {
"name": "OrderDetail",
},
},
],
"name": "query",
},
Object {
"fields": Array [
Object {
"name": "orderId",
"type": Object {
"name": "Float",
},
},
Object {
"name": "purchasedAt",
"type": Object {
"name": "Date",
},
},
Object {
"name": "purchasedBy",
"type": Object {
"name": null,
},
},
],
"name": "OrderDetail",
},
Object {
"fields": null,
"name": "Float",
},
Object {
"fields": null,
"name": "Date",
},
Object {
"fields": Array [
Object {
"name": "customerId",
"type": Object {
"name": "Float",
},
},
Object {
"name": "name",
"type": Object {
"name": "String",
},
},
],
"name": "OrderDetailPurchaser",
},
Object {
"fields": null,
"name": "String",
},
Object {
"fields": null,
"name": "Boolean",
},
Object {
"fields": Array [
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "types",
"type": Object {
"name": null,
},
},
Object {
"name": "queryType",
"type": Object {
"name": null,
},
},
Object {
"name": "mutationType",
"type": Object {
"name": "__Type",
},
},
Object {
"name": "subscriptionType",
"type": Object {
"name": "__Type",
},
},
Object {
"name": "directives",
"type": Object {
"name": null,
},
},
],
"name": "__Schema",
},
Object {
"fields": Array [
Object {
"name": "kind",
"type": Object {
"name": null,
},
},
Object {
"name": "name",
"type": Object {
"name": "String",
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "fields",
"type": Object {
"name": null,
},
},
Object {
"name": "interfaces",
"type": Object {
"name": null,
},
},
Object {
"name": "possibleTypes",
"type": Object {
"name": null,
},
},
Object {
"name": "enumValues",
"type": Object {
"name": null,
},
},
Object {
"name": "inputFields",
"type": Object {
"name": null,
},
},
Object {
"name": "ofType",
"type": Object {
"name": "__Type",
},
},
],
"name": "__Type",
},
Object {
"fields": null,
"name": "__TypeKind",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "args",
"type": Object {
"name": null,
},
},
Object {
"name": "type",
"type": Object {
"name": null,
},
},
Object {
"name": "isDeprecated",
"type": Object {
"name": null,
},
},
Object {
"name": "deprecationReason",
"type": Object {
"name": "String",
},
},
],
"name": "__Field",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "type",
"type": Object {
"name": null,
},
},
Object {
"name": "defaultValue",
"type": Object {
"name": "String",
},
},
],
"name": "__InputValue",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "isDeprecated",
"type": Object {
"name": null,
},
},
Object {
"name": "deprecationReason",
"type": Object {
"name": "String",
},
},
],
"name": "__EnumValue",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "isRepeatable",
"type": Object {
"name": null,
},
},
Object {
"name": "locations",
"type": Object {
"name": null,
},
},
Object {
"name": "args",
"type": Object {
"name": null,
},
},
],
"name": "__Directive",
},
Object {
"fields": null,
"name": "__DirectiveLocation",
},
],
},
},
}
`);
// @snippet:end
const result = await graphql(
schema,
`
query {
orderDetails(orderId: 1) {
orderId
purchasedAt
purchasedBy {
customerId
name
}
}
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"orderDetails": Object {
"orderId": 1,
"purchasedAt": "2020-01-01",
"purchasedBy": Array [
Object {
"customerId": 1,
"name": "John Doe",
},
Object {
"customerId": 2,
"name": "Jane Doe",
},
],
},
},
}
`);
});
}); | the_stack |
const stubbedRPCServiceConstructor = jest.fn()
const stubbedWalletsServiceConstructor = jest.fn()
const stubbedGetLiveCell = jest.fn()
const stubbedGetTransaction = jest.fn()
const stubbedGetBlockByNumber = jest.fn()
const stubbedGetHeaderByNumber = jest.fn()
const stubbedGetHeader = jest.fn()
const stubbedSendTransaction = jest.fn()
const stubbedCalculateDaoMaximumWithdraw = jest.fn()
const stubbedGetNextAddress = jest.fn()
const stubbedGetNextChangeAddress = jest.fn()
const stubbedGetWallet = jest.fn()
const stubbedGetCurrentWallet = jest.fn()
const stubbedStartWithdrawFromDao = jest.fn()
const stubbedGenerateDepositTx = jest.fn()
const stubbedGenerateSendingAllTx = jest.fn()
const stubbedGenerateTx = jest.fn()
const stubbedSaveWithSentTx = jest.fn()
const stubbedCheckAndGenerateAddresses = jest.fn()
const stubbedGenerateDepositAllTx = jest.fn()
const stubbedGenerateWithdrawMultiSignTx = jest.fn()
const resetMocks = () => {
stubbedGetLiveCell.mockReset()
stubbedGetTransaction.mockReset()
stubbedGetBlockByNumber.mockReset()
stubbedGetHeaderByNumber.mockReset()
stubbedGetHeader.mockReset()
stubbedSendTransaction.mockReset()
stubbedCalculateDaoMaximumWithdraw.mockReset()
stubbedGetNextAddress.mockReset()
stubbedGetNextChangeAddress.mockReset()
stubbedGetWallet.mockReset()
stubbedGetCurrentWallet.mockReset()
stubbedStartWithdrawFromDao.mockReset()
stubbedGenerateDepositTx.mockReset()
stubbedGenerateSendingAllTx.mockReset()
stubbedGenerateTx.mockReset()
stubbedSaveWithSentTx.mockReset()
stubbedCheckAndGenerateAddresses.mockReset()
stubbedGenerateDepositAllTx.mockReset()
stubbedGenerateWithdrawMultiSignTx.mockReset()
}
stubbedRPCServiceConstructor.mockImplementation(
() => ({
getLiveCell: stubbedGetLiveCell,
getTransaction: stubbedGetTransaction,
getBlockByNumber: stubbedGetBlockByNumber,
getHeaderByNumber: stubbedGetHeaderByNumber,
getHeader: stubbedGetHeader,
})
)
stubbedWalletsServiceConstructor.mockImplementation(
() => ({
get: stubbedGetWallet,
isHardware: () => false
})
)
//@ts-ignore
stubbedWalletsServiceConstructor.getInstance = () => ({
get: stubbedGetWallet,
getCurrent: stubbedGetCurrentWallet
})
jest.doMock('services/rpc-service', () => {
return stubbedRPCServiceConstructor
});
jest.doMock('services/wallets', () => {
return stubbedWalletsServiceConstructor
});
jest.doMock('services/tx/transaction-generator', () => {
return {
TransactionGenerator: {
startWithdrawFromDao: stubbedStartWithdrawFromDao,
generateDepositTx: stubbedGenerateDepositTx,
generateSendingAllTx: stubbedGenerateSendingAllTx,
generateTx: stubbedGenerateTx,
generateDepositAllTx: stubbedGenerateDepositAllTx,
generateWithdrawMultiSignTx: stubbedGenerateWithdrawMultiSignTx,
}
}
});
jest.doMock('services/tx/transaction-persistor', () => {
return {
TransactionPersistor: {
saveSentTx: stubbedSaveWithSentTx
}
}
});
import Transaction from '../../../src/models/chain/transaction'
import TxStatus from '../../../src/models/chain/tx-status'
import CellDep, { DepType } from '../../../src/models/chain/cell-dep'
import OutPoint from '../../../src/models/chain/out-point'
import Input from '../../../src/models/chain/input'
import Script, { ScriptHashType } from '../../../src/models/chain/script'
import Output from '../../../src/models/chain/output'
import Keystore from '../../../src/models/keys/keystore'
import { AddressType } from '../../../src/models/keys/address'
import WitnessArgs from '../../../src/models/chain/witness-args'
import CellWithStatus from '../../../src/models/chain/cell-with-status'
import SystemScriptInfo from '../../../src/models/system-script-info'
import NodeService from '../../../src/services/node'
import AssetAccountInfo from '../../../src/models/asset-account-info'
import { CapacityNotEnoughForChange, CapacityNotEnoughForChangeByTransfer } from '../../../src/exceptions/wallet'
const TransactionSender = require('../../../src/services/transaction-sender').default
const fakeScript = new Script(
'0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8',
'0x36c329ed630d6ce750712a477543672adab57f4c',
ScriptHashType.Type
)
const generateTxWithStatus = (
id: string,
block: any,
lock: Script = fakeScript,
type: Script | undefined,
outputsData: string[] | undefined
) => {
const inputs = [
Input.fromObject({
previousOutput: new OutPoint('0x' + (parseInt(id) - 1).toString().repeat(64), '0'),
since: '',
lock: fakeScript
})
]
const outputs = [
Output.fromObject({
capacity: '1',
lock,
type
})
]
return {
transaction: Transaction.fromObject({
version: '1',
hash: '0x' + id.repeat(64),
blockNumber: block.number,
timestamp: block.timestamp.toString(),
inputs,
outputs,
outputsData
}),
txStatus: TxStatus.fromSDK({status: 'committed', blockHash: block.hash})
}
}
describe('TransactionSender Test', () => {
const transactionSender = new TransactionSender()
const fakeBlock1 = {number: '1', hash: '0x' + '0'.repeat(64), timestamp: '1'}
const fakeTx1 = generateTxWithStatus(
'1',
fakeBlock1,
undefined,
SystemScriptInfo.generateDaoScript(),
['0x0000000000000000'],
)
const fakeWallet = {
name: 'wallet-test1',
id: '11',
extendedKey: 'a',
keystore: new Keystore(
{
cipher: 'wallet1',
cipherparams: { iv: 'wallet1' },
ciphertext: 'wallet1',
kdf: '1',
kdfparams: {
dklen: 1,
n: 1,
r: 1,
p: 1,
salt: '1',
},
mac: '1',
},
'0'
),
isHardware: () => false,
getNextAddress: stubbedGetNextAddress,
getNextChangeAddress: stubbedGetNextChangeAddress,
checkAndGenerateAddresses: stubbedCheckAndGenerateAddresses,
}
const fakeCellWithStatus = CellWithStatus.fromSDK({
'cell': {
'output': {
'capacity': '10200000000',
'lock': {
'args': '0x61c928dedf2afc8cb434c1af311a29cbb16f7076',
'codeHash': '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8',
'hashType': 'type'
},
'type': {
'args': '0x',
'codeHash': '0x82d76d1b75fe2fd9a27dfbaa65a039221a380d76c926f378d3f81cf3e7e13f2e',
'hashType': 'type'
},
},
'data': {
'content': '0x6400000000000000',
'hash': '0xa731cac6893c41dba273a301c57e5bd2cf88dbcf8e1ddd39961b97dd0b710822'
}
},
'status': 'live' as CKBComponents.CellStatus,
})
const fakeAddress1 = 'ckt1qyqrdsefa43s6m882pcj53m4gdnj4k440axqswmu83'
const fakeAddress2 = 'ckt1qyqrdsefa43s6m882pcj53m4gdnj4k440axqswmu82'
beforeEach(async () => {
resetMocks()
stubbedGetWallet.mockReturnValue(fakeWallet)
//@ts-ignore
NodeService.getInstance().ckb.rpc = {
calculateDaoMaximumWithdraw: stubbedCalculateDaoMaximumWithdraw,
sendTransaction: stubbedSendTransaction
}
})
describe('sign', () => {
const pathAndPrivateKey = {
path: `m/44'/309'/0'/0/0`,
privateKey: '0xe79f3207ea4980b7fed79956d5934249ceac4751a4fae01a0f7c4a96884bc4e3'
}
const mockGetPk = jest.fn()
mockGetPk.mockReturnValue([pathAndPrivateKey])
transactionSender.getPrivateKeys = mockGetPk.bind(transactionSender)
const addr = {
walletId: fakeWallet.id,
address: '',
path: `m/44'/309'/0'/0/0`,
addressType: AddressType.Receiving,
addressIndex: 1,
txCount: 0,
liveBalance: '0',
sentBalance: '0',
pendingBalance: '0',
balance: '0',
blake160: "0x36c329ed630d6ce750712a477543672adab57f4c",
version: 'testnet'
}
const mockGAI = jest.fn()
mockGAI.mockReturnValue([addr])
transactionSender.getAddressInfos = mockGAI.bind(transactionSender)
describe('#sign', () => {
describe('single sign', () => {
const tx = Transaction .fromObject({
"version": "0x0",
"cellDeps": [
CellDep.fromObject({
"outPoint": OutPoint.fromObject({
"txHash": "0x0d9c4af3dd158d6359c9d25d0a600f1dd20b86072b85a095e7bc70c34509b73d",
"index": "0x0"
}),
"depType": "depGroup" as DepType
})
],
"headerDeps": [],
"inputs": [
Input.fromObject({
"previousOutput": OutPoint.fromObject({
"txHash": "0x1879851943fa686af29bed5c95acd566d0244e7b3ca89cf7c435622a5a5b4cb3",
"index": "0x0"
}),
"since": "0x0",
"lock": Script.fromObject({
"args": "0x36c329ed630d6ce750712a477543672adab57f4c",
"codeHash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
"hashType": "type" as ScriptHashType
})
})
],
"outputs": [
Output.fromObject({
"capacity": "0x174876e800",
"lock": Script.fromObject({
"codeHash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
"args": "0xe2193df51d78411601796b35b17b4f8f2cd85bd0",
"hashType": "type" as ScriptHashType
}),
"type": null
}),
Output.fromObject({
"capacity": "0x12319d9962f4",
"lock": Script.fromObject({
"codeHash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
"args": "0x36c329ed630d6ce750712a477543672adab57f4c",
"hashType": "type" as ScriptHashType
}),
"type": null
})
],
"outputsData": [
"0x",
"0x"
],
"witnesses": [
"0x55000000100000005500000055000000410000003965f54cc684d35d886358ad57214e5f4a5fd13ecc7aba67950495b9be7740267a1d6bb14f1c215e3bc926f9655648b75e173ce6f5fd1e60218383b45503c30301"
],
"hash": "0x230ab250ee0ae681e88e462102e5c01a9994ac82bf0effbfb58d6c11a86579f1"
})
it('success', async () => {
// @ts-ignore: Private method
const ntx = await transactionSender.sign(fakeWallet.id, tx, '1234')
expect(ntx.witnesses[0]).toEqual(tx.witnesses[0])
})
})
describe('multi sign with since', () => {
const tx = Transaction .fromObject({
"version": "0x0",
"cellDeps": [
CellDep.fromObject({
"outPoint": OutPoint.fromObject({
"txHash": "0x0d9c4af3dd158d6359c9d25d0a600f1dd20b86072b85a095e7bc70c34509b73d",
"index": "0x1"
}),
"depType": "depGroup" as DepType
})
],
"headerDeps": [],
"inputs": [
Input.fromObject({
"previousOutput": OutPoint.fromSDK({
"txHash": "0xf1181e7d0ef95fa2e6c334f6aa647520a898d9f8259a2bb021a622434bc73a63",
"index": "0x0"
}),
"since": "0x2000f00078000002",
"lock": Script.fromObject({
// "args": "0x36c329ed630d6ce750712a477543672adab57f4c",
"args": "0x56f281b3d4bb5fc73c751714af0bf78eb8aba0d80200007800f00020",
"codeHash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
"hashType": "type" as ScriptHashType
})
})
],
"outputs": [
Output.fromObject({
"capacity": "0xd18c2e2800",
"lock": Script.fromObject({
"codeHash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",
"args": "0x36c329ed630d6ce750712a477543672adab57f4c",
"hashType": "type" as ScriptHashType
}),
"type": null
})
],
"outputsData": [
"0x"
],
"witnesses": [
new WitnessArgs()
],
"hash": "0x7e69c5b95b25aa70e6e72f0e29ec7b92d6415f4bdacfb9562f9d40c3fddb8dca"
})
const expectedWitness = [
"0x6d000000100000006d0000006d000000590000000000010136c329ed630d6ce750712a477543672adab57f4c1c12c81448189a3455996c31022b8a5407a3d54ff1710eaf4220375f906cb53423040ca9f81e56f41f2df0d6cfd124dbda30b8213a0b15173b745e20449afd5401"
]
it('success', async () => {
// @ts-ignore: Private method
const ntx = await transactionSender.sign(fakeWallet.id, tx, '1234')
expect(ntx.witnesses[0]).toEqual(expectedWitness[0])
})
})
describe('sign for cheque claim tx', () => {
const assetAccountInfo = new AssetAccountInfo()
const receiverDefaultLock = SystemScriptInfo.generateSecpScript(addr.blake160)
const tx = Transaction .fromObject({
"version": "0x0",
"cellDeps": [],
"headerDeps": [],
"inputs": [
Input.fromObject({
"previousOutput": OutPoint.fromObject({
"txHash": "0x1879851943fa686af29bed5c95acd566d0244e7b3ca89cf7c435622a5a5b4cb3",
"index": "0x0"
}),
"since": "0x0",
})
],
"outputs": [],
"outputsData": [],
"witnesses": [
"0x5500000010000000550000005500000041000000b6d1e054606d7229b594820357397ececac31685646d3dbf07d6afe421c96ff72d32ed139f20c7b97b47ec8361c00c1924976ed90031380c488c1bae8ce3bd9d00"
],
})
describe('when matched receiver lock hash', () => {
beforeEach(() => {
const chequeLock = assetAccountInfo.generateChequeScript(receiverDefaultLock.computeHash(), '0'.repeat(40))
tx.inputs[0].lock = chequeLock
});
it('success', async () => {
// @ts-ignore: Private method
const ntx = await transactionSender.sign(fakeWallet.id, tx, '1234')
expect(ntx.witnesses[0]).toEqual(tx.witnesses[0])
})
});
describe('when not matched receiver lock hash', () => {
beforeEach(() => {
const chequeLock = assetAccountInfo.generateChequeScript('0'.repeat(40), '0'.repeat(40))
tx.inputs[0].lock = chequeLock
});
it('throws', async () => {
try {
// @ts-ignore: Private method
await transactionSender.sign(fakeWallet.id, tx, '1234')
} catch (error) {
expect(error.message).toBe('no private key found')
}
})
});
})
describe('sign for cheque withdraw tx', () => {
const assetAccountInfo = new AssetAccountInfo()
const senderDefaultLock = SystemScriptInfo.generateSecpScript(addr.blake160)
const tx = Transaction .fromObject({
"version": "0x0",
"cellDeps": [],
"headerDeps": [],
"inputs": [
Input.fromObject({
"previousOutput": OutPoint.fromObject({
"txHash": "0x1879851943fa686af29bed5c95acd566d0244e7b3ca89cf7c435622a5a5b4cb3",
"index": "0x0"
}),
"since": "0x0",
})
],
"outputs": [],
"outputsData": [],
"witnesses": [
"0x5500000010000000550000005500000041000000b6d1e054606d7229b594820357397ececac31685646d3dbf07d6afe421c96ff72d32ed139f20c7b97b47ec8361c00c1924976ed90031380c488c1bae8ce3bd9d00"
],
})
describe('when matched sender lock hash', () => {
beforeEach(() => {
const chequeLock = assetAccountInfo.generateChequeScript('0'.repeat(40), senderDefaultLock.computeHash())
tx.inputs[0].lock = chequeLock
});
it('success', async () => {
// @ts-ignore: Private method
const ntx = await transactionSender.sign(fakeWallet.id, tx, '1234')
expect(ntx.witnesses[0]).toEqual(tx.witnesses[0])
})
});
describe('when not matched sender lock hash', () => {
beforeEach(() => {
const chequeLock = assetAccountInfo.generateChequeScript('0'.repeat(40), '0'.repeat(40))
tx.inputs[0].lock = chequeLock
});
it('throws', async () => {
try {
// @ts-ignore: Private method
await transactionSender.sign(fakeWallet.id, tx, '1234')
} catch (error) {
expect(error.message).toBe('no private key found')
}
})
});
})
});
describe('#sendTx', () => {
let txHash: any
beforeEach(async () => {
txHash = await transactionSender.sendTx(fakeWallet.id, fakeTx1.transaction)
});
it('posts tx to rpc', () => {
expect(stubbedSendTransaction).toHaveBeenCalled()
})
it('saves tx', () => {
expect(stubbedSaveWithSentTx).toHaveBeenCalled()
})
it('returns tx hash', () => {
expect(txHash).toEqual('0xb3dcea26138cb9f714502e52ad2c18a60a197cc2f397301da0b84ad727051158')
})
it('check and generate new addresses', () => {
expect(stubbedCheckAndGenerateAddresses).toHaveBeenCalled()
})
});
describe('#generateTx', () => {
const fee = '1'
const feeRate = '10'
const targetOutputs = [
{address: '1', capacity: 1},
{address: '1', capacity: 1},
]
beforeEach(() => {
stubbedGetCurrentWallet.mockReturnValue(fakeWallet)
stubbedGetNextChangeAddress.mockReturnValue({
address: fakeAddress1
})
});
describe('success', () => {
beforeEach(async () => {
await transactionSender.generateTx(fakeWallet.id, targetOutputs, fee, feeRate)
});
it('generates transaction', () => {
expect(stubbedGenerateTx).toHaveBeenCalledWith(
fakeWallet.id,
[
{address: '1', capacity: '1'},
{address: '1', capacity: '1'},
],
fakeAddress1,
fee,
feeRate
)
})
});
describe('fail', () => {
beforeEach(async () => {
stubbedGenerateTx.mockRejectedValue(new CapacityNotEnoughForChange())
});
it('generates transaction', async () => {
expect(transactionSender.generateTx(fakeWallet.id, targetOutputs, fee, feeRate))
.rejects.toThrowError(CapacityNotEnoughForChangeByTransfer)
})
});
});
describe('#generateSendingAllTx', () => {
const fee = '1'
const feeRate = '10'
beforeEach(async () => {
const targetOutputs = [
{address: '1', capacity: 1},
{address: '1', capacity: 1},
]
await transactionSender.generateSendingAllTx(fakeWallet.id, targetOutputs, fee, feeRate)
});
it('generates transaction', () => {
expect(stubbedGenerateSendingAllTx).toHaveBeenCalledWith(
fakeWallet.id,
[
{address: '1', capacity: '1'},
{address: '1', capacity: '1'},
],
fee,
feeRate
)
})
});
describe('#generateDepositTx', () => {
const fee = '1'
const feeRate = '10'
const capacity = '100'
beforeEach(async () => {
stubbedGetCurrentWallet.mockReturnValue(fakeWallet)
stubbedGetNextChangeAddress.mockReturnValue({
address: fakeAddress1
})
stubbedGetNextAddress.mockReturnValue({
address: fakeAddress2
})
await transactionSender.generateDepositTx(fakeWallet.id, capacity, fee, feeRate)
});
it('generates transaction', () => {
expect(stubbedGenerateDepositTx).toHaveBeenCalledWith(
fakeWallet.id,
capacity,
fakeAddress2,
fakeAddress1,
fee,
feeRate
)
})
});
describe('#generateDepositAllTx', () => {
const fee = '1'
const feeRate = '10'
beforeEach(async () => {
stubbedGetWallet.mockReturnValue(fakeWallet)
stubbedGetNextAddress.mockReturnValue({
address: fakeAddress1
})
await transactionSender.generateDepositAllTx(fakeWallet.id, fee, feeRate)
});
it('generates transaction', () => {
expect(stubbedGenerateDepositAllTx).toHaveBeenCalledWith(
fakeWallet.id,
fakeAddress1,
fee,
feeRate
)
})
});
describe('#generateWithdrawMultiSignTx', () => {
const fee = '1'
const feeRate = '10'
const fakeDepositOutPoint = OutPoint.fromObject({txHash: '0x' + '0'.repeat(64), index: '0x0'})
beforeEach(async () => {
stubbedGetLiveCell.mockResolvedValue(fakeCellWithStatus)
stubbedGetTransaction.mockResolvedValue(fakeTx1)
stubbedGetNextAddress.mockResolvedValue({address: fakeAddress1})
await transactionSender.generateWithdrawMultiSignTx(
fakeWallet.id,
fakeDepositOutPoint,
fee,
feeRate
)
});
it('generates transaction', () => {
expect(stubbedGenerateWithdrawMultiSignTx).toHaveBeenCalledWith(
fakeDepositOutPoint,
fakeCellWithStatus.cell!.output,
fakeAddress1,
fee,
feeRate
)
});
});
describe('#startWithdrawFromDao', () => {
const fakeDepositOutPoint = OutPoint.fromObject({txHash: '0x' + '0'.repeat(64), index: '0x0'})
const fakeDepositBlockHeader = {
"version": "0",
"timestamp": "1606961260974",
"number": "100",
"epoch": "2199023255602",
"hash": "0x97b3620c97bf47b4b85f4de678165ea78768be98f080854b54a9e03b78ba21b3",
"parentHash": "0x9ddda4dd7edd9e413cbd25f6258ad182ea4a0f8af6835a431e72553f28a61086"
}
const fee = '1'
const feeRate = '10'
beforeEach(async () => {
stubbedGetLiveCell.mockResolvedValue(fakeCellWithStatus)
stubbedGetTransaction.mockResolvedValue(fakeTx1)
stubbedGetHeader.mockResolvedValue(fakeDepositBlockHeader)
stubbedGetNextChangeAddress.mockReturnValue({
address: fakeAddress1
})
await transactionSender.startWithdrawFromDao(
fakeWallet.id,
fakeDepositOutPoint,
'1',
'10'
)
});
it('generates transaction', () => {
expect(stubbedStartWithdrawFromDao).toHaveBeenCalledWith(
fakeWallet.id,
fakeDepositOutPoint,
fakeCellWithStatus.cell!.output,
fakeDepositBlockHeader.number,
fakeDepositBlockHeader.hash,
fakeAddress1,
fee,
feeRate,
)
})
});
describe('#withdrawFromDao', () => {
let tx: any
beforeEach(async () => {
stubbedGetLiveCell.mockResolvedValue(fakeCellWithStatus)
stubbedGetTransaction.mockResolvedValue(fakeTx1)
stubbedGetBlockByNumber.mockResolvedValue({
header: {hash: '0x92b197aa1fba0f63633922c61c92375c9c074a93e85963554f5499fe1450d0e5'},
transactions: [
{hash: '0x' + '0'.repeat(64)},
{hash: '0x' + '1'.repeat(64)},
]
})
const depositBlockHeader = {
"version": "0",
"timestamp": "1606961260974",
"number": "100",
"epoch": "2199023255602",
"hash": "0x97b3620c97bf47b4b85f4de678165ea78768be98f080854b54a9e03b78ba21b3",
"parentHash": "0x9ddda4dd7edd9e413cbd25f6258ad182ea4a0f8af6835a431e72553f28a61086"
}
stubbedGetHeaderByNumber.mockResolvedValue(depositBlockHeader)
const withdrawBlockHeader = {
"version": "0",
"timestamp": "1606961260974",
"number": "100",
"epoch": "2199023255602",
"hash": "0x97b3620c97bf47b4b85f4de678165ea78768be98f080854b54a9e03b78ba21b3",
"parentHash": "0x9ddda4dd7edd9e413cbd25f6258ad182ea4a0f8af6835a431e72553f28a61086"
}
stubbedGetHeader.mockResolvedValue(withdrawBlockHeader)
stubbedCalculateDaoMaximumWithdraw.mockResolvedValue(10300000000)
stubbedGetNextAddress.mockReturnValue({
address: fakeAddress1
})
const depositOutPoint = OutPoint.fromObject({
'txHash': '0x' + '0'.repeat(64),
'index': '0x0'
})
const withdrawingOutPoint = OutPoint.fromObject({
'txHash': '0x' + '1'.repeat(64),
'index': '0x0'
})
tx = await transactionSender.withdrawFromDao(fakeWallet.id, depositOutPoint, withdrawingOutPoint, undefined, '1000')
});
it('generates transaction', () => {
expect(tx.interest).toEqual('100000000')
expect(tx.inputs[0].since).toEqual('2305845208236949554')
expect(tx.witnesses[0].inputType).toEqual('0x0000000000000000')
})
});
})
}) | the_stack |
'use strict';
import commander = require('commander');
import fs = require('fs');
import path = require('path');
import log = require('./log');
import my_request = require('./my_request');
import cfg = require('./config');
import series from './series';
/* correspondances between resolution and value CR excpect */
const resol_table: { [id: string]: IResolData; } =
{
360: {quality: '60', format: '106'},
480: {quality: '61', format: '106'},
720: {quality: '62', format: '106'},
1080: {quality: '80', format: '108'},
};
/**
* Streams the batch of series to disk.
*/
export default function(args: string[], done: (err?: Error) => void)
{
const config = Object.assign(cfg.load(), parse(args));
let batchPath;
if (path.isAbsolute(config.batch))
{
batchPath = path.normalize(config.batch);
}
else
{
batchPath = path.normalize(path.join(process.cwd(), config.batch));
}
if (config.nametmpl === undefined)
{
config.nametmpl = '{SERIES_TITLE} - s{SEASON_NUMBER}e{EPISODE_NUMBER} - {EPISODE_TITLE} - [{TAG}]';
}
if (config.tag === undefined)
{
config.tag = 'CrunchyRoll';
}
if (config.sublang === undefined)
{
config.sublang = [ 'enUS' ];
}
// set resolution
if (config.resolution)
{
try
{
config.video_format = resol_table[config.resolution].format;
config.video_quality = resol_table[config.resolution].quality;
}
catch (e)
{
log.warn('Invalid resolution ' + config.resolution + 'p. Setting to 1080p');
config.video_format = resol_table['1080'].format;
config.video_quality = resol_table['1080'].quality;
}
}
else
{
/* 1080 by default */
config.video_format = resol_table['1080'].format;
config.video_quality = resol_table['1080'].quality;
}
// Update the config file with new parameters
cfg.save(config);
if (config.unlog)
{
config.crDeviceId = undefined;
config.user = undefined;
config.pass = undefined;
my_request.eatCookies(config);
cfg.save(config);
log.info('Unlogged!');
process.exit(0);
}
if (config.debug)
{
/* Ugly but meh */
const tmp = JSON.parse(JSON.stringify(config));
tmp.pass = 'obfuscated';
tmp.user = 'obfustated';
tmp.rawArgs = undefined;
tmp.options = undefined;
log.dumpToDebug('Config', JSON.stringify(tmp), true);
}
tasks(config, batchPath, (err, tasksArr) =>
{
if (err)
{
return done(err);
}
if (!tasksArr || !tasksArr[0] || (tasksArr[0].address === ''))
{
return done();
}
let i = 0;
(function next()
{
if (i >= tasksArr.length)
{
// Save configuration before leaving (should store info like session & other)
cfg.save(config);
return done();
}
if (config.debug)
{
log.dumpToDebug('Task ' + i, JSON.stringify(tasksArr[i]));
}
series(config, tasksArr[i], (errin) =>
{
if (errin)
{
if (errin.error)
{
/* Error from the request, so ignore it */
tasksArr[i].retry = 0;
}
if (errin.authError)
{
/* Force a graceful exit */
log.error(errin.message);
i = tasksArr.length;
}
else if (tasksArr[i].retry <= 0)
{
if (config.verbose)
{
log.error(JSON.stringify(errin));
}
if (config.debug)
{
log.dumpToDebug('BatchGiveUp', JSON.stringify(errin));
}
log.error('Cannot get episodes from "' + tasksArr[i].address + '", please rerun later');
/* Go to the next on the list */
i += 1;
}
else
{
if (config.verbose)
{
log.error(JSON.stringify(errin));
}
if (config.debug)
{
log.dumpToDebug('BatchRetry', JSON.stringify(errin));
}
log.warn('Retrying to fetch episodes list from' + tasksArr[i].retry + ' / ' + config.retry);
tasksArr[i].retry -= 1;
}
}
else
{
i += 1;
}
setTimeout(next, config.sleepTime);
});
})();
});
}
/**
* Splits the value into arguments.
*/
function split(value: string): string[]
{
let inQuote = false;
let i: number;
const pieces: string[] = [];
let previous = 0;
for (i = 0; i < value.length; i += 1)
{
if (value.charAt(i) === '"')
{
inQuote = !inQuote;
}
if (!inQuote && value.charAt(i) === ' ')
{
pieces.push(value.substring(previous, i).match(/^"?(.+?)"?$/)[1]);
previous = i + 1;
}
}
const lastPiece = value.substring(previous, i).match(/^"?(.+?)"?$/);
if (lastPiece)
{
pieces.push(lastPiece[1]);
}
return pieces;
}
function get_min_filter(filter: string): IEpisodeNumber
{
if (filter !== undefined)
{
const tok = filter.split('-');
if (tok.length > 2)
{
log.error('Invalid episode filter \'' + filter + '\'');
process.exit(-1);
}
if (tok[0] !== '')
{
/* If first item is not empty, ie '10-20' */
if (tok[0].includes('e'))
{
/* include a e so we probably have something like 5e10
aka season 5 episode 10
*/
const tok2 = tok[0].split('else');
if (tok2.length > 2)
{
log.error('Invalid episode filter \'' + filter + '\'');
process.exit(-1);
}
if (tok[0] !== '')
{
/* So season is properly filled */
return {season: parseInt(tok2[0], 10), episode: parseInt(tok2[1], 10)};
}
else
{
/* we have 'e10' */
return {season: 0, episode: parseInt(tok2[1], 10)};
}
}
else
{
return {season: 0, episode: parseInt(tok[0], 10)};
}
}
}
/* First item is empty, ie '-20' */
return {season: 0, episode: 0};
}
function get_max_filter(filter: string): IEpisodeNumber
{
if (filter !== undefined)
{
const tok = filter.split('-');
if (tok.length > 2)
{
log.error('Invalid episode filter \'' + filter + '\'');
process.exit(-1);
}
if ((tok.length > 1) && (tok[1] !== ''))
{
/* We have a max value */
return {season: +Infinity, episode: parseInt(tok[1], 10)};
}
else if ((tok.length === 1) && (tok[0] !== ''))
{
/* A single episode has been requested */
return {season: +Infinity, episode: parseInt(tok[0], 10) + 1};
}
}
return {season: +Infinity, episode: +Infinity};
}
/**
* Check that URL start with http:// or https://
* As for some reason request just return an error but a useless one when that happen so check it
* soon enough.
*/
function checkURL(address: string): boolean
{
if (address.startsWith('http:\/\/'))
{
return true;
}
if (address.startsWith('https:\/\/'))
{
return true;
}
if (address.startsWith('@http:\/\/'))
{
return true;
}
if (address.startsWith('@https:\/\/'))
{
return true;
}
log.error('URL ' + address + ' miss \'http:\/\/\' or \'https:\/\/\' => will be ignored');
return false;
}
/**
* Parses the configuration or reads the batch-mode file for tasks.
*/
function tasks(config: IConfigLine, batchPath: string, done: (err: Error, tasks?: IConfigTask[]) => void)
{
if (config.args.length)
{
return done(null, config.args.map((addressIn) =>
{
if (checkURL(addressIn))
{
return {address: addressIn, retry: config.retry,
episode_min: get_min_filter(config.episodes), episode_max: get_max_filter(config.episodes)};
}
return {address: '', retry: 0, episode_min: {season: 0, episode: 0}, episode_max: {season: 0, episode: 0}};
}));
}
fs.exists(batchPath, (exists) =>
{
if (!exists)
{
return done(null, []);
}
fs.readFile(batchPath, 'utf8', (err, data) =>
{
if (err)
{
return done(err);
}
const map: IConfigTask[] = [];
data.split(/\r?\n/).forEach((line) =>
{
if (/^(\/\/|#)/.test(line))
{
return;
}
const lineConfig = parse(process.argv.concat(split(line)));
lineConfig.args.forEach((addressIn) =>
{
if (!addressIn)
{
return;
}
if (checkURL(addressIn))
{
map.push({address: addressIn, retry: lineConfig.retry,
episode_min: get_min_filter(lineConfig.episodes), episode_max: get_max_filter(lineConfig.episodes)});
}
});
});
done(null, map);
});
});
}
function commaSeparatedList(value: any, dummyPrevious: any) {
return value.split(',');
}
/**
* Parses the arguments and returns a configuration.
*/
function parse(args: string[]): IConfigLine
{
return new commander.Command().version(require('../package').version)
// Authentication
.option('-p, --pass <s>', 'The password.')
.option('-u, --user <s>', 'The e-mail address or username.')
.option('-d, --unlog', 'Unlog')
// Disables
.option('-c, --cache', 'Disables the cache.')
.option('-m, --merge', 'Disables merging subtitles and videos.')
// Episode filter
.option('-e, --episodes <s>', 'Episode list. Read documentation on how to use')
// Settings
.option('-l, --crlang <s>', 'CR page language (valid: en, fr, es, it, pt, de, ru).')
.option('-s, --sublang <items>', 'Select the subtitle languages, multiple value separated by a comma ' +
'are accepted (like: frFR,enUS )', commaSeparatedList)
.option('-f, --format <s>', 'The subtitle format.', 'ass')
.option('-o, --output <s>', 'The output path.')
.option('-s, --series <s>', 'The series name override.')
.option('--ignoredub', 'Experimental: Ignore all seasons where the title end with \'Dub)\'')
.option('-n, --nametmpl <s>', 'Output name template')
.option('-t, --tag <s>', 'The subgroup.')
.option('-r, --resolution <s>', 'The video resolution. (valid: 360, 480, 720, 1080)')
.option('-b, --batch <s>', 'Batch file', 'CrunchyRoll.txt')
.option('--verbose', 'Make tool verbose')
.option('--debug', 'Create a debug file. Use only if requested!')
.option('--rebuildcrp', 'Rebuild the crpersistant file.')
.option('--retry <i>', 'Number or time to retry fetching an episode.', '5')
.option('--sleepTime <i>', 'Minimum wait time between each http requests.')
.parse(args);
} | the_stack |
declare class TKBERTLVRecord extends TKTLVRecord {
static alloc(): TKBERTLVRecord; // inherited from NSObject
static dataForTag(tag: number): NSData;
static new(): TKBERTLVRecord; // inherited from NSObject
static recordFromData(data: NSData): TKBERTLVRecord; // inherited from TKTLVRecord
constructor(o: { tag: number; records: NSArray<TKTLVRecord> | TKTLVRecord[]; });
constructor(o: { tag: number; value: NSData; });
initWithTagRecords(tag: number, records: NSArray<TKTLVRecord> | TKTLVRecord[]): this;
initWithTagValue(tag: number, value: NSData): this;
}
declare class TKCompactTLVRecord extends TKTLVRecord {
static alloc(): TKCompactTLVRecord; // inherited from NSObject
static new(): TKCompactTLVRecord; // inherited from NSObject
static recordFromData(data: NSData): TKCompactTLVRecord; // inherited from TKTLVRecord
constructor(o: { tag: number; value: NSData; });
initWithTagValue(tag: number, value: NSData): this;
}
declare const enum TKErrorCode {
CodeNotImplemented = -1,
CodeCommunicationError = -2,
CodeCorruptedData = -3,
CodeCanceledByUser = -4,
CodeAuthenticationFailed = -5,
CodeObjectNotFound = -6,
CodeTokenNotFound = -7,
CodeBadParameter = -8,
CodeAuthenticationNeeded = -9,
AuthenticationFailed = -5,
ObjectNotFound = -6,
TokenNotFound = -7
}
declare var TKErrorDomain: string;
declare class TKSimpleTLVRecord extends TKTLVRecord {
static alloc(): TKSimpleTLVRecord; // inherited from NSObject
static new(): TKSimpleTLVRecord; // inherited from NSObject
static recordFromData(data: NSData): TKSimpleTLVRecord; // inherited from TKTLVRecord
constructor(o: { tag: number; value: NSData; });
initWithTagValue(tag: number, value: NSData): this;
}
declare class TKSmartCard extends NSObject {
static alloc(): TKSmartCard; // inherited from NSObject
static new(): TKSmartCard; // inherited from NSObject
allowedProtocols: TKSmartCardProtocol;
cla: number;
context: any;
readonly currentProtocol: TKSmartCardProtocol;
sensitive: boolean;
readonly slot: TKSmartCardSlot;
useCommandChaining: boolean;
useExtendedLength: boolean;
readonly valid: boolean;
beginSessionWithReply(reply: (p1: boolean, p2: NSError) => void): void;
endSession(): void;
inSessionWithErrorExecuteBlock(error: interop.Pointer | interop.Reference<NSError>, block: (p1: interop.Pointer | interop.Reference<NSError>) => boolean): boolean;
sendInsP1P2DataLeReply(ins: number, p1: number, p2: number, requestData: NSData, le: number, reply: (p1: NSData, p2: number, p3: NSError) => void): void;
sendInsP1P2DataLeSwError(ins: number, p1: number, p2: number, requestData: NSData, le: number, sw: interop.Pointer | interop.Reference<number>): NSData;
transmitRequestReply(request: NSData, reply: (p1: NSData, p2: NSError) => void): void;
userInteractionForSecurePINChangeWithPINFormatAPDUCurrentPINByteOffsetNewPINByteOffset(PINFormat: TKSmartCardPINFormat, APDU: NSData, currentPINByteOffset: number, newPINByteOffset: number): TKSmartCardUserInteractionForSecurePINChange;
userInteractionForSecurePINVerificationWithPINFormatAPDUPINByteOffset(PINFormat: TKSmartCardPINFormat, APDU: NSData, PINByteOffset: number): TKSmartCardUserInteractionForSecurePINVerification;
}
declare class TKSmartCardATR extends NSObject {
static alloc(): TKSmartCardATR; // inherited from NSObject
static new(): TKSmartCardATR; // inherited from NSObject
readonly bytes: NSData;
readonly historicalBytes: NSData;
readonly historicalRecords: NSArray<TKCompactTLVRecord>;
readonly protocols: NSArray<number>;
constructor(o: { bytes: NSData; });
constructor(o: { source: () => number; });
initWithBytes(bytes: NSData): this;
initWithSource(source: () => number): this;
interfaceGroupAtIndex(index: number): TKSmartCardATRInterfaceGroup;
interfaceGroupForProtocol(protocol: TKSmartCardProtocol): TKSmartCardATRInterfaceGroup;
}
declare class TKSmartCardATRInterfaceGroup extends NSObject {
static alloc(): TKSmartCardATRInterfaceGroup; // inherited from NSObject
static new(): TKSmartCardATRInterfaceGroup; // inherited from NSObject
readonly TA: number;
readonly TB: number;
readonly TC: number;
readonly protocol: number;
}
declare const enum TKSmartCardPINCharset {
Numeric = 0,
Alphanumeric = 1,
UpperAlphanumeric = 2
}
declare const enum TKSmartCardPINCompletion {
MaxLength = 1,
Key = 2,
Timeout = 4
}
declare const enum TKSmartCardPINConfirmation {
None = 0,
New = 1,
Current = 2
}
declare const enum TKSmartCardPINEncoding {
Binary = 0,
ASCII = 1,
BCD = 2
}
declare class TKSmartCardPINFormat extends NSObject {
static alloc(): TKSmartCardPINFormat; // inherited from NSObject
static new(): TKSmartCardPINFormat; // inherited from NSObject
PINBitOffset: number;
PINBlockByteLength: number;
PINJustification: TKSmartCardPINJustification;
PINLengthBitOffset: number;
PINLengthBitSize: number;
charset: TKSmartCardPINCharset;
encoding: TKSmartCardPINEncoding;
maxPINLength: number;
minPINLength: number;
}
declare const enum TKSmartCardPINJustification {
Left = 0,
Right = 1
}
declare const enum TKSmartCardProtocol {
None = 0,
T0 = 1,
T1 = 2,
T15 = 32768,
Any = 65535
}
declare class TKSmartCardSlot extends NSObject {
static alloc(): TKSmartCardSlot; // inherited from NSObject
static new(): TKSmartCardSlot; // inherited from NSObject
readonly ATR: TKSmartCardATR;
readonly maxInputLength: number;
readonly maxOutputLength: number;
readonly name: string;
readonly state: TKSmartCardSlotState;
makeSmartCard(): TKSmartCard;
}
declare class TKSmartCardSlotManager extends NSObject {
static alloc(): TKSmartCardSlotManager; // inherited from NSObject
static new(): TKSmartCardSlotManager; // inherited from NSObject
readonly slotNames: NSArray<string>;
static readonly defaultManager: TKSmartCardSlotManager;
getSlotWithNameReply(name: string, reply: (p1: TKSmartCardSlot) => void): void;
slotNamed(name: string): TKSmartCardSlot;
}
declare const enum TKSmartCardSlotState {
Missing = 0,
Empty = 1,
Probing = 2,
MuteCard = 3,
ValidCard = 4
}
declare class TKSmartCardToken extends TKToken {
static alloc(): TKSmartCardToken; // inherited from NSObject
static new(): TKSmartCardToken; // inherited from NSObject
readonly AID: NSData;
constructor(o: { smartCard: TKSmartCard; AID: NSData; instanceID: string; tokenDriver: TKSmartCardTokenDriver; });
initWithSmartCardAIDInstanceIDTokenDriver(smartCard: TKSmartCard, AID: NSData, instanceID: string, tokenDriver: TKSmartCardTokenDriver): this;
}
declare class TKSmartCardTokenDriver extends TKTokenDriver {
static alloc(): TKSmartCardTokenDriver; // inherited from NSObject
static new(): TKSmartCardTokenDriver; // inherited from NSObject
}
interface TKSmartCardTokenDriverDelegate extends TKTokenDriverDelegate {
tokenDriverCreateTokenForSmartCardAIDError(driver: TKSmartCardTokenDriver, smartCard: TKSmartCard, AID: NSData): TKSmartCardToken;
}
declare var TKSmartCardTokenDriverDelegate: {
prototype: TKSmartCardTokenDriverDelegate;
};
declare class TKSmartCardTokenSession extends TKTokenSession {
static alloc(): TKSmartCardTokenSession; // inherited from NSObject
static new(): TKSmartCardTokenSession; // inherited from NSObject
readonly smartCard: TKSmartCard;
}
declare class TKSmartCardUserInteraction extends NSObject {
static alloc(): TKSmartCardUserInteraction; // inherited from NSObject
static new(): TKSmartCardUserInteraction; // inherited from NSObject
delegate: TKSmartCardUserInteractionDelegate;
initialTimeout: number;
interactionTimeout: number;
cancel(): boolean;
runWithReply(reply: (p1: boolean, p2: NSError) => void): void;
}
interface TKSmartCardUserInteractionDelegate {
characterEnteredInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
correctionKeyPressedInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
invalidCharacterEnteredInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
newPINConfirmationRequestedInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
newPINRequestedInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
oldPINRequestedInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
validationKeyPressedInUserInteraction?(interaction: TKSmartCardUserInteraction): void;
}
declare var TKSmartCardUserInteractionDelegate: {
prototype: TKSmartCardUserInteractionDelegate;
};
declare class TKSmartCardUserInteractionForPINOperation extends TKSmartCardUserInteraction {
static alloc(): TKSmartCardUserInteractionForPINOperation; // inherited from NSObject
static new(): TKSmartCardUserInteractionForPINOperation; // inherited from NSObject
PINCompletion: TKSmartCardPINCompletion;
PINMessageIndices: NSArray<number>;
locale: NSLocale;
resultData: NSData;
resultSW: number;
}
declare class TKSmartCardUserInteractionForSecurePINChange extends TKSmartCardUserInteractionForPINOperation {
static alloc(): TKSmartCardUserInteractionForSecurePINChange; // inherited from NSObject
static new(): TKSmartCardUserInteractionForSecurePINChange; // inherited from NSObject
PINConfirmation: TKSmartCardPINConfirmation;
}
declare class TKSmartCardUserInteractionForSecurePINVerification extends TKSmartCardUserInteractionForPINOperation {
static alloc(): TKSmartCardUserInteractionForSecurePINVerification; // inherited from NSObject
static new(): TKSmartCardUserInteractionForSecurePINVerification; // inherited from NSObject
}
declare class TKTLVRecord extends NSObject {
static alloc(): TKTLVRecord; // inherited from NSObject
static new(): TKTLVRecord; // inherited from NSObject
static recordFromData(data: NSData): TKTLVRecord;
static sequenceOfRecordsFromData(data: NSData): NSArray<TKTLVRecord>;
readonly data: NSData;
readonly tag: number;
readonly value: NSData;
}
declare class TKToken extends NSObject {
static alloc(): TKToken; // inherited from NSObject
static new(): TKToken; // inherited from NSObject
readonly configuration: TKTokenConfiguration;
delegate: TKTokenDelegate;
readonly keychainContents: TKTokenKeychainContents;
readonly tokenDriver: TKTokenDriver;
constructor(o: { tokenDriver: TKTokenDriver; instanceID: string; });
initWithTokenDriverInstanceID(tokenDriver: TKTokenDriver, instanceID: string): this;
}
declare class TKTokenAuthOperation extends NSObject implements NSSecureCoding {
static alloc(): TKTokenAuthOperation; // inherited from NSObject
static new(): TKTokenAuthOperation; // inherited from NSObject
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
encodeWithCoder(coder: NSCoder): void;
finishWithError(): boolean;
initWithCoder(coder: NSCoder): this;
}
declare class TKTokenConfiguration extends NSObject {
static alloc(): TKTokenConfiguration; // inherited from NSObject
static new(): TKTokenConfiguration; // inherited from NSObject
configurationData: NSData;
readonly instanceID: string;
keychainItems: NSArray<TKTokenKeychainItem>;
certificateForObjectIDError(objectID: any): TKTokenKeychainCertificate;
keyForObjectIDError(objectID: any): TKTokenKeychainKey;
}
interface TKTokenDelegate extends NSObjectProtocol {
tokenCreateSessionWithError(token: TKToken): TKTokenSession;
tokenTerminateSession?(token: TKToken, session: TKTokenSession): void;
}
declare var TKTokenDelegate: {
prototype: TKTokenDelegate;
};
declare class TKTokenDriver extends NSObject {
static alloc(): TKTokenDriver; // inherited from NSObject
static new(): TKTokenDriver; // inherited from NSObject
delegate: TKTokenDriverDelegate;
}
declare class TKTokenDriverConfiguration extends NSObject {
static alloc(): TKTokenDriverConfiguration; // inherited from NSObject
static new(): TKTokenDriverConfiguration; // inherited from NSObject
readonly classID: string;
readonly tokenConfigurations: NSDictionary<string, TKTokenConfiguration>;
static readonly driverConfigurations: NSDictionary<string, TKTokenDriverConfiguration>;
addTokenConfigurationForTokenInstanceID(instanceID: string): TKTokenConfiguration;
removeTokenConfigurationForTokenInstanceID(instanceID: string): void;
}
interface TKTokenDriverDelegate extends NSObjectProtocol {
tokenDriverTerminateToken?(driver: TKTokenDriver, token: TKToken): void;
tokenDriverTokenForConfigurationError?(driver: TKTokenDriver, configuration: TKTokenConfiguration): TKToken;
}
declare var TKTokenDriverDelegate: {
prototype: TKTokenDriverDelegate;
};
declare class TKTokenKeyAlgorithm extends NSObject {
static alloc(): TKTokenKeyAlgorithm; // inherited from NSObject
static new(): TKTokenKeyAlgorithm; // inherited from NSObject
isAlgorithm(algorithm: any): boolean;
supportsAlgorithm(algorithm: any): boolean;
}
declare class TKTokenKeyExchangeParameters extends NSObject {
static alloc(): TKTokenKeyExchangeParameters; // inherited from NSObject
static new(): TKTokenKeyExchangeParameters; // inherited from NSObject
readonly requestedSize: number;
readonly sharedInfo: NSData;
}
declare class TKTokenKeychainCertificate extends TKTokenKeychainItem {
static alloc(): TKTokenKeychainCertificate; // inherited from NSObject
static new(): TKTokenKeychainCertificate; // inherited from NSObject
readonly data: NSData;
constructor(o: { certificate: any; objectID: any; });
initWithCertificateObjectID(certificateRef: any, objectID: any): this;
}
declare class TKTokenKeychainContents extends NSObject {
static alloc(): TKTokenKeychainContents; // inherited from NSObject
static new(): TKTokenKeychainContents; // inherited from NSObject
readonly items: NSArray<TKTokenKeychainItem>;
certificateForObjectIDError(objectID: any): TKTokenKeychainCertificate;
fillWithItems(items: NSArray<TKTokenKeychainItem> | TKTokenKeychainItem[]): void;
keyForObjectIDError(objectID: any): TKTokenKeychainKey;
}
declare class TKTokenKeychainItem extends NSObject {
static alloc(): TKTokenKeychainItem; // inherited from NSObject
static new(): TKTokenKeychainItem; // inherited from NSObject
constraints: NSDictionary<number, any>;
label: string;
readonly objectID: any;
constructor(o: { objectID: any; });
initWithObjectID(objectID: any): this;
}
declare class TKTokenKeychainKey extends TKTokenKeychainItem {
static alloc(): TKTokenKeychainKey; // inherited from NSObject
static new(): TKTokenKeychainKey; // inherited from NSObject
applicationTag: NSData;
canDecrypt: boolean;
canPerformKeyExchange: boolean;
canSign: boolean;
keySizeInBits: number;
keyType: string;
publicKeyData: NSData;
publicKeyHash: NSData;
suitableForLogin: boolean;
constructor(o: { certificate: any; objectID: any; });
initWithCertificateObjectID(certificateRef: any, objectID: any): this;
}
declare const enum TKTokenOperation {
None = 0,
ReadData = 1,
SignData = 2,
DecryptData = 3,
PerformKeyExchange = 4
}
declare class TKTokenPasswordAuthOperation extends TKTokenAuthOperation {
static alloc(): TKTokenPasswordAuthOperation; // inherited from NSObject
static new(): TKTokenPasswordAuthOperation; // inherited from NSObject
password: string;
}
declare class TKTokenSession extends NSObject {
static alloc(): TKTokenSession; // inherited from NSObject
static new(): TKTokenSession; // inherited from NSObject
delegate: TKTokenSessionDelegate;
readonly token: TKToken;
constructor(o: { token: TKToken; });
initWithToken(token: TKToken): this;
}
interface TKTokenSessionDelegate extends NSObjectProtocol {
tokenSessionBeginAuthForOperationConstraintError?(session: TKTokenSession, operation: TKTokenOperation, constraint: any): TKTokenAuthOperation;
tokenSessionDecryptDataUsingKeyAlgorithmError?(session: TKTokenSession, ciphertext: NSData, keyObjectID: any, algorithm: TKTokenKeyAlgorithm): NSData;
tokenSessionPerformKeyExchangeWithPublicKeyUsingKeyAlgorithmParametersError?(session: TKTokenSession, otherPartyPublicKeyData: NSData, objectID: any, algorithm: TKTokenKeyAlgorithm, parameters: TKTokenKeyExchangeParameters): NSData;
tokenSessionSignDataUsingKeyAlgorithmError?(session: TKTokenSession, dataToSign: NSData, keyObjectID: any, algorithm: TKTokenKeyAlgorithm): NSData;
tokenSessionSupportsOperationUsingKeyAlgorithm?(session: TKTokenSession, operation: TKTokenOperation, keyObjectID: any, algorithm: TKTokenKeyAlgorithm): boolean;
}
declare var TKTokenSessionDelegate: {
prototype: TKTokenSessionDelegate;
};
declare class TKTokenSmartCardPINAuthOperation extends TKTokenAuthOperation {
static alloc(): TKTokenSmartCardPINAuthOperation; // inherited from NSObject
static new(): TKTokenSmartCardPINAuthOperation; // inherited from NSObject
APDUTemplate: NSData;
PIN: string;
PINByteOffset: number;
PINFormat: TKSmartCardPINFormat;
smartCard: TKSmartCard;
}
declare class TKTokenWatcher extends NSObject {
static alloc(): TKTokenWatcher; // inherited from NSObject
static new(): TKTokenWatcher; // inherited from NSObject
readonly tokenIDs: NSArray<string>;
constructor(o: { insertionHandler: (p1: string) => void; });
addRemovalHandlerForTokenID(removalHandler: (p1: string) => void, tokenID: string): void;
initWithInsertionHandler(insertionHandler: (p1: string) => void): this;
setInsertionHandler(insertionHandler: (p1: string) => void): void;
tokenInfoForTokenID(tokenID: string): TKTokenWatcherTokenInfo;
}
declare class TKTokenWatcherTokenInfo extends NSObject {
static alloc(): TKTokenWatcherTokenInfo; // inherited from NSObject
static new(): TKTokenWatcherTokenInfo; // inherited from NSObject
readonly driverName: string;
readonly slotName: string;
readonly tokenID: string;
} | the_stack |
import mongoose from 'mongoose';
import _ from 'lodash';
import Logger from 'bunyan';
import { Observable, Subject } from 'rxjs';
import { injectable } from 'inversify';
import { ExistenceEvent, ExistenceEventType } from './existence';
import { from } from 'rxjs/observable/from';
import { concat, exhaustMap, filter, map, share, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { v1 as uuid } from 'uuid';
import { IDbService } from '@pyro/db-server/i-db-service';
import { DBObject } from '@pyro/db';
import { RawObject } from '@pyro/db/db-raw-object';
import { CreateObject } from '@pyro/db/db-create-object';
import { FindObject } from '@pyro/db/db-find-object';
import { UpdateObject } from '@pyro/db/db-update-object';
import { EntityService } from '@pyro/db-server/entity-service';
@injectable()
export abstract class DBService<T extends DBObject<any, any>>
extends EntityService<T>
implements IDbService<T> {
public abstract readonly DBObject: {
new (arg: RawObject<T>): T;
modelName: string;
};
public readonly existence: Subject<ExistenceEvent<T>>;
protected abstract readonly log: Logger;
constructor() {
super();
this.existence = new Subject<ExistenceEvent<T>>();
}
get(id: T['id']): Observable<T | null> {
const callId = uuid();
this.log.info({ objectId: id, callId }, '.get(id) called');
return from(this.getCurrent(id)).pipe(
concat(
this.existence.pipe(
filter((existenceEvent) => id === existenceEvent.id),
map((existenceEvent) => existenceEvent.value),
share()
)
),
tap({
next: (obj) => {
this.log.info(
{
objectId: id,
object: obj,
callId,
},
'.get(id) emitted next value'
);
},
error: (err) => {
this.log.error(
{
objectId: id,
err,
callId,
},
'.get(id), emitted error!'
);
},
})
);
}
async getCurrent(id: T['id']): Promise<T | null> {
const callId = uuid();
this.log.info({ objectId: id, callId }, '.getCurrent(id) called');
const obj = await this.Model.findById(id).lean().exec();
return this.parse(obj as RawObject<T>);
}
getMultiple(ids: T['id'][]): Observable<T[]> {
const callId = uuid();
this.log.info({ objectIds: ids, callId }, '.getMultiple(ids) called');
return of(null).pipe(
concat(
this.existence.pipe(
filter((event) => _.includes(ids, event.id)),
share()
)
),
exhaustMap(() => this.getCurrentMultiple(ids)),
tap({
next: (objects) => {
this.log.info(
{ objectIds: ids, objects, callId },
'.getMultiple(ids) emitted next value'
);
},
error: (err) => {
this.log.error(
{ objectIds: ids, err, callId },
'.getMultiple(ids), emitted error!'
);
},
})
);
}
async getCurrentMultiple(ids: T['id'][]): Promise<T[]> {
const callId = uuid();
this.log.info(
{ objectIds: ids, callId },
'.getCurrentMultiple(ids) called'
);
const objs = await this.Model.find({
_id: {
$in: _.map(ids, (id) => this.getObjectId(id)),
},
})
.lean()
.exec();
return _.map(objs as RawObject<T>[], (obj) => this.parse(obj));
}
async create(createObject: CreateObject<T>): Promise<T> {
const callId = uuid();
this.log.info({ callId, createObject }, '.create(createObject) called');
let object;
try {
const document = await this.Model.create(createObject);
object = this.parse(document.toObject() as RawObject<T>);
} catch (error) {
this.log.error(
{ callId, createObject, error },
'.create(createObject) thrown error!'
);
throw error;
}
this.existence.next({
id: object.id,
value: object,
lastValue: null,
type: ExistenceEventType.Created,
});
this.log.info(
{ callId, createObject, object },
'.create(createObject) created object'
);
return object;
}
/**
* Removes all records from the DB
* TODO: add Guards to avoid run on production
*
* @returns {Promise<void>}
* @memberof DBService
*/
async removeAll(): Promise<void> {
const callId = uuid();
this.log.info({ callId }, '.removeAll() called!');
try {
await this.Model.remove({}).exec();
} catch (err) {
this.log.error({ callId, err }, '.removeAll() thrown error!');
throw err;
}
this.log.info({ callId }, '.removeAll() removed all!');
}
/**
* Removes record from the DB
* TODO: we should add another method which set IsDeteled = true and do not delete record from DB in most cases
*
* @param {T['id']} objectId
* @returns {Promise<void>}
* @memberof DBService
*/
async remove(objectId: T['id']): Promise<void> {
const callId = uuid();
this.log.info({ callId, objectId }, '.remove(objectId) called');
let lastValue: T | null;
try {
const lastValueRaw = (await this.Model.findByIdAndRemove(objectId)
.lean()
.exec()) as RawObject<T>;
lastValue = this.parse(lastValueRaw);
} catch (err) {
this.log.error(
{ callId, objectId, err },
'.remove(objectId) thrown error!'
);
throw err;
}
if (lastValue == null) {
throw new Error(".remove(objectId) error - Object don't exist");
} else {
this.existence.next({
id: objectId,
value: null,
lastValue,
type: ExistenceEventType.Removed,
});
this.log.info(
{ callId, objectId, lastValue },
'.remove(objectId) removed object'
);
}
}
/**
* Remove multiple records from DB (efficient way)
*
* @param {FindObject<T>} conditions
* @returns {Promise<void>}
* @memberof DBService
*/
async removeMultiple(conditions: FindObject<T>): Promise<void> {
const callId = uuid();
this.log.info(
{ callId, conditions },
'.removeMultiple(conditions) called'
);
let lastValues: T[];
try {
lastValues = await this.find(conditions);
await this.Model.deleteMany({
_id: { $in: lastValues.map((o) => this.getObjectId(o.id)) },
}).exec();
} catch (err) {
this.log.error(
{ callId, conditions, err },
'.removeMultiple(conditions) thrown error!'
);
throw err;
}
_.each(lastValues, (lastValue) => {
this.existence.next({
id: lastValue.id,
lastValue,
value: null,
type: ExistenceEventType.Removed,
});
});
this.log.info(
{
callId,
conditions,
lastValues,
},
'.removeMultiple(conditions) removed objects'
);
}
/**
* Remove multiple records by Ids
*
* @param {Array<T['id']>} ids
* @returns {Promise<void>}
* @memberof DBService
*/
async removeMultipleByIds(ids: T['id'][]): Promise<void> {
this.Model.update(
{
_id: { $in: ids.map((id) => this.getObjectId(id)) },
},
{ isDeleted: true },
{ multi: true }
).exec();
}
async find(conditions: FindObject<RawObject<T>>): Promise<T[]> {
const callId = uuid();
this.log.info({ callId, conditions }, '.find(conditions) called');
let results: T[];
try {
const documents = (await this.Model.find(
conditions == null ? {} : conditions
)
.lean()
.exec()) as RawObject<T>[];
results = _.map(documents, (obj) => this.parse(obj));
} catch (err) {
this.log.error(
{ callId, conditions, err },
'.find(conditions) thrown error!'
);
throw err;
}
this.log.info(
{ callId, conditions, results },
'.find(conditions) found results'
);
return results;
}
async findOne(conditions: FindObject<RawObject<T>>): Promise<T> {
const callId = uuid();
this.log.info({ callId, conditions }, '.findOne(conditions) called');
let result: T;
try {
const obj = (await this.Model.findOne(conditions)
.lean()
.exec()) as RawObject<T>;
result = this.parse(obj);
} catch (err) {
this.log.error(
{ callId, conditions, err },
'.findOne(conditions) thrown error!'
);
throw err;
}
this.log.info(
{ callId, conditions, result },
'.findOne(conditions) found result'
);
return result;
}
async update(objectId: T['id'], updateObj: UpdateObject<T>): Promise<T> {
const callId = uuid();
this.log.info(
{ callId, objectId, updateObj },
'.update(objectId, updateObj) called'
);
let beforeUpdateObject: T | null;
let updatedObject: T;
try {
beforeUpdateObject = await this.getCurrent(objectId);
if (beforeUpdateObject != null) {
const obj = (await this.Model.findByIdAndUpdate(
objectId,
updateObj as any,
{ new: true }
)
.lean()
.exec()) as RawObject<T>;
updatedObject = this.parse(obj);
} else {
throw new Error(
`There is no such object with the id ${beforeUpdateObject}`
);
}
} catch (err) {
this.log.error(
{ callId, objectId, updateObj, err },
'.update(objectId, updateObj) thrown error!'
);
throw err;
}
this.existence.next({
id: objectId,
value: updatedObject,
lastValue: beforeUpdateObject,
type: ExistenceEventType.Updated,
});
this.log.info(
{
callId,
objectId,
updateObj,
updatedValue: updatedObject,
lastValue: beforeUpdateObject,
},
'.update(objectId, updateObj) updated object'
);
return updatedObject;
}
async updateMultiple(
findObj: FindObject<T>,
updateObj: UpdateObject<T>
): Promise<T[]> {
const callId = uuid();
this.log.info(
{ callId, findObj, updateObj },
'.updateMultiple(findObj, updateObj) called'
);
let lastValues: T[];
let updatedObjects: T[];
try {
lastValues = await this.find(findObj);
await this.Model.updateMany(findObj, updateObj, {
new: true,
}).exec();
updatedObjects = await this.getCurrentMultiple(
_.map(lastValues, (value) => value.id)
);
} catch (err) {
this.log.error(
{ callId, findObj, updateObj, err },
'.updateMultiple(findObj, updateObj) thrown error!'
);
throw err;
}
_.each(lastValues, (lastValue) => {
const newValue = _.find(
updatedObjects,
(obj) => obj.id === lastValue.id
) as T;
this.existence.next({
id: lastValue.id,
lastValue,
value: newValue,
type: ExistenceEventType.Updated,
});
});
this.log.info(
{
callId,
findObj,
updateObj,
lastValues,
updatedObjects,
},
'.updateMultiple(objectId, updateObj) updated objects'
);
return updatedObjects;
}
async updateMultipleByIds(
ids: T['id'][],
updateObj: UpdateObject<T>
): Promise<T[]> {
const callId = uuid();
this.log.info(
{ callId, ids, updateObj },
'.updateMultipleByIds(ids, updateObj) called'
);
let updatedObjects: T[];
try {
updatedObjects = await this.updateMultiple(
{
// TODO: rewrite below
// tslint:disable-next-line:no-object-literal-type-assertion
_id: {
$in: _.map(
ids,
(id) => new mongoose.Types.ObjectId(id)
),
} as FindObject<T>,
},
updateObj
);
} catch (err) {
this.log.error(
{ callId, ids, updateObj, err },
'.updateMultipleByIds(ids, updateObj) thrown error!'
);
throw err;
}
this.log.info(
{
callId,
ids,
updateObj,
updatedObjects,
},
'.updateMultipleByIds(ids, updateObj) updated objects'
);
return updatedObjects;
}
async count(findObj: FindObject<T>): Promise<number> {
const callId = uuid();
this.log.info({ callId, findObj }, '.countDocuments(findObj) called');
let count: number;
try {
count = (await this.Model.countDocuments(findObj).exec()) as number;
} catch (err) {
this.log.error(
{ callId, findObj, err },
'.countDocuments(findObj) thrown error!'
);
throw err;
}
this.log.info(
{ callId, findObj, count },
'.countDocuments(findObj) counted objects'
);
return count;
}
/**
* Return all store documents with specified fields
* @param selectFields Example { field: 1 } = true, { field: 0 } = false.
*/
async findAll(selectFields: any = {}) {
return this.Model.find({}).select(selectFields).lean().exec();
}
} | the_stack |
import { render } from 'lit-html';
import EventManager from '../utils/event-manager';
import BXPagination from '../../src/components/pagination/pagination';
import BXPageSizesSelect from '../../src/components/pagination/page-sizes-select';
import BXPagesSelect from '../../src/components/pagination/pages-select';
import { Default } from '../../src/components/pagination/pagination-story';
const template = (props?) =>
Default({
'bx-pagination': props,
});
describe('bx-pagination', function() {
const events = new EventManager();
describe('Misc attributes', function() {
it('should render <bx-pagination> with minimum attributes', async function() {
render(template(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-pagination')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render <bx-pagination> with various attributes', async function() {
render(
template({
pageSize: 20,
start: 10,
total: 200,
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-pagination')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render <bx-page-sizes-select> with minimum attributes', async function() {
render(template(), document.body);
await Promise.resolve(); // Update cycle for `<bx-pagination>`
await Promise.resolve(); // Update cycle for `<bx-page-sizes-select>`
expect(document.body.querySelector('bx-page-sizes-select')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render <bx-pages-select> with minimum attributes', async function() {
render(template({ total: 100 }), document.body);
await Promise.resolve(); // Update cycle for `<bx-pagination>`
await Promise.resolve(); // Update cycle for `<bx-pages-select>`
expect(document.body.querySelector('bx-pages-select')).toMatchSnapshot({ mode: 'shadow' });
});
});
describe('Rendering status text', function() {
it('should handle plural for total row count', async function() {
render(
template({
pageSize: 1,
start: 0,
total: 1,
}),
document.body
);
await Promise.resolve();
const textContentNode = document.body.querySelector('bx-pagination')!.shadowRoot!.querySelector('.bx--pagination__text');
expect(textContentNode!.textContent!.trim()).toBe('1–1 of 1 item');
});
it('should render page range without total rows for infinite row count', async function() {
render(
template({
pageSize: 20,
start: 10,
total: null,
}),
document.body
);
await Promise.resolve();
const textContentNode = document.body.querySelector('bx-pagination')!.shadowRoot!.querySelector('.bx--pagination__text');
expect(textContentNode!.textContent!.trim()).toBe('Item 11–30');
});
it('should render only the start at the last page for infinite row count', async function() {
render(
template({
atLastPage: true,
pageSize: 20,
start: 30,
total: null,
}),
document.body
);
await Promise.resolve();
const textContentNode = document.body.querySelector('bx-pagination')!.shadowRoot!.querySelector('.bx--pagination__text');
expect(textContentNode!.textContent!.trim()).toBe('Item 31–');
});
});
describe('Propagating changes', function() {
it('should propagate `pageSize` property to `<bx-page-sizes-select>`', async function() {
render(template(), document.body);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
paginationNode.pageSize = 20;
await Promise.resolve();
const pageSizesSelectNode = document.body.querySelector('bx-page-sizes-select') as BXPageSizesSelect;
expect(pageSizesSelectNode.value).toBe(20);
});
it('should propagate the current page to `<bx-pages-select>`', async function() {
render(template({ total: 100 }), document.body);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
paginationNode.pageSize = 5;
paginationNode.start = 21;
await Promise.resolve();
const pagesSelectNode = document.body.querySelector('bx-pages-select') as BXPagesSelect;
expect(pagesSelectNode.value).toBe(4);
});
it('should propagate the total pages to `<bx-pages-select>`', async function() {
render(template({ total: 100 }), document.body);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
paginationNode.pageSize = 5;
paginationNode.total = 21;
await Promise.resolve();
const pagesSelectNode = document.body.querySelector('bx-pages-select') as BXPagesSelect;
expect(pagesSelectNode.total).toBe(5);
});
it('should handle change in page size at non-first page', async function() {
// This test case hits the following issue if we don't apply the workaround:
// https://github.com/Polymer/lit-html/issues/1052
render(
template({
pageSize: 10,
start: 190,
total: 200,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
paginationNode.pageSize = 5;
await Promise.resolve(); // Update in `<bx-pagination>`
await Promise.resolve(); // Update in `<bx-pages-select>`
const pagesSelectNode = document.body.querySelector('bx-pages-select') as BXPagesSelect;
expect(pagesSelectNode.shadowRoot!.querySelector('select')!.value).toBe('38');
});
});
describe('Handling user gestures', function() {
it('should support prev button', async function() {
let newStart;
render(
template({
pageSize: 10,
start: 20,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
events.on(paginationNode, 'bx-pagination-changed-current', (event: CustomEvent) => {
newStart = event.detail.start;
});
paginationNode.shadowRoot!.querySelectorAll('button')[0].click();
expect(paginationNode.start).toBe(10);
expect(newStart).toBe(10);
});
it('should ensure the start position will not be negative by hitting prev button', async function() {
let newStart;
render(
template({
pageSize: 10,
start: 5,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
events.on(paginationNode, 'bx-pagination-changed-current', (event: CustomEvent) => {
newStart = event.detail.start;
});
paginationNode.shadowRoot!.querySelectorAll('button')[0].click();
expect(paginationNode.start).toBe(0);
expect(newStart).toBe(0);
});
it('should ensure prev button will not be in effect at the first page even if it is not disabled', async function() {
render(
template({
pageSize: 10,
start: 0,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
const spyChanged = jasmine.createSpy('changed');
events.on(paginationNode, 'bx-pagination-changed-current', spyChanged);
// Prev button should be disabled when `start` indicates that we are at the first page,
// but we ensure nothing happens even if the button is enabled
paginationNode.shadowRoot!.querySelectorAll('button')[0].disabled = false;
paginationNode.shadowRoot!.querySelectorAll('button')[0].click();
expect(paginationNode.start).toBe(0);
expect(spyChanged).not.toHaveBeenCalled();
});
it('should support next button', async function() {
let newStart;
render(
template({
pageSize: 10,
start: 20,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
events.on(paginationNode, 'bx-pagination-changed-current', (event: CustomEvent) => {
newStart = event.detail.start;
});
paginationNode.shadowRoot!.querySelectorAll('button')[1].click();
expect(paginationNode.start).toBe(30);
expect(newStart).toBe(30);
});
it('should ensure the start position will not exceed the total size by hitting next button', async function() {
render(
template({
pageSize: 10,
start: 20,
total: 30,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
const spyChanged = jasmine.createSpy('changed');
events.on(paginationNode, 'bx-pagination-changed-current', spyChanged);
// Next button should be disabled when `start` indicates that we are at the last page,
// but we ensure nothing happens even if the button is enabled
paginationNode.shadowRoot!.querySelectorAll('button')[1].disabled = false;
paginationNode.shadowRoot!.querySelectorAll('button')[1].click();
expect(paginationNode.start).toBe(20);
expect(spyChanged).not.toHaveBeenCalled();
});
it('should support next button at the last page', async function() {
render(
template({
pageSize: 10,
start: 25,
total: 30,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
const spyChanged = jasmine.createSpy('changed');
events.on(paginationNode, 'bx-pagination-changed-current', spyChanged);
// Next button should be disabled when `start` indicates that we are at the last page,
// but we ensure nothing happens even if the button is enabled
paginationNode.shadowRoot!.querySelectorAll('button')[1].disabled = false;
paginationNode.shadowRoot!.querySelectorAll('button')[1].click();
expect(paginationNode.start).toBe(25);
expect(spyChanged).not.toHaveBeenCalled();
});
it('should support next button for infinite row count', async function() {
let newStart;
render(
template({
pageSize: 10,
start: 25,
total: null,
}),
document.body
);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
events.on(paginationNode, 'bx-pagination-changed-current', (event: CustomEvent) => {
newStart = event.detail.start;
});
paginationNode.shadowRoot!.querySelectorAll('button')[1].click();
expect(paginationNode.start).toBe(35);
expect(newStart).toBe(35);
});
it('should support user-initiated change in page size', async function() {
render(template({ total: 100 }), document.body);
await Promise.resolve();
const pagesSelectNode = document.body.querySelector('bx-pages-select') as BXPagesSelect;
pagesSelectNode.dispatchEvent(new CustomEvent('bx-page-sizes-select-changed', { bubbles: true, detail: { value: 5 } }));
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
expect(paginationNode.pageSize).toBe(5);
});
it('should support user-initiated change in current page', async function() {
let newStart;
render(template({ pageSize: 10, total: 100 }), document.body);
await Promise.resolve();
const paginationNode = document.body.querySelector('bx-pagination') as BXPagination;
events.on(paginationNode, 'bx-pagination-changed-current', (event: CustomEvent) => {
newStart = event.detail.start;
});
const pagesSelectNode = document.body.querySelector('bx-pages-select') as BXPagesSelect;
pagesSelectNode.dispatchEvent(new CustomEvent('bx-pages-select-changed', { bubbles: true, detail: { value: 3 } }));
expect(paginationNode.start).toBe(30);
expect(newStart).toBe(30);
});
});
afterEach(async function() {
await render(undefined!, document.body);
events.reset();
});
}); | the_stack |
process.worker = true;
// tslint:disable:no-import-side-effect
import './dotenv';
import { ipcRenderer, remote } from 'electron';
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
import { join } from 'path';
import { PubSub } from 'graphql-subscriptions';
// @ts-ignore no declaration file
import { updateUI } from 'redux-ui/transpiled/action-reducer';
import { openProcessManager, setFullScreenState, setOnlineStatus, toggleKbdShortcuts } from './app/duck';
import { getFocus } from './app/selectors';
import {
detachCurrentlyFocusedApplicationTab,
dispatchURLNavigationActiveApp,
resetZoomActiveApp,
zoomInActiveApp,
zoomOutActiveApp,
} from './applications/ApplicationsActions';
import { dispatchUrl } from './applications/duck';
import ManifestProvider from './applications/manifest-provider/manifest-provider';
import DistantFetcher from './applications/manifest-provider/distant-fetcher';
import { getForeFrontNavigationStateProperty } from './applications/utils';
import { setReleaseNotesSubdockVisibility } from './auto-update/duck';
import * as bang from './bang/duck';
import { AlertDialogProviderServiceImpl } from './dialogs/alertDialogProvider';
import * as inTabSearch from './in-tab-search/duck';
import * as notificationCenter from './notification-center/duck';
import { NotificationProps } from './notification-center/types';
import { TabWebContentsAutoLoginDetailsProviderServiceImpl } from './password-managers/autoLoginProvider';
import ResourceRouterDispatcher from './resources/ResourceRouterDispatcher';
import bxSDK from './sdk';
import { handleError } from './services/api/helpers';
import { observer } from './services/lib/helpers';
import { ApolloLinkServiceImpl } from './services/services/apollo-link/worker';
import { AutolaunchProviderServiceImpl } from './services/services/autolaunch/autolaunch-provider/worker';
import { ManifestServiceImpl } from './services/services/manifest/main';
import { IMenuServiceObserverOnClickItemParam } from './services/services/menu/interface';
import { SDKv2ServiceImpl } from './services/services/sdkv2/worker';
import services from './services/servicesManager';
import { configureStore } from './store/configureStore.worker';
import { BasicAuthDetailsProviderServiceImpl } from './tab-webcontents/basicAuthDetailsProvider';
import { executeWebviewMethodForCurrentTab } from './tab-webcontents/duck';
import { WebContentsOverrideProviderServiceImpl } from './tab-webcontents/overrideProvider';
import { StationStoreWorker } from './types';
import * as ui from './ui/duck';
import { NEW_TAB } from './urlrouter/constants';
import { UrlDispatcherProviderServiceImpl } from './urlrouter/urlDispatcherProvider';
import { isPackaged } from './utils/env';
import AboutWindowManager from './windows/utils/AboutWindowManager';
import GenericWindowManager from './windows/utils/GenericWindowManager';
import MainWindowManager from './windows/utils/MainWindowManager';
import URLRouter from './urlrouter/URLRouter';
import { closeCurrentTab } from './tabs/duck';
export class BrowserXAppWorker {
public store: StationStoreWorker;
public mainWindowManager: MainWindowManager;
public apolloClient: ApolloClient<NormalizedCacheObject>;
public manifestProvider: ManifestProvider;
public pubsub: PubSub;
public router: URLRouter;
public resourceRouter: ResourceRouterDispatcher;
constructor() {
try {
this.initStore();
this.initManifestProvider();
this.pubsub = new PubSub();
this.initRouter();
this.initResourceRouter();
this.initApolloLink();
this.initWindowManager();
this.initSDK();
this.initAppLifeCycle().catch(handleError());
this.initOnlineListener();
this.initMenu();
this.initContextMenu();
this.initApolloClient();
this.initAlertProvider().catch(handleError());
this.initAutoLoginProvider().catch(handleError());
this.initBasicAuthProvider().catch(handleError());
this.initUrlDispatcherProvider().catch(handleError());
this.initWebContentsOverrideProvider().catch(handleError());
this.initSDKv2();
this.initAutoLaunch().catch(handleError());
} catch (e) {
handleError()(e);
remote.app.exit(1);
}
}
initManifestProvider() {
this.manifestProvider = new ManifestProvider({
// Use native fetch for manifests fetching
distantFetcher: new DistantFetcher(),
cachePath: join(remote.app.getPath('userData'), 'ApplicationManifestsCache'),
});
(services.manifest as ManifestServiceImpl).init(this.manifestProvider);
}
initRouter() {
this.router = new URLRouter(this.store.getState, this.manifestProvider);
}
initResourceRouter() {
this.resourceRouter = new ResourceRouterDispatcher(this.store, this.router, this.manifestProvider);
}
initApolloLink() {
(services.apolloLink as ApolloLinkServiceImpl).init(
this.store,
this.manifestProvider,
this.resourceRouter,
this.pubsub,
);
}
initApolloClient() {
// local apollo client
this.apolloClient = new ApolloClient({
link: (services.apolloLink as ApolloLinkServiceImpl).link!,
cache: new InMemoryCache({
// reactive-graphql does not like this
addTypename: false,
}),
// see apollographql/apollo-client#4322
queryDeduplication: false,
});
}
initAlertProvider() {
return services.tabWebContents.setAlertDialogProvider(new AlertDialogProviderServiceImpl(this.store));
}
initAutoLoginProvider() {
return services.tabWebContents
.setAutoLoginDetailsProvider(new TabWebContentsAutoLoginDetailsProviderServiceImpl(this.store));
}
initBasicAuthProvider() {
return services.tabWebContents
.setBasicAuthDetailsProvider(new BasicAuthDetailsProviderServiceImpl(this.store));
}
initUrlDispatcherProvider() {
return services.tabWebContents
.setUrlDispatcherProvider(new UrlDispatcherProviderServiceImpl(this.store));
}
initWebContentsOverrideProvider() {
return services.tabWebContents
.setWebContentsOverrideProvider(new WebContentsOverrideProviderServiceImpl(this.store, this.manifestProvider));
}
// this is temporary public
public handleMenuItemClick({
event,
action,
args,
}: IMenuServiceObserverOnClickItemParam) {
switch (action) {
case 'about':
AboutWindowManager.show().catch(handleError());
break;
case 'settings':
this.dispatch(ui.toggleVisibility(['settings', 'isVisible']));
break;
case 'bang':
this.mainWindowManager.focus().catch(handleError());
this.dispatch(bang.toggleVisibility('center-modal', 'topbar_menu_or_keyboard_shortcut'));
break;
case 'notification-center':
this.dispatch(notificationCenter.toggleVisibility());
break;
case 'page-reload':
this.dispatch(executeWebviewMethodForCurrentTab('reload'));
break;
case 'page-reset-zoom':
this.dispatch(resetZoomActiveApp());
break;
case 'page-zoom-in':
this.dispatch(zoomInActiveApp());
break;
case 'page-zoom-out':
this.dispatch(zoomOutActiveApp());
break;
case 'page-go-back':
this.dispatch(executeWebviewMethodForCurrentTab('go-back'));
break;
case 'page-go-forward':
this.dispatch(executeWebviewMethodForCurrentTab('go-forward'));
break;
case 'copy-url-to-clipboard':
this.dispatch(executeWebviewMethodForCurrentTab('copy-url-to-clipboard'));
break;
case 'paste-and-match-style':
case 'paste-and-match-style-hidden':
this.dispatch(executeWebviewMethodForCurrentTab('paste-and-match-style'));
break;
case 'full-screen':
services.browserWindow.getFocusedWindow()
.then((w) => {
if (w) return w.toggleFullscreen();
return;
})
.catch(handleError());
break;
case 'app-devtools':
services.browserWindow.getFocusedWindow()
.then((w) => {
if (w) return w.toggleDevTools();
return;
})
.catch(handleError());
break;
case 'page-devtools':
this.dispatch(executeWebviewMethodForCurrentTab('toggle-dev-tools'));
break;
case 'worker-devtools':
services.browserWindow.toggleWorkerDevTools();
break;
case 'app-quit':
services.electronApp.quit().catch(handleError());
break;
case 'app-reload':
services.browserWindow.getFocusedWindow()
.then((w) => {
if (w) return w.reload();
return;
})
.catch(handleError());
break;
case 'new-page': {
const [url] = args;
this.dispatch(dispatchURLNavigationActiveApp(url, { target: NEW_TAB }));
break;
}
case 'find':
this.dispatch(inTabSearch.activateForCurrentTab());
break;
case 'detach-current-tab':
this.dispatch(detachCurrentlyFocusedApplicationTab());
break;
case 'close-current-tab':
const via = Boolean(event.triggeredByAccelerator) ? 'keyboard-shortcut' : 'click';
this.dispatch(closeCurrentTab(via));
break;
case 'reset-window-position':
if (this.mainWindowManager.window) {
this.mainWindowManager.window.resetWindowPosition().catch(handleError());
}
break;
case 'toggle-kbd-shortcuts':
this.dispatch(toggleKbdShortcuts());
break;
case 'show-community':
this.dispatch(dispatchUrl('https://feedback.getstation.com/'));
break;
case 'show-release-notes':
this.dispatch(setReleaseNotesSubdockVisibility(true));
break;
case 'station-tour':
break;
case 'reset-current-application':
this.dispatch(updateUI('confirmResetApplicationModal', 'isVisible', getFocus(this.getState())));
break;
case 'open-process-manager':
this.dispatch(openProcessManager());
break;
default:
throw new Error(`No handled menu action: ${action}`);
}
}
initContextMenu() {
const handleMenuItemClick = this.handleMenuItemClick.bind(this);
/* tslint:disable-next-line no-this-assignment */
const { store } = this;
services.tabWebContents.addGlobalObserver(observer({
async onNewWebview(webContentsId: number) {
const contextMenuService = await services.contextMenu.create({ webcontentsId: webContentsId });
return contextMenuService.addObserver(observer({
async onShow(props: Electron.ContextMenuParams) {
const newProps = !props.misspelledWord ? props : {
...props,
misspellingCorrections: await services.tabWebContents
.querySpellchecker(webContentsId, props.misspelledWord),
};
const state = store.getState();
contextMenuService.popup({
props: newProps,
context: {
inWebview: true,
backForwardState: {
canGoBack: getForeFrontNavigationStateProperty(state, 'canGoBack'),
canGoForward: getForeFrontNavigationStateProperty(state, 'canGoForward'),
},
},
});
},
onClickItem(params: IMenuServiceObserverOnClickItemParam) {
handleMenuItemClick(params);
},
}, 'ctx-show-click'));
},
}, 'wc-global')).catch(handleError());
}
private initStore() {
this.store = configureStore(this);
// @ts-ignore debug purpose
window.stationStore = this.store;
}
private initWindowManager() {
GenericWindowManager.store = this.store;
this.mainWindowManager = new MainWindowManager();
this.mainWindowManager.on('enter-full-screen', () => this.dispatch(setFullScreenState(true)));
this.mainWindowManager.on('leave-full-screen', () => this.dispatch(setFullScreenState(false)));
this.mainWindowManager.on('swipe-left', () => this.dispatch(executeWebviewMethodForCurrentTab('go-back')));
this.mainWindowManager.on('swipe-right', () => this.dispatch(executeWebviewMethodForCurrentTab('go-forward')));
this.mainWindowManager.on('new-notification', (notificationId: string, props: NotificationProps, options: NotificationOptions) =>
this.dispatch(notificationCenter.newNotification(undefined, undefined, notificationId, props, options))
);
}
private initSDK() {
bxSDK.init(this.store, this.resourceRouter);
}
private async initAppLifeCycle() {
// Don't wrap this in this.store.ready()
// because we want the window to be created as soon as possible
await this.mainWindowManager.create();
const onActivate = async () => {
const isReady = await services.electronApp.isReady();
if (!isReady) return;
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
await this.mainWindowManager.create();
};
services.electronApp.addObserver(observer({ onActivate }, 'app-on-activate')).catch(handleError());
}
private initMenu() {
const { dispatch } = this.store;
const mainWindowManager = this.mainWindowManager;
const handleMenuItemClick = this.handleMenuItemClick.bind(this);
// install the menu
services.menu.addObserver(observer({
onClickItem(param: any) {
// dispatch actions from the menu
handleMenuItemClick(param);
},
onGlobalBangShortcut() {
if (!mainWindowManager.isCreated()) return;
dispatch(bang.setVisibility('center-modal', true));
mainWindowManager.focus();
},
}, 'init-menu')).catch(handleError());
}
private initOnlineListener() {
const updateOnlineStatus = (isOnline: boolean) => {
this.dispatch(setOnlineStatus(isOnline));
};
window.addEventListener('online', () => updateOnlineStatus(true));
window.addEventListener('offline', () => updateOnlineStatus(false));
updateOnlineStatus(navigator.onLine);
}
private initSDKv2() {
return (services.sdkv2 as SDKv2ServiceImpl).setStore(this.store);
}
private async initAutoLaunch() {
return services.autolaunch.setAutolaunchProvider(new AutolaunchProviderServiceImpl(this.store));
}
private dispatch(action: any) {
return this.store.dispatch(action);
}
private getState() {
return this.store.getState();
}
}
if (!isPackaged) {
process.on('unhandledRejection', error => {
console.trace(error);
});
}
if (module.hot) {
module.hot.accept();
module.hot.addDisposeHandler(() => {
// We ask the main process to restart as if the main process was edited
ipcRenderer.send('hmr:worker');
});
}
export default new BrowserXAppWorker(); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/servicePrincipalsMappers";
import * as Parameters from "../models/parameters";
import { GraphRbacManagementClientContext } from "../graphRbacManagementClientContext";
/** Class representing a ServicePrincipals. */
export class ServicePrincipals {
private readonly client: GraphRbacManagementClientContext;
/**
* Create a ServicePrincipals.
* @param {GraphRbacManagementClientContext} client Reference to the service client.
*/
constructor(client: GraphRbacManagementClientContext) {
this.client = client;
}
/**
* Creates a service principal in the directory.
* @param parameters Parameters to create a service principal.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsCreateResponse>
*/
create(parameters: Models.ServicePrincipalCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsCreateResponse>;
/**
* @param parameters Parameters to create a service principal.
* @param callback The callback
*/
create(parameters: Models.ServicePrincipalCreateParameters, callback: msRest.ServiceCallback<Models.ServicePrincipal>): void;
/**
* @param parameters Parameters to create a service principal.
* @param options The optional parameters
* @param callback The callback
*/
create(parameters: Models.ServicePrincipalCreateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServicePrincipal>): void;
create(parameters: Models.ServicePrincipalCreateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServicePrincipal>, callback?: msRest.ServiceCallback<Models.ServicePrincipal>): Promise<Models.ServicePrincipalsCreateResponse> {
return this.client.sendOperationRequest(
{
parameters,
options
},
createOperationSpec,
callback) as Promise<Models.ServicePrincipalsCreateResponse>;
}
/**
* Gets a list of service principals from the current tenant.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsListResponse>
*/
list(options?: Models.ServicePrincipalsListOptionalParams): Promise<Models.ServicePrincipalsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.ServicePrincipalListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: Models.ServicePrincipalsListOptionalParams, callback: msRest.ServiceCallback<Models.ServicePrincipalListResult>): void;
list(options?: Models.ServicePrincipalsListOptionalParams | msRest.ServiceCallback<Models.ServicePrincipalListResult>, callback?: msRest.ServiceCallback<Models.ServicePrincipalListResult>): Promise<Models.ServicePrincipalsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.ServicePrincipalsListResponse>;
}
/**
* Updates a service principal in the directory.
* @param objectId The object ID of the service principal to delete.
* @param parameters Parameters to update a service principal.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
update(objectId: string, parameters: Models.ServicePrincipalUpdateParameters, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param objectId The object ID of the service principal to delete.
* @param parameters Parameters to update a service principal.
* @param callback The callback
*/
update(objectId: string, parameters: Models.ServicePrincipalUpdateParameters, callback: msRest.ServiceCallback<void>): void;
/**
* @param objectId The object ID of the service principal to delete.
* @param parameters Parameters to update a service principal.
* @param options The optional parameters
* @param callback The callback
*/
update(objectId: string, parameters: Models.ServicePrincipalUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
update(objectId: string, parameters: Models.ServicePrincipalUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
objectId,
parameters,
options
},
updateOperationSpec,
callback);
}
/**
* Deletes a service principal from the directory.
* @param objectId The object ID of the service principal to delete.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(objectId: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param objectId The object ID of the service principal to delete.
* @param callback The callback
*/
deleteMethod(objectId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param objectId The object ID of the service principal to delete.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(objectId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(objectId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
objectId,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Gets service principal information from the directory. Query by objectId or pass a filter to
* query by appId
* @param objectId The object ID of the service principal to get.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsGetResponse>
*/
get(objectId: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsGetResponse>;
/**
* @param objectId The object ID of the service principal to get.
* @param callback The callback
*/
get(objectId: string, callback: msRest.ServiceCallback<Models.ServicePrincipal>): void;
/**
* @param objectId The object ID of the service principal to get.
* @param options The optional parameters
* @param callback The callback
*/
get(objectId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServicePrincipal>): void;
get(objectId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServicePrincipal>, callback?: msRest.ServiceCallback<Models.ServicePrincipal>): Promise<Models.ServicePrincipalsGetResponse> {
return this.client.sendOperationRequest(
{
objectId,
options
},
getOperationSpec,
callback) as Promise<Models.ServicePrincipalsGetResponse>;
}
/**
* The owners are a set of non-admin users who are allowed to modify this object.
* @summary Directory objects that are owners of this service principal.
* @param objectId The object ID of the service principal for which to get owners.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsListOwnersResponse>
*/
listOwners(objectId: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsListOwnersResponse>;
/**
* @param objectId The object ID of the service principal for which to get owners.
* @param callback The callback
*/
listOwners(objectId: string, callback: msRest.ServiceCallback<Models.DirectoryObjectListResult>): void;
/**
* @param objectId The object ID of the service principal for which to get owners.
* @param options The optional parameters
* @param callback The callback
*/
listOwners(objectId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DirectoryObjectListResult>): void;
listOwners(objectId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DirectoryObjectListResult>, callback?: msRest.ServiceCallback<Models.DirectoryObjectListResult>): Promise<Models.ServicePrincipalsListOwnersResponse> {
return this.client.sendOperationRequest(
{
objectId,
options
},
listOwnersOperationSpec,
callback) as Promise<Models.ServicePrincipalsListOwnersResponse>;
}
/**
* Get the keyCredentials associated with the specified service principal.
* @param objectId The object ID of the service principal for which to get keyCredentials.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsListKeyCredentialsResponse>
*/
listKeyCredentials(objectId: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsListKeyCredentialsResponse>;
/**
* @param objectId The object ID of the service principal for which to get keyCredentials.
* @param callback The callback
*/
listKeyCredentials(objectId: string, callback: msRest.ServiceCallback<Models.KeyCredentialListResult>): void;
/**
* @param objectId The object ID of the service principal for which to get keyCredentials.
* @param options The optional parameters
* @param callback The callback
*/
listKeyCredentials(objectId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.KeyCredentialListResult>): void;
listKeyCredentials(objectId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.KeyCredentialListResult>, callback?: msRest.ServiceCallback<Models.KeyCredentialListResult>): Promise<Models.ServicePrincipalsListKeyCredentialsResponse> {
return this.client.sendOperationRequest(
{
objectId,
options
},
listKeyCredentialsOperationSpec,
callback) as Promise<Models.ServicePrincipalsListKeyCredentialsResponse>;
}
/**
* Update the keyCredentials associated with a service principal.
* @param objectId The object ID for which to get service principal information.
* @param value A collection of KeyCredentials.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
updateKeyCredentials(objectId: string, value: Models.KeyCredential[], options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param objectId The object ID for which to get service principal information.
* @param value A collection of KeyCredentials.
* @param callback The callback
*/
updateKeyCredentials(objectId: string, value: Models.KeyCredential[], callback: msRest.ServiceCallback<void>): void;
/**
* @param objectId The object ID for which to get service principal information.
* @param value A collection of KeyCredentials.
* @param options The optional parameters
* @param callback The callback
*/
updateKeyCredentials(objectId: string, value: Models.KeyCredential[], options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
updateKeyCredentials(objectId: string, value: Models.KeyCredential[], options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
objectId,
value,
options
},
updateKeyCredentialsOperationSpec,
callback);
}
/**
* Gets the passwordCredentials associated with a service principal.
* @param objectId The object ID of the service principal.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsListPasswordCredentialsResponse>
*/
listPasswordCredentials(objectId: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsListPasswordCredentialsResponse>;
/**
* @param objectId The object ID of the service principal.
* @param callback The callback
*/
listPasswordCredentials(objectId: string, callback: msRest.ServiceCallback<Models.PasswordCredentialListResult>): void;
/**
* @param objectId The object ID of the service principal.
* @param options The optional parameters
* @param callback The callback
*/
listPasswordCredentials(objectId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PasswordCredentialListResult>): void;
listPasswordCredentials(objectId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PasswordCredentialListResult>, callback?: msRest.ServiceCallback<Models.PasswordCredentialListResult>): Promise<Models.ServicePrincipalsListPasswordCredentialsResponse> {
return this.client.sendOperationRequest(
{
objectId,
options
},
listPasswordCredentialsOperationSpec,
callback) as Promise<Models.ServicePrincipalsListPasswordCredentialsResponse>;
}
/**
* Updates the passwordCredentials associated with a service principal.
* @param objectId The object ID of the service principal.
* @param value A collection of PasswordCredentials.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
updatePasswordCredentials(objectId: string, value: Models.PasswordCredential[], options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param objectId The object ID of the service principal.
* @param value A collection of PasswordCredentials.
* @param callback The callback
*/
updatePasswordCredentials(objectId: string, value: Models.PasswordCredential[], callback: msRest.ServiceCallback<void>): void;
/**
* @param objectId The object ID of the service principal.
* @param value A collection of PasswordCredentials.
* @param options The optional parameters
* @param callback The callback
*/
updatePasswordCredentials(objectId: string, value: Models.PasswordCredential[], options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
updatePasswordCredentials(objectId: string, value: Models.PasswordCredential[], options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
objectId,
value,
options
},
updatePasswordCredentialsOperationSpec,
callback);
}
/**
* Gets a list of service principals from the current tenant.
* @param nextLink Next link for the list operation.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsListNextResponse>
*/
listNext(nextLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsListNextResponse>;
/**
* @param nextLink Next link for the list operation.
* @param callback The callback
*/
listNext(nextLink: string, callback: msRest.ServiceCallback<Models.ServicePrincipalListResult>): void;
/**
* @param nextLink Next link for the list operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServicePrincipalListResult>): void;
listNext(nextLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServicePrincipalListResult>, callback?: msRest.ServiceCallback<Models.ServicePrincipalListResult>): Promise<Models.ServicePrincipalsListNextResponse> {
return this.client.sendOperationRequest(
{
nextLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.ServicePrincipalsListNextResponse>;
}
/**
* The owners are a set of non-admin users who are allowed to modify this object.
* @summary Directory objects that are owners of this service principal.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ServicePrincipalsListOwnersNextResponse>
*/
listOwnersNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicePrincipalsListOwnersNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listOwnersNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DirectoryObjectListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listOwnersNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DirectoryObjectListResult>): void;
listOwnersNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DirectoryObjectListResult>, callback?: msRest.ServiceCallback<Models.DirectoryObjectListResult>): Promise<Models.ServicePrincipalsListOwnersNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listOwnersNextOperationSpec,
callback) as Promise<Models.ServicePrincipalsListOwnersNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "{tenantID}/servicePrincipals",
urlParameters: [
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ServicePrincipalCreateParameters,
required: true
}
},
responses: {
201: {
bodyMapper: Mappers.ServicePrincipal
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{tenantID}/servicePrincipals",
urlParameters: [
Parameters.tenantID
],
queryParameters: [
Parameters.filter,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ServicePrincipalListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "{tenantID}/servicePrincipals/{objectId}",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ServicePrincipalUpdateParameters,
required: true
}
},
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{tenantID}/servicePrincipals/{objectId}",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{tenantID}/servicePrincipals/{objectId}",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ServicePrincipal
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const listOwnersOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{tenantID}/servicePrincipals/{objectId}/owners",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DirectoryObjectListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const listKeyCredentialsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{tenantID}/servicePrincipals/{objectId}/keyCredentials",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.KeyCredentialListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const updateKeyCredentialsOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "{tenantID}/servicePrincipals/{objectId}/keyCredentials",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: {
value: "value"
},
mapper: {
...Mappers.KeyCredentialsUpdateParameters,
required: true
}
},
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const listPasswordCredentialsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{tenantID}/servicePrincipals/{objectId}/passwordCredentials",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PasswordCredentialListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const updatePasswordCredentialsOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "{tenantID}/servicePrincipals/{objectId}/passwordCredentials",
urlParameters: [
Parameters.objectId,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: {
value: "value"
},
mapper: {
...Mappers.PasswordCredentialsUpdateParameters,
required: true
}
},
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{tenantID}/{nextLink}",
urlParameters: [
Parameters.nextLink,
Parameters.tenantID
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ServicePrincipalListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
};
const listOwnersNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://graph.windows.net",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DirectoryObjectListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
serializer
}; | the_stack |
import { Constants } from './Constants';
import { LocaleOptions, Locales } from './Locale';
import { Weekday } from './Weekday';
export type Unit =
'millis' |
'second' |
'minute' |
'hour' |
'day' |
'week' |
'month' |
'quarter' |
'year';
export type UnitRecord<T> = Record<Unit, T>;
export type Starter = (x: Date, options?: LocaleOptions) => void;
export const startOf: UnitRecord<Starter> =
{
millis: x => x,
second: startOfSecond,
minute: startOfMinute,
hour: startOfHour,
day: startOfDay,
week: startOfWeek,
month: startOfMonth,
quarter: startOfQuarter,
year: startOfYear,
};
export type Ender = (x: Date, options?: LocaleOptions) => void;
export const endOf: UnitRecord<Ender> =
{
millis: x => x,
second: endOfSecond,
minute: endOfMinute,
hour: endOfHour,
day: endOfDay,
week: endOfWeek,
month: endOfMonth,
quarter: endOfQuarter,
year: endOfYear,
};
export type Adder = (x: Date, amount: number) => void;
export const add: UnitRecord<Adder> =
{
millis: addMilliseconds,
second: addSeconds,
minute: addMinutes,
hour: addHours,
day: addDays,
week: addWeeks,
month: addMonths,
quarter: addQuarters,
year: addYears,
};
export type Differ = (a: Date, b: Date) => number;
export const diff: UnitRecord<Differ> =
{
millis: diffMilliseconds,
second: diffSeconds,
minute: diffMinutes,
hour: diffHours,
day: diffDays,
week: diffWeeks,
month: diffMonths,
quarter: diffQuarters,
year: diffYears,
};
/**
* The number of milliseconds for various duration units. These are worse case
* scenario and do not include DST changes.
*/
export const durations: UnitRecord<number> =
{
millis: 1,
second: Constants.MILLIS_IN_SECOND,
minute: Constants.MILLIS_IN_MINUTE,
hour: Constants.MILLIS_IN_HOUR,
day: Constants.MILLIS_IN_DAY,
week: Constants.MILLIS_IN_WEEK,
month: Constants.MILLIS_IN_DAY * Constants.DAY_MAX,
quarter: Constants.MILLIS_IN_DAY * Constants.DAY_MAX * Constants.MONTHS_IN_QUARTER,
year: Constants.MILLIS_IN_DAY * Constants.DAYS_IN_YEAR
}
export function mutate(a: Date, mutator: (a: Date, options?: LocaleOptions) => void, options?: LocaleOptions): Date
{
const b = new Date(a.getTime());
mutator(b, options);
return b;
}
export function compare(a: Date, b: Date, precision: Unit = 'millis', options: LocaleOptions = Locales.current): number
{
const starter = startOf[precision];
const x = mutate(a, starter, options);
const y = mutate(b, starter, options);
return x.getTime() - y.getTime();
}
export function getLastDayOfMonth(x: Date): number
{
return getDaysInMonth(x) - x.getDate() + 1;
}
export function getLastWeekspanOfYear(x: Date): number
{
const fromEnd = getDaysInYear(x) - getDayOfYear(x);
return Math.floor(fromEnd / Constants.DAYS_IN_WEEK);
}
export function getWeekOfYearISO(x: Date, options: LocaleOptions = Locales.current): number
{
return getWeekISO(mutate(x, startOfYear), getDayOfYear(x), options);
}
export function getWeekOfYear(x: Date, options: LocaleOptions = Locales.current): number
{
return getWeek(mutate(x, startOfYear), getDayOfYear(x), options);
}
export function getWeekspanOfYear(x: Date): number
{
return Math.floor((getDayOfYear(x) - 1) / Constants.DAYS_IN_WEEK);
}
export function getFullWeekOfYear(x: Date, options: LocaleOptions = Locales.current): number
{
return getFullWeekOf(mutate(x, startOfYear), getDaysInYear(x), options);
}
export function getWeeksInYear(x: Date, options: LocaleOptions = Locales.current): number
{
return getWeekOfYearISO(mutate(x, endOfYear), options) + 1;
}
export function getLastFullWeekOfYear(x: Date, options: LocaleOptions = Locales.current): number
{
const lastOfYear = mutate(x, endOfYear);
const week = getWeekOfYearISO(x, options);
const weekMax = getWeekOfYearISO(lastOfYear, options);
const lastWeek = weekMax - week;
return getDayOfWeek(lastOfYear, options) === Constants.WEEKDAY_MAX
? lastWeek + 1
: lastWeek;
}
export function getWeekspanOfMonth(x: Date): number
{
return Math.floor((x.getDate() - 1) / Constants.DAYS_IN_WEEK);
}
export function getLastWeekspanOfMonth(x: Date): number
{
const fromEnd = getDaysInMonth(x) - x.getDate();
return Math.floor(fromEnd / Constants.DAYS_IN_WEEK);
}
export function getFullWeekOfMonth(x: Date, options: LocaleOptions = Locales.current): number
{
return getFullWeekOf(mutate(x, startOfMonth), x.getDate(), options);
}
export function getLastFullWeekOfMonth(x: Date, options: LocaleOptions = Locales.current): number
{
const fromEnd = getDaysInMonth(x) - x.getDate();
const invertedDayOfWeek = Constants.WEEKDAY_MAX - getDayOfWeek(x, options);
return Math.floor((fromEnd - invertedDayOfWeek + Constants.DAYS_IN_WEEK) / Constants.DAYS_IN_WEEK);
}
export function getWeekOfMonthISO(x: Date, options: LocaleOptions = Locales.current): number
{
return getWeekISO(mutate(x, startOfMonth), x.getDate(), options);
}
export function getWeekOfMonth(x: Date, options: LocaleOptions = Locales.current): number
{
return getWeek(mutate(x, startOfMonth), x.getDate(), options);
}
export function getWeekISO(start: Date, dayOfStart: number, options: LocaleOptions = Locales.current): number
{
const { firstWeekContainsDate } = options;
const dayOfWeekFirst = getDayOfWeek(start, options);
const hasWeekZero = Constants.DAYS_IN_WEEK - dayOfWeekFirst < firstWeekContainsDate;
const offset = hasWeekZero
? dayOfWeekFirst - 1
: dayOfWeekFirst - 1 + Constants.DAYS_IN_WEEK;
return Math.floor((dayOfStart + offset) / Constants.DAYS_IN_WEEK);
}
export function getWeek(start: Date, dayOfStart: number, options: LocaleOptions): number
{
const dayOfWeekFirst = getDayOfWeek(start, options);
const offset = dayOfWeekFirst - 1 + Constants.DAYS_IN_WEEK;
return Math.floor((dayOfStart + offset) / Constants.DAYS_IN_WEEK);
}
export function getFullWeekOf(start: Date, dayOfStart: number, options: LocaleOptions = Locales.current): number
{
const dayOfWeekFirst = getDayOfWeek(start, options);
const hasWeekZero = dayOfWeekFirst !== Weekday.SUNDAY;
const offset = hasWeekZero
? dayOfWeekFirst - 1
: dayOfWeekFirst - 1 + Constants.DAYS_IN_WEEK;
return Math.floor((dayOfStart + offset) / Constants.DAYS_IN_WEEK);
}
export function getDayOfWeek(x: Date, options: LocaleOptions = Locales.current): number
{
const { weekStartsOn } = options;
const day = x.getDay();
return day < weekStartsOn
? day - weekStartsOn + Constants.DAYS_IN_WEEK
: day - weekStartsOn;
}
export function getDayOfYear(a: Date): number
{
return Math.round(diffDays(a, mutate(a, startOfYear))) + 1;
}
export function getDateOffset(x: Date): number
{
// tslint:disable-next-line: no-magic-numbers
return -Math.round(x.getTimezoneOffset() / 15) * 15;
}
export function isDaylightSavingTime(x: Date): boolean
{
const offset = getDateOffset(x);
return (
offset > getDateOffset(mutate(x, d => d.setMonth(0))) ||
// tslint:disable-next-line: no-magic-numbers
offset > getDateOffset(mutate(x, d => d.setMonth(5)))
);
}
export function isLeapYear(x: Date): boolean
{
const year = x.getFullYear();
// tslint:disable-next-line: no-magic-numbers
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
}
export function getDaysInYear(x: Date): number
{
// tslint:disable-next-line: no-magic-numbers
return isLeapYear(x) ? 366 : 365;
}
const daysInMonth = [
// tslint:disable-next-line: no-magic-numbers
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
// tslint:disable-next-line: no-magic-numbers
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
];
export function getDaysInMonth(x: Date): number
{
return daysInMonth[isLeapYear(x) ? 1 : 0][x.getMonth()];
}
export function getAbsoluteTimestamp(a: Date): number
{
return a.getTime() - getTimezoneOffsetInMilliseconds(a);
}
export function getTimezoneOffsetInMilliseconds(a: Date): number
{
const b = new Date(a.getTime());
const offsetMinutes = b.getTimezoneOffset();
b.setSeconds(0, 0);
const offsetMilliseconds = b.getTime() % Constants.MILLIS_IN_MINUTE;
return offsetMinutes * Constants.MILLIS_IN_MINUTE + offsetMilliseconds;
}
export function getQuarter(x: Date): number
{
return Math.floor(x.getMonth() / Constants.MONTHS_IN_QUARTER);
}
export function startOfSecond(x: Date): void
{
x.setMilliseconds(0);
}
export function startOfMinute(x: Date): void
{
x.setSeconds(0, 0);
}
export function startOfHour(x: Date): void
{
x.setMinutes(0, 0, 0);
}
export function startOfDay(x: Date): void
{
x.setHours(0, 0, 0, 0);
}
export function startOfWeek(x: Date, options: LocaleOptions = Locales.current): void
{
const dayOfWeek = getDayOfWeek(x, options);
x.setDate(x.getDate() - dayOfWeek);
x.setHours(0, 0, 0, 0);
}
export function startOfMonth(x: Date): void
{
x.setDate(Constants.DAY_MIN);
x.setHours(0, 0, 0, 0);
}
export function startOfQuarter(x: Date): void
{
const month = x.getMonth();
x.setMonth(month - (month % Constants.MONTHS_IN_QUARTER), Constants.DAY_MIN);
x.setHours(0, 0, 0, 0);
}
export function startOfYear(x: Date): void
{
const year = x.getFullYear();
x.setTime(0);
x.setFullYear(year, 0, 1);
x.setHours(0, 0, 0, 0);
}
export function endOfSecond(x: Date): void
{
x.setMilliseconds(Constants.MILLIS_MAX);
}
export function endOfMinute(x: Date): void
{
x.setSeconds(Constants.SECOND_MAX, Constants.MILLIS_MAX);
}
export function endOfHour(x: Date): void
{
x.setMinutes(Constants.MINUTE_MAX, Constants.SECOND_MAX, Constants.MILLIS_MAX);
}
export function endOfDay(x: Date): void
{
x.setHours(Constants.HOUR_MAX, Constants.MINUTE_MAX, Constants.SECOND_MAX, Constants.MILLIS_MAX);
}
export function endOfWeek(x: Date, options: LocaleOptions = Locales.current): void
{
const dayOfWeek = getDayOfWeek(x, options);
x.setDate(x.getDate() + (Constants.WEEKDAY_MAX - dayOfWeek));
endOfDay(x);
}
export function endOfMonth(x: Date): void
{
x.setFullYear(x.getFullYear(), x.getMonth() + 1, 0);
endOfDay(x);
}
export function endOfQuarter(x: Date): void
{
const month = x.getMonth();
x.setMonth(month - (month % Constants.MONTHS_IN_QUARTER) + Constants.MONTHS_IN_QUARTER, Constants.DAY_MIN);
endOfDay(x);
}
export function endOfYear(x: Date): void
{
x.setFullYear(x.getFullYear() + 1, 0, 0);
endOfDay(x);
}
export function addMilliseconds(x: Date, amount: number): void
{
x.setTime(x.getTime() + amount);
}
export function addSeconds(x: Date, amount: number): void
{
addMilliseconds(x, amount * Constants.MILLIS_IN_SECOND);
}
export function addMinutes(x: Date, amount: number): void
{
addMilliseconds(x, amount * Constants.MILLIS_IN_MINUTE);
}
export function addHours(x: Date, amount: number): void
{
addMilliseconds(x, amount * Constants.MILLIS_IN_HOUR);
}
export function addDays(x: Date, amount: number): void
{
x.setDate(x.getDate() + amount);
}
export function addWeeks(x: Date, amount: number): void
{
addDays(x, amount * Constants.DAYS_IN_WEEK);
}
export function addMonths(x: Date, amount: number): void
{
const month = x.getMonth() + amount;
const y = new Date(0)
y.setFullYear(y.getFullYear(), month, 1)
y.setHours(0, 0, 0, 0)
const dayMax = getDaysInMonth(y);
x.setMonth(month, Math.min(dayMax, x.getDate()));
}
export function addQuarters(x: Date, amount: number): void
{
addMonths(x, amount * Constants.MONTHS_IN_QUARTER);
}
export function addYears(x: Date, amount: number): void
{
addMonths(x, amount * Constants.MONTHS_IN_YEAR);
}
export function diffMilliseconds(a: Date, b: Date): number
{
return a.getTime() - b.getTime();
}
export function diffSeconds(a: Date, b: Date): number
{
return diffMilliseconds(a, b) / Constants.MILLIS_IN_SECOND;
}
export function diffMinutes(a: Date, b: Date): number
{
return diffMilliseconds(a, b) / Constants.MILLIS_IN_MINUTE;
}
export function diffHours(a: Date, b: Date): number
{
return diffMilliseconds(a, b) / Constants.MILLIS_IN_HOUR;
}
export function diffDays(a: Date, b: Date): number
{
const leftTimestamp = getAbsoluteTimestamp(a);
const rightTimestamp = getAbsoluteTimestamp(b);
return (leftTimestamp - rightTimestamp) / Constants.MILLIS_IN_DAY;
}
export function diffWeeks(a: Date, b: Date): number
{
return diffDays(a, b) / Constants.DAYS_IN_WEEK;
}
export function diffMonths(a: Date, b: Date): number
{
const years = a.getFullYear() - b.getFullYear();
const months = a.getMonth() - b.getMonth();
const date = (a.getDate() - b.getDate()) / Constants.DAY_MAX;
return years * Constants.MONTHS_IN_YEAR + months + date;
}
export function diffQuarters(a: Date, b: Date): number
{
return diffMonths(a, b) / Constants.MONTHS_IN_QUARTER;
}
export function diffYears(a: Date, b: Date): number
{
return diffMonths(a, b) / Constants.MONTHS_IN_YEAR;
} | the_stack |
import {
Component,
OnDestroy,
ChangeDetectorRef,
ViewContainerRef,
AfterViewInit,
ViewChild,
Input,
AfterContentInit,
HostListener,
ViewEncapsulation,
} from '@angular/core';
import { Subscription, Subject } from 'rxjs';
import { Session } from '../../../../controller/session/session';
import {
ControllerSessionTabSearchOutput,
IStreamState,
ILoadedRange,
} from '../../../../controller/session/dependencies/search/dependencies/output/controller.session.tab.search.output';
import {
IDataAPI,
IRange,
IRowsPacket,
IStorageInformation,
ComplexScrollBoxComponent,
IScrollBoxSelection,
} from 'chipmunk-client-material';
import { IComponentDesc } from 'chipmunk-client-material';
import { ViewOutputRowComponent } from '../../row/component';
import { ViewSearchControlsComponent, IButton } from './controls/component';
import { IMenuItem } from '../../../../services/standalone/service.contextmenu';
import { ISelectionParser } from '../../../../services/standalone/service.selection.parsers';
import { cleanupOutput } from '../../row/helpers';
import { FilterRequest } from '../../../../controller/session/dependencies/search/dependencies/filters/controller.session.tab.search.filters.storage';
import { IStreamStateEvent } from '../../../../controller/session/dependencies/search/dependencies/output/controller.session.tab.search.output';
import { copyTextToClipboard } from '../../../../controller/helpers/clipboard';
import { fullClearRowStr } from '../../../../controller/helpers/row.helpers';
import { IRow } from '../../../../controller/session/dependencies/row/controller.row.api';
import { IExportAction } from '../../../../services/standalone/service.output.exports';
import { IPC } from '../../../../services/service.electron.ipc';
import FocusOutputService from '../../../../services/service.focus.output';
import ViewsEventsService from '../../../../services/standalone/service.views.events';
import EventsHubService from '../../../../services/standalone/service.eventshub';
import ContextMenuService from '../../../../services/standalone/service.contextmenu';
import SelectionParsersService from '../../../../services/standalone/service.selection.parsers';
import OutputRedirectionsService from '../../../../services/standalone/service.output.redirections';
import OutputExportsService from '../../../../services/standalone/service.output.exports';
import * as Toolkit from 'chipmunk.client.toolkit';
const CSettings: {
preloadCount: number;
} = {
preloadCount: 100,
};
@Component({
selector: 'app-views-search-output',
templateUrl: './template.html',
styleUrls: ['./styles.less'],
encapsulation: ViewEncapsulation.None,
})
export class ViewSearchOutputComponent implements OnDestroy, AfterViewInit, AfterContentInit {
@ViewChild(ComplexScrollBoxComponent) _scrollBoxCom!: ComplexScrollBoxComponent;
@Input() public session: Session | undefined;
@Input() public onSessionChanged: Subject<Session> | undefined;
@Input() public injectionIntoTitleBar!: Subject<IComponentDesc | undefined>;
public _ng_outputAPI: IDataAPI;
private _subscriptions: { [key: string]: Subscription } = {};
private _outputSubscriptions: { [key: string]: Subscription } = {};
private _output: ControllerSessionTabSearchOutput | undefined;
private _frames: Map<string, IRange> = new Map();
private _activeSessionId: string = '';
private _controls: {
update: Subject<IButton[]>;
keepScrollDown: boolean;
} = {
update: new Subject<IButton[]>(),
keepScrollDown: true,
};
private _logger: Toolkit.Logger = new Toolkit.Logger('ViewSearchOutputComponent');
constructor(private _cdRef: ChangeDetectorRef, private _vcRef: ViewContainerRef) {
this._ng_outputAPI = {
getLastFrame: this._api_getLastFrame.bind(this),
getComponentFactory: this._api_getComponentFactory.bind(this),
getItemHeight: this._api_getItemHeight.bind(this),
getRange: this._api_getRange.bind(this),
getStorageInfo: this._api_getStorageInfo.bind(this),
updatingDone: this._api_updatingDone.bind(this),
cleanUpClipboard: this._api_cleanUpClipboard.bind(this),
onSourceUpdated: new Subject<void>(),
onStorageUpdated: new Subject<IStorageInformation>(),
onScrollTo: new Subject<number>(),
onScrollUntil: new Subject<number>(),
onRowsDelivered: new Subject<IRowsPacket>(),
onRerequest: new Subject<void>(),
onRedraw: new Subject<void>(),
};
}
@HostListener('contextmenu', ['$event']) public onContexMenu(event: MouseEvent) {
const session = this.session;
if (session === undefined) {
return;
}
if (this._scrollBoxCom === undefined || this._scrollBoxCom === null) {
return;
}
const textSelection: IScrollBoxSelection | undefined = this._scrollBoxCom.getSelection();
const contextRowNumber: number = SelectionParsersService.getContextRowNumber();
const items: IMenuItem[] = [
{
caption: 'Copy',
handler: () => {
if (textSelection !== undefined) {
return this._scrollBoxCom.copySelection();
}
if (!OutputRedirectionsService.hasSelection(session.getGuid())) {
return;
}
OutputRedirectionsService.getOutputSelectionRanges(session.getGuid())
.then((selection) => {
return session
.getSessionStream()
.getRowsSelection(selection)
.then((rows) => {
copyTextToClipboard(
fullClearRowStr(rows.map((row) => row.str).join('\n')),
);
})
.catch((err: Error) => {
this._logger.warn(
`Fail get text selection for range ${selection.join(
'; ',
)} due error: ${err.message}`,
);
});
})
.catch((err: Error) => {
this._logger.warn(
`Fail to call OutputRedirectionsService.getOutputSelectionRanges due error: ${err.message}`,
);
});
},
disabled:
textSelection === undefined &&
!OutputRedirectionsService.hasSelection(session.getGuid()),
},
];
if (textSelection === undefined) {
const win_sel = window.getSelection();
win_sel !== null && win_sel.removeAllRanges();
}
if (contextRowNumber !== -1 && this._output !== undefined) {
const row: IRow | undefined = this._output.getRowByPosition(contextRowNumber);
if (row !== undefined) {
items.push(
...[
{
/* delimiter */
},
{
caption: `Show row #${contextRowNumber}`,
handler: () => {
row.str !== undefined &&
SelectionParsersService.memo(
row.str,
`Row #${contextRowNumber}`,
);
},
},
],
);
}
}
if (textSelection !== undefined) {
const parsers: ISelectionParser[] = SelectionParsersService.getParsers(
textSelection.selection,
);
if (parsers.length > 0) {
items.push(
...[
{
/* delimiter */
},
...parsers.map((parser: ISelectionParser) => {
return {
caption: parser.name,
handler: () => {
SelectionParsersService.parse(
textSelection.selection,
parser.guid,
parser.name,
);
},
};
}),
],
);
}
}
items.push(
...[
{
/* delimiter */
},
{
caption: 'Search with selection',
handler: () => {
if (textSelection === undefined) {
return;
}
const filter: FilterRequest | undefined = this._getFilterFromStr(
textSelection.selection,
);
if (filter === undefined) {
return;
}
session.getSessionSearch().search(filter);
},
disabled:
textSelection === undefined ||
this._getFilterFromStr(textSelection.selection) === undefined,
},
],
);
OutputExportsService.getActions(session.getGuid(), IPC.EOutputExportFeaturesSource.search)
.then((actions: IExportAction[]) => {
if (actions.length > 0) {
items.push(
...[
{
/* delimiter */
},
...actions.map((action: IExportAction) => {
return {
caption: action.caption,
handler: action.caller,
};
}),
],
);
}
})
.catch((err: Error) => {
this._logger.warn(`Fail get actions due error: ${err.message}`);
});
ContextMenuService.show({
items: items,
x: event.pageX,
y: event.pageY,
});
}
ngAfterViewInit() {
if (this._scrollBoxCom === undefined || this._scrollBoxCom === null) {
return;
}
this._subscriptions.onScrolled = this._scrollBoxCom
.getObservable()
.onScrolled.subscribe(this._onScrolled.bind(this));
this._subscriptions.onKeepScrollPrevent =
EventsHubService.getObservable().onKeepScrollPrevent.subscribe(
this._onKeepScrollPrevent.bind(this),
);
this._ng_outputAPI.onRedraw.next();
FocusOutputService.addScrollbox(this._scrollBoxCom);
}
ngAfterContentInit() {
if (this.session === undefined || this.onSessionChanged === undefined) {
return;
}
this._activeSessionId = this.session.getGuid();
// Get reference to stream wrapper
this._output = this.session.getSessionSearch().getOutputStream();
// Make subscriptions
this._subscribeOutputEvents();
this._subscriptions.onResize = ViewsEventsService.getObservable().onResize.subscribe(
this._onResize.bind(this),
);
this._subscriptions.onSessionChanged = this.onSessionChanged
.asObservable()
.subscribe(this._onSessionChanged.bind(this));
// Inject controls to caption of dock
this._ctrl_inject();
}
public ngOnDestroy() {
FocusOutputService.removeScrollbox(this._scrollBoxCom);
Object.keys(this._subscriptions).forEach((key: string) => {
this._subscriptions[key].unsubscribe();
});
this._unsubscribeOutputEvents();
this._ctrl_drop();
}
private _subscribeOutputEvents() {
if (this.session === undefined || this._output === undefined) {
this._logger.error(
`Fail to subscribe: session controller or output controller aren't defined`,
);
return;
}
this._outputSubscriptions.onBookmarkSelected = this.session
.getBookmarks()
.getObservable()
.onSelected.subscribe(this._onScrollTo.bind(this, true));
this._outputSubscriptions.onStateUpdated = this._output
.getObservable()
.onStateUpdated.subscribe(this._onStateUpdated.bind(this));
this._outputSubscriptions.onRangeLoaded = this._output
.getObservable()
.onRangeLoaded.subscribe(this._onRangeLoaded.bind(this));
this._outputSubscriptions.onBookmarksChanged = this._output
.getObservable()
.onBookmarksChanged.subscribe(this._onBookmarksChanged.bind(this));
this._outputSubscriptions.onReset = this._output
.getObservable()
.onReset.subscribe(this._onReset.bind(this));
this._outputSubscriptions.onScrollTo = this._output
.getObservable()
.onScrollTo.subscribe(this._onScrollTo.bind(this, false));
}
private _unsubscribeOutputEvents() {
Object.keys(this._outputSubscriptions).forEach((key: string) => {
this._outputSubscriptions[key].unsubscribe();
});
}
private _api_getComponentFactory(): any {
return ViewOutputRowComponent;
}
private _api_getItemHeight(): number {
return 16;
}
private _api_getLastFrame(): IRange {
if (this._output === undefined) {
throw new Error(this._logger.error(`Output controller isn't available`));
}
return this._output.getFrame();
}
private _api_getRange(range: IRange, antiLoopCounter: number = 0): IRowsPacket {
if (this._output === undefined) {
throw new Error(this._logger.error(`Output controller isn't available`));
}
const rows: IRow[] | Error = this._output.getRange(range);
if (rows instanceof Error) {
if (antiLoopCounter > 1000) {
throw rows;
}
return this._api_getRange(range, antiLoopCounter + 1);
}
return {
range: range,
rows: rows,
};
}
private _api_getStorageInfo(): IStorageInformation {
if (this._output === undefined) {
throw new Error(this._logger.error(`Output controller isn't available`));
}
return {
count: this._output.getState().count,
};
}
private _api_updatingDone(range: IRange): void {
if (this._output === undefined) {
throw new Error(this._logger.error(`Output controller isn't available`));
}
this._output.setFrame(range);
}
private _api_cleanUpClipboard(str: string): string {
return cleanupOutput(str);
}
private _getFilterFromStr(str: string): FilterRequest | undefined {
try {
return new FilterRequest({
request: str,
flags: { casesensitive: true, wholeword: true, regexp: false },
});
} catch (e) {
return undefined;
}
}
private _onSessionChanged(session: Session) {
if (this._output !== undefined) {
// Get current frame (cursor)
const frameToStore: IRange = this._output.getFrame();
this._frames.set(this._activeSessionId, frameToStore);
}
// Update session
this._activeSessionId = session.getGuid();
this.session = session;
// Unsubscribe
this._unsubscribeOutputEvents();
// Get reference to stream wrapper
this._output = this.session.getSessionSearch().getOutputStream();
// Subscribe
this._subscribeOutputEvents();
// Update
this._ng_outputAPI.onSourceUpdated.next();
this._cdRef.detectChanges();
}
private _onReset() {
this._ng_outputAPI.onStorageUpdated.next({
count: 0,
});
}
private _onStateUpdated(event: IStreamStateEvent) {
this._ng_outputAPI.onStorageUpdated.next({
count: event.state.count,
});
if (!event.isBookmarkInjection) {
this._keepScrollDown();
}
}
private _onRangeLoaded(packet: ILoadedRange) {
this._ng_outputAPI.onRowsDelivered.next({
range: packet.range,
rows: packet.rows,
});
}
private _onBookmarksChanged() {
this._ng_outputAPI.onRerequest.next();
}
private _onScrollTo(bookmark: boolean, row: number) {
if (isNaN(row) || !isFinite(row)) {
return;
}
OutputRedirectionsService.getIndexAround(row)
.then((around: IPC.ISearchIndexAroundResponse) => {
const target: number | undefined =
around.before !== -1
? around.before
: around.after !== -1
? around.after
: undefined;
if (target === undefined) {
return;
}
// Make offset because bookmarks
// const offset: number = this.session.getSessionBooksmarks().getNumberBookmarksBefore(pos.position);
if (bookmark) {
this._onKeepScrollPrevent();
}
this._ng_outputAPI.onScrollTo.next(target);
})
.catch((err: Error) => {
this._logger.warn(
`Fail to detect nearest position in search. Error: ${err.message}`,
);
});
}
private _onScrolled(range: IRange) {
if (this._output === undefined) {
return;
}
const last: number = this._output.getRowsCount() - 1;
if (range.end === last && !this._controls.keepScrollDown) {
this._controls.keepScrollDown = true;
this._controls.update.next(this._ctrl_getButtons());
} else if (range.end < last && this._controls.keepScrollDown) {
this._controls.keepScrollDown = false;
this._controls.update.next(this._ctrl_getButtons());
}
}
private _onResize() {
this._cdRef.detectChanges();
this._ng_outputAPI.onRedraw.next();
}
private _onKeepScrollPrevent() {
this._controls.keepScrollDown = false;
this._controls.update.next(this._ctrl_getButtons());
}
private _keepScrollDown() {
if (this._output === undefined) {
return;
}
if (this._scrollBoxCom === undefined || this._scrollBoxCom === null) {
return;
}
if (!this._controls.keepScrollDown) {
return;
}
const last: number = this._output.getRowsCount() - 1;
const range: IRange = {
start: last - CSettings.preloadCount < 0 ? 0 : last - CSettings.preloadCount,
end: last,
};
const frame: IRange = this._scrollBoxCom.getFrame();
if (frame.end === range.end) {
return;
}
this._output
.preload(range)
.then((loaded: IRange | null) => {
if (loaded === null) {
// Already some request is in progress: do nothing
return;
}
this._ng_outputAPI.onScrollUntil.next(loaded.end);
})
.catch((error: Error) => {
// Do nothing, no data available
});
}
private _ctrl_inject() {
if (this.injectionIntoTitleBar === undefined) {
return;
}
this.injectionIntoTitleBar.next({
inputs: {
getButtons: this._ctrl_getButtons.bind(this),
onUpdate: this._controls.update.asObservable(),
},
factory: ViewSearchControlsComponent,
});
}
private _ctrl_drop() {
if (this.injectionIntoTitleBar === undefined) {
return;
}
this.injectionIntoTitleBar.next(undefined);
}
private _ctrl_getButtons(): IButton[] {
return [
{
alias: 'scroll',
icon: `small-icon-button fa-arrow-alt-circle-down ${
this._controls.keepScrollDown ? 'fas' : 'far'
}`,
disabled: false,
handler: this._ctrl_onScrollDown.bind(this),
title: 'Scroll with updates',
},
];
}
private _ctrl_onScrollDown(button: IButton) {
if (this._scrollBoxCom === undefined || this._scrollBoxCom === null) {
return;
}
if (this._output === undefined) {
return;
}
this._controls.keepScrollDown = !this._controls.keepScrollDown;
this._controls.update.next(this._ctrl_getButtons());
const last: number = this._output.getRowsCount() - 1;
if (this._controls.keepScrollDown && this._scrollBoxCom.getFrame().end < last) {
this._ng_outputAPI.onScrollTo.next(last);
}
}
} | the_stack |
import { Table } from "apache-arrow";
import ndarray, { NdArray } from "ndarray";
import prefixSum from "ndarray-prefix-sum";
import { Dimension, View1D, View2D, Views } from "../api";
import { Interval } from "../basic";
import { BitSet, union } from "../bitset";
import { CUM_ARR_TYPE, HIST_TYPE } from "../consts";
import { binNumberFunction, binNumberFunctionBins, numBins } from "../util";
import { DataBase, SyncIndex } from "./db";
export class ArrowDB<V extends string, D extends string>
implements DataBase<V, D>
{
private data: Table<{ [key in D]: any }>;
public readonly blocking: boolean = true;
public constructor(private readonly urlOrArrayBuffer: string | ArrayBuffer) {}
private filterMaskIndex = new Map<string, BitSet>();
public async initialize() {
let buffer: ArrayBuffer;
if (typeof this.urlOrArrayBuffer === "string") {
const response = await fetch(this.urlOrArrayBuffer);
buffer = await response.arrayBuffer();
} else {
buffer = this.urlOrArrayBuffer;
}
console.time("Load Apache Arrow");
this.data = Table.from(new Uint8Array(buffer));
console.timeEnd("Load Apache Arrow");
return;
}
private getFilterMask(dimension: D, extent: Interval<number>) {
const key = `${dimension} ${extent}`;
const m = this.filterMaskIndex.get(key);
if (m) {
return m;
}
const column = this.data.getColumn(dimension)!;
const mask = new BitSet(column.length);
for (let i = 0; i < column.length; i++) {
const val: number = column.get(i)!;
if (val < extent[0] || val >= extent[1]) {
mask.set(i, true);
}
}
this.filterMaskIndex.set(key, mask);
return mask;
}
public length() {
return this.data.length;
}
public histogram(
dimension: Dimension<D>,
brushes?: Map<D, Interval<number>>
) {
console.time("Histogram");
const filterMask = union(
...this.getFilterMasks(brushes || new Map()).values()
);
const binConfig = dimension.binConfig!;
const bin = binNumberFunction(binConfig);
const binCount = numBins(binConfig);
const column = this.data.getColumn(dimension.name)!;
const noBrush = ndarray(new HIST_TYPE(binCount));
const hist = filterMask ? ndarray(new HIST_TYPE(binCount)) : noBrush;
for (let i = 0; i < this.data.length; i++) {
const value: number = column.get(i)!;
const key = bin(value);
if (0 <= key && key < binCount) {
const idx = hist.index(key);
noBrush.data[idx]++;
if (filterMask && !filterMask.get(i)) {
hist.data[idx]++;
}
}
}
console.timeEnd("Histogram");
return {
hist,
noBrush
};
}
public heatmap(dimensions: [Dimension<D>, Dimension<D>]) {
console.time("Heatmap");
const binConfigs = dimensions.map(d => d.binConfig!);
const [numBinsX, numBinsY] = binConfigs.map(numBins);
const [binX, binY] = binConfigs.map(binNumberFunction);
const [columnX, columnY] = dimensions.map(
d => this.data.getColumn(d.name)!
);
const heat = ndarray(new HIST_TYPE(numBinsX * numBinsY), [
numBinsX,
numBinsY
]);
for (let i = 0; i < this.data.length; i++) {
const keyX = binX(columnX.get(i)!);
const keyY = binY(columnY.get(i)!);
if (0 <= keyX && keyX < numBinsX && 0 <= keyY && keyY < numBinsY) {
heat.data[heat.index(keyX, keyY)]++;
}
}
console.timeEnd("Heatmap");
return heat;
}
private getFilterMasks(brushes: Map<D, Interval<number>>): Map<D, BitSet> {
if (!brushes.size) {
// no brushes => no filters
return new Map();
}
console.time("Build filter masks");
const filters = new Map<D, BitSet>();
for (const [dimension, extent] of brushes) {
filters.set(dimension, this.getFilterMask(dimension, extent));
}
console.timeEnd("Build filter masks");
return filters;
}
public loadData1D(
activeView: View1D<D>,
pixels: number,
views: Views<V, D>,
brushes: Map<D, Interval<number>>
) {
console.time("Build index");
const filterMasks = this.getFilterMasks(brushes);
const cubes: SyncIndex<V> = new Map();
const activeDim = activeView.dimension;
const binActive = binNumberFunctionBins(activeDim.binConfig!, pixels);
const activeCol = this.data.getColumn(activeDim.name)!;
const numPixels = pixels + 1; // extending by one pixel so we can compute the right diff later
for (const [name, view] of views) {
// array for histograms with last histogram being the complete histogram
let hists: NdArray;
let noBrush: NdArray;
// get union of all filter masks that don't contain the dimension(s) for the current view
const relevantMasks = new Map(filterMasks);
if (view.type === "0D") {
// use all filters
} else if (view.type === "1D") {
relevantMasks.delete(view.dimension.name);
} else {
relevantMasks.delete(view.dimensions[0].name);
relevantMasks.delete(view.dimensions[1].name);
}
const filterMask = union(...relevantMasks.values());
if (view.type === "0D") {
hists = ndarray(new CUM_ARR_TYPE(numPixels));
noBrush = ndarray(new HIST_TYPE(1), [1]);
// add data to aggregation matrix
for (let i = 0; i < this.data.length; i++) {
// ignore filtered entries
if (filterMask && filterMask.get(i)) {
continue;
}
const keyActive = binActive(activeCol.get(i)!) + 1;
if (0 <= keyActive && keyActive < numPixels) {
hists.data[hists.index(keyActive)]++;
}
noBrush.data[0]++;
}
prefixSum(hists);
} else if (view.type === "1D") {
const dim = view.dimension;
const binConfig = dim.binConfig!;
const bin = binNumberFunction(binConfig);
const binCount = numBins(binConfig);
hists = ndarray(new CUM_ARR_TYPE(numPixels * binCount), [
numPixels,
binCount
]);
noBrush = ndarray(new HIST_TYPE(binCount), [binCount]);
const column = this.data.getColumn(dim.name)!;
// add data to aggregation matrix
for (let i = 0; i < this.data.length; i++) {
// ignore filtered entries
if (filterMask && filterMask.get(i)) {
continue;
}
const key = bin(column.get(i)!);
const keyActive = binActive(activeCol.get(i)!) + 1;
if (0 <= key && key < binCount) {
if (0 <= keyActive && keyActive < numPixels) {
hists.data[hists.index(keyActive, key)]++;
}
noBrush.data[key]++;
}
}
// compute cumulative sums
for (let x = 0; x < hists.shape[1]; x++) {
prefixSum(hists.pick(null, x));
}
} else {
const dimensions = view.dimensions;
const binConfigs = dimensions.map(d => d.binConfig!);
const [numBinsX, numBinsY] = binConfigs.map(numBins);
const [binX, binY] = binConfigs.map(c => binNumberFunction(c));
const [columnX, columnY] = dimensions.map(
d => this.data.getColumn(d.name)!
);
hists = ndarray(new CUM_ARR_TYPE(numPixels * numBinsX * numBinsY), [
numPixels,
numBinsX,
numBinsY
]);
noBrush = ndarray(new HIST_TYPE(numBinsX * numBinsY), [
numBinsX,
numBinsY
]);
for (let i = 0; i < this.data.length; i++) {
// ignore filtered entries
if (filterMask && filterMask.get(i)) {
continue;
}
const keyX = binX(columnX.get(i)!);
const keyY = binY(columnY.get(i)!);
const keyActive = binActive(activeCol.get(i)!) + 1;
if (0 <= keyX && keyX < numBinsX && 0 <= keyY && keyY < numBinsY) {
if (0 <= keyActive && keyActive < numPixels) {
hists.data[hists.index(keyActive, keyX, keyY)]++;
}
noBrush.data[noBrush.index(keyX, keyY)]++;
}
}
// compute cumulative sums
for (let x = 0; x < hists.shape[1]; x++) {
for (let y = 0; y < hists.shape[2]; y++) {
prefixSum(hists.pick(null, x, y));
}
}
}
cubes.set(name, { hists, noBrush: noBrush });
}
console.timeEnd("Build index");
return cubes;
}
public loadData2D(
activeView: View2D<D>,
pixels: [number, number],
views: Views<V, D>,
brushes: Map<D, Interval<number>>
) {
console.time("Build index");
const filterMasks = this.getFilterMasks(brushes);
const cubes: SyncIndex<V> = new Map();
const [activeDimX, activeDimY] = activeView.dimensions;
const binActiveX = binNumberFunctionBins(activeDimX.binConfig!, pixels[0]);
const binActiveY = binNumberFunctionBins(activeDimY.binConfig!, pixels[1]);
const activeColX = this.data.getColumn(activeDimX.name)!;
const activeColY = this.data.getColumn(activeDimY.name)!;
const [numPixelsX, numPixelsY] = [pixels[0] + 1, pixels[1] + 1];
for (const [name, view] of views) {
// array for histograms with last histogram being the complete histogram
let hists: NdArray;
let noBrush: NdArray;
// get union of all filter masks that don't contain the dimension(s) for the current view
const relevantMasks = new Map(filterMasks);
if (view.type === "0D") {
// use all filters
} else if (view.type === "1D") {
relevantMasks.delete(view.dimension.name);
} else {
relevantMasks.delete(view.dimensions[0].name);
relevantMasks.delete(view.dimensions[1].name);
}
const filterMask = union(...relevantMasks.values());
if (view.type === "0D") {
hists = ndarray(new CUM_ARR_TYPE(numPixelsX * numPixelsY), [
numPixelsX,
numPixelsY
]);
noBrush = ndarray(new HIST_TYPE(1));
// add data to aggregation matrix
for (let i = 0; i < this.data.length; i++) {
// ignore filtered entries
if (filterMask && filterMask.get(i)) {
continue;
}
const keyActiveX = binActiveX(activeColX.get(i)!) + 1;
const keyActiveY = binActiveY(activeColY.get(i)!) + 1;
if (
0 <= keyActiveX &&
keyActiveX < numPixelsX &&
0 <= keyActiveY &&
keyActiveY < numPixelsY
) {
hists.data[hists.index(keyActiveX, keyActiveY)]++;
}
// add to cumulative hist
noBrush.data[0]++;
}
prefixSum(hists);
} else if (view.type === "1D") {
const dim = view.dimension;
const binConfig = dim.binConfig!;
const bin = binNumberFunction(binConfig);
const binCount = numBins(binConfig);
hists = ndarray(new CUM_ARR_TYPE(numPixelsX * numPixelsY * binCount), [
numPixelsX,
numPixelsY,
binCount
]);
noBrush = ndarray(new HIST_TYPE(binCount));
const column = this.data.getColumn(dim.name)!;
// add data to aggregation matrix
for (let i = 0; i < this.data.length; i++) {
// ignore filtered entries
if (filterMask && filterMask.get(i)) {
continue;
}
const key = bin(column.get(i)!);
const keyActiveX = binActiveX(activeColX.get(i)!) + 1;
const keyActiveY = binActiveY(activeColY.get(i)!) + 1;
if (0 <= key && key < binCount) {
if (
0 <= keyActiveX &&
keyActiveX < numPixelsX &&
0 <= keyActiveY &&
keyActiveY < numPixelsY
) {
hists.data[hists.index(keyActiveX, keyActiveY, key)]++;
}
// add to cumulative hist
noBrush.data[key]++;
}
}
// compute cumulative sums
for (let x = 0; x < hists.shape[2]; x++) {
prefixSum(hists.pick(null, null, x));
}
} else {
throw new Error("2D view brushing and viewing not yet implemented.");
}
cubes.set(name, { hists, noBrush: noBrush });
}
console.timeEnd("Build index");
return cubes;
}
public getDimensionExtent(dimension: Dimension<D>): Interval<number> {
const column = this.data.getColumn(dimension.name)!;
let max: number = column.get(0)!;
let min = max;
for (let value of column) {
if (value! > max) {
max = value!;
} else if (value! < min) {
min = value!;
}
}
return [min, max];
}
} | the_stack |
"use strict";
(function() {
function log(code: string, message?: string, success?: boolean) {
message = message || '';
if (document && document.body) {
if (message) {
message = $.views.converters.html(message);
message = success === undefined ? "<br/>==== <b><em>" + message + "</em></b> ====<br/>" : message;
}
if (success === false) {
message += ": <b>Failure</b>";
}
if (code !== undefined) {
code = $.views.converters.html(code);
message = arguments.length>1 ? "<code>" + code + "...</code> " + message : "log: " + "<code>" + code + "</code> ";
}
$(document.body).append(message + "<br/>");
} else {
if (success === undefined) {
message = "==== " + message + " ====";
} else {
if (code) {
message = code + "... " + message;
}
if (!success) {
message += ": Failure";
}
}
console.log(message);
}
}
let assert = {
equal: function(a: string, b: string, code: string, message?: string) {
log(code, message || '', a === b);
},
ok: function(a: boolean, code: string, message?: string) {
log(code, message || '', a);
},
testGroup: function(message: string) {
log('', message);
}
};
function text() {
return $("#result").text();
}
$(document.body).append('<div style="display: none;" id="result"></div>');
$.views.settings.trigger(false);
/*<<<<<<<<<<<<<*/ assert.testGroup("$.templates, and basic link"); /*>>>>>>>>>>>>>*/
$(document.body).append('<script id="myTmpl" type="text/x-jsrender">{^{:name}} </script>');
let tmpl = $.templates("#myTmpl");
assert.ok(tmpl.markup === "{^{:name}} ", 'tmpl = $.templates("#myTmpl")');
assert.ok($.views.templates("#myTmpl").markup === "{^{:name}} ", 'tmpl = $.views.templates("#myTmpl")');
assert.ok($.views.templates === $.templates, '$.views.templates === $.templates');
let data = { name: "Jo" };
tmpl.link("#result", data);
assert.ok(text() === "Jo ", 'tmpl.link(...)', 'Template link');
$.templates("myTmpl", "#myTmpl");
data = { name: "Bob" };
$.templates.myTmpl.link("#result", data);
assert.ok(text() === "Bob ", '$.templates("myTmpl", "#myTmpl"); $.templates.myTmpl.link(...)', 'Named template as expando on $.templates');
let array = [{ name: "Jo" }, { name: "Amy" }, { name: "Bob" }];
tmpl.link("#result", array);
assert.ok(text() === "Jo Amy Bob ", 'tmpl.link("#result", array)', 'Link array');
let helpers = {
title: "Mr"
};
tmpl = $.templates("tmplFromString", "{^{:~title}} {^{:name}}. ");
assert.ok(tmpl.tmplName + tmpl.markup + tmpl.useViews === "tmplFromString{^{:~title}} {^{:name}}. true", 'tmpl.tmplName + tmpl.markup + tmpl.useViews', 'tmpl properties');
/*<<<<<<<<<<<<<*/ assert.testGroup("link() access helpers and set noIteration"); /*>>>>>>>>>>>>>*/
tmpl.link("#result", array, helpers);
assert.ok(text() === "Mr Jo. Mr Amy. Mr Bob. ", 'tmpl.link(..., array, helpers)', 'Access helpers');
$.views.helpers("title", "Sir");
tmpl.link("#result", array, helpers);
assert.ok(text() === "Mr Jo. Mr Amy. Mr Bob. ", 'tmpl.link(..., array, helpers)', 'Access helpers');
tmpl.link("#result", array);
assert.ok(text() === "Sir Jo. Sir Amy. Sir Bob. ", 'tmpl.link(..., array, helpers)', 'Access helpers');
tmpl = $.templates("{^{:length}} {^{for}}{^{:~title}} {^{:name}} {{/for}}");
tmpl.link("#result", array, helpers, true);
assert.ok(text() === "3 Mr Jo Mr Amy Mr Bob ", 'tmpl.link(..., array, helpers, true)', 'Link array, no iteration');
tmpl.link("#result", array, true);
assert.ok(text() === "3 Sir Jo Sir Amy Sir Bob ", 'tmpl.link(..., array, true)', 'Link array, no iteration');
$("#result").link(tmpl, array, helpers, true);
assert.ok(text() === "3 Mr Jo Mr Amy Mr Bob ", '$("#result").link(tmpl, array, helpers, true)', 'Link array, no iteration');
$("#result").link(tmpl, array, true);
assert.ok(text() === "3 Sir Jo Sir Amy Sir Bob ", '$("#result").link(tmpl, array, true)', 'Link array, no iteration');
$.observable(array).insert({name: "Jane"});
$.observable(helpers).setProperty({title: "Chief"});
$.observable(array[0]).setProperty({name: "Fiona"});
$("#result").link(tmpl, array, helpers, true);
assert.ok(text() === "4 Chief Fiona Chief Amy Chief Bob Chief Jane ", '$("#result").link(tmpl, array, helpers, true)', 'Observable changes');
$.views.helpers("title", null);
tmpl.link("#result", array, true);
assert.ok(text() === "4 Fiona Amy Bob Jane ", '$.views.helpers("title", null); ...tmpl.link(..., array, true)', 'Unregister named helper, then link array, no iteration');
/*<<<<<<<<<<<<<*/ assert.testGroup("Compile template with private resources"); /*>>>>>>>>>>>>>*/
tmpl = $.templates({
markup: "{^{:~title}}{^{:~title2}}{^{:~title3}} {^{upper:name}} {^{full/}} {{include tmpl='inner2'/}}{{include tmpl='inner'/}}",
converters: { // private converter
upper: function(val) {
return val.toUpperCase();
}
},
tags: { // private tag
full: "{{upper:~title}} {{:name}}"
},
helpers: { // private helper
title: "Mr"
},
templates: { // private template
inner: "Inner: {{:~title}} {{:name}} {{full/}} {{short/}}"
}
});
$.views.converters({lower: function(val) {return val.toLowerCase();}}, tmpl); // Additional private converter
$.templates("inner2", "Inner2", tmpl); // Additional private template
$.views.helpers({title2: "Sir",
title3: "Ms",
myob: {amount: 33},
myfn: function(a: number) {return a + 10;}
}, tmpl); // Additional private helpers
$.views.tags("short", "{{lower:name}} ", tmpl); // Additional private tag
tmpl.link("#result", array);
$.observable(array).remove(0);
assert.ok(text() === "MrSirMs AMY MR Amy Inner2Inner: Mr Amy MR Amy amy MrSirMs BOB MR Bob Inner2Inner: Mr Bob MR Bob bob MrSirMs JANE MR Jane Inner2Inner: Mr Jane MR Jane jane ",
'tmpl = $.templates({markup: ..., converters: tags ... etc', 'Compile template with resources');
assert.equal(
tmpl.converters.upper("jo") +
tmpl.converters.lower("JO") +
tmpl.tags.short.template.markup +
tmpl.helpers.title +
tmpl.helpers.title2 +
tmpl.helpers.title3 +
tmpl.helpers.myob.amount +
tmpl.helpers.myfn(5) +
tmpl.templates.inner.markup +
tmpl.templates.inner2.markup,
"JOjo{{lower:name}} MrSirMs3315Inner: {{:~title}} {{:name}} {{full/}} {{short/}}Inner2",
'tmpl.converters.upper("jo") ... +tmpl.templates.inner2.markup',
"Accessing tmpl resources");
/*<<<<<<<<<<<<<*/ assert.testGroup("template.useViews"); /*>>>>>>>>>>>>>*/
assert.ok(!$.templates("{{for/}}").useViews, '$.templates("{{for/}}").useViews' , "useViews defaults to false");
assert.ok($.templates({
markup: "{{for/}}",
useViews: true
}).useViews, '$.templates({ ... useViews: true, ...})', "useViews forced to true");
assert.ok($.templates("{{for}}{{:#parent}}{{/for}}").useViews, '$.templates("{{for}}{{:#parent}}{{/for}}").useViews', "useViews defaults to true");
/*<<<<<<<<<<<<<*/ assert.testGroup("$.views.tags()"); /*>>>>>>>>>>>>>*/
let tag = $.views.tags("add", function(val1, val2) { return val1 + "|" + val2; });
let test = tag._is;
tmpl = $.templates("{^{add first last foo=last/}} {^{privateadd first last /}}");
tag = $.views.tags("privateadd", function(val1, val2) { return val1 + "!!" + val2; }, tmpl);
test += tag._is;
assert.equal(test + tmpl({first: "A", last: "B"}), "tagtagA|B A!!B", '$.views.tags("add", function() { ... })', "create tag from function, public or private");
$.views
.tags({add: "{{: ~tagCtx.args[0] + '&' + ~tagCtx.args[1]}}"}) // Create public tag (replaces previous version)
.tags({privateadd: "{{: ~tagCtx.args[0] + '$$' + ~tagCtx.args[1]}}"}, tmpl); // Create private tag (replaces previous version)
assert.equal(tmpl({first: "A", last: "B"}), "A&B A$$B", '$.views.tags("add", "...")', "create tag from string, public or private");
$.views.tags("add", {
init: function(tagCtx, linkCtx, ctx) {
this.baseApply(arguments);
test = this.sortDataMap;
this.foo = tagCtx.props.foo;
test = this.render();
this.template = {markup: "bar"};
},
render: function(val1, val2) {
return val1 + "==" + val2 + ":" + this.foo + "?" + this.ctxPrm("xfoo");
},
template: {markup: "none"},
baseTag: "for",
contentCtx: true, // function() { return "aaa"; },
convert: function(val1, val2) {
return [val1.toLowerCase(), val2.toLowerCase()];
},
argDefault: true,
bindTo: [0, "foo"],
bindFrom: [0, "foo"],
flow: false,
ctx: { x: 'myctx' },
dataBoundOnly: true,
boundProps: ["a", "b"],
depends: function() { return "foo"; },
mapProps: ["a2", "b2"],
mapDepends: function() { return "foo"; },
setSize: true,
height: 23,
width: "3em",
className: "blue",
linkedElement: [".a", "b"],
linkedCtxParam: ["w", "xfoo"],
mainElement: "#d",
displayElement: "#e",
trigger: true,
attr: "html",
dataMap: null,
lateRender: false,
onAfterLink: function(tagCtx, linkCtx, ctx, ev, eventArgs) {},
onBind: function(tagCtx, linkCtx, ctx, ev, eventArgs) {},
onUnbind: function(tagCtx, linkCtx, ctx, ev, eventArgs) {},
onUpdate: false,
onDispose: function() {},
convertBack: "upper",
onBeforeUpdateVal: function(ev, eventArgs) {},
onBeforeChange: function(ev, eventArgs) {},
onAfterChange: function(ev, eventArgs) {},
onArrayChange: function(ev, eventArgs) {},
setValue: function(value, index, elseBlock) {},
domChange: function() {},
});
$.views.tags({privateadd: {
template: {markup: "none"},
}}, tmpl);
tmpl.link("#result", {first: "Aval", last: "Bval"});
test = $.views.tags.add.foo;
assert.equal(text(), "aval==Bval:Bval?bval none", '$.views.tags("add", {...})', "create tag from tagOptions hash, public or private");
/*<<<<<<<<<<<<<*/ assert.testGroup("$.views.converters()"); /*>>>>>>>>>>>>>*/
let converter = $.views.converters("add", function(val1, val2) { return val1 + "|" + val2 + ", "; });
test = converter("a", "b");
tmpl = $.templates("{{add: first last}} {{privateadd: first last}}");
converter = $.views.converters({privateadd: function(val1, val2) { return val1 + "!!" + val2 + ", "; }}, tmpl)
.converters.privateadd; // returns views, then access private converter resource 'privateadd'
test += converter("c", "d");
assert.equal(test + "--" + tmpl({first: "A", last: "B"}), "a|b, c!!d, --A|B, A!!B, ",
'$.views.converters("add", function() { ... })', "register converter, public or private");
converter = $.views.converters("add", null);
assert.ok(converter === null && $.views.converters.add === undefined, '$.views.converters("...", null)', "unregister converter");
/*<<<<<<<<<<<<<*/ assert.testGroup("$.views.helpers()"); /*>>>>>>>>>>>>>*/
let helper = $.views.helpers("add", function(val1: string, val2: string) { return val1 + "|" + val2 + ", "; });
test = helper("a", "b");
tmpl = $.templates("{{:~add(first, last)}} {{:~privateadd(first, last)}}");
helper = $.views.helpers({privateadd: function(val1: string, val2: string) { return val1 + "!!" + val2 + ", "; }}, tmpl)
.helpers.privateadd; // returns views, then access private helper resource 'privateadd'
test += helper("c", "d");
assert.equal(test + "--" + tmpl({first: "A", last: "B"}), "a|b, c!!d, --A|B, A!!B, ",
'$.views.helpers("add", function() { ... })', "register helper, public or private");
helper = $.views.helpers("add", null);
assert.ok(helper === null && $.views.helpers.add === undefined, '$.views.helpers("...", null)', "unregister helper");
/*<<<<<<<<<<<<<*/ assert.testGroup("$.views.viewModels()"); /*>>>>>>>>>>>>>*/
let Book = $.views.viewModels({
getters: ["title", "price"],
extend: {nameAndPrice: function(reverse?: boolean) {
return reverse ? this._price + " for " + this._title : this._title + ": " + this._price;
}}
});
let book1 = Book("Hope", "$1.50");
assert.ok(book1.title() + ": " + book1.price() === "Hope: $1.50"
&& book1.nameAndPrice() === "Hope: $1.50"
&& book1.nameAndPrice(true) === "$1.50 for Hope",
'VM=$.views.viewModels(vmOptions)', "Create VM, instantiate and access members");
tmpl = $.templates("Title: {{:title()}}, Price: {{:price()}}, PriceName: {{:nameAndPrice(true)}}");
tmpl.link("#result", book1);
assert.ok(text() === "Title: Hope, Price: $1.50, PriceName: $1.50 for Hope",
'tmpl.link("#result", book1)', "Link vm instance with template");
book1.title(book1.title() + "+");
book1.price(book1.price() + "+");
tmpl.link("#result", book1);
assert.ok(text() === "Title: Hope+, Price: $1.50+, PriceName: $1.50+ for Hope+",
'book1.title(newValue)', "Modify vm instance, with setters, then link template");
let MyVMs: JsViews.Hash<JsViews.ViewModel> = {};
Book = $.views.viewModels("Bk", {
getters: ["title", "price"],
extend: {nameAndPrice: function(reverse: boolean) {
return reverse ? this._price + " for " + this._title : this._title + ":" + this._price;
}}
});
assert.ok(Book===$.views.viewModels.Bk, '$.views.viewModels("Bk", vmOptions)', "Register named VM");
Book = $.views.viewModels("Bk", {
getters: ["title", "price"],
extend: {nameAndPrice: function(reverse: boolean) {
return reverse ? this._price + " for " + this._title : this._title + ":" + this._price;
}}
}, MyVMs);
assert.ok(Book===MyVMs.Bk, '$.views.viewModels("Bk", vmOptions, MyVMs)', "Register named VM on local MyVMs collection");
$.views.viewModels({
Bk: {
getters: ["title", "price"],
extend: {nameAndPrice: function(reverse: boolean) {
return reverse ? this._price + " for " + this._title : this._title + ":" + this._price;
}}
}
});
$.views.viewModels({
Bk: {
getters: ["title", "price"],
extend: {nameAndPrice: function(reverse: boolean) {
return reverse ? this._price + " for " + this._title : this._title + ":" + this._price;
}}
}
}, MyVMs);
test = $.views.viewModels.Bk("Hope", "$1.50").title();
assert.ok(test === "Hope", '$.views.viewModels({Bk: vmOptions})', "Register one or more named VMs");
test = MyVMs.Bk("Hope", "$1.50").title();
assert.ok(test === "Hope", '$.views.viewModels({Bk: vmOptions}, MyVMs)', "Register one or more named VMs on local myVms collection");
let bookData1 = {title: "Faith", price: "$10.50"}; // book (plain object)
book1 = Book.map(bookData1); // book (instance of Book View Model)
assert.ok(book1.title() === "Faith", 'Book.map(...)', "Instantiate vm instance from data, with map()");
book1.merge({ title: "Hope2", price: "$1.50" });
assert.ok(book1.title() === "Hope2", 'book.merge(...)', "Modify vm instance from data, with merge()");
test = book1.unmap();
assert.ok(test.title === "Hope2" && test.price === "$1.50", 'book.unmap()', "Round-trip data changes back to data, using unmap()");
let bookDataArray1 = [ // book array (plain objects)
{title: "Hope", price: "$1.50"},
{title: "Courage", price: "$2.50"}
];
let booksArray1 = Book.map(bookDataArray1); // book array (instances of Book View Model)
booksArray1.merge([
{title: "Hope2", price: "$1.50"},
{title: "Courage", price: "$222.50"}
]);
test = booksArray1.unmap();
assert.ok(test[1].title === "Courage" && test[1].price === "$222.50",
'bookArray = Book.map(dataArray) bookArray.merge(...) bookArray.unmap()', "Round-trip data array to array of book vm instances");
tmpl = $.templates("Name: {{:name()}}, Street: {{:address().street()}}, Phones:" +
"{{for phones()}} {{:number()}} ({{:person.name()}}) {{/for}}");
// The following code is from sample: https://www.jsviews.com/#viewmodelsapi@mergesampleadv plus use of parentRef
let myVmCollection: JsViews.Hash<JsViews.ViewModel> = {};
interface Person {
_name: string;
_comment: string;
_address: Address;
phones: () => Phone[];
}
interface Address {
_street: string;
}
interface Phone {
_number: string;
id: string;
}
$.views.viewModels({
Person: {
getters: [
{getter: "name", defaultVal: "No name"}, // Compiled name() get/set
{getter: "address", type: "Address", defaultVal: defaultAddress},
{getter: "phones", type: "Phone", defaultVal: [], parentRef: "person"}
],
extend: {
name: myNameGetSet, // Override name() get/set
addPhone: addPhone,
comment: comment // Additional get/set property, not initialized by data)
},
id: function(vm, plain) { // Callback function to determine 'identity'
return vm.personId === plain.personId;
}
},
Address: {
getters: ["street"]
},
Phone: {
getters: ["number"],
id: "phoneId" // Treat phoneId as 'primary key', for identity
}
}, myVmCollection); // Store View Models (typed hierarchy) on myVmCollection
// Override generated name() get/set
function myNameGetSet(this: Person, val: string) {
if (!arguments.length) { // This is standard compiled get/set code
return this._name; // If there is no argument, use as a getter
}
this._name = val; // If there is an argument, use as a setter
}
// Method for Person class
function addPhone(this: Person, phoneNo: string) { // Uses myVmCollection.Phone() to construct new instance
this.phones().push(myVmCollection.Phone(phoneNo, "person", this));
}
// get/set for comment (state on View Model instance, not initialized from data)
function comment(this: Person, val: string) {
if (!arguments.length) {
return this._comment; // If there is no argument, use as a getter
}
this._comment = val;
}
function defaultAddress(this: {name: string}) { // Function providing default address if undefined in data
return {street: 'No street for "' + this.name + '"'};
}
// First version of data - array of objects (e.g. from JSON request):
let peopleData = [
{
personId: "1",
address: {
street: "2nd Ave"
}
},
{
personId: "2",
name: "Pete",
phones: [
{number: "333 333 3333", phoneId: "2a"}
]
}
];
// Second version of data - JSON string (e.g. new JSON request):
let peopleData2 = '[{"personId":"2","name":"Peter","address":{"street":"11 1st Ave"},'
+ '"phones":[{"number":"111 111 9999","phoneId":"1a"},{"number":"333 333 9999","phoneId":"2a"}]}]';
// Instantiate View Model hierarchy using map()
let people = myVmCollection.Person.map(peopleData);
// Link template against people (array of Person instances)
tmpl.link("#result", people);
assert.equal(text(), 'Name: No name, Street: 2nd Ave, Phones:Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ',
'Person.map(peopleData)', "map data to full VM hierarchy");
people.merge(peopleData2);
tmpl.link("#result", people);
assert.equal(text(), 'Name: Peter, Street: 11 1st Ave, Phones: 111 111 9999 (Peter) 333 333 9999 (Peter) ',
'people.merge(peopleData2)', "Merge data on full hierarchy");
people.merge(peopleData);
tmpl.link("#result", people);
assert.equal(text(), 'Name: No name, Street: 2nd Ave, Phones:Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ',
'people.merge(peopleData)', "Merge back to previous data on full hierarchy");
people[0].name("newName");
tmpl.link("#result", people);
assert.equal(text(), 'Name: newName, Street: 2nd Ave, Phones:Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ',
'people[0].name("newName")', "Change a property, deep in hierarchy");
people[0].addPhone("xxx xxx xxxx");
tmpl.link("#result", people);
assert.equal(text(), 'Name: newName, Street: 2nd Ave, Phones: xxx xxx xxxx (newName) Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ',
'people[0].addPhone("xxx xxx xxxx")', "Insert instance, deep in hierarchy");
let updatedPeopleData = people.unmap();
assert.ok(updatedPeopleData[0].name === "newName" && updatedPeopleData[0].phones[0].number === "xxx xxx xxxx",
'updatedPeopleData = people.unmap()', "Round-trip back to data");
/*<<<<<<<<<<<<<*/ assert.testGroup("view"); /*>>>>>>>>>>>>>*/
test = '';
$.views.helpers("hlp", "Hlp");
$.views.tags("mytag", {
init: function(tagCtx, linkCtx, ctx) {
let view = tagCtx.view;
test = ""
+ (view === this.tagCtx.view)
+ view.ctxPrm("foo")
+ "(" + view.getIndex() + ")";
},
contentCtx: function(arg0) {
return this.ctx.root; // The returned value will be the data context inside {{mytag}}
},
show: function(this: JsViews.Tag, view: JsViews.View) {
test += "show";
},
do: function(this: JsViews.Tag, tagCtx: JsViews.TagCtx, ev: JsViews.EventObject, eventArgs: JsViews.EvtArgs) {
data3.a = "A2";
let view = tagCtx.contentView;
view.refresh();
view.ctxPrm("x", "X");
test += view.ctxPrm("x")
+ (view.parent.views._1 === view && view.parent === this.tagCtx.view)
+ view.content.markup.slice(0, 8)
+ view.type
+ view.parent.type
+ (view.get("mytag").get(true, "mytag") === view)
+ view.get("array").get(true, "item").index
+ view.root.type
+ view.getRsc("helpers", "hlp")
+ " contents: " + view.contents().length + view.contents(true).length + view.contents("em").length + view.contents(true, "em").length
+ " childTags: " + view.parent.childTags().length + view.parent.childTags(true).length + view.parent.childTags("on").length + view.parent.childTags(true, "on").length
+ " nodes: " + view.nodes().length;
},
template: "startTag {^{on ~tag.do ~tagCtx id='btn'/}} {{include tmpl=#content /}} endTag"
});
tmpl = $.templates("{^{for contentCtx=true start=0 end=1 ~foo ='FOO'}}{^{mytag a 'b' 33}} in tag {^{:~tag.show(#view)}} {^{:a}} <span><em>inspan</em></span> <input data-link='a' id='inp1'/> <input data-link='~hlp' id='inp2'/>{{/mytag}}{{/for}}");
let data3 = {a: "A"};
tmpl.link("#result", data3, {ctxHlp: "Ctxhlp"});
$("#btn").click();
assert.equal(test,
"trueFOO(0)showshowshowshowXtrue in tag mytagitemtrue0dataHlp contents: 13501 childTags: 1201 nodes: 13",
'view.get(), view.parent, view.data, view.contents(), view.childTags(), view.root etc etc', "View APIs tested");
/*<<<<<<<<<<<<<*/ assert.testGroup("tagCtx, linkCtx"); /*>>>>>>>>>>>>>*/
$.views.tags("mytag", {
linkedElement: ["input", "#inp"],
mainElement: "input",
displayElement: "#inp",
bindTo: [0, "bar"],
init: function(tagCtx, linkCtx, ctx) {
test = '' + linkCtx
+ tagCtx.ctxPrm("foo")
+ tagCtx.view.type
+ tagCtx.args[1]
+ tagCtx.props.bar
+ tagCtx.ctxPrm("foo")
+ (tagCtx.ctx === ctx)
+ tagCtx.bndArgs()
+ tagCtx.cvtArgs()
+ tagCtx.index
+ (this.tagCtxs[0] === tagCtx)
+ tagCtx.params.props.bar
+ (tagCtx.params.ctx && tagCtx.params.ctx.foo)
+ !!tagCtx.render(0, {foo: "FOO2"})
+ (tagCtx.tag === this)
+ tagCtx.tag.tagName
+ (tagCtx.tmpl === null)
+ (tagCtx.tmpl && tagCtx.tmpl.markup)
+ (tagCtx.content && tagCtx.content.markup);
},
onBind: function(tagCtx, linkCtx, ctx) {
test += " tagCtx " + tagCtx.linkedElems[1][0].outerHTML
+ tagCtx.mainElem[0].tagName
+ tagCtx.displayElem[0].tagName
+ tagCtx.contentView.type
+ tagCtx.nodes()[0].textContent
+ tagCtx.contents("#inp")[0].id
+ tagCtx.childTags().length
+ $.isFunction(tagCtx.setValues);
},
onAfterLink: function(tagCtx, linkCtx, ctx) {
test += " linkCtx " +linkCtx.data.a
+ linkCtx.elem.tagName
+ linkCtx.elem.tagName
+ (linkCtx.view === tagCtx.view)
+ linkCtx.attr
+ linkCtx.tag.tagName
+ linkCtx.ctx.root.a
+ linkCtx.type;
}
});
tmpl = $.templates("{^{mytag a 'mode' bar=b ~foo='FOO'}}inner{^{:~foo}}<input/><input id='inp'/>{{/mytag}}");
tmpl.link("#result", {a: "A", b: "B"});
assert.equal(test, "falseFOOdatamodeBFOOtrueA,modeA,mode0trueb'FOO'truetruemytagfalseinner{^{:~foo}}<input/><input id='inp'/>inner{^{:~foo}}<input/><input id='inp'/>"
+ ' tagCtx <input id="inp">INPUTINPUTmytaginnerinp0true'
+ " linkCtx ASCRIPTSCRIPTtruehtmlmytagAinline",
'tagCtx.ctxPrm(), linkCtx.attr etc etc', "tagCtx and linkCtx APIs tested, {{myTag ...}}...{{/myTag}}");
/*<<<<<<<<<<<<<*/ assert.testGroup("settings"); /*>>>>>>>>>>>>>*/
let delims = $.views.settings.delimiters();
let allowCode = $.views.settings.allowCode();
let trigger = $.views.settings.trigger();
$.views.settings.delimiters("<%", "%>", "&");
$.views.settings.allowCode(true);
$.views.settings.trigger(true);
test = "" + $.views.settings.delimiters() + $.views.settings.allowCode() + $.views.settings.trigger();
$.views.settings.delimiters(delims);
$.views.settings.allowCode(allowCode);
$.views.settings.trigger(trigger);
test += "" + $.views.settings.delimiters() + $.views.settings.allowCode() + $.views.settings.trigger();
assert.equal(test, "<%,%>,&truetrue{{,}},^falsefalse", "settings.delimiters()/allowCode()/trigger()", "get/set settings");
/*<<<<<<<<<<<<<*/ assert.testGroup("binding"); /*>>>>>>>>>>>>>*/
tmpl = $.templates('{{include ~person=person}}<input data-link="person.name" id="nmOuter"/>{^{for person}}{^{:name}}<div>{^{:~person.name}}{{if true}} <input data-link="name" id="nm"/> <input data-link="~person.name"/>{{/if}}</div>{{/for}}{{/include}}');
let data2 = {person: {name: "Jo"} };
$.link(tmpl, "#result", data2);
let view = $.view("#nm");
test = "" + (
view === $.view("#nm") &&
view === $.view($("#nm")) &&
view === $.view($("#nm")[0]) &&
view === $("#nm").view()
); // Different variants of $.view()
assert.equal(test, "true", "$.view()", "Variants of $.view() and $(...).view()");
view = $.view("#nm").parent;
test = "" + (
view === $.view("#nm", "for") &&
view === $("#nm").view("for") &&
view === $.view("#nm").get("for") &&
view === $("#nm").view().get("for")
); // Different variants of $.view(type)
view = $.view("#nm").root;
test += "" + (view === $.view("#nm", view.type))
+ "" + (view === $.view("#nm", "root"));
assert.equal(test, "truetruetrue", "$.view(type)", "Variants of $.view(..., type) and $(...).view(type)");
view = $.view("#result", true, "for");
test = "" + (
view === $.view("#result", true, "for") &&
view === $("#result").view(true, "for") &&
view === $("#result").view().get(true, "for") &&
view === $("#nmOuter").view().get(true, "for")
); // Different variants of $.view(true, type)
test += $("#nmOuter").view(true) === undefined;
test += $("#nmOuter").view().get(true).type;
assert.equal(test, "truetruefor", "$.view(type)", "Variants of $.view(..., true, type) and $(...).view(true, type)");
test = text();
$("#nmOuter").val("Bob").change();
test += text();
test += $.view("#nmOuter").type + $.view("#nm").type;
$.unlink("#result div");
$.unlink($("#result div")); // Variant
$.unlink($("#result div")[0]); // Variant
$("#nm").val("Jane").change();
$("#nmOuter").val("Fiona").change();
test += "| unlink: " + text();
test += $.view("#nmOuter").type + $.view("#nm").type;
$.link(tmpl, "#result", data2);
$("#nm").val("Carlos").change();
test += "| relink: " + text() + $.view("#nm").type;
$("#result div").unlink();
$("#nm").val("Henri").change();
test += "| unlink2: " + text() + $.view("#nm").type;
assert.equal(test, "JoJo BobBob includeif| unlink: FionaBob includefor| relink: CarlosCarlos if| unlink2: CarlosCarlos for",
"$.unlink()", "Data-linking, two-way, and unlink() variants");
$.link($.templates('{{:length}}{^{:#data[0].person.name}}'), "#result", [data2], {}, true);
$.observable(data2).setProperty({"person.name": "Maria"});
test += "| relink array noIteration: " + text();
assert.equal(test, "JoJo BobBob includeif| unlink: FionaBob includefor| relink: CarlosCarlos if| unlink2: CarlosCarlos for| relink array noIteration: 1Maria",
"$.link(tmpl ...), $.unlink()", "Data-linking, two-way, and link() / unlink() variants");
data2 = {person: {name: "Jo"} };
$("#result").html('<div data-link="person.name"></div><div data-link="~hlp"></div><input data-link="person.name"/>');
$.link(true, "#result", data2);
test = "link " + text();
$.observable(data2).setProperty({"person.name": "Fiona"});
test += text();
$("#result input").val("Henri").change();
test += text();
$.unlink();
test += " unlink ";
$("#result input").val("James").change();
test += text();
$.observable(data2).setProperty({"person.name": "Fiona"});
test += text();
$.link(true, "#result", data2, { hlp: "Helper" });
test += " link " + text();
$("#result div").unlink();
$("#result input").val("Canut").change();
test += data2.person.name + text();
$("#result").link(true, data2, { hlp: "Helper" }).link(true, data2, { hlp: "Helper2" });
test += text();
$.link(true, "#result", data2, { hlp: "Helper" }).link(true, data2, { hlp: "Helper3" });
test += text();
$.observable(data2).setProperty({"person.name": "Reggie"});
test += text();
assert.equal(test, "link JoHlpFionaHlpHenriHlp unlink HenriHlpHenriHlp link FionaHelperCanutFionaHelperCanutHelper2CanutHelper3ReggieHelper3",
"$.link(true ...), $.unlink()", "Data-linking, top-level, declarative");
$.unlink("#result");
$("#result").html('<div class="nm"></div><div class="hlp"></div><input class="nm"/>');
$.link("person.name", "#result .nm", data2, { hlp: "Helper" });
$.link("~hlp", "#result .hlp", data2, { hlp: "Helper" });
test = text();
$("#result input").val("Rick").change();
test += text();
$.observable(data2).setProperty({"person.name": "Paul"});
test += text();
$.unlink("#result");
test += " unlink ";
$("#result input").val("Josephine").change();
test += text();
$.observable(data2).setProperty("person.name", "Ray");
test += text();
assert.equal(test, "ReggieHelperRickHelperPaulHelper unlink PaulHelperPaulHelper",
"$.link(expr ...), $.unlink()", "Data-linking, top-level, programmatic");
/*<<<<<<<<<<<<<*/ assert.testGroup("Observable"); /*>>>>>>>>>>>>>*/
let data4 = {person: {name: "Jo", address: {street: "Main St"}, phones: [1, 2, 3], info: <JsViews.GetSet>null}};
data4.person.info = function(this: JsViews.Hash<any>) {
return "info: " + this.name + " " + this.address.street;
} as JsViews.GetSet;
data4.person.info.depends = function() {
return ["name", "address^street"];
};
tmpl = $.templates("{^{:person.name}} {^{:person.address.street}} {^{for person.phones}}{^{:}}{{/for}} {^{:person.info()}} {^{:~personinfo}} {^{:~personstuff()}}");
tmpl.link("#result", data4, {personinfo: "Joseph", personstuff: function() {
return "xxx";
}});
test = text();
$.observable(data4).setProperty("person.name", "Ray");
$.observable(data4).setProperty({"person.address.street": "Broadway"});
$.observable(data4.person.phones).insert(1, [5, 6]);
test += text();
$.observable(data4).setProperty({"person.address": {street: "Narrowway"}});
test += text();
$.observable(data4.person.phones).move(1, 2, 2);
test += text();
$.observable(data4.person.phones).remove(1);
test += text();
$.observable(data4.person.phones).refresh([4, 3, 2, 1]);
test += text();
$.view("#result", true, "item").ctxPrm("personinfo", "YYYY");
test += text();
assert.equal(test, "Jo Main St 123 info: Jo Main St Joseph xxxRay Broadway 15623"
+ " info: Ray Broadway Joseph xxxRay Broadway 15623"
+ " info: Ray Narrowway Joseph xxxRay Broadway 12563"
+ " info: Ray Narrowway Joseph xxxRay Broadway 1563"
+ " info: Ray Narrowway Joseph xxxRay Broadway 4321"
+ " info: Ray Narrowway Joseph xxxRay Broadway 4321"
+ " info: Ray Narrowway YYYY xxx",
"$.observable(...)", "Observable APIs");
function keydown(elem: any) {
if ("oninput" in document) {
elem.trigger("input");
} else {
elem.keydown();
}
}
var fullName = function(this: JsViews.Hash<string>, reversed: boolean) {
return reversed
? this.lastName + " " + this.firstName
: this.firstName + " " + this.lastName;
} as JsViews.GetSet;
var person = {
firstName: "Jeff",
lastName: "Smith",
fullName: fullName
};
fullName.depends = "*";
fullName.set = function(val: string) {
let vals = val.split(" ");
$.observable(this).setProperty({
lastName: vals.pop(),
firstName: vals.join(" ")
});
};
$.templates('{^{:firstName}} {^{:lastName}} {^{:fullName()}} {^{:fullName(true)}} <input id="full" data-link="fullName()"/>')
.link("#result", person);
// ................................ Act ..................................
test = text();
$.observable(person).setProperty({firstName: "newFirst", lastName: "newLast"});
test += text();
$.observable(person).setProperty({fullName: "compFirst compLast"});
test += text();
keydown($("#full").val("2wayFirst 2wayLast"));
test += text();
assert.equal(test, "Jeff Smith Jeff Smith Smith Jeff newFirst newLast newFirst newLast newLast newFirst compFirst compLast compFirst compLast compLast compFirst compFirst compLast compFirst compLast compLast compFirst ",
"fullName as JsViews.GetSet; fullName.depends/set etc", "GetSet computed function");
})(); | the_stack |
import type { DataStore, DataStoreAdapter, SortParams, Schema, BaseConfig } from '@tanker/datastore-base';
import { errors as dbErrors, transform } from '@tanker/datastore-base';
import type { Class } from '@tanker/types';
import type { IDexie, ITable, ICollection, IWhereClause } from './types';
export type Config = BaseConfig;
export type { Schema, IDexie, ITable, ICollection, IWhereClause };
export type { IndexableType } from './types';
class UnsupportedTypeError extends Error {
override name: string;
constructor(type: string) {
super(`Dexie can't support search for ${type} values on an index, as they are invalid IndexedDB keys.`);
Object.setPrototypeOf(this, UnsupportedTypeError.prototype);
this.name = this.constructor.name;
}
}
const iframe = (typeof window !== 'undefined') && window.parent && window.parent !== window;
const fromDB = iframe ? transform.fixObjects : transform.identity;
export default ((DexieClass: Class<IDexie>): DataStoreAdapter => class DexieBrowserStore implements DataStore {
declare _db: IDexie;
declare _indexes: Record<string, Record<string, boolean>>;
constructor(db: IDexie) {
// _ properties won't be enumerable, nor reconfigurable
Object.defineProperty(this, '_db', { value: db, writable: true });
Object.defineProperty(this, '_indexes', { value: {}, writable: true });
}
get className(): string {
return this.constructor.name;
}
// Note: this does NOT support multi-column indexes (yet)
isIndexed(table: string, field: string): boolean {
return field === '_id' || !!(this._indexes[table] && this._indexes[table]![field]);
}
async close(): Promise<void> {
if (!this._db)
return;
try {
this._db.close(); // completes immediately, no promise
// @ts-expect-error
this._db = null;
// @ts-expect-error
this._indexes = null;
} catch (error) {
console.error(`Error when closing ${this.className}: `, error);
}
}
/// WARNING: This WILL destroy ALL YOUR DATA! No refunds.
async destroy(): Promise<void> {
if (!this._db)
return;
await this._db.delete();
// @ts-expect-error
this._db = null;
// @ts-expect-error
this._indexes = null;
}
async clear(table: string): Promise<void> {
await this._db.table(table).clear();
}
static async open(config: Config): Promise<DexieBrowserStore> {
if (!config || !config.dbName) {
throw new Error('Invalid empty dbName in config');
}
const dbOptions = { autoOpen: false };
const db = new DexieClass(config.dbName, dbOptions);
const store = new DexieBrowserStore(db);
await store.defineSchemas(config.schemas!);
try {
await db.open();
} catch (err) {
const e = err as Error;
if (e.name === 'VersionError') {
throw new dbErrors.VersionError(e);
}
throw new dbErrors.UnknownError(e);
}
return store;
}
async defineSchemas(schemas: Array<Schema>): Promise<void> {
// Example:
//
// const schemas = [
// {
// version: 1,
// tables: [{
// name: 'something',
// indexes: [['field1'], ['field2', 'field3']]
// }]
// }
// ]
//
// => { something: '_id,field1,[field2+field3]' }
//
for (const schema of schemas) {
const { version, tables } = schema;
const definitions: Record<string, string | null> = {};
for (const table of tables) {
const { name, indexes, deleted } = table;
if (deleted) {
definitions[name] = null; // Dexie's way to delete a collection
} else {
const definition = ['_id']; // non auto-incremented primaryKey
if (indexes) {
for (const i of indexes) {
if (!this._indexes[name]) {
this._indexes[name] = {};
}
this._indexes[name]![i[0]!] = true; // remember indexed fields
definition.push(i.length === 1 ? i[0]! : `[${i.join('+')}]`);
}
}
definitions[name] = definition.join(',');
}
}
this._db.version(version).stores(definitions);
}
const tableMap: Record<string, boolean> = {};
for (const schema of schemas) {
for (const table of schema.tables) {
tableMap[table.name] = true;
}
}
}
add = async (table: string, record: Record<string, any>) => {
try {
await this._db.table(table).add(record);
} catch (err) {
const e = err as Error;
if (e.name === 'ConstraintError') {
throw new dbErrors.RecordNotUnique(e);
}
throw new dbErrors.UnknownError(e);
}
};
put = async (table: string, record: Record<string, any>) => {
try {
await this._db.table(table).put(record);
} catch (err) {
const e = err as Error;
if (e.name === 'ConstraintError') {
throw new dbErrors.RecordNotUnique(e);
}
throw new dbErrors.UnknownError(e);
}
};
bulkAdd = async (table: string, records: Array<Record<string, any>> | Record<string, any>, ...otherRecords: Array<Record<string, any>>) => {
const allRecords = (records instanceof Array) ? records : [records, ...otherRecords];
try {
await this._db.table(table).bulkAdd(allRecords);
} catch (error) {
const e = error as Error;
if (e.name === 'BulkError') {
if ((e as (Error & { failures: Array<Error> })).failures.every(err => err.name === 'ConstraintError')) {
return; // ignore duplicate adds
}
}
throw new dbErrors.UnknownError(e);
}
};
bulkPut = async (table: string, records: Array<Record<string, any>> | Record<string, any>, ...otherRecords: Array<Record<string, any>>) => {
const allRecords = (records instanceof Array) ? records : [records, ...otherRecords];
try {
await this._db.table(table).bulkPut(allRecords);
} catch (err) {
const e = err as Error;
if (e.name === 'ConstraintError') {
throw new dbErrors.RecordNotUnique(e);
}
throw new dbErrors.UnknownError(e);
}
};
bulkDelete = async (table: string, records: Array<Record<string, any>> | Record<string, any>, ...otherRecords: Array<Record<string, any>>) => {
const allRecords = records instanceof Array ? records : [records, ...otherRecords];
try {
await this._db.table(table).bulkDelete(allRecords.map(r => r['_id']));
} catch (e) {
throw new dbErrors.UnknownError(e as Error);
}
};
get = async (table: string, id: string) => {
let record;
try {
record = fromDB(await this._db.table(table).get(id));
} catch (e) {
throw new dbErrors.UnknownError(e as Error);
}
// undefined is returned when record not found
if (!record) {
throw new dbErrors.RecordNotFound();
}
return record;
};
getAll = async (table: string) => {
const records = await this._db.table(table).toArray();
return fromDB(records);
};
find = async (table: string, query: { selector?: Record<string, any>; sort?: SortParams; limit?: number; } = {}) => {
const { selector, sort, limit } = query;
const dexieTable: ITable = this._db.table(table);
let index: string | null = null;
let withSelector: ITable | ICollection = dexieTable;
if (selector) {
const keys = Object.keys(selector);
const fields = [];
if (keys.length < 1) {
throw new Error('A selector must provide at least one field');
}
keys.forEach(k => {
if (!index && this.isIndexed(table, k)) {
index = k;
} else {
fields.push(k);
}
});
if (!index) {
// console.warn('Querying with no indexed field in the selector: ', JSON.stringify(selector)); // eslint-disable-line no-console
throw new Error('A selector must provide at least one indexed field');
}
const withWhere = this._chainWhere(dexieTable, index, selector[index]);
withSelector = withWhere;
if (fields.length > 0) {
const andValues = { ...selector };
delete andValues[index];
withSelector = this._chainAnd(withWhere, andValues);
}
}
let withSort: ITable | ICollection | Promise<Array<Record<string, any>>> = withSelector;
if (sort) {
withSort = this._chainSort(withSelector, sort, index, table);
}
let withLimit: ITable | ICollection | Promise<Array<Record<string, any>>> = withSort;
if (limit) {
withLimit = this._chainLimit(withSort, limit);
}
let res: Promise<Array<Record<string, any>>>;
// At this point:
// - either withLimit is a Dexie Collection or Table to convert to a Promise<Array<Object>>
// - or sortBy() has been called and withLimit is already a Promise<Array<Object>>,
if (this._isTable(withLimit) || this._isCollection(withLimit)) {
res = (withLimit as ITable | ICollection).toArray();
} else {
res = withLimit as typeof res;
}
return fromDB(await res);
};
first = async (table: string, query: { selector?: Record<string, any>; sort?: SortParams; } = {}) => {
const results = await this.find(table, { ...query, limit: 1 });
return results[0];
};
delete = async (table: string, id: string) => {
try {
await this._db.table(table).delete(id);
} catch (e) {
throw new dbErrors.UnknownError(e as Error);
}
};
_isTable(obj: any): boolean {
// @ts-expect-error this._db.Table is a Class (has a prototype)
return obj instanceof this._db.Table;
}
_isCollection(obj: any): boolean {
// @ts-expect-error this._db.Collection is a Class (has a prototype)
return obj instanceof this._db.Collection;
}
_chainWhere(table: ITable, key: string, value: string | number | Record<string, any>): ICollection {
const where: IWhereClause = table.where(key); // WhereClause (Dexie)
let res: ICollection;
// object
if (value instanceof Object) {
if ('$in' in value) {
res = where.anyOf(value['$in']);
} else if ('$gt' in value) {
res = where.above(value['$gt']);
} else if ('$gte' in value) {
res = where.aboveOrEqual(value['$gte']);
} else if ('$lt' in value) {
res = where.below(value['$lt']);
} else if ('$lte' in value) {
res = where.belowOrEqual(value['$lte']);
} else if ('$eq' in value) {
res = where.equals(value['$eq']);
} else if ('$ne' in value) {
res = where.notEqual(value['$ne']);
} else {
throw new Error(`A selector provided an unknown value: ${JSON.stringify(value)}`);
}
// primitive type
} else {
if (typeof value === 'boolean') {
throw new UnsupportedTypeError('boolean');
} else if (value === null) {
throw new UnsupportedTypeError('null');
}
res = where.equals(value);
}
return res; // ICollection (Dexie)
}
_chainAnd(collection: ICollection, andValues: Record<string, any>): ICollection {
const keys = Object.keys(andValues);
return collection.and((record: Record<string, any>) => {
for (const key of keys) {
const value = andValues[key];
if (value instanceof Object) {
if ('$in' in value) {
if (!value.$in.includes(record[key])) {
return false;
}
} else if ('$gt' in value) {
if (record[key] <= value.$gt) {
return false;
}
} else if ('$gte' in value) {
if (record[key] < value.$gte) {
return false;
}
} else if ('$lt' in value) {
if (record[key] >= value.$lt) {
return false;
}
} else if ('$lte' in value) {
if (record[key] > value.$lte) {
return false;
}
} else if ('$eq' in value) {
if (record[key] !== value.$eq) {
return false;
}
} else if ('$ne' in value) {
if (record[key] === value.$ne) {
return false;
}
} else if ('$exists' in value) {
if (value.$exists && !(key in record)) {
return false;
}
if (!value.$exists && key in record) {
return false;
}
} else {
throw new Error(`A selector provided an unknown value: ${JSON.stringify(value)}`);
}
// equality
} else if (record[key] !== value) {
return false;
}
}
return true;
});
}
_chainSort(query: ITable | ICollection, sort: SortParams, index: string | null | undefined, table: string): ICollection | Promise<Array<Record<string, any>>> {
if (sort.length !== 1) {
throw new Error(`Exactly one sort param should be provided: found ${sort.length}`);
}
const sortParam = sort[0];
let dir = 'asc';
let sortKey: string;
if (sortParam instanceof Object) {
// @ts-expect-error Object.keys() is never empty
[sortKey] = Object.keys(sortParam);
if (sortParam[sortKey] === 'desc') {
dir = 'desc';
}
} else {
sortKey = sortParam as string;
}
let q = query;
if (dir === 'desc') {
q = q.reverse();
}
let res: ICollection | Promise<Array<Record<string, any>>>;
// In Dexie, orderBy() uses backend sorting and needs an index,
// whereas sortBy() is done in memory on the result array.
if (
this._isTable(q)
&& (index === sortKey || !index && this.isIndexed(table, sortKey))
) {
res = (q as ITable).orderBy(sortKey); // ICollection (Dexie)
} else {
res = (q as ICollection).sortBy(sortKey); // Promise<Array<Object>>
}
return res;
}
_chainLimit(query: ITable | ICollection | Promise<Array<Record<string, any>>>, limit: number): ICollection | Promise<Array<Record<string, any>>> {
let res: ICollection | Promise<Array<Record<string, any>>>;
if (this._isTable(query) || this._isCollection(query)) {
res = (query as ITable | ICollection).limit(limit);
} else {
res = (query as Promise<Array<Record<string, any>>>).then((array) => array.slice(0, limit));
}
return res;
}
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Definition of custom Cloud Build WorkerPools for running jobs with custom configuration and custom networking.
*
* > This resource is not currently public, and requires allow-listing of projects prior to use.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const pool = new gcp.cloudbuild.WorkerPool("pool", {
* location: "europe-west1",
* workerConfig: {
* diskSizeGb: 100,
* machineType: "e2-standard-4",
* noExternalIp: false,
* },
* });
* ```
* ### Network Config
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const servicenetworking = new gcp.projects.Service("servicenetworking", {
* service: "servicenetworking.googleapis.com",
* disableOnDestroy: false,
* });
* const network = new gcp.compute.Network("network", {autoCreateSubnetworks: false}, {
* dependsOn: [servicenetworking],
* });
* const workerRange = new gcp.compute.GlobalAddress("workerRange", {
* purpose: "VPC_PEERING",
* addressType: "INTERNAL",
* prefixLength: 16,
* network: network.id,
* });
* const workerPoolConn = new gcp.servicenetworking.Connection("workerPoolConn", {
* network: network.id,
* service: "servicenetworking.googleapis.com",
* reservedPeeringRanges: [workerRange.name],
* }, {
* dependsOn: [servicenetworking],
* });
* const pool = new gcp.cloudbuild.WorkerPool("pool", {
* location: "europe-west1",
* workerConfig: {
* diskSizeGb: 100,
* machineType: "e2-standard-4",
* noExternalIp: false,
* },
* networkConfig: {
* peeredNetwork: network.id,
* },
* }, {
* dependsOn: [workerPoolConn],
* });
* ```
*
* ## Import
*
* WorkerPool can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:cloudbuild/workerPool:WorkerPool default projects/{{project}}/locations/{{location}}/workerPools/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:cloudbuild/workerPool:WorkerPool default {{project}}/{{location}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:cloudbuild/workerPool:WorkerPool default {{location}}/{{name}}
* ```
*/
export class WorkerPool extends pulumi.CustomResource {
/**
* Get an existing WorkerPool resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: WorkerPoolState, opts?: pulumi.CustomResourceOptions): WorkerPool {
return new WorkerPool(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:cloudbuild/workerPool:WorkerPool';
/**
* Returns true if the given object is an instance of WorkerPool. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is WorkerPool {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === WorkerPool.__pulumiType;
}
/**
* User specified annotations. See https://google.aip.dev/128#annotations for more details such as format and size
* limitations.
*/
public readonly annotations!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Output only. Time at which the request to create the `WorkerPool` was received.
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* Output only. Time at which the request to delete the `WorkerPool` was received.
*/
public /*out*/ readonly deleteTime!: pulumi.Output<string>;
/**
* A user-specified, human-readable name for the `WorkerPool`. If provided, this value must be 1-63 characters.
*/
public readonly displayName!: pulumi.Output<string | undefined>;
/**
* The location for the resource
*/
public readonly location!: pulumi.Output<string>;
/**
* User-defined name of the `WorkerPool`.
*/
public readonly name!: pulumi.Output<string>;
/**
* Network configuration for the `WorkerPool`. Structure is documented below.
*/
public readonly networkConfig!: pulumi.Output<outputs.cloudbuild.WorkerPoolNetworkConfig | undefined>;
/**
* The project for the resource
*/
public readonly project!: pulumi.Output<string>;
/**
* Output only. `WorkerPool` state. Possible values: STATE_UNSPECIFIED, PENDING, APPROVED, REJECTED, CANCELLED
*/
public /*out*/ readonly state!: pulumi.Output<string>;
/**
* Output only. A unique identifier for the `WorkerPool`.
*/
public /*out*/ readonly uid!: pulumi.Output<string>;
/**
* Output only. Time at which the request to update the `WorkerPool` was received.
*/
public /*out*/ readonly updateTime!: pulumi.Output<string>;
/**
* Configuration to be used for a creating workers in the `WorkerPool`. Structure is documented below.
*/
public readonly workerConfig!: pulumi.Output<outputs.cloudbuild.WorkerPoolWorkerConfig>;
/**
* Create a WorkerPool resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: WorkerPoolArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: WorkerPoolArgs | WorkerPoolState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as WorkerPoolState | undefined;
inputs["annotations"] = state ? state.annotations : undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["deleteTime"] = state ? state.deleteTime : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["networkConfig"] = state ? state.networkConfig : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["state"] = state ? state.state : undefined;
inputs["uid"] = state ? state.uid : undefined;
inputs["updateTime"] = state ? state.updateTime : undefined;
inputs["workerConfig"] = state ? state.workerConfig : undefined;
} else {
const args = argsOrState as WorkerPoolArgs | undefined;
if ((!args || args.location === undefined) && !opts.urn) {
throw new Error("Missing required property 'location'");
}
inputs["annotations"] = args ? args.annotations : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["networkConfig"] = args ? args.networkConfig : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["workerConfig"] = args ? args.workerConfig : undefined;
inputs["createTime"] = undefined /*out*/;
inputs["deleteTime"] = undefined /*out*/;
inputs["state"] = undefined /*out*/;
inputs["uid"] = undefined /*out*/;
inputs["updateTime"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(WorkerPool.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering WorkerPool resources.
*/
export interface WorkerPoolState {
/**
* User specified annotations. See https://google.aip.dev/128#annotations for more details such as format and size
* limitations.
*/
annotations?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Output only. Time at which the request to create the `WorkerPool` was received.
*/
createTime?: pulumi.Input<string>;
/**
* Output only. Time at which the request to delete the `WorkerPool` was received.
*/
deleteTime?: pulumi.Input<string>;
/**
* A user-specified, human-readable name for the `WorkerPool`. If provided, this value must be 1-63 characters.
*/
displayName?: pulumi.Input<string>;
/**
* The location for the resource
*/
location?: pulumi.Input<string>;
/**
* User-defined name of the `WorkerPool`.
*/
name?: pulumi.Input<string>;
/**
* Network configuration for the `WorkerPool`. Structure is documented below.
*/
networkConfig?: pulumi.Input<inputs.cloudbuild.WorkerPoolNetworkConfig>;
/**
* The project for the resource
*/
project?: pulumi.Input<string>;
/**
* Output only. `WorkerPool` state. Possible values: STATE_UNSPECIFIED, PENDING, APPROVED, REJECTED, CANCELLED
*/
state?: pulumi.Input<string>;
/**
* Output only. A unique identifier for the `WorkerPool`.
*/
uid?: pulumi.Input<string>;
/**
* Output only. Time at which the request to update the `WorkerPool` was received.
*/
updateTime?: pulumi.Input<string>;
/**
* Configuration to be used for a creating workers in the `WorkerPool`. Structure is documented below.
*/
workerConfig?: pulumi.Input<inputs.cloudbuild.WorkerPoolWorkerConfig>;
}
/**
* The set of arguments for constructing a WorkerPool resource.
*/
export interface WorkerPoolArgs {
/**
* User specified annotations. See https://google.aip.dev/128#annotations for more details such as format and size
* limitations.
*/
annotations?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A user-specified, human-readable name for the `WorkerPool`. If provided, this value must be 1-63 characters.
*/
displayName?: pulumi.Input<string>;
/**
* The location for the resource
*/
location: pulumi.Input<string>;
/**
* User-defined name of the `WorkerPool`.
*/
name?: pulumi.Input<string>;
/**
* Network configuration for the `WorkerPool`. Structure is documented below.
*/
networkConfig?: pulumi.Input<inputs.cloudbuild.WorkerPoolNetworkConfig>;
/**
* The project for the resource
*/
project?: pulumi.Input<string>;
/**
* Configuration to be used for a creating workers in the `WorkerPool`. Structure is documented below.
*/
workerConfig?: pulumi.Input<inputs.cloudbuild.WorkerPoolWorkerConfig>;
} | the_stack |
import { fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import { ClientService } from './client.service';
import * as sinon from 'sinon';
import * as chai from 'chai';
import { AdminService } from './admin.service';
import { AlertService } from '../basic-modals/alert.service';
import {
AclFile,
BusinessNetworkCardStore,
BusinessNetworkDefinition,
IdCard,
ModelFile,
QueryFile,
Script
} from 'composer-common';
import { BusinessNetworkConnection } from 'composer-client';
import { IdentityService } from './identity.service';
import { IdentityCardService } from './identity-card.service';
import { BusinessNetworkCardStoreService } from './cardStores/businessnetworkcardstore.service';
let should = chai.should();
let expect = chai.expect;
describe('ClientService', () => {
let sandbox;
let adminMock;
let alertMock;
let businessNetworkDefMock;
let identityCardServiceMock;
let businessNetworkConMock;
let modelFileMock;
let scriptFileMock;
let aclFileMock;
let queryFileMock;
let mockCardStoreService;
let idCard;
let mockCardStore;
beforeEach(() => {
sandbox = sinon.sandbox.create();
businessNetworkDefMock = sinon.createStubInstance(BusinessNetworkDefinition);
adminMock = sinon.createStubInstance(AdminService);
alertMock = sinon.createStubInstance(AlertService);
identityCardServiceMock = sinon.createStubInstance(IdentityCardService);
businessNetworkConMock = sinon.createStubInstance(BusinessNetworkConnection);
modelFileMock = sinon.createStubInstance(ModelFile);
scriptFileMock = sinon.createStubInstance(Script);
aclFileMock = sinon.createStubInstance(AclFile);
queryFileMock = sinon.createStubInstance(QueryFile);
mockCardStoreService = sinon.createStubInstance(BusinessNetworkCardStoreService);
mockCardStore = sinon.createStubInstance(BusinessNetworkCardStore);
alertMock.errorStatus$ = {next: sinon.stub()};
alertMock.busyStatus$ = {next: sinon.stub()};
idCard = new IdCard({userName: 'banana'}, {'x-type': 'web', 'name': '$default'});
identityCardServiceMock.getCurrentIdentityCard.returns(idCard);
identityCardServiceMock.getCurrentCardRef.returns('cardRef');
mockCardStoreService.getBusinessNetworkCardStore.returns(mockCardStore);
TestBed.configureTestingModule({
providers: [ClientService,
{provide: AdminService, useValue: adminMock},
{provide: AlertService, useValue: alertMock},
{provide: IdentityCardService, useValue: identityCardServiceMock},
{provide: BusinessNetworkCardStoreService, useValue: mockCardStoreService}]
});
});
afterEach(() => {
sandbox.restore();
});
describe('createBusinessNetwork', () => {
it('should pass through and call createNewBusinessDefinition from common', inject([ClientService], (service: ClientService) => {
let name = 'myname';
let nameversion = 'myname@0.0.1';
let desc = 'my description';
let busNetDef = service.createBusinessNetwork(nameversion, desc, null, null);
busNetDef.getName().should.equal(name);
busNetDef.getDescription().should.equal(desc);
busNetDef.getVersion().should.equal('0.0.1');
}));
});
describe('getBusinessNetworkConnection', () => {
it('should get business network connection if set', inject([ClientService], (service: ClientService) => {
service['businessNetworkConnection'] = businessNetworkConMock;
let result = service.getBusinessNetworkConnection();
result.should.deep.equal(businessNetworkConMock);
}));
it('should create a new business network connection if not set', inject([ClientService], (service: ClientService) => {
let result = service.getBusinessNetworkConnection();
result.should.be.an.instanceOf(BusinessNetworkConnection);
(<any> result).cardStore.should.equal(mockCardStore);
}));
});
describe('getBusinessNetwork', () => {
it('should get the buisness network', inject([ClientService], (service: ClientService) => {
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getBusinessNetwork();
result.should.deep.equal(businessNetworkDefMock);
}));
it('should create business network if it doesn\'t exist', inject([ClientService], (service: ClientService) => {
let metadataMock = {
getVersion: sinon.stub().returns('1.0.0')
};
businessNetworkConMock.getBusinessNetwork.returns(businessNetworkDefMock);
businessNetworkDefMock.getMetadata.returns(metadataMock);
let businessNetworkConnectionMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
let result = service.getBusinessNetwork();
businessNetworkConnectionMock.should.have.been.called;
result.should.deep.equal(businessNetworkDefMock);
}));
it('should retrieve the deployed business network version if it doesn\'t exist', inject([ClientService], (service: ClientService) => {
let metadataMock = {
getVersion: sinon.stub().returns('1.0.0')
};
businessNetworkConMock.getBusinessNetwork.returns(businessNetworkDefMock);
businessNetworkDefMock.getMetadata.returns(metadataMock);
sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
let result = service.getBusinessNetwork();
metadataMock.getVersion.should.have.been.called;
result.should.deep.equal(businessNetworkDefMock);
}));
});
describe('getDeployedBusinessNetworkVersion', () => {
it('should get the deployed business network version', inject([ClientService], (service: ClientService) => {
service['deployedBusinessNetworkVersion'] = 'deployedVersion';
let result = service.getDeployedBusinessNetworkVersion();
result.should.equal('deployedVersion');
}));
it('should create business network if it doesn\'t exist', inject([ClientService], (service: ClientService) => {
let metadataMock = {
getVersion: sinon.stub().returns('deployedVersion')
};
businessNetworkConMock.getBusinessNetwork.returns(businessNetworkDefMock);
businessNetworkDefMock.getMetadata.returns(metadataMock);
sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
let result = service.getDeployedBusinessNetworkVersion();
metadataMock.getVersion.should.have.been.called;
result.should.equal('deployedVersion');
}));
});
describe('ensureConnected', () => {
it('should return if connected when not forced', fakeAsync(inject([ClientService], (service: ClientService) => {
service['isConnected'] = true;
service.ensureConnected();
adminMock.connect.should.not.have.been.called;
})));
it('should return if connecting', fakeAsync(inject([ClientService], (service: ClientService) => {
service['connectingPromise'] = Promise.resolve();
service.ensureConnected();
adminMock.connect.should.not.have.been.called;
})));
it('should connect if not connected', fakeAsync(inject([ClientService], (service: ClientService) => {
adminMock.connect.returns(Promise.resolve());
let refreshMock = sinon.stub(service, 'refresh').returns(Promise.resolve());
service.ensureConnected(false);
tick();
alertMock.busyStatus$.next.should.have.been.calledTwice;
alertMock.busyStatus$.next.firstCall.should.have.been.calledWith({
title: 'Establishing connection',
text: 'Using the connection profile web',
force: true
});
adminMock.connect.should.have.been.calledWith('cardRef', idCard, false);
refreshMock.should.have.been.called;
alertMock.busyStatus$.next.secondCall.should.have.been.calledWith(null);
service['isConnected'].should.equal(true);
should.not.exist(service['connectingPromise']);
})));
it('should connect if not connected to hlfv1 connection', fakeAsync(inject([ClientService], (service: ClientService) => {
idCard = new IdCard({userName: 'banana'}, {'x-type': 'hlfv1', 'name': 'myProfile'});
identityCardServiceMock.getCurrentIdentityCard.returns(idCard);
adminMock.connect.returns(Promise.resolve());
let refreshMock = sinon.stub(service, 'refresh').returns(Promise.resolve());
service.ensureConnected(false);
tick();
alertMock.busyStatus$.next.should.have.been.calledTwice;
alertMock.busyStatus$.next.firstCall.should.have.been.calledWith({
title: 'Establishing connection',
text: 'Using the connection profile myProfile',
force: true
});
adminMock.connect.should.have.been.calledWith('cardRef', idCard, false);
refreshMock.should.have.been.called;
alertMock.busyStatus$.next.secondCall.should.have.been.calledWith(null);
service['isConnected'].should.equal(true);
should.not.exist(service['connectingPromise']);
})));
it('should send alert if error thrown', fakeAsync(inject([ClientService], (service: ClientService) => {
adminMock.connect.returns(Promise.resolve());
let refreshMock = sinon.stub(service, 'refresh').returns(Promise.reject('forced error'));
service.ensureConnected(false)
.then(() => {
throw new Error('should not get here');
})
.catch((error) => {
error.should.equal('forced error');
alertMock.busyStatus$.next.should.have.been.calledWith(null);
});
})));
it('should set connection variables if error thrown', fakeAsync(inject([ClientService], (service: ClientService) => {
adminMock.connect.returns(Promise.resolve());
let refreshMock = sinon.stub(service, 'refresh').returns(Promise.reject('forced error'));
alertMock.errorStatus$ = {next: sinon.stub()};
service.ensureConnected(false)
.then(() => {
throw new Error('should not get here');
})
.catch((error) => {
alertMock.busyStatus$.next.should.have.been.calledWith(null);
error.should.equal('forced error');
service['isConnected'].should.be.false;
expect(service['connectingPromise']).to.be.null;
});
})));
});
describe('refresh', () => {
it('should diconnect and reconnect the business network connection', fakeAsync(inject([ClientService], (service: ClientService) => {
let businessNetworkConnectionMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
businessNetworkConMock.disconnect.returns(Promise.resolve());
service.refresh();
tick();
businessNetworkConMock.disconnect.should.have.been.calledOnce;
businessNetworkConMock.connect.should.have.been.calledOnce;
businessNetworkConMock.connect.should.have.been.calledWith('cardRef');
alertMock.busyStatus$.next.should.have.been.calledWith({
title: 'Refreshing Connection',
text: 'refreshing the connection to web',
force: true
});
})));
it('should diconnect and reconnect the business network connection with hlfv1 connection', fakeAsync(inject([ClientService], (service: ClientService) => {
idCard = new IdCard({userName: 'banana'}, {'x-type': 'hlfv1', 'name': 'myProfile'});
identityCardServiceMock.getCurrentIdentityCard.returns(idCard);
let businessNetworkConnectionMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
businessNetworkConMock.disconnect.returns(Promise.resolve());
service.refresh();
tick();
businessNetworkConMock.disconnect.should.have.been.calledOnce;
businessNetworkConMock.connect.should.have.been.calledOnce;
businessNetworkConMock.connect.should.have.been.calledWith('cardRef');
alertMock.busyStatus$.next.should.have.been.calledWith({
title: 'Refreshing Connection',
text: 'refreshing the connection to myProfile',
force: true
});
})));
it('should diconnect and reconnect with no enrollment credentials', fakeAsync(inject([ClientService], (service: ClientService) => {
let businessNetworkConnectionMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
businessNetworkConMock.disconnect.returns(Promise.resolve());
service.refresh();
tick();
businessNetworkConMock.disconnect.should.have.been.calledOnce;
businessNetworkConMock.connect.should.have.been.calledOnce;
businessNetworkConMock.connect.should.have.been.calledWith('cardRef');
alertMock.busyStatus$.next.should.have.been.calledWith({
title: 'Refreshing Connection',
text: 'refreshing the connection to web',
force: true
});
})));
});
describe('getBusinessNetworkFromArchive', () => {
it('should get a business network from an archive', fakeAsync(inject([ClientService], (service: ClientService) => {
let buffer = Buffer.from('a buffer');
let businessNetworkFromArchiveMock = sandbox.stub(BusinessNetworkDefinition, 'fromArchive').returns(Promise.resolve({name: 'myNetwork'}));
service.getBusinessNetworkFromArchive(buffer).then((result) => {
result.should.deep.equal({name: 'myNetwork'});
});
tick();
businessNetworkFromArchiveMock.should.have.been.calledWith(buffer);
})));
});
describe('issueIdentity', () => {
it('should generate and return an identity using internally held state information', fakeAsync(inject([ClientService], (service: ClientService) => {
businessNetworkConMock.issueIdentity.returns(Promise.resolve({
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: undefined}
}));
let businessNetworkConnectionMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
service.issueIdentity('userId', 'uniqueName', {issuer: false, affiliation: undefined}).then((identity) => {
let expected = {
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: undefined}
};
identity.should.deep.equal(expected);
});
tick();
businessNetworkConnectionMock.should.have.been.called;
})));
it('should generate and return an identity, detecting blockchain.ibm.com URLs', fakeAsync(inject([ClientService], (service: ClientService) => {
idCard.connectionProfile = {
name: 'myProfile',
membershipServicesURL: 'memberURL\.blockchain\.ibm\.com',
peerURL: 'peerURL\.blockchain\.ibm\.com'
};
businessNetworkConMock.issueIdentity.returns(Promise.resolve({
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: 'group1'}
}));
let businessNetworkConnectionMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
service.issueIdentity('userId', 'uniqueName', {issuer: false, affiliation: undefined}).then((identity) => {
let expected = {
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: 'group1'}
};
identity.should.deep.equal(expected);
});
tick();
businessNetworkConnectionMock.should.have.been.called;
})));
});
describe('revokeIdentity', () => {
it('should call the revokeIdentity() function for the relevant BusinessNetworkConnection', fakeAsync(inject([ClientService], (service: ClientService) => {
let mockGetBusinessNetwork = sinon.stub(service, 'getBusinessNetworkConnection').returns({
revokeIdentity: sinon.stub().returns(Promise.resolve())
});
service.revokeIdentity({fake: 'identity'});
tick();
mockGetBusinessNetwork().revokeIdentity.should.have.been.calledWith({fake: 'identity'});
})));
});
describe('disconnect', () => {
it('should disconnect', inject([ClientService], (service: ClientService) => {
let businessNetworkMock = sinon.stub(service, 'getBusinessNetworkConnection').returns(businessNetworkConMock);
service.disconnect();
service['isConnected'].should.equal(false);
adminMock.disconnect.should.have.been.called;
businessNetworkConMock.disconnect.should.have.been.called;
}));
});
describe('revokeIdentity', () => {
it('should call the revokeIdentity() function for the relevant BusinessNetworkConnection', fakeAsync(inject([ClientService], (service: ClientService) => {
let mockGetBusinessNetwork = sinon.stub(service, 'getBusinessNetworkConnection').returns({
revokeIdentity: sinon.stub().returns(Promise.resolve())
});
service.revokeIdentity({fake: 'identity'});
tick();
mockGetBusinessNetwork().revokeIdentity.should.have.been.calledWith({fake: 'identity'});
})));
});
describe('#filterModelFiles', () => {
it('should filter passed model files', inject([ClientService], (service: ClientService) => {
let mockFile0 = sinon.createStubInstance(ModelFile);
mockFile0.isSystemModelFile.returns(true);
let mockFile1 = sinon.createStubInstance(ModelFile);
mockFile1.isSystemModelFile.returns(true);
let mockFile2 = sinon.createStubInstance(ModelFile);
mockFile2.isSystemModelFile.returns(false);
let mockFile3 = sinon.createStubInstance(ModelFile);
mockFile3.isSystemModelFile.returns(false);
let mockFile4 = sinon.createStubInstance(ModelFile);
mockFile4.isSystemModelFile.returns(true);
let modelManagerMock = {
getModelFiles: sinon.stub().returns([mockFile0, mockFile1, mockFile2, mockFile3, mockFile4]),
addModelFiles: sinon.stub()
};
let aclManagerMock = {
setAclFile: sinon.stub(),
getAclFile: sinon.stub().returns(aclFileMock)
};
let scriptManagerMock = {
getScripts: sinon.stub().returns([scriptFileMock, scriptFileMock]),
addScript: sinon.stub()
};
let queryManagerMock = {
setQueryFile: sinon.stub(),
getQueryFile: sinon.stub().returns(queryFileMock)
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
businessNetworkDefMock.getAclManager.returns(aclManagerMock);
businessNetworkDefMock.getQueryManager.returns(queryManagerMock);
sinon.stub(service, 'getBusinessNetwork').returns(businessNetworkDefMock);
let mockCreateBusinessNetwork = sinon.stub(service, 'createBusinessNetwork').returns(businessNetworkDefMock);
mockFile3.isSystemModelFile.returns(true);
let allFiles = [mockFile0, mockFile1, mockFile2, mockFile3];
let filteredFiles = service['filterModelFiles'](allFiles);
filteredFiles.length.should.be.equal(1);
}));
});
describe('resolveTransactionRelationship', () => {
let mockRegistry;
beforeEach(() => {
mockRegistry = {
get: sinon.stub().returns({$class: 'myTransaction'})
};
businessNetworkConMock.getTransactionRegistry.returns(Promise.resolve(mockRegistry));
});
it('should resolve the transaction relationship', fakeAsync(inject([ClientService], (service: ClientService) => {
let getBusinessNetworkConStub = sinon.stub(service, 'getBusinessNetworkConnection');
let transaction = {
getIdentifier: sinon.stub().returns('1234')
};
getBusinessNetworkConStub.returns(businessNetworkConMock);
service.resolveTransactionRelationship(transaction).then((result) => {
result.should.deep.equal({$class: 'myTransaction'});
});
tick();
getBusinessNetworkConStub.should.have.been.called;
businessNetworkConMock.getTransactionRegistry.should.have.been.called;
})));
});
}); | the_stack |
import { tsUtils } from '@neo-one/ts-utils';
import ts from 'typescript';
import { Types } from '../../constants';
import { ScriptBuilder } from '../../sb';
import { VisitOptions } from '../../types';
import { Helper } from '../Helper';
export interface EqualsEqualsHelperOptions {
readonly left: ts.Node;
readonly right: ts.Node;
}
// Input: []
// Output: [boolean]
export class EqualsEqualsHelper extends Helper {
private readonly left: ts.Node;
private readonly right: ts.Node;
public constructor(options: EqualsEqualsHelperOptions) {
super();
this.left = options.left;
this.right = options.right;
}
public emit(sb: ScriptBuilder, node: ts.Node, options: VisitOptions): void {
if (!options.pushValue) {
sb.visit(this.left, options);
sb.visit(this.right, options);
return;
}
const leftType = sb.context.analysis.getType(this.left);
const rightType = sb.context.analysis.getType(this.right);
if (leftType !== undefined && rightType !== undefined) {
this.equalsEqualsType(sb, node, options, leftType, rightType);
} else {
this.equalsEqualsUnknown(sb, node, options);
}
}
public equalsEqualsType(
sb: ScriptBuilder,
node: ts.Node,
options: VisitOptions,
leftType: ts.Type,
rightType: ts.Type,
): void {
if (
tsUtils.type_.isOnly(leftType) &&
tsUtils.type_.isOnly(rightType) &&
tsUtils.type_.isSame(leftType, rightType)
) {
sb.emitHelper(node, options, sb.helpers.equalsEqualsEquals({ leftType, rightType }));
} else if (
(tsUtils.type_.hasNull(leftType) || tsUtils.type_.hasUndefined(leftType)) &&
(tsUtils.type_.isOnlyUndefined(rightType) || tsUtils.type_.isOnlyNull(rightType))
) {
// [left]
sb.visit(this.left, options);
// [left]
sb.visit(this.right, sb.noPushValueOptions(options));
// [equals]
sb.emitHelper(node, options, sb.helpers.isNullOrUndefined({ type: rightType }));
} else if (
tsUtils.type_.isOnlyNumberish(leftType) &&
(tsUtils.type_.isOnlyStringish(rightType) || tsUtils.type_.isOnlyBooleanish(rightType))
) {
// [left]
sb.visit(this.left, options);
// [right, left]
sb.visit(this.right, options);
// [equals]
this.equalsEqualsLeftNumberRightBooleanOrString(sb, node, options);
} else if (
tsUtils.type_.isOnlyBooleanish(leftType) &&
(tsUtils.type_.isOnlyStringish(rightType) || tsUtils.type_.isOnlyBooleanish(rightType))
) {
// [left]
sb.visit(this.left, options);
// [leftNumber]
sb.emitHelper(this.left, options, sb.helpers.toNumber({ type: sb.context.analysis.getType(this.left) }));
// [leftNumberVal]
sb.emitHelper(this.left, options, sb.helpers.wrapNumber);
// [right, leftNumberVal]
sb.visit(this.right, options);
// [equals]
this.equalsEqualsLeftNumberRightBooleanOrString(sb, node, options);
} else if (
(tsUtils.type_.isOnlyStringish(leftType) || tsUtils.type_.isOnlyBooleanish(leftType)) &&
tsUtils.type_.isOnlyNumberish(rightType)
) {
// [left]
sb.visit(this.left, options);
// [right, left]
sb.visit(this.right, options);
// [equals]
this.equalsEqualsRightNumberLeftBooleanOrString(sb, node, options);
} else if (
(tsUtils.type_.isOnlyStringish(leftType) || tsUtils.type_.isOnlyBooleanish(leftType)) &&
tsUtils.type_.isOnlyBooleanish(rightType)
) {
// [left]
sb.visit(this.left, options);
// [right, left]
sb.visit(this.right, options);
// [rightNumber, left]
sb.emitHelper(this.right, options, sb.helpers.toNumber({ type: sb.context.analysis.getType(this.right) }));
// [rightNumberVal, left]
sb.emitHelper(this.right, options, sb.helpers.wrapNumber);
// [equals]
this.equalsEqualsRightNumberLeftBooleanOrString(sb, node, options);
} else {
this.equalsEqualsUnknown(sb, node, options);
}
}
public equalsEqualsLeftNumberRightBooleanOrString(sb: ScriptBuilder, node: ts.Node, options: VisitOptions): void {
// [rightNumber, left]
sb.emitHelper(this.right, options, sb.helpers.toNumber({ type: sb.context.analysis.getType(this.right) }));
// [rightNumber, left]
sb.emitHelper(this.right, options, sb.helpers.wrapNumber);
// [equals]
sb.emitHelper(
node,
options,
sb.helpers.equalsEqualsEquals({
leftType: undefined,
leftKnownType: Types.Number,
rightType: undefined,
rightKnownType: Types.Number,
}),
);
}
public equalsEqualsRightNumberLeftBooleanOrString(sb: ScriptBuilder, node: ts.Node, options: VisitOptions): void {
// [left, right]
sb.emitOp(node, 'SWAP');
// [leftNumber, right]
sb.emitHelper(this.left, options, sb.helpers.toNumber({ type: sb.context.analysis.getType(this.left) }));
// [leftNumber, right]
sb.emitHelper(this.left, options, sb.helpers.wrapNumber);
// [right, leftNumber]
sb.emitOp(node, 'SWAP');
// [equals]
sb.emitHelper(
node,
options,
sb.helpers.equalsEqualsEquals({
leftType: undefined,
leftKnownType: Types.Number,
rightType: undefined,
rightKnownType: Types.Number,
}),
);
}
public equalsEqualsUnknown(sb: ScriptBuilder, node: ts.Node, options: VisitOptions): void {
const copy = () => {
// [left, right]
sb.emitOp(this.right, 'SWAP');
// [left, right, left]
sb.emitOp(this.right, 'TUCK');
// [right, left, right, left]
sb.emitOp(this.right, 'OVER');
};
// [left]
sb.visit(this.left, options);
// [right, left]
sb.visit(this.right, options);
const cases = [
{
condition: () => {
copy();
// [right, left]
sb.emitHelper(
node,
options,
sb.helpers.equalsEqualsEquals({
leftType: undefined,
rightType: undefined,
}),
);
},
whenTrue: () => {
sb.emitOp(node, 'DROP');
sb.emitOp(node, 'DROP');
sb.emitPushBoolean(node, true);
},
},
{
condition: () => {
copy();
// [rightIsNullOrUndefined, left, right, left]
sb.emitHelper(node, options, sb.helpers.isNullOrUndefined({ type: undefined }));
// [left, rightIsNullOrUndefined, right, left]
sb.emitOp(node, 'SWAP');
// [leftIsNullOrUndefined, rightIsNullOrUndefined, right, left]
sb.emitHelper(node, options, sb.helpers.isNullOrUndefined({ type: undefined }));
// [equals, right, left]
sb.emitOp(node, 'BOOLOR');
},
whenTrue: () => {
// [isNullOrUndefined, left]
sb.emitHelper(node, options, sb.helpers.isNullOrUndefined({ type: undefined }));
// [left, rightIsNullOrUndefined]
sb.emitOp(node, 'SWAP');
// [leftIsNullOrUndefined, rightIsNullOrUndefined]
sb.emitHelper(node, options, sb.helpers.isNullOrUndefined({ type: undefined }));
// [equals]
sb.emitOp(node, 'EQUAL');
},
},
{
condition: () => {
copy();
// [right, right, left, right, left]
sb.emitOp(node, 'DUP');
// [isString, right, left, right, left]
sb.emitHelper(this.right, options, sb.helpers.isString);
// [right, isString, left, right, left]
sb.emitOp(node, 'SWAP');
// [isBoolean, isString, left, right, left]
sb.emitHelper(this.right, options, sb.helpers.isBoolean);
// [isBooleanOrString, left, right, left]
sb.emitOp(node, 'BOOLOR');
// [left, isBooleanOrString, right, left]
sb.emitOp(node, 'SWAP');
// [left, left, isBooleanOrString, right, left]
sb.emitOp(node, 'DUP');
// [isNumber, left, isBooleanOrString, right, left]
sb.emitHelper(this.right, options, sb.helpers.isNumber);
// [left, isNumber, isBooleanOrString, right, left]
sb.emitOp(node, 'SWAP');
// [isBoolean, isNumber, isBooleanOrString, right, left]
sb.emitHelper(this.right, options, sb.helpers.isBoolean);
// [isBooleanOrNumber, isBooleanOrString, right, left]
sb.emitOp(node, 'BOOLOR');
// [is(BooleanOrNumber)And(BooleanOrString), right, left]
sb.emitOp(node, 'BOOLAND');
},
whenTrue: () => {
// [left, right]
sb.emitOp(node, 'SWAP');
// [leftNumber, right]
sb.emitHelper(node, options, sb.helpers.toNumber({ type: sb.context.analysis.getType(this.left) }));
// [leftNumber, right]
sb.emitHelper(node, options, sb.helpers.wrapNumber);
// [right, leftNumber]
sb.emitOp(node, 'SWAP');
this.equalsEqualsLeftNumberRightBooleanOrString(sb, node, options);
},
},
{
condition: () => {
copy();
// [left, right, right, left]
sb.emitOp(node, 'SWAP');
// [left, left, right, right, left]
sb.emitOp(node, 'DUP');
// [isString, left, right, right, left]
sb.emitHelper(this.right, options, sb.helpers.isString);
// [left, isString, right, right, left]
sb.emitOp(node, 'SWAP');
// [isBoolean, isString, right, right, left]
sb.emitHelper(this.right, options, sb.helpers.isBoolean);
// [isBooleanOrString, right, right, left]
sb.emitOp(node, 'BOOLOR');
// [right, isBooleanOrString, right, left]
sb.emitOp(node, 'SWAP');
// [right, right, isBooleanOrString, right, left]
sb.emitOp(node, 'DUP');
// [isNumber, right, isBooleanOrString, right, left]
sb.emitHelper(this.right, options, sb.helpers.isNumber);
// [right, isNumber, isBooleanOrString, right, left]
sb.emitOp(node, 'SWAP');
// [isBoolean, isNumber, isBooleanOrString, right, left]
sb.emitHelper(this.right, options, sb.helpers.isBoolean);
// [isBooleanOrNumber, isBooleanOrString, right, left]
sb.emitOp(node, 'BOOLOR');
// [is(BooleanOrNumber)And(BooleanOrString), right, left]
sb.emitOp(node, 'BOOLAND');
},
whenTrue: () => {
// [rightNumber, left]
sb.emitHelper(node, options, sb.helpers.toNumber({ type: sb.context.analysis.getType(this.right) }));
// [rightNumber, left]
sb.emitHelper(node, options, sb.helpers.wrapNumber);
this.equalsEqualsRightNumberLeftBooleanOrString(sb, node, options);
},
},
];
sb.emitHelper(
node,
options,
sb.helpers.case(cases, () => {
// [rightPrim, left]
sb.emitHelper(node, options, sb.helpers.toPrimitive({ type: sb.context.analysis.getType(this.right) }));
// [left, rightPrim]
sb.emitOp(node, 'SWAP');
// [leftPrim, rightPrim]
sb.emitHelper(node, options, sb.helpers.toPrimitive({ type: sb.context.analysis.getType(this.left) }));
// [rightPrim, leftPrim]
sb.emitOp(node, 'SWAP');
sb.emitHelper(
node,
options,
sb.helpers.case(cases, () => {
// [leftPrim]
sb.emitOp(node, 'DROP');
// []
sb.emitOp(node, 'DROP');
// [equals]
sb.emitPushBoolean(node, false);
}),
);
}),
);
}
} | the_stack |
import nj from '../core';
import * as tools from '../utils/tools';
import * as tranElem from '../transforms/transformElement';
const { preAsts } = nj;
const SPLIT_FLAG = '_njParam';
const TEXT_CONTENT = ['style', 'script', 'textarea', 'xmp', nj.textTag];
const { OMITTED_CLOSE_TAGS } = tranElem;
//Compile string template
export function compileStringTmpl(tmpl) {
const tmplKey = tmpl.toString(); //Get unique key
let ret = preAsts[tmplKey];
const { outputH, tmplRule, onlyParse, fileName, isExpression, isCss } = this;
if (!ret) {
//If the cache already has template data, direct return the template.
const isStr = tools.isString(tmpl),
xmls = isStr ? [tmpl] : tmpl,
l = xmls.length;
let fullXml = '',
isInBrace: boolean | string = false;
//Connection xml string
tools.each(
xmls,
(xml, i) => {
let split = '';
if (i == 0) {
if (isExpression) {
xml = (outputH ? tmplRule.firstChar : '') + tmplRule.startRule + ' ' + xml;
} else if (isCss) {
xml = '<' + tmplRule.extensionRule + 'css style="' + xml;
}
}
if (i < l - 1) {
const last = xml.length - 1,
lastChar = xml[last],
lastChar3 = xml.substr(last - 2),
isAccessor = lastChar === '#',
isSpread = lastChar3 === '...';
if (isInBrace) {
isInBrace = !tmplRule['incompleteEnd' + (isInBrace === 'isR' ? 'R' : '')].test(xml);
}
if (!isInBrace) {
if (tmplRule.incompleteStartR.test(xml)) {
isInBrace = 'isR';
} else {
isInBrace = tmplRule.incompleteStart.test(xml);
}
}
if (isAccessor) {
xml = xml.substr(0, last);
} else if (isSpread) {
xml = xml.substr(0, last - 2);
}
split = (isAccessor ? '#' : isSpread ? '...' : '') + SPLIT_FLAG + i;
if (!isInBrace) {
split = tmplRule.startRule + split + tmplRule.endRule;
}
}
if (i == l - 1) {
if (isExpression) {
xml += ' ' + tmplRule.endRule + (outputH ? tmplRule.lastChar : '');
} else if (isCss) {
xml += '" />';
}
}
fullXml += xml + split;
},
true
);
//Merge all include tags
const includeParser = nj.includeParser;
if (includeParser) {
fullXml = includeParser(fullXml, fileName, tmplRule);
}
fullXml = _formatAll(fullXml, tmplRule);
if (!outputH) {
if (nj.textMode) {
fullXml = '<' + nj.textTag + '>' + fullXml + '</' + nj.textTag + '>';
}
if (nj.noWsMode) {
fullXml = '<' + nj.noWsTag + '>' + fullXml + '</' + nj.noWsTag + '>';
}
}
//Resolve string to element
ret = _checkStringElem(fullXml, tmplRule, outputH);
tools.defineProp(ret, '_njParamCount', {
value: l - 1
});
//Save to the cache
preAsts[tmplKey] = ret;
}
let tmplFn;
if (!onlyParse) {
let params;
const args = arguments,
paramCount = ret._njParamCount;
if (paramCount > 0) {
params = {};
tools.defineProp(params, '_njParam', {
value: true
});
for (let i = 0; i < paramCount; i++) {
params[SPLIT_FLAG + i] = args[i + 1];
}
}
tmplFn = params
? function() {
return tmplMainFn.apply(this, tools.arrayPush([params], arguments));
}
: function() {
return tmplMainFn.apply(this, arguments);
};
tools.defineProps(tmplFn, {
_njTmpl: {
value: ret
},
_njTmplKey: {
value: tmplKey
}
});
const tmplMainFn = nj['compile' + (outputH ? 'H' : '')](tmplFn, tmplKey, null, null, tmplRule);
} else {
tmplFn = {
_njTmpl: ret,
_njTmplKey: tmplKey
};
}
return tmplFn;
}
function _createCurrent(elemName, parent) {
const current = {
elem: [],
elemName,
parent
};
parent.elem.push(current.elem);
return current;
}
function _setTextAfter(textAfter, current) {
textAfter && textAfter !== '' && _setText(textAfter, current.elem);
}
//Resolve string to element
function _checkStringElem(xml, tmplRule, outputH) {
const root = [],
pattern = tmplRule.checkElem;
let current = {
elem: root,
elemName: 'root',
parent: null
},
parent = null,
matchArr,
inTextContent,
omittedCloseElem = null;
while ((matchArr = pattern.exec(xml))) {
const textBefore = matchArr[1],
elem = matchArr[2],
elemName = matchArr[3],
elemParams = matchArr[4];
let textAfter = matchArr[5];
//处理上一次循环中的可省略闭合标签
if (omittedCloseElem) {
const [_elem, _elemName, _elemParams, _textAfter] = omittedCloseElem;
const isEx = elem ? tranElem.isExAll(elemName, tmplRule) : false;
if (
isEx &&
!isEx[1] &&
(tranElem.isPropS(elemName, tmplRule) ||
tranElem.isStrPropS(elemName, tmplRule) ||
tranElem.isParamsEx(isEx[3]) ||
tranElem.exCompileConfig(isEx[3]).isDirective)
) {
parent = current;
current = _createCurrent(_elemName, parent);
_setElem(_elem, _elemName, _elemParams, current.elem, null, tmplRule, outputH);
} else {
_setSelfCloseElem(_elem, _elemName, _elemParams, current.elem, tmplRule, outputH);
}
_setTextAfter(_textAfter, current);
omittedCloseElem = null;
}
//Text before tag
if (textBefore && textBefore !== '') {
_setText(textBefore, current.elem);
}
//Element tag
if (elem) {
if (elem !== '<') {
if (elem.indexOf('<!') === 0) {
//一些特殊标签当做文本处理
_setText(elem, current.elem);
} else {
const isEx = tranElem.isExAll(elemName, tmplRule);
if (elemName[0] === '/') {
//Close tag
if (elemName.substr(1).toLowerCase() === inTextContent) {
//取消纯文本子节点标记
inTextContent = null;
}
if (isEx || !inTextContent) {
const cName = current.elemName;
if (
cName.indexOf(SPLIT_FLAG) < 0
? elemName === '/' + cName
: elemName.indexOf(SPLIT_FLAG) > -1 || elemName === '//'
) {
//如果开始标签包含SPLIT_FLAG,则只要结束标签包含SPLIT_FLAG就认为该标签已关闭
current = current.parent;
}
} else {
_setText(elem, current.elem);
}
} else if (elem[elem.length - 2] === '/') {
//Self close tag
if (isEx || !inTextContent) {
_setSelfCloseElem(elem, elemName, elemParams, current.elem, tmplRule, outputH);
} else {
_setText(elem, current.elem);
}
} else {
//Open tag
if (isEx || !inTextContent) {
if (!inTextContent && OMITTED_CLOSE_TAGS[elemName.toLowerCase()]) {
//img等可不闭合标签
omittedCloseElem = [elem, elemName, elemParams, textAfter];
} else {
const elemNameL = elemName.toLowerCase();
if (TEXT_CONTENT.indexOf(elemNameL) > -1) {
//标记该标签为纯文本子节点
inTextContent = elemNameL;
}
parent = current;
current = _createCurrent(elemName, parent);
_setElem(elem, elemName, elemParams, current.elem, null, tmplRule, outputH);
}
} else {
_setText(elem, current.elem);
}
}
}
} else {
//单独的"<"和后面的文本拼合在一起
if (textAfter == null) {
textAfter = '';
}
textAfter = elem + textAfter;
}
}
//Text after tag
!omittedCloseElem && _setTextAfter(textAfter, current);
}
//处理最后一次循环中遗留的可省略闭合标签
if (omittedCloseElem) {
const [_elem, _elemName, _elemParams, _textAfter] = omittedCloseElem;
_setSelfCloseElem(_elem, _elemName, _elemParams, current.elem, tmplRule, outputH);
_setTextAfter(_textAfter, current);
}
return root;
}
const LT_GT_LOOKUP = {
'<': '_njLt_',
'>': '_njGt_'
};
const REGEX_LT_GT = />|</g;
function _formatAll(str, tmplRule) {
const commentRule = tmplRule.commentRule;
return str
.replace(new RegExp('<!--' + commentRule + '[\\s\\S]*?' + commentRule + '-->', 'g'), '')
.replace(
new RegExp('([\\s]+:[^\\s=>]+=((\'[^\']+\')|("[^"]+")))|(' + tmplRule.braceParamStr + ')', 'g'),
(all, g1, g2, g3, g4, g5) => (g1 ? g1 : g5).replace(REGEX_LT_GT, match => LT_GT_LOOKUP[match])
);
}
function _transformToEx(isStr, elemName, elemParams, tmplRule) {
return (
tmplRule.extensionRule +
(isStr ? 'strProp' : 'prop') +
' ' +
tmplRule.startRule +
`'` +
elemName.substr((isStr ? tmplRule.strPropRule.length : 0) + tmplRule.propRule.length) +
`'` +
tmplRule.endRule +
elemParams
);
}
//Set element node
function _setElem(elem, elemName, elemParams, elemArr, bySelfClose, tmplRule, outputH) {
let ret, paramsEx;
const fixedExTagName = tranElem.fixExTagName(elemName, tmplRule);
if (fixedExTagName) {
elemName = fixedExTagName;
}
if (tranElem.isEx(elemName, tmplRule, true)) {
ret = elem.substring(1, elem.length - 1);
if (fixedExTagName) {
ret = tmplRule.extensionRule + tools.lowerFirst(ret);
}
const retS = _getSplitParams(ret, tmplRule, outputH);
ret = retS.elem;
paramsEx = retS.params;
} else if (tranElem.isStrPropS(elemName, tmplRule)) {
ret = _transformToEx(true, elemName, elemParams, tmplRule);
} else if (tranElem.isPropS(elemName, tmplRule)) {
ret = _transformToEx(false, elemName, elemParams, tmplRule);
} else {
const retS = _getSplitParams(elem, tmplRule, outputH);
ret = retS.elem;
paramsEx = retS.params;
}
if (bySelfClose) {
const retC = [ret];
if (paramsEx) {
retC.push(paramsEx);
}
elemArr.push(retC);
} else {
elemArr.push(ret);
if (paramsEx) {
elemArr.push(paramsEx);
}
}
}
const REGEX_EX_ATTR = /([^\s-$.]+)(([$.][^\s-$.]+)*)((-[^\s-$.]+([$.][^\s-$.]+)*)*)/;
//Extract split parameters
function _getSplitParams(elem, tmplRule, outputH) {
const { extensionRule, startRule, endRule, firstChar, lastChar, spreadProp, directives } = tmplRule;
let paramsEx;
//Replace the parameter like "{...props}".
elem = elem.replace(spreadProp, (all, g1, propR, g3, prop) => {
if (propR) {
prop = propR;
}
if (!paramsEx) {
paramsEx = [extensionRule + 'props'];
}
paramsEx.push([
extensionRule +
'spread ' +
(propR ? firstChar : '') +
startRule +
prop.replace(/\.\.\./, '') +
endRule +
(propR ? lastChar : '') +
'/'
]);
return ' ';
});
//Replace the parameter like "#show={false}".
elem = elem.replace(directives, (all, g1, g2, g3, g4, g5, g6, key, hasColon, hasEx, name, hasEqual, value) => {
if (hasEx == null) {
return all;
}
if (!paramsEx) {
paramsEx = [extensionRule + 'props'];
}
let args, modifiers;
name = name.replace(REGEX_EX_ATTR, (all, name, modifier, g3, arg) => {
if (arg) {
args = arg
.substr(1)
.split('-')
.map(item => {
let argStr;
let modifierStr = '';
const strs = item.split(/[$.]/);
strs.forEach((str, i) => {
if (i == 0) {
argStr = `name:'${str}'` + (i < strs.length - 1 ? ',' : '');
} else {
modifierStr += `'${str}'` + (i < strs.length - 1 ? ',' : '');
}
});
return '{' + argStr + (modifierStr != '' ? 'modifiers:[' + modifierStr + ']' : '') + '}';
});
}
if (modifier) {
modifiers = modifier
.substr(1)
.split(/[$.]/)
.map(item => `'${item}'`);
}
return name;
});
const exPreAst = [
extensionRule +
name +
' _njIsDirective' +
(args ? ' arguments="' + firstChar + startRule + '[' + args.join(',') + ']' + endRule + lastChar + '"' : '') +
(modifiers ? ' modifiers="' + startRule + '[' + modifiers.join(',') + ']' + endRule + '"' : '') +
(hasEqual ? '' : ' /')
];
hasEqual &&
exPreAst.push(
(hasColon ? (outputH ? firstChar : '') + startRule + ' ' : '') +
tools.clearQuot(value) +
(hasColon ? ' ' + endRule + (outputH ? lastChar : '') : '')
);
paramsEx.push(exPreAst);
return ' ';
});
return {
elem,
params: paramsEx
};
}
//Set self close element node
function _setSelfCloseElem(elem, elemName, elemParams, elemArr, tmplRule, outputH) {
if (/\/$/.test(elemName)) {
elemName = elemName.substr(0, elemName.length - 1);
}
_setElem(elem, elemName, elemParams, elemArr, true, tmplRule, outputH);
}
//Set text node
function _setText(text, elemArr) {
elemArr.push(text);
} | the_stack |
* @module UiItemsProvider
*/
import { BeEvent, Logger, MarkRequired } from "@itwin/core-bentley";
import { BackstageItem } from "./backstage/BackstageItem";
import { CommonStatusBarItem } from "./statusbar/StatusBarItem";
import { CommonToolbarItem, ToolbarOrientation, ToolbarUsage } from "./toolbars/ToolbarItem";
import { AbstractWidgetProps } from "./widget/AbstractWidgetProps";
import { AbstractZoneLocation, StagePanelLocation, StagePanelSection } from "./widget/StagePanel";
import { loggerCategory } from "./utils/misc";
import { UiItemsProvider } from "./UiItemsProvider";
/** Action taken by the application on item provided by a UiItemsProvider
* @public @deprecated this was only used by the previously removed UiItemsArbiter.
*/
export enum UiItemsApplicationAction {
/** Allow the change to the item */
Allow,
/** Disallow the change to the item */
Disallow,
/** Update the item during the change */
Update,
}
/** UIProvider Registered Event Args interface.
* @public
*/
export interface UiItemProviderRegisteredEventArgs {
providerId: string;
}
/** UiItemProviderOverrides allows the application that registers a provider to limit when it is allowed to provide items
* @public
*/
export interface AllowedUiItemProviderOverrides {
/** allows providerId to be overridden in the items manager for cases where the same provider needs to provide different content to different stages
* @beta
*/
providerId?: string;
/** if specified then the current stage's Usage will be compared before allowing any items to be provided
* @beta
*/
stageUsages?: string[];
/** if specified then the current stage's Id will be compared before allowing any items to be provided
* @beta
*/
stageIds?: string[];
}
/** Allowed overrides applied to a UiItemsProvider the application that registers a provider to limit when it is allowed to provide items.
* Note that if an override `providerId` is specified then either `stageIds` or `stageUsages` must be defined to limit when the provider's
* items are allowed.
* @public
*/
export type UiItemProviderOverrides = MarkRequired<AllowedUiItemProviderOverrides, "providerId" | "stageUsages"> |
MarkRequired<AllowedUiItemProviderOverrides, "providerId" | "stageIds"> | // eslint-disable-line @typescript-eslint/indent
MarkRequired<AllowedUiItemProviderOverrides, "stageIds"> | // eslint-disable-line @typescript-eslint/indent
MarkRequired<AllowedUiItemProviderOverrides, "stageUsages"> | // eslint-disable-line @typescript-eslint/indent
MarkRequired<AllowedUiItemProviderOverrides, "providerId" | "stageUsages" | "stageIds">; // eslint-disable-line @typescript-eslint/indent
/** Interface that defines an instance of a UiItemsProvider and its application specified overrides.
* @beta
*/
interface UiItemProviderEntry {
provider: UiItemsProvider;
overrides?: UiItemProviderOverrides;
}
/**
* Controls registering of UiItemsProviders and calls the provider's methods when populating different parts of the User Interface.
* @public
*/
export class UiItemsManager {
private static _registeredUiItemsProviders: Map<string, UiItemProviderEntry> = new Map<string, UiItemProviderEntry>();
/** For use in unit testing
* @internal */
public static clearAllProviders() {
UiItemsManager._registeredUiItemsProviders.clear();
}
/** Event raised any time a UiProvider is registered or unregistered. */
public static readonly onUiProviderRegisteredEvent = new BeEvent<(ev: UiItemProviderRegisteredEventArgs) => void>();
/** Return number of registered UiProvider. */
public static get registeredProviderIds() {
const ids = [...UiItemsManager._registeredUiItemsProviders.keys()];
return ids;
}
/** Return true if there is any registered UiProvider. */
public static get hasRegisteredProviders(): boolean {
return this._registeredUiItemsProviders.size > 0;
}
/**
* Retrieves a previously loaded UiItemsProvider.
* @param providerId id of the UiItemsProvider to get
*/
public static getUiItemsProvider(providerId: string): UiItemsProvider | undefined {
return UiItemsManager._registeredUiItemsProviders.get(providerId)?.provider;
}
private static sendRegisteredEvent(ev: UiItemProviderRegisteredEventArgs) {
UiItemsManager.onUiProviderRegisteredEvent.raiseEvent(ev);
}
/**
* Registers a UiItemsProvider with the UiItemsManager.
* @param uiProvider the UI items provider to register.
*/
public static register(uiProvider: UiItemsProvider, overrides?: UiItemProviderOverrides): void {
const providerId = overrides?.providerId ?? uiProvider.id;
if (UiItemsManager.getUiItemsProvider(providerId)) {
Logger.logInfo(loggerCategory(this), `UiItemsProvider (${providerId}) is already loaded`);
} else {
UiItemsManager._registeredUiItemsProviders.set(providerId, { provider: uiProvider, overrides });
Logger.logInfo(loggerCategory(this), `UiItemsProvider ${uiProvider.id} registered as ${providerId} `);
UiItemsManager.sendRegisteredEvent({ providerId } as UiItemProviderRegisteredEventArgs);
}
}
/** Remove a specific UiItemsProvider from the list of available providers. */
public static unregister(uiProviderId: string): void {
const provider = UiItemsManager.getUiItemsProvider(uiProviderId);
if (!provider)
return;
provider.onUnregister && provider.onUnregister();
UiItemsManager._registeredUiItemsProviders.delete(uiProviderId);
Logger.logInfo(loggerCategory(this), `UiItemsProvider (${uiProviderId}) unloaded`);
// trigger a refresh of the ui
UiItemsManager.sendRegisteredEvent({ providerId: uiProviderId } as UiItemProviderRegisteredEventArgs);
}
private static allowItemsFromProvider(entry: UiItemProviderEntry, stageId?: string, stageUsage?: string) {
// istanbul ignore else
const overrides = entry.overrides;
if (undefined !== stageId && overrides?.stageIds && !(overrides.stageIds.some((value: string) => value === stageId)))
return false;
if (undefined !== stageUsage && overrides?.stageUsages && !(overrides.stageUsages.some((value: string) => value === stageUsage)))
return false;
return true;
}
/** Called when the application is populating a toolbar so that any registered UiItemsProvider can add tool buttons that either either execute
* an action or specify a registered ToolId into toolbar.
* @param stageId a string identifier the active stage.
* @param stageUsage the StageUsage of the active stage.
* @param toolbarUsage usage of the toolbar
* @param toolbarOrientation orientation of the toolbar
* @returns an array of error messages. The array will be empty if the load is successful, otherwise it is a list of one or more problems.
*/
public static getToolbarButtonItems(stageId: string, stageUsage: string, toolbarUsage: ToolbarUsage,
toolbarOrientation: ToolbarOrientation, stageAppData?: any): CommonToolbarItem[] {
const buttonItems: CommonToolbarItem[] = [];
if (0 === UiItemsManager._registeredUiItemsProviders.size)
return buttonItems;
UiItemsManager._registeredUiItemsProviders.forEach((entry: UiItemProviderEntry) => {
const uiProvider = entry.provider;
const providerId = entry.overrides?.providerId ?? uiProvider.id;
// istanbul ignore else
if (uiProvider.provideToolbarButtonItems && this.allowItemsFromProvider(entry, stageId, stageUsage)) {
uiProvider.provideToolbarButtonItems(stageId, stageUsage, toolbarUsage, toolbarOrientation, stageAppData)
.forEach((spec: CommonToolbarItem) => {
// ignore duplicate ids
if (-1 === buttonItems.findIndex((existingItem)=> spec.id === existingItem.id ))
buttonItems.push({ ...spec, providerId });
});
}
});
return buttonItems;
}
/** Called when the application is populating the statusbar so that any registered UiItemsProvider can add status fields
* @param stageId a string identifier the active stage.
* @param stageUsage the StageUsage of the active stage.
* @returns An array of CommonStatusBarItem that will be used to create controls for the status bar.
*/
public static getStatusBarItems(stageId: string, stageUsage: string, stageAppData?: any): CommonStatusBarItem[] {
const statusBarItems: CommonStatusBarItem[] = [];
if (0 === UiItemsManager._registeredUiItemsProviders.size)
return statusBarItems;
UiItemsManager._registeredUiItemsProviders.forEach((entry: UiItemProviderEntry) => {
const uiProvider = entry.provider;
const providerId = entry.overrides?.providerId ?? uiProvider.id;
// istanbul ignore else
if (uiProvider.provideStatusBarItems && this.allowItemsFromProvider(entry, stageId, stageUsage)) {
uiProvider.provideStatusBarItems(stageId, stageUsage, stageAppData)
.forEach((item: CommonStatusBarItem) => {
// ignore duplicate ids
if (-1 === statusBarItems.findIndex((existingItem)=> item.id === existingItem.id ))
statusBarItems.push({ ...item, providerId });
});
}
});
return statusBarItems;
}
/** Called when the application is populating the statusbar so that any registered UiItemsProvider can add status fields
* @returns An array of BackstageItem that will be used to create controls for the backstage menu.
*/
public static getBackstageItems(): BackstageItem[] {
const backstageItems: BackstageItem[] = [];
if (0 === UiItemsManager._registeredUiItemsProviders.size)
return backstageItems;
UiItemsManager._registeredUiItemsProviders.forEach((entry: UiItemProviderEntry) => {
const uiProvider = entry.provider;
const providerId = entry.overrides?.providerId ?? uiProvider.id;
// istanbul ignore else
if (uiProvider.provideBackstageItems && this.allowItemsFromProvider(entry)) {
uiProvider.provideBackstageItems()
.forEach((item: BackstageItem) => {
// ignore duplicate ids
if (-1 === backstageItems.findIndex((existingItem)=> item.id === existingItem.id ))
backstageItems.push({ ...item, providerId });
});
}
});
return backstageItems;
}
/** Called when the application is populating the Stage Panels so that any registered UiItemsProvider can add widgets
* @param stageId a string identifier the active stage.
* @param stageUsage the StageUsage of the active stage.
* @param location the location within the stage.
* @param section the section within location.
* @returns An array of AbstractWidgetProps that will be used to create widgets.
*/
public static getWidgets(stageId: string, stageUsage: string, location: StagePanelLocation, section?: StagePanelSection, zoneLocation?: AbstractZoneLocation, stageAppData?: any): ReadonlyArray<AbstractWidgetProps> {
const widgets: AbstractWidgetProps[] = [];
if (0 === UiItemsManager._registeredUiItemsProviders.size)
return widgets;
UiItemsManager._registeredUiItemsProviders.forEach((entry: UiItemProviderEntry) => {
const uiProvider = entry.provider;
const providerId = entry.overrides?.providerId ?? uiProvider.id;
// istanbul ignore else
if (uiProvider.provideWidgets && this.allowItemsFromProvider(entry, stageId, stageUsage)) {
uiProvider.provideWidgets(stageId, stageUsage, location, section, zoneLocation, stageAppData)
.forEach((widget: AbstractWidgetProps) => {
// ignore duplicate ids
if (-1 === widgets.findIndex((existingItem)=> widget.id === existingItem.id ))
widgets.push({ ...widget, providerId });
});
}
});
return widgets;
}
} | the_stack |
'use strict';
import * as os from 'os';
import * as chai from 'chai';
import * as fs from 'fs-extra';
import * as sinon from 'sinon';
import * as yaml from 'js-yaml';
import * as sinonChai from 'sinon-chai';
import * as _ from 'lodash';
import { TknImpl } from '../../src/tkn';
import { getPipelineRunFrom, createTriggerTemplate, createEventListener, getPipelineRunWorkspaces, addTriggerToPipeline, addTrigger } from '../../src/tekton/addtrigger';
import { AddTriggerFormValues, TriggerBindingKind } from '../../src/tekton/triggertype';
import { PipelineRunData, TriggerTemplateKindParam, TriggerTemplateKind } from '../../src/tekton';
import { window } from 'vscode';
const expect = chai.expect;
chai.use(sinonChai);
suite('Tekton/Pipeline', () => {
const sandbox = sinon.createSandbox();
let execStub: sinon.SinonStub;
let osStub: sinon.SinonStub;
let writeFileStub: sinon.SinonStub;
let unlinkStub: sinon.SinonStub;
let safeDumpStub: sinon.SinonStub;
let infoMsgStub: sinon.SinonStub;
setup(() => {
execStub = sandbox.stub(TknImpl.prototype, 'execute').resolves({ error: null, stdout: '', stderr: '' });
osStub = sandbox.stub(os, 'tmpdir').returns('path');
writeFileStub = sandbox.stub(fs, 'writeFile').resolves();
unlinkStub = sandbox.stub(fs, 'unlink').resolves();
safeDumpStub = sandbox.stub(yaml, 'safeDump').returns('empty');
infoMsgStub = sandbox.stub(window, 'showInformationMessage').resolves();
});
teardown(() => {
sandbox.restore();
});
const triggerContent = {
name:'vote-app',
resource: {
apiVersion:'triggers.tekton.dev/v1alpha1',
kind:'TriggerBinding',
metadata: {
name:'vote-app',
namespace:'pipelines-tutorial'
},
spec: {
params: [{
name:'git-repo-url',
value:'$(body.repository.url)'
}]
}
}
}
const createTrigger: AddTriggerFormValues = {
name:'sample-pipeline-cluster-task-4',
params: [
{
default: 'gcr.io/christiewilson-catfactory',
name: 'image-registry'
}
],
resources: [
{
name: 'source-repo',
resourceRef: 'skaffold-git-multiple-output-image'
}
],
workspaces: [
{
name: 'git-source',
workspaceName: 'test',
workspaceType: 'PersistentVolumeClaim'
},
{
name: 'git-source',
workspaceType: 'EmptyDirectory'
}
],
volumeClaimTemplate: [
{
kind: 'volumeClaimTemplate',
metadata: {
name: 'git-source'
},
spec: {
accessModes: ['ReadWriteOnce'],
resources: {
requests: {
storage: '1Mi'
}
}
}
}
],
trigger: triggerContent,
serviceAccount: 'default'
}
const pipeline = {
apiVersion:'tekton.dev/v1beta1',
kind:'Pipeline',
metadata: {
name:'sample-pipeline-cluster-task-4',
namespace:'pipelines-tutorial',
resourceVersion:'34655',
selfLink:'/apis/tekton.dev/v1beta1/namespaces/pipelines-tutorial/pipelines/sample-pipeline-cluster-task-4',
uid:'b2e31019-dece-4201-b8b5-e29b627da0aa'
},
spec: {
tasks: [{
name:'cluster-task-pipeline-4',
taskRef: {
kind:'ClusterTask',
name:'cluster-task-pipeline-4'
}
}]
}
}
const eventListener = {
apiVersion:'triggers.tekton.dev/v1alpha1',
kind:'EventListener',
metadata: {
name:'event-listener-'
},
spec: {
serviceAccountName:'pipeline',
triggers: [{
bindings: [{
kind:'TriggerBinding',
name:'vote-app'
}],
template: {
name:'trigger-template-sample-pipeline-cluster-task-4-z0we6m'
}
}]
}
}
const serviceResource = {
spec: {
ports: [
{
name: 'http-listener',
port: 8080,
protocol: 'TCP',
targetPort: 8000
}
]
}
}
const tknVersion = 'Client version: 0.12.1\nPipeline version: v0.16.3\nTriggers version: v0.5.0\n';
const inputAddTrigger: AddTriggerFormValues = {
name:'sample-pipeline-cluster-task-4',
params: [],
resources: [],
workspaces: [],
trigger: triggerContent
}
const option: { generateName: boolean } = {
generateName: true
}
const pipelieRun: PipelineRunData = {
apiVersion:'tekton.dev/v1beta1',
kind:'PipelineRun',
metadata: {
generateName:'sample-pipeline-cluster-task-4-',
labels: {
'tekton.dev/pipeline':'sample-pipeline-cluster-task-4'
}
},
spec: {
params: [],
pipelineRef: {
name: 'sample-pipeline-cluster-task-4'
},
resources: [],
workspaces: undefined
}
}
const params: TriggerTemplateKindParam[] = [{
name:'git-repo-url'
}]
const triggerTemplate: TriggerTemplateKind = {
apiVersion:'triggers.tekton.dev/v1alpha1',
kind:'TriggerTemplate',
metadata: {
name:'trigger-template-sample-pipeline-cluster-task-4-z0we6m'
},
spec: {
params: [{
name:'git-repo-url'
}],
resourcetemplates: [{
apiVersion:'tekton.dev/v1beta1',
kind:'PipelineRun',
metadata: {
generateName:'sample-pipeline-cluster-task-4-',
labels: {
'tekton.dev/pipeline':'sample-pipeline-cluster-task-4'
}
},
spec: {
param: [],
pipelineRef: {
name:'sample-pipeline-cluster-task-4'
},
resources: [],
status:null,
workspaces:undefined
}
}]
}
}
const triggerBindings: TriggerBindingKind[] = [{
apiVersion:'triggers.tekton.dev/v1alpha1',
kind:'TriggerBinding',
metadata: {
name:'vote-app'
},
spec: {
params: [{
name:'git-repo-url',
value:'$(body.repository.url)'
}]
}
}]
const pipelineName = 'sample-pipeline-cluster-task-4';
suite('Add trigger', () => {
test('create object for workspace', async () => {
const result = getPipelineRunWorkspaces([
{
item: [],
name:'password-vault',
workspaceName:'sensitive-recipe-storage',
workspaceType:'ConfigMap'
},
{
item: [],
name:'recipe-store',
workspaceName:'secret-password',
workspaceType:'Secret'
},
{
item: [],
name:'shared-data',
workspaceName:'shared-task-storage',
workspaceType:'PersistentVolumeClaim',
}
]);
expect(result).deep.equals([
{
configMap: {
name:'sensitive-recipe-storage'
},
name:'password-vault'
},
{
name:'recipe-store',
secret: {
secretName:'secret-password'
}
},
{
name:'shared-data',
persistentVolumeClaim: {
claimName:'shared-task-storage'
}
}
]);
})
test('create object for pipelineRun', async () => {
execStub.onFirstCall().resolves({ error: null, stdout: JSON.stringify(pipeline), stderr: '' });
const result = await getPipelineRunFrom(inputAddTrigger, option);
expect(execStub).called;
expect(result).deep.equals({
apiVersion:'tekton.dev/v1beta1',
kind:'PipelineRun',
metadata: {
generateName:'sample-pipeline-cluster-task-4-',
labels: {
'tekton.dev/pipeline':'sample-pipeline-cluster-task-4'
}
},
spec: {
params: [],
pipelineRef: {
name:'sample-pipeline-cluster-task-4'
},
resources: [],
status: null,
workspaces: [],
serviceAccountName: undefined
}
});
});
test('create object for TriggerTemplate', async () => {
sandbox.stub(Math, 'random').returns(1);
const result = createTriggerTemplate(pipelieRun, params, pipelineName);
expect(result).deep.equals({
apiVersion:'triggers.tekton.dev/v1alpha1',
kind:'TriggerTemplate',
metadata: {
name:'trigger-template-sample-pipeline-cluster-task-4-'
},
spec: {
params: [{
name:'git-repo-url'
}],
resourcetemplates: [{
apiVersion:'tekton.dev/v1beta1',
kind:'PipelineRun',
metadata: {
generateName:'sample-pipeline-cluster-task-4-',
labels: {
'tekton.dev/pipeline':'sample-pipeline-cluster-task-4'
}
},
spec: {
params: [],
pipelineRef: {
name:'sample-pipeline-cluster-task-4'
},
resources: [],
workspaces: undefined
}
}]
}
});
});
test('create object for EventListener', async () => {
execStub.onFirstCall().resolves({ error: null, stdout: tknVersion, stderr: '' });
sandbox.stub(Math, 'random').returns(1);
const result = await createEventListener(triggerBindings, triggerTemplate);
expect(result).deep.equals(eventListener);
});
test('create trigger', async () => {
execStub.onFirstCall().resolves({ error: null, stdout: JSON.stringify(pipeline), stderr: '' });
execStub.onSecondCall().resolves({ error: null, stdout: JSON.stringify({kind: 'TriggerTemplate'}), stderr: '' });
execStub.onThirdCall().resolves({ error: null,
stdout: tknVersion,
stderr: '' });
execStub.onCall(3).resolves({ error: null, stdout: JSON.stringify({kind: 'EventListener'}), stderr: '' });
execStub.onCall(4).resolves({ error: null,
stdout: JSON.stringify(eventListener),
stderr: '' });
execStub.onCall(5).resolves({ error: null,
stdout: JSON.stringify(serviceResource),
stderr: '' });
execStub.onCall(6).resolves({ error: null, stdout: 'successful', stderr: '' });
execStub.onCall(7).resolves({ error: null,
stdout: JSON.stringify({
spec: {
host: 'el-event-listener-dbpg2j-pipelines-tutorial.apps.dev-svc-4.8-042807.devcluster.openshift.com'
}
}),
stderr: '' });
sandbox.stub(_, 'get').returns('https');
await addTriggerToPipeline(createTrigger);
infoMsgStub.calledOnce;
safeDumpStub.calledOnce;
osStub.calledOnce;
writeFileStub.calledOnce;
unlinkStub.calledOnce;
});
test('return null if fails to create triggerTemplate', async () => {
execStub.onFirstCall().resolves({ error: null, stdout: JSON.stringify(pipeline), stderr: '' });
execStub.onSecondCall().resolves({ error: 'error', stdout: '' });
const result = await addTrigger(createTrigger);
expect(result).equals(null);
});
test('return null if fails to create eventListener', async () => {
execStub.onFirstCall().resolves({ error: null, stdout: JSON.stringify(pipeline), stderr: '' });
execStub.onSecondCall().resolves({ error: null, stdout: JSON.stringify({kind: 'TriggerTemplate'}), stderr: '' });
execStub.onThirdCall().resolves({ error: null,
stdout: tknVersion,
stderr: '' });
execStub.onCall(3).resolves({ error: 'error', stdout: '', stderr: '' });
const result = await addTrigger(createTrigger);
expect(result).equals(null);
});
test('return null if fails to create tempPath', async () => {
execStub.onFirstCall().resolves({ error: null, stdout: JSON.stringify(pipeline), stderr: '' });
osStub.onFirstCall().returns(null);
const result = await addTrigger(createTrigger);
expect(result).equals(null);
});
});
}); | the_stack |
import {MDCRipple} from '../../mdc-ripple/index';
import {supportsCssVariables} from '../../mdc-ripple/util';
import {emitEvent} from '../../../testing/dom/events';
import {createMockFoundation} from '../../../testing/helpers/foundation';
import {setUpMdcTestEnvironment} from '../../../testing/helpers/setup';
import {strings} from '../constants';
import {MDCCheckbox, MDCCheckboxFoundation} from '../index';
function getFixture(): Element {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<div class="mdc-checkbox">
<input type="checkbox"
class="mdc-checkbox__native-control"
id="my-checkbox"
aria-labelledby="my-checkbox-label"/>
<div class="mdc-checkbox__frame"></div>
<div class="mdc-checkbox__background">
<svg class="mdc-checkbox__checkmark"
viewBox="0 0 24 24">
<path class="mdc-checkbox__checkmark-path"
fill="none"
d="M4.1,12.7 9,17.6 20.3,6.3"/>
</svg>
<div class="mdc-checkbox__mixedmark"></div>
</div>
</div>
`;
const el = wrapper.firstElementChild as Element;
wrapper.removeChild(el);
return el;
}
function setupTest() {
const root = getFixture();
const cb =
root.querySelector(strings.NATIVE_CONTROL_SELECTOR) as HTMLInputElement;
const component = new MDCCheckbox(root);
return {root, cb, component};
}
function setupMockFoundationTest() {
const root = getFixture();
const cb =
root.querySelector(strings.NATIVE_CONTROL_SELECTOR) as HTMLInputElement;
const mockFoundation = createMockFoundation(MDCCheckboxFoundation);
const component = new MDCCheckbox(root, mockFoundation);
return {root, cb, component, mockFoundation};
}
describe('MDCCheckbox', () => {
setUpMdcTestEnvironment();
if (supportsCssVariables(window)) {
it('#constructor initializes the root element with a ripple', () => {
const {root} = setupTest();
jasmine.clock().tick(1);
expect(root.classList.contains('mdc-ripple-upgraded')).toBeTruthy();
});
it('#destroy removes the ripple', () => {
const {root, component} = setupTest();
jasmine.clock().tick(1);
component.destroy();
jasmine.clock().tick(1);
expect(root.classList.contains('mdc-ripple-upgraded')).toBeFalsy();
});
it('(regression) activates ripple on keydown when the input element surface is active',
() => {
const {root} = setupTest();
const input = root.querySelector('input') as HTMLInputElement;
jasmine.clock().tick(1);
const fakeMatches = jasmine.createSpy('.matches');
fakeMatches.and.returnValue(true);
input.matches = fakeMatches;
expect(root.classList.contains('mdc-ripple-upgraded')).toBe(true);
emitEvent(input, 'keydown');
jasmine.clock().tick(1);
expect(root.classList.contains(
'mdc-ripple-upgraded--foreground-activation'))
.toBe(true);
});
}
it('attachTo initializes and returns a MDCCheckbox instance', () => {
expect(MDCCheckbox.attachTo(getFixture()) instanceof MDCCheckbox)
.toBeTruthy();
});
it('get/set checked updates the checked property on the native checkbox element',
() => {
const {cb, component} = setupTest();
component.checked = true;
expect(cb.checked).toBeTruthy();
expect(component.checked).toEqual(cb.checked);
});
it('get/set indeterminate updates the indeterminate property on the native checkbox element',
() => {
const {cb, component} = setupTest();
component.indeterminate = true;
expect(cb.indeterminate).toBeTruthy();
expect(component.indeterminate).toEqual(cb.indeterminate);
});
it('get/set disabled updates the indeterminate property on the native checkbox element',
() => {
const {cb, component} = setupTest();
component.disabled = true;
expect(cb.disabled).toBeTruthy();
expect(component.disabled).toEqual(cb.disabled);
});
it('get/set value updates the value of the native checkbox element', () => {
const {cb, component} = setupTest();
component.value = 'new value';
expect(cb.value).toEqual('new value');
expect(component.value).toEqual(cb.value);
});
it('get ripple returns a MDCRipple instance', () => {
const {component} = setupTest();
expect(component.ripple instanceof MDCRipple).toBeTruthy();
});
it('checkbox change event calls #foundation.handleChange', () => {
const {cb, component} = setupTest();
(component as any).foundation.handleChange = jasmine.createSpy();
emitEvent(cb, 'change');
expect((component as any).foundation.handleChange).toHaveBeenCalled();
});
it('root animationend event calls #foundation.handleAnimationEnd', () => {
const {root, component} = setupTest();
(component as any).foundation.handleAnimationEnd = jasmine.createSpy();
emitEvent(root, 'animationend');
expect((component as any).foundation.handleAnimationEnd)
.toHaveBeenCalled();
});
it('"checked" property change hook calls foundation#handleChange', () => {
const {cb, mockFoundation} = setupMockFoundationTest();
cb.checked = true;
expect(mockFoundation.handleChange).toHaveBeenCalled();
});
it('"indeterminate" property change hook calls foundation#handleChange',
() => {
const {cb, mockFoundation} = setupMockFoundationTest();
cb.indeterminate = true;
expect(mockFoundation.handleChange).toHaveBeenCalled();
});
it('checkbox change event handler is destroyed on #destroy', () => {
const {cb, component} = setupTest();
(component as any).foundation.handleChange = jasmine.createSpy();
component.destroy();
emitEvent(cb, 'change');
expect((component as any).foundation.handleChange).not.toHaveBeenCalled();
});
it('root animationend event handler is destroyed on #destroy', () => {
const {root, component} = setupTest();
(component as any).foundation.handleAnimationEnd = jasmine.createSpy();
component.destroy();
emitEvent(root, 'animationend');
expect((component as any).foundation.handleAnimationEnd)
.not.toHaveBeenCalled();
});
it('"checked" property change hook is removed on #destroy', () => {
const {component, cb, mockFoundation} = setupMockFoundationTest();
component.destroy();
cb.checked = true;
expect(mockFoundation.handleChange).not.toHaveBeenCalled();
});
it('"indeterminate" property change hook is removed on #destroy', () => {
const {component, cb, mockFoundation} = setupMockFoundationTest();
component.destroy();
cb.indeterminate = true;
expect(mockFoundation.handleChange).not.toHaveBeenCalled();
});
it('adapter#addClass adds a class to the root element', () => {
const {root, component} = setupTest();
(component.getDefaultFoundation() as any).adapter.addClass('foo');
expect(root.classList.contains('foo')).toBeTruthy();
});
it('adapter#removeClass removes a class from the root element', () => {
const {root, component} = setupTest();
root.classList.add('foo');
(component.getDefaultFoundation() as any).adapter.removeClass('foo');
expect(root.classList.contains('foo')).toBeFalsy();
});
it('adapter#setNativeControlAttr sets an attribute on the input element',
() => {
const {cb, component} = setupTest();
(component.getDefaultFoundation() as any)
.adapter.setNativeControlAttr('aria-checked', 'mixed');
expect(cb.getAttribute('aria-checked')).toEqual('mixed');
});
it('adapter#removeNativeControlAttr removes an attribute from the input element',
() => {
const {cb, component} = setupTest();
cb.setAttribute('aria-checked', 'mixed');
(component.getDefaultFoundation() as any)
.adapter.removeNativeControlAttr('aria-checked');
expect(cb.hasAttribute('aria-checked')).toBe(false);
});
it('adapter#forceLayout touches "offsetWidth" on the root in order to force layout',
() => {
const {root, component} = setupTest();
const mockGetter = jasmine.createSpy('.offsetWidth');
Object.defineProperty(root, 'offsetWidth', {
get: mockGetter,
set() {},
enumerable: false,
configurable: true,
});
(component.getDefaultFoundation() as any).adapter.forceLayout();
expect(mockGetter).toHaveBeenCalled();
});
it('adapter#isAttachedToDOM returns true when root is attached to DOM',
() => {
const {root, component} = setupTest();
document.body.appendChild(root);
expect(
(component.getDefaultFoundation() as any).adapter.isAttachedToDOM())
.toBeTruthy();
document.body.removeChild(root);
});
it('adapter#isAttachedToDOM returns false when root is not attached to DOM',
() => {
const {component} = setupTest();
expect(
(component.getDefaultFoundation() as any).adapter.isAttachedToDOM())
.toBeFalsy();
});
it('#adapter.isIndeterminate returns true when checkbox is indeterminate',
() => {
const {cb, component} = setupTest();
cb.indeterminate = true;
expect(
(component.getDefaultFoundation() as any).adapter.isIndeterminate())
.toBe(true);
});
it('#adapter.isIndeterminate returns false when checkbox is not indeterminate',
() => {
const {cb, component} = setupTest();
cb.indeterminate = false;
expect(
(component.getDefaultFoundation() as any).adapter.isIndeterminate())
.toBe(false);
});
it('#adapter.isChecked returns true when checkbox is checked', () => {
const {cb, component} = setupTest();
cb.checked = true;
expect((component.getDefaultFoundation() as any).adapter.isChecked())
.toBe(true);
});
it('#adapter.isChecked returns false when checkbox is not checked', () => {
const {cb, component} = setupTest();
cb.checked = false;
expect((component.getDefaultFoundation() as any).adapter.isChecked())
.toBe(false);
});
it('#adapter.hasNativeControl returns true when checkbox exists', () => {
const {component} = setupTest();
expect(
(component.getDefaultFoundation() as any).adapter.hasNativeControl())
.toBe(true);
});
it('#adapter.setNativeControlDisabled returns true when checkbox is disabled',
() => {
const {cb, component} = setupTest();
(component.getDefaultFoundation() as any)
.adapter.setNativeControlDisabled(true);
expect(cb.disabled).toBe(true);
});
it('#adapter.setNativeControlDisabled returns false when checkbox is not disabled',
() => {
const {cb, component} = setupTest();
(component.getDefaultFoundation() as any)
.adapter.setNativeControlDisabled(false);
expect(cb.disabled).toBe(false);
});
}); | the_stack |
import Tile from '../source/tile';
import {mat4, vec2} from 'gl-matrix';
import {OverscaledTileID} from '../source/tile_id';
import {RGBAImage} from '../util/image';
import {warnOnce} from '../util/util';
import {PosArray, TriangleIndexArray} from '../data/array_types.g';
import posAttributes from '../data/pos_attributes';
import SegmentVector from '../data/segment';
import VertexBuffer from '../gl/vertex_buffer';
import IndexBuffer from '../gl/index_buffer';
import Style from '../style/style';
import Texture from '../render/texture';
import type Framebuffer from '../gl/framebuffer';
import Point from '@mapbox/point-geometry';
import MercatorCoordinate from '../geo/mercator_coordinate';
import TerrainSourceCache from '../source/terrain_source_cache';
import SourceCache from '../source/source_cache';
import EXTENT from '../data/extent';
import {number as mix} from '../style-spec/util/interpolate';
import type {TerrainSpecification} from '../style-spec/types.g';
/**
* This is the main class which handles most of the 3D Terrain logic. It has the follwing topics:
* 1) loads raster-dem tiles via the internal sourceCache this.sourceCache
* 2) creates a depth-framebuffer, which is used to calculate the visibility of coordinates
* 3) creates a coords-framebuffer, which is used the get to tile-coordinate for a screen-pixel
* 4) stores all render-to-texture tiles in the this.sourceCache._tiles
* 5) calculates the elevation for a spezific tile-coordinate
* 6) creates a terrain-mesh
*
* A note about the GPU resource-usage:
* Framebuffers:
* - one for the depth & coords framebuffer with the size of the map-div.
* - one for rendering a tile to texture with the size of tileSize (= 512x512).
* Textures:
* - one texture for an empty raster-dem tile with size 1x1
* - one texture for an empty depth-buffer, when terrain is disabled with size 1x1
* - one texture for an each loaded raster-dem with size of the source.tileSize
* - one texture for the coords-framebuffer with the size of the map-div.
* - one texture for the depth-framebuffer with the size of the map-div.
* - one texture for the encoded tile-coords with the size 2*tileSize (=1024x1024)
* - finally for each render-to-texture tile (= this._tiles) a set of textures
* for each render stack (The stack-concept is documented in painter.ts).
* Normally there exists 1-3 Textures per tile, depending on the stylesheet.
* Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a
* cache of the last 150 newest rendered tiles.
*
*/
export type TerrainData = {
'u_depth': number;
'u_terrain': number;
'u_terrain_dim': number;
'u_terrain_matrix': mat4;
'u_terrain_unpack': number[];
'u_terrain_offset': number;
'u_terrain_exaggeration': number;
texture: WebGLTexture;
depthTexture: WebGLTexture;
tile: Tile;
}
export type TerrainMesh = {
indexBuffer: IndexBuffer;
vertexBuffer: VertexBuffer;
segments: SegmentVector;
}
export default class Terrain {
// The style this terrain crresponds to
style: Style;
// the sourcecache this terrain is based on
sourceCache: TerrainSourceCache;
// the TerrainSpecification object passed to this instance
options: TerrainSpecification;
// define the meshSize per tile.
meshSize: number;
// multiplicator for the elevation. Used to make terrain more "extrem".
exaggeration: number;
// defines the global offset of putting negative elevations (e.g. dead-sea) into positive values.
elevationOffset: number;
// to not see pixels in the render-to-texture tiles it is good to render them bigger
// this number is the multiplicator (must be a power of 2) for the current tileSize.
// So to get good results with not too much memory footprint a value of 2 should be fine.
qualityFactor: number;
// holds the framebuffer object in size of the screen to render the coords & depth into a texture.
_fbo: Framebuffer;
_fboCoordsTexture: Texture;
_fboDepthTexture: Texture;
_emptyDepthTexture: Texture;
// GL Objects for the terrain-mesh
// The mesh is a regular mesh, which has the advantage that it can be reused for all tiles.
_mesh: TerrainMesh;
// coords index contains a list of tileID.keys. This index is used to identify
// the tile via the alpha-cannel in the coords-texture.
// As the alpha-channel has 1 Byte a max of 255 tiles can rendered without an error.
coordsIndex: Array<string>;
// tile-coords encoded in the rgb channel, _coordsIndex is in the alpha-channel.
_coordsTexture: Texture;
// accuracy of the coords. 2 * tileSize should be enoughth.
_coordsTextureSize: number;
// variables for an empty dem texture, which is used while the raster-dem tile is loading.
_emptyDemUnpack: number[];
_emptyDemTexture: Texture;
_emptyDemMatrix: mat4;
// as of overzooming of raster-dem tiles in high zoomlevels, this cache contains
// matrices to transform from vector-tile coords to raster-dem-tile coords.
_demMatrixCache: {[_: string]: { matrix: mat4; coord: OverscaledTileID }};
// because of overzooming raster-dem tiles this cache holds the corresponding
// framebuffer-object to render tiles to texture
_rttFramebuffer: Framebuffer;
// loading raster-dem tiles foreach render-to-texture tile results in loading
// a lot of terrain-dem tiles with very low visual advantage. So with this setting
// remember all tiles which contains new data for a spezific source and tile-key.
_rerender: {[_: string]: {[_: number]: boolean}};
constructor(style: Style, sourceCache: SourceCache, options: TerrainSpecification) {
this.style = style;
this.sourceCache = new TerrainSourceCache(sourceCache);
this.options = options;
this.exaggeration = typeof options.exaggeration === 'number' ? options.exaggeration : 1.0;
this.elevationOffset = typeof options.elevationOffset === 'number' ? options.elevationOffset : 450; // ~ dead-sea
this.qualityFactor = 2;
this.meshSize = 128;
this._demMatrixCache = {};
this.coordsIndex = [];
this._coordsTextureSize = 1024;
this.clearRerenderCache();
}
/**
* get the elevation-value from original dem-data for a given tile-coordinate
* @param {OverscaledTileID} tileID - the tile to get elevation for
* @param {number} x between 0 .. EXTENT
* @param {number} y between 0 .. EXTENT
* @param {number} extent optional, default 8192
* @returns {number} - the elevation
*/
getDEMElevation(tileID: OverscaledTileID, x: number, y: number, extent: number = EXTENT): number {
if (!(x >= 0 && x < extent && y >= 0 && y < extent)) return this.elevationOffset;
let elevation = 0;
const terrain = this.getTerrainData(tileID);
if (terrain.tile && terrain.tile.dem) {
const pos = vec2.transformMat4([] as any, [x / extent * EXTENT, y / extent * EXTENT], terrain.u_terrain_matrix);
const coord = [ pos[0] * terrain.tile.dem.dim, pos[1] * terrain.tile.dem.dim ];
const c = [ Math.floor(coord[0]), Math.floor(coord[1]) ];
const tl = terrain.tile.dem.get(c[0], c[1]);
const tr = terrain.tile.dem.get(c[0], c[1] + 1);
const bl = terrain.tile.dem.get(c[0] + 1, c[1]);
const br = terrain.tile.dem.get(c[0] + 1, c[1] + 1);
elevation = mix(mix(tl, tr, coord[0] - c[0]), mix(bl, br, coord[0] - c[0]), coord[1] - c[1]);
}
return elevation;
}
rememberForRerender(source: string, tileID: OverscaledTileID) {
for (const key in this.sourceCache._tiles) {
const tile = this.sourceCache._tiles[key];
if (tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID)) {
if (source === this.sourceCache.sourceCache.id) tile.timeLoaded = Date.now();
this._rerender[source] = this._rerender[source] || {};
this._rerender[source][tile.tileID.key] = true;
}
}
}
needsRerender(source: string, tileID: OverscaledTileID) {
return this._rerender[source] && this._rerender[source][tileID.key];
}
clearRerenderCache() {
this._rerender = {};
}
/**
* get the Elevation for given coordinate in respect of elevationOffset and exaggeration.
* @param {OverscaledTileID} tileID - the tile id
* @param {number} x between 0 .. EXTENT
* @param {number} y between 0 .. EXTENT
* @param {number} extent optional, default 8192
* @returns {number} - the elevation
*/
getElevation(tileID: OverscaledTileID, x: number, y: number, extent: number = EXTENT): number {
return (this.getDEMElevation(tileID, x, y, extent) + this.elevationOffset) * this.exaggeration;
}
/**
* returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object
* @param {OverscaledTileID} tileID - the tile to get the terrain for
* @returns {TerrainData} the terrain data to use in the program
*/
getTerrainData(tileID: OverscaledTileID): TerrainData {
// create empty DEM Obejcts, which will used while raster-dem tiles are loading.
// creates an empty depth-buffer texture which is needed, during the initialisation process of the 3d mesh..
if (!this._emptyDemTexture) {
const context = this.style.map.painter.context;
const image = new RGBAImage({width: 1, height: 1}, new Uint8Array(1 * 4));
this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, {premultiply: false});
this._emptyDemUnpack = [0, 0, 0, 0];
this._emptyDemTexture = new Texture(context, new RGBAImage({width: 1, height: 1}), context.gl.RGBA, {premultiply: false});
this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
this._emptyDemMatrix = mat4.identity([] as any);
}
// find covering dem tile and prepare demTexture
const sourceTile = this.sourceCache.getSourceTile(tileID, true);
if (sourceTile && sourceTile.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) {
const context = this.style.map.painter.context;
sourceTile.demTexture = this.style.map.painter.getTileTexture(sourceTile.dem.stride);
if (sourceTile.demTexture) sourceTile.demTexture.update(sourceTile.dem.getPixels(), {premultiply: false});
else sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, {premultiply: false});
sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
sourceTile.needsTerrainPrepare = false;
}
// create matrix for lookup in dem data
const matrixKey = sourceTile && (sourceTile + sourceTile.tileID.key) + tileID.key;
if (matrixKey && !this._demMatrixCache[matrixKey]) {
const maxzoom = this.sourceCache.sourceCache._source.maxzoom;
let dz = tileID.canonical.z - sourceTile.tileID.canonical.z;
if (tileID.overscaledZ > tileID.canonical.z) {
if (tileID.canonical.z >= maxzoom) dz = tileID.canonical.z - maxzoom;
else warnOnce('cannot calculate elevation if elevation maxzoom > source.maxzoom');
}
const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);
const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);
const demMatrix = mat4.fromScaling(new Float64Array(16) as any, [1 / (EXTENT << dz), 1 / (EXTENT << dz), 0]);
mat4.translate(demMatrix, demMatrix, [dx * EXTENT, dy * EXTENT, 0]);
this._demMatrixCache[tileID.key] = {matrix: demMatrix, coord: tileID};
}
// return uniform values & textures
return {
'u_depth': 2,
'u_terrain': 3,
'u_terrain_dim': sourceTile && sourceTile.dem && sourceTile.dem.dim || 1,
'u_terrain_matrix': matrixKey ? this._demMatrixCache[tileID.key].matrix : this._emptyDemMatrix,
'u_terrain_unpack': sourceTile && sourceTile.dem && sourceTile.dem.getUnpackVector() || this._emptyDemUnpack,
'u_terrain_offset': this.elevationOffset,
'u_terrain_exaggeration': this.exaggeration,
texture: (sourceTile && sourceTile.demTexture || this._emptyDemTexture).texture,
depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture,
tile: sourceTile
};
}
/**
* create the render-to-texture framebuffer
* @returns {Framebuffer} - the frame buffer
*/
getRTTFramebuffer() {
const painter = this.style.map.painter;
if (!this._rttFramebuffer) {
const size = this.sourceCache.tileSize * this.qualityFactor;
this._rttFramebuffer = painter.context.createFramebuffer(size, size, true);
this._rttFramebuffer.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, size, size));
}
return this._rttFramebuffer;
}
/**
* get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture
* @param {string} texture - the texture
* @returns {Framebuffer} the frame buffer
*/
getFramebuffer(texture: string): Framebuffer {
const painter = this.style.map.painter;
const width = painter.width / devicePixelRatio;
const height = painter.height / devicePixelRatio;
if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) {
this._fbo.destroy();
this._fboCoordsTexture.destroy();
this._fboDepthTexture.destroy();
delete this._fbo;
delete this._fboDepthTexture;
delete this._fboCoordsTexture;
}
if (!this._fboCoordsTexture) {
this._fboCoordsTexture = new Texture(painter.context, {width, height, data: null}, painter.context.gl.RGBA, {premultiply: false});
this._fboCoordsTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);
}
if (!this._fboDepthTexture) {
this._fboDepthTexture = new Texture(painter.context, {width, height, data: null}, painter.context.gl.RGBA, {premultiply: false});
this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);
}
if (!this._fbo) {
this._fbo = painter.context.createFramebuffer(width, height, true);
this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height));
}
this._fbo.colorAttachment.set(texture === 'coords' ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture);
return this._fbo;
}
/**
* create coords texture, needed to grab coordinates from canvas
* encode coords coordinate into 4 bytes:
* - 8 lower bits for x
* - 8 lower bits for y
* - 4 higher bits for x
* - 4 higher bits for y
* - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later setted in draw_terrain uniform value
* @returns {Texture} - the texture
*/
getCoordsTexture(): Texture {
const context = this.style.map.painter.context;
if (this._coordsTexture) return this._coordsTexture;
const data = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4);
for (let y = 0, i = 0; y < this._coordsTextureSize; y++) for (let x = 0; x < this._coordsTextureSize; x++, i += 4) {
data[i + 0] = x & 255;
data[i + 1] = y & 255;
data[i + 2] = ((x >> 8) << 4) | (y >> 8);
data[i + 3] = 0;
}
const image = new RGBAImage({width: this._coordsTextureSize, height: this._coordsTextureSize}, new Uint8Array(data.buffer));
const texture = new Texture(context, image, context.gl.RGBA, {premultiply: false});
texture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
this._coordsTexture = texture;
return texture;
}
/**
* Reads a pixel from the coords-framebuffer and translate this to mercator.
* @param {Point} p Screen-Coordinate
* @returns {MercatorCoordinate} mercator coordinate for a screen pixel
*/
pointCoordinate(p: Point): MercatorCoordinate {
const rgba = new Uint8Array(4);
const painter = this.style.map.painter, context = painter.context, gl = context.gl;
// grab coordinate pixel from coordinates framebuffer
context.bindFramebuffer.set(this.getFramebuffer('coords').framebuffer);
gl.readPixels(p.x, painter.height / devicePixelRatio - p.y - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
context.bindFramebuffer.set(null);
// decode coordinates (encoding see getCoordsTexture)
const x = rgba[0] + ((rgba[2] >> 4) << 8);
const y = rgba[1] + ((rgba[2] & 15) << 8);
const tileID = this.coordsIndex[255 - rgba[3]];
const tile = tileID && this.sourceCache.getTileByID(tileID);
if (!tile) return null;
const coordsSize = this._coordsTextureSize;
const worldSize = (1 << tile.tileID.canonical.z) * coordsSize;
return new MercatorCoordinate(
(tile.tileID.canonical.x * coordsSize + x) / worldSize,
(tile.tileID.canonical.y * coordsSize + y) / worldSize,
this.getElevation(tile.tileID, x, y, coordsSize)
);
}
/**
* create a regular mesh which will be used by all terrain-tiles
* @returns {TerrainMesh} - the created regular mesh
*/
getTerrainMesh(): TerrainMesh {
if (this._mesh) return this._mesh;
const context = this.style.map.painter.context;
const vertexArray = new PosArray(), indexArray = new TriangleIndexArray();
const meshSize = this.meshSize, delta = EXTENT / meshSize, meshSize2 = meshSize * meshSize;
for (let y = 0; y <= meshSize; y++) for (let x = 0; x <= meshSize; x++)
vertexArray.emplaceBack(x * delta, y * delta);
for (let y = 0; y < meshSize2; y += meshSize + 1) for (let x = 0; x < meshSize; x++) {
indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2);
indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1);
}
this._mesh = {
indexBuffer: context.createIndexBuffer(indexArray),
vertexBuffer: context.createVertexBuffer(vertexArray, posAttributes.members),
segments: SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)
};
return this._mesh;
}
} | the_stack |
import * as path from 'path';
import * as fse from 'fs-extra';
import chalk = require('chalk');
import portfinder = require('portfinder');
import * as TypeScript from 'typescript';
import webpack = require('webpack');
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import { WebpackPluginServe } from 'webpack-plugin-serve';
import MiniCssExtractPlugin = require('mini-css-extract-plugin');
import ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const webpackPluginServeClientJS = require.resolve('webpack-plugin-serve/client');
const reactRefreshBabelPluginJS = require.resolve('react-refresh/babel');
const babelPluginDynamicImportJS = require.resolve('@babel/plugin-syntax-dynamic-import');
import { resolveFrom } from "./importers/resolveFrom";
import { Shout } from './Shout';
import { BuildVariables } from './variables-factory/BuildVariables';
import { PathFinder } from './variables-factory/PathFinder';
import { LoaderPaths } from './loaders/LoaderPaths';
import { parseTypescriptConfig } from './TypescriptConfigParser';
import { InstapackBuildPlugin } from './plugins/InstapackBuildPlugin';
import { mergeTypeScriptPathAlias, getWildcardModules } from './TypeScriptPathsTranslator';
import { UserSettingsPath } from './user-settings/UserSettingsPath';
/**
* Contains methods for compiling a TypeScript project.
*/
export class TypeScriptBuildEngine {
private readonly variables: BuildVariables;
private readonly finder: PathFinder;
private readonly typescriptCompilerOptions: TypeScript.CompilerOptions;
private useBabel = false;
private vueLoaderPath: string | undefined;
private vueLoader: VueLoader | undefined;
private port = 28080;
private certificates: {
key: Buffer;
cert: Buffer;
} | null = null;
/**
* Constructs a new instance of TypeScriptBuildTool using the specified settings and build flags.
* @param settings
* @param flags
*/
constructor(variables: BuildVariables) {
this.variables = variables;
this.finder = new PathFinder(variables);
this.typescriptCompilerOptions = parseTypescriptConfig(variables.root, variables.typescriptConfiguration).options;
if (!this.typescriptCompilerOptions.target) { // undefined || (ES3 === 0)
Shout.warning('instapack does not support targeting ES3! JS build target has been set to ES5. (TypeScript compiler options)');
this.typescriptCompilerOptions.target = TypeScript.ScriptTarget.ES5
}
this.typescriptCompilerOptions.noEmit = false;
this.typescriptCompilerOptions.emitDeclarationOnly = false;
this.typescriptCompilerOptions.sourceMap = variables.sourceMap;
this.typescriptCompilerOptions.inlineSources = variables.sourceMap;
}
/**
* Gets JS Babel transpile rules for webpack.
*/
get jsBabelWebpackRules(): webpack.RuleSetRule {
return {
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: LoaderPaths.babel,
ident: 'babel-js'
}
};
}
/**
* Gets a configured TypeScript rules for webpack.
*/
get typescriptWebpackRules(): webpack.RuleSetRule {
const loaders: {
ident: string;
loader: string;
options?: {
[key: string]: unknown;
};
}[] = [{
loader: LoaderPaths.typescript,
ident: 'typescript',
options: {
compilerOptions: this.typescriptCompilerOptions
}
}];
if (this.useBabel) {
// Babel post-processing should be done after TypeScript compilation.
// webpack rules are run from right-to-left / LIFO.
loaders.unshift({
loader: LoaderPaths.babel,
ident: 'babel-typescript'
});
}
const tsRules: webpack.RuleSetRule = {
test: /\.tsx?$/,
exclude: /node_modules/,
use: loaders
};
return tsRules;
}
/**
* Gets a Vue Single-File Component rule for webpack.
*/
get vueWebpackRules(): webpack.RuleSetRule {
return {
test: /\.vue$/,
exclude: /node_modules/,
use: [{
loader: this.vueLoaderPath,
ident: 'vue',
options: {
transformAssetUrls: {} // remove <img> src and SVG <image> xlink:href resolution
}
}]
};
}
/**
* Gets a configured HTML template rules for webpack.
*/
get htmlWebpackRules(): webpack.RuleSetRule {
return {
test: /\.html?$/,
exclude: /node_modules/,
use: [{
loader: LoaderPaths.html,
ident: 'html-txt'
}]
};
}
/**
* Gets CSS rules for webpack to prevent explosion during vue compile.
*/
get vueCssWebpackRules(): webpack.RuleSetRule {
// https://vue-loader.vuejs.org/guide/css-modules.html#usage
const cssModulesLoader = {
loader: LoaderPaths.css,
ident: 'vue-css-module',
options: {
esModule: false,
modules: { // enable CSS Modules
localIdentName: '[local]_[contenthash:8]'
},
url: false
}
};
const cssLoader = {
loader: LoaderPaths.css,
ident: 'vue-css',
options: {
esModule: false,
url: false
}
};
return {
test: /\.css$/,
oneOf: [
{
// this matches <style module>
// ./HelloWorld.vue?vue&type=style&index=0&module=true&lang=css&
resourceQuery: /module=true/,
use: [MiniCssExtractPlugin.loader, cssModulesLoader]
},
{
// this matches plain <style> or <style scoped>
// HelloWorld.vue?vue&type=style&index=0&lang=css&
use: [MiniCssExtractPlugin.loader, cssLoader]
}
]
};
}
/**
* Gets JS Babel transpile rules for webpack.
*/
get reactRefreshWebpackRules(): webpack.RuleSetRule {
return {
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: [{
loader: LoaderPaths.babel,
ident: 'react-fast-refresh-babel',
options: {
plugins: [
babelPluginDynamicImportJS,
reactRefreshBabelPluginJS,
]
}
}]
};
}
/**
* Gets transpile libraries (to ES5) rules for webpack
*/
get transpileLibrariesWebpackRules(): webpack.RuleSetRule {
return {
test: /\.js$/,
include: /node_modules/,
use: {
loader: LoaderPaths.transpileLibraries,
ident: 'js-libraries-to-es5',
options: {
compilerOptions: this.typescriptCompilerOptions
}
}
};
}
/**
* Gets webpack plugins array.
*/
get webpackPlugins(): webpack.WebpackPluginInstance[] {
const plugins: webpack.WebpackPluginInstance[] = [];
const typescriptTarget = this.typescriptCompilerOptions.target ?? TypeScript.ScriptTarget.ES3;
plugins.push(new InstapackBuildPlugin(this.variables, typescriptTarget));
if (this.vueLoader) {
plugins.push(new this.vueLoader.VueLoaderPlugin());
}
if (Object.keys(this.variables.env).length > 0) {
plugins.push(new webpack.EnvironmentPlugin(this.variables.env));
}
if (this.variables.serve) {
// wps: webpack-plugin-serve adds HotModuleReplacementPlugin automatically. Please remove it from your config.
plugins.push(new WebpackPluginServe({
host: 'localhost',
port: this.port,
https: this.certificates,
progress: 'minimal',
log: {
level: 'error'
}
}));
}
if (this.variables.reactRefresh) {
plugins.push(new ReactRefreshWebpackPlugin());
}
if (this.variables.production) {
plugins.push(new CleanWebpackPlugin());
}
plugins.push(new MiniCssExtractPlugin({
filename: 'ipack.jss.css',
chunkFilename: 'ipack.[id].js.css'
}));
return plugins;
}
/**
* Gets webpack rules array using input TypeScript configuration and Babel flag.
*/
get webpackRules(): webpack.RuleSetRule[] {
const rules: webpack.RuleSetRule[] = [
this.typescriptWebpackRules,
];
if (this.vueLoaderPath) {
rules.push(this.vueCssWebpackRules);
rules.push(this.vueWebpackRules);
}
// Vue Loader Error if HTML Loader is defined before it!
rules.push(this.htmlWebpackRules);
if (this.useBabel) {
rules.push(this.jsBabelWebpackRules);
}
if (this.typescriptCompilerOptions.target === TypeScript.ScriptTarget.ES5) {
rules.push(this.transpileLibrariesWebpackRules)
}
if (this.variables.reactRefresh) {
// loader rules are evaluated LIFO
// https://stackoverflow.com/questions/32234329/what-is-the-loader-order-for-webpack
// React Refresh Babel transformations should be done AFTER ALL other loaders!
rules.unshift(this.reactRefreshWebpackRules);
}
return rules;
}
/**
* Get the suitable webpack configuration dev tool for the job, according to instapack settings.
*/
get webpackConfigurationDevTool(): false | 'hidden-source-map' | 'source-map' | 'eval-source-map' {
if (this.variables.sourceMap === false) {
return false;
}
if (this.variables.production) {
return 'hidden-source-map';
}
// dev mode, faster build only during incremental compilation
if (this.variables.watch === false) {
return 'source-map';
}
return 'eval-source-map';
}
/**
* Returns webpack configuration from blended instapack settings and build flags.
*/
createWebpackConfiguration(): webpack.Configuration {
// https://github.com/webpack/webpack/releases/tag/v5.0.0-beta.14
const entry = {
main: {
filename: this.finder.jsOutputFileName,
// webpack configuration errors if using UNIX path in Windows!
import: [this.finder.jsEntry] as [string, ...string[]],
}
};
if (this.variables.serve) {
entry.main.import.push(webpackPluginServeClientJS);
}
const config: webpack.Configuration = {
entry: entry,
output: {
filename: this.finder.jsChunkFileName,
path: path.normalize(this.finder.jsOutputFolder),
publicPath: 'js/',
library: this.variables.namespace,
libraryTarget: (this.variables.umdLibraryProject ? 'umd' : undefined)
},
externals: this.variables.externals,
resolve: this.webpackResolveOptions,
plugins: this.webpackPlugins,
module: {
rules: this.webpackRules
},
mode: (this.variables.production ? 'production' : 'development'),
devtool: this.webpackConfigurationDevTool,
optimization: {
emitOnErrors: false,
},
performance: { // https://webpack.js.org/configuration/performance
hints: false
}
};
const tsTarget = this.typescriptCompilerOptions.target ?? TypeScript.ScriptTarget.ES5;
if (tsTarget < TypeScript.ScriptTarget.ES2015) {
// https://webpack.js.org/migrate/5/
config.target = ['web', 'es5'];
}
if (!this.variables.umdLibraryProject && config.optimization) {
// https://webpack.js.org/plugins/split-chunks-plugin/
config.optimization.splitChunks = {
// minSize: 1,
// maxAsyncRequests: Infinity,
cacheGroups: {
vendors: {
name: 'dll',
test: /[\\/]node_modules[\\/]/,
chunks: 'initial',
enforce: true,
priority: 99
}
}
}
}
return config;
}
get webpackResolveOptions(): webpack.ResolveOptions {
// apparently we don't need to normalize paths for alias and wildcards.
const alias = mergeTypeScriptPathAlias(this.typescriptCompilerOptions, this.finder.root, this.variables.alias);
const wildcards = getWildcardModules(this.typescriptCompilerOptions, this.finder.root);
// console.log(alias);
// console.log(wildcards);
if (this.variables.reactRefresh) {
alias['react-refresh'] = [path.resolve(__dirname, '../node_modules/react-refresh')];
}
const config: webpack.ResolveOptions = {
// .vue automatic resolution follows vue-cli behavior, although is still required in TypeScript...
// .html module import must now be explicit!
// .mjs causes runtime error when `module.exports` is being used instead of `export`. (Experimental in Webpack 5, requires experiments.mjs: true)
// .wasm requires adding `application/wasm` MIME to web server (both IIS and Kestrel). (Experimental in Webpack 5, requires experiments: { asyncWebAssembly: true, importAsync: true })
extensions: ['.ts', '.tsx', '.js', '.jsx', '.vue', '.json'],
alias: alias
};
if (wildcards) {
config.modules = wildcards;
}
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-5.html#the---preservesymlinks-compiler-flag
// This flag also exhibits the opposite behavior to Webpack’s resolve.symlinks option
// (TypeScript’s preserveSymlinks true === Webpack’s resolve.symlinks to false) and vice-versa.
// https://webpack.js.org/configuration/resolve/#resolvesymlinks defaults to true
if (this.typescriptCompilerOptions.preserveSymlinks) {
config.symlinks = false;
}
return config;
}
buildOnce(webpackConfiguration: webpack.Configuration): Promise<webpack.Stats | undefined> {
// https://github.com/webpack/changelog-v5/blob/master/README.md#compiler-idle-and-close
// The webpack() facade automatically calls close when being passed a callback.
return new Promise<webpack.Stats | undefined>((ok, reject) => {
webpack(webpackConfiguration, (err, stats) => {
if (err) {
reject(err);
}
ok(stats);
});
});
}
watch(webpackConfiguration: webpack.Configuration): Promise<void> {
const compiler = webpack(webpackConfiguration);
return new Promise<void>((ok, reject) => {
compiler.watch({
ignored: ['node_modules'],
aggregateTimeout: 300
}, (err) => {
if (err) {
reject(err);
}
return ok();
});
});
}
/**
* Runs the TypeScript build engine.
*/
async build(): Promise<void> {
this.useBabel = await fse.pathExists(this.finder.babelConfiguration);
if (this.variables.vue) {
const vueLoaderPath = resolveFrom('vue-loader', this.variables.root);
if (vueLoaderPath) {
this.vueLoaderPath = vueLoaderPath;
this.vueLoader = require(vueLoaderPath);
}
}
if (this.variables.serve) {
this.port = await portfinder.getPortPromise({
port: this.port
});
const host = `${this.variables.https ? 'https' : 'http'}://localhost:${chalk.greenBright(this.port)}`;
Shout.timed(chalk.yellowBright('Hot Reload'), `server running on ${host}`);
}
if (this.variables.https) {
const certFileAsync = fse.readFile(UserSettingsPath.certFile);
const keyFileAsync = fse.readFile(UserSettingsPath.keyFile);
// https://webpack.js.org/configuration/dev-server/#devserverhttps
this.certificates = {
key: await keyFileAsync,
cert: await certFileAsync
}
}
const webpackConfiguration = this.createWebpackConfiguration();
if (this.variables.watch) {
await this.watch(webpackConfiguration);
} else {
const stats = await this.buildOnce(webpackConfiguration);
if (this.variables.stats && stats) {
await fse.outputJson(this.finder.statsJsonFilePath, stats.toJson());
}
}
}
}
interface VueLoader {
VueLoaderPlugin: {
new(): webpack.WebpackPluginInstance
}
} | the_stack |
require("chromedriver");
import { resolve } from "path";
import {
Builder,
Locator,
until,
WebDriver,
WebElement,
WebElementPromise
} from "selenium-webdriver";
import Chrome, { Options, ServiceBuilder } from "selenium-webdriver/chrome";
import {
EXTENSION_LIST_SELECTOR,
METAMASK_EXTENSION_URL_SELECTOR
} from "./chrome-selectors";
import {
ACCOUNT_DEPOSIT_SELECTORS,
ACCOUNT_REGISTRATION_SELECTORS,
LAYOUT_HEADER_SELECTORS
} from "./counterfactual-wallet-selectors";
import {
DEPOSIT_SELECTORS,
findItemByExactTextMatch,
findItemByPartialTextMatch,
FIRST_TIME_FLOW_SELECTORS,
MAIN_SCREEN_SELECTORS,
NETWORK_SELECTORS,
NOTIFICATION_SELECTORS,
REQUEST_SIGNATURE_SELECTORS,
UNLOCK_FLOW_SELECTORS,
WALLET_AUTHORIZATION_MODAL_SELECTORS
} from "./metamask-selectors";
import StateCollector from "./state-collector";
import {
CounterfactualScreenName,
MetamaskFlowType,
MetamaskNetwork,
MetamaskOptions,
MetamaskTransaction,
StringHashMap,
TestBrowserContext
} from "./types";
export const EXTENSION_INSPECTOR = "chrome://inspect/#extensions";
export const LOCATOR_TIMEOUT = 10000;
export const METAMASK_ETH_ADDRESS =
"0x212C90fdF90BbD5E9b352b9d2B086f2666CFEED6";
export const METAMASK_MNEMONIC =
"mistake cash photo pond little nerve neutral adapt item kite radar tray";
export const METAMASK_PASSWORD = "The Cake Is A Lie";
export const COUNTERFACTUAL_USER_USERNAME = "teapot";
export const COUNTERFACTUAL_USER_EMAIL_ADDRESS = "i.am.a@tea.pot";
/**
* Creates a Chrome browser, with a build of the Metamask + CF extension.
*/
export class TestBrowser {
constructor(
private browser: WebDriver = {} as WebDriver,
private homeUrl: string = "",
private popupUrl: string = "",
private readonly handlesByContext: {
[key in Exclude<TestBrowserContext, "counterfactual:wallet">]: string;
} = {
[TestBrowserContext.MetamaskMain]: "",
[TestBrowserContext.MetamaskPopup]: ""
},
private currentContext?: TestBrowserContext,
private readonly locatorTimeout: number = LOCATOR_TIMEOUT,
private readonly stateCollector: StateCollector = new StateCollector()
) {}
/**
* Initializes an instance of the TestBrowser with the following flags:
*
* --load-extension: Pointed towards packages/greenboard/extension, to an
* unpacked build of the Metamask extension for Chrome.
*
* --disable-web-security: Removes the execution of preflight checks for CORS.
* Necessary for simple, quick communication with the Hub API.
*
* --user-data-dir: Pointed towards packages/greenboard/chrome-profile, it is
* a temporary profile directory for Chrome.
*
* If the CHROME_DRIVER_PATH environment variable is supplied, it'll try to
* use that as a ChromeDriver builder. Otherwise, it'll fallback to the
* "chromedriver" package supplied by Greenboard.
*
* If the CHROME_BINARY_PATH environment variable is set, the TestBrowser
* will use that as a Chrome browser.
*
* Unless the `--discover-metamask` flag is passed by the `test:e2e` run-script,
* the TestBrowser will wait up to 5 seconds for Chrome to automatically
* open the extension's homepage tab.
*/
async start() {
const extensionDirectory = resolve(__dirname, "../extension");
const chromeProfileDirectory = resolve(__dirname, "../chrome-profile");
const chromeDriver = new ServiceBuilder(
process.env.CHROME_DRIVER_PATH || require("chromedriver").path
).build();
Chrome.setDefaultService(chromeDriver);
await chromeDriver.start();
const browserFactory = new Builder().forBrowser("chrome");
const options = new Options();
options.addArguments(
`--load-extension=${extensionDirectory}`,
`--disable-web-security`,
`--user-data-dir=${chromeProfileDirectory}`
);
if (process.env.CHROME_BINARY_PATH) {
options.setChromeBinaryPath(process.env.CHROME_BINARY_PATH as string);
}
this.browser = browserFactory
.setChromeOptions(options)
.setAlertBehavior("accept")
.build();
if (!process.argv.includes("--discover-metamask")) {
await this.browser.sleep(5000);
const handles = await this.browser.getAllWindowHandles();
this.handlesByContext[
TestBrowserContext.MetamaskMain
] = handles.pop() as string;
await this.switchToMetamask();
this.homeUrl = await this.browser.getCurrentUrl();
this.popupUrl = this.homeUrl.replace(/home/gi, "popup").split("#")[0];
}
}
/****************************************************************
* Metamask Automations API
****************************************************************/
/**
* This function is a convenient wrapper for openMetamask(),
* setupMetamask(), loginToMetamask(), waitForMetamaskMainScreen,
* setMetamaskNetwork(), openCounterfactualWallet() and authorizeWallet().
*
* This function will prepare the browser for using the Counterfactual
* Wallet UI by doing the following tasks:
*
* 1) Open the Metamask homepage.
*
* 2) Either automate Metamask's onboarding flow by configuring a wallet
* with a given seed phrase and password (using the `NewUser` flow type)
* *or* logging into Metamask using the password from the onboarding flow.
*
* 3) Wait for Metamask to show the main UI.
*
* 4) Change the extension's network according to `networkName`. For all purposes,
* testing with Counterfactual is done through the "kovan" network.
*
* 5) Open the Wallet UI in the IFRAME.
*
* 6) Wait for Metamask to request permission to connect the Wallet UI
* with the Ethereum Provider and grant permission by clicking
* the "Connect" button.
*
* @param flowType {MetamaskFlowType}
* @param networkName {MetamaskNetwork}
*/
async prepare(
flowType: MetamaskFlowType,
networkName: MetamaskNetwork = "kovan"
) {
await this.openMetamask();
switch (flowType) {
case MetamaskFlowType.NewUser:
await this.setupMetamask();
break;
case MetamaskFlowType.ReturningUser:
await this.loginToMetamask();
}
await this.waitForMetamaskMainScreen();
await this.setMetamaskNetwork(networkName);
await this.openCounterfactualWallet();
await this.authorizeWallet();
}
/**
* Only used if the `--discover-metamask` flag is passed to the test runner.
*
* Opens the Metamask extension page in the current window. It'll automatically
* lookup the extension ID from the Extensions Inspector and save the `home`
* and `popup` URLs for later usage. If such URLs are already defined,
* it'll skip the lookup and navigate to `homeUrl`.
*/
async openMetamask() {
if (!process.argv.includes("--discover-metamask")) {
await this.switchToMetamask();
return;
}
if (this.homeUrl && this.popupUrl) {
await this.navigateTo(this.homeUrl);
return;
}
await this.waitForExtensionsList();
const backgroundPageUrl = await this.getTextFromElement(
METAMASK_EXTENSION_URL_SELECTOR
);
this.homeUrl = backgroundPageUrl.replace(
"_generated_background_page",
"home"
);
this.popupUrl = backgroundPageUrl.replace(
"_generated_background_page",
"popup"
);
await this.navigateTo(this.homeUrl);
await this.switchToMetamask();
}
/**
* Automates Metamask's onboarding flow by configuring a wallet
* with a given seed phrase and password.
*
* @param settings
*/
async setupMetamask(
settings: MetamaskOptions = {
seedPhraseValue: METAMASK_MNEMONIC,
passwordValue: METAMASK_PASSWORD
}
) {
const { seedPhraseValue, passwordValue } = settings;
const {
getStartedButton,
importFromSeedPhraseButton,
iAgreeButton,
seedPhraseInput,
passwordInput,
confirmPasswordInput,
acceptTermsAndConditionsCheckbox,
importSubmitButton,
endOfFlowScreen,
allDoneButton
} = FIRST_TIME_FLOW_SELECTORS;
// Welcome screen
await this.clickOnElement(getStartedButton);
// Import from seed phrase or create a new wallet?
await this.clickOnElement(importFromSeedPhraseButton);
// Accept privacy policy
await this.clickOnElement(iAgreeButton);
// Set seed phrase, password, accept terms and conditions and submit.
await this.typeOnInput(seedPhraseInput, seedPhraseValue);
await this.typeOnInput(passwordInput, passwordValue);
await this.typeOnInput(confirmPasswordInput, passwordValue);
await this.clickOnElement(acceptTermsAndConditionsCheckbox);
await this.clickOnElement(importSubmitButton);
// Wait for process to finish and leave onboarding.
await this.waitForElement(endOfFlowScreen);
await this.clickOnElement(allDoneButton);
}
/**
* Unlocks Metamask by logging in with a provided password
* (defaults to the password used while filling the registration
* form on the onboarding flow).
*/
async loginToMetamask(passwordValue = METAMASK_PASSWORD) {
const {
unlockScreen,
passwordInput,
loginSubmitButton
} = UNLOCK_FLOW_SELECTORS;
await this.waitForElement(unlockScreen);
await this.typeOnInput(passwordInput, passwordValue);
await this.clickOnElement(loginSubmitButton);
}
/**
* Waits for Metamask to show the main UI.
*/
async waitForMetamaskMainScreen() {
const { mainScreenContainer } = MAIN_SCREEN_SELECTORS;
await this.waitForElement(mainScreenContainer);
}
/**
* Changes the extension's network according to `networkName`. For all purposes,
* testing with Counterfactual is done through the "kovan" network.
*
* @param networkName {MetamaskNetwork}
*/
async setMetamaskNetwork(networkName: MetamaskNetwork = "kovan") {
const {
networkMenuButton,
networkMenuList,
networkMenuItem
} = MAIN_SCREEN_SELECTORS;
await this.clickOnElement(networkMenuButton);
await this.waitForElement(networkMenuList);
await this.clickOnElement(networkMenuItem(networkName));
await this.waitForElement(NETWORK_SELECTORS[networkName]);
}
/**
* Clicks on the "Counterfactual" button on Metamask's sidebar and waits
* until the Wallet UI's IFRAME is rendered.
*/
async openCounterfactualWallet() {
const { counterfactualToken, pluginIframe } = MAIN_SCREEN_SELECTORS;
await this.clickOnElement(counterfactualToken);
await this.waitForElement(pluginIframe);
}
/**
* Waits for Metamask to request permission to connect the Wallet UI
* with the Ethereum Provider and grants permission by clicking
* the "Connect" button.
*/
async authorizeWallet() {
const {
modalContainer,
modalPrimaryButton
} = WALLET_AUTHORIZATION_MODAL_SELECTORS;
// Wait for authorization modal.
await this.waitForElement(modalContainer);
// Click "Connect".
await this.clickOnElement(modalPrimaryButton);
}
/**
* Changes the WebDriver's context to operate on the Metamask window.
* Use this before further actions if you've been interacting with
* other contexts before (Wallet UI, Metamask Popups).
*/
async switchToMetamask() {
await this.updateContext(TestBrowserContext.MetamaskMain);
}
/**
* Simulates a click in the Metamask extension button by opening
* a new tab pointing to the `popup.html` file, which handles
* Metamask notifications. It'll wait for the expected popup
* to be opened by checking if a selector related to that transaction
* is rendered.
*
* @param transactionType
*/
async switchToMetamaskPopup(transactionType: MetamaskTransaction) {
// Timeouts are needed so Metamask has enough time to generate
// the transaction and render the proper screen when forcing the
// popup on a tab.
const popupHandle = await this.openNewTab();
this.handlesByContext[TestBrowserContext.MetamaskPopup] = popupHandle;
await this.updateContext(TestBrowserContext.MetamaskPopup);
await this.navigateTo(this.popupUrl);
// Wait for popup to be ready.
await this.waitForElement(NOTIFICATION_SELECTORS[transactionType]);
}
/**
* Waits for the Signature Request popup to be opened,
* clicks the "Sign" button and closes the popup.
*/
async signTransaction() {
const { signButton } = REQUEST_SIGNATURE_SELECTORS;
await this.switchToMetamaskPopup("signatureRequest");
await this.clickOnElement(signButton);
await this.closeTab();
await this.switchToWallet();
}
/**
* Waits for the Deposit Confirmation popup to be opened,
* clicks the "Confirm" button and closes the popup.
*/
async confirmDeposit() {
const { confirmButton } = DEPOSIT_SELECTORS;
await this.switchToMetamaskPopup("deposit");
await this.clickOnElement(confirmButton);
await this.closeTab();
await this.switchToWallet();
}
/****************************************************************
* Counterfactual Wallet UI Automations API
****************************************************************/
/**
* Changes the WebDriver's context to operate on the Wallet UI's IFRAME.
* Use this before trying to interact with any elements belonging to the
* Wallet UI.
*/
async switchToWallet() {
await this.switchToMetamask();
await this.updateContext(TestBrowserContext.CounterfactualWallet);
}
/**
* Types in a username and an e-mail address for the "Create an account"
* step of the onboarding flow, then clicks the "Create an account"
* submit button. Then it'll wait for the button to show the "Check wallet"
* label.
*
* @param username
* @param email
*/
async fillAccountRegistrationFormAndSubmit(
username: string = COUNTERFACTUAL_USER_USERNAME,
email: string = COUNTERFACTUAL_USER_EMAIL_ADDRESS
) {
const {
usernameInput,
emailInput,
createAccountButton
} = ACCOUNT_REGISTRATION_SELECTORS;
await this.typeOnInput(usernameInput, username);
await this.typeOnInput(emailInput, email);
await this.clickOnElement(createAccountButton);
await this.waitForElementToHaveText(
createAccountButton,
"Check your wallet"
);
await this.signTransaction();
await this.waitForElementToHaveText(
createAccountButton,
"Creating your account"
);
}
/**
* Waits for the Deposit screen to show, then clicks the Proceed button.
* Confirms the deposit and waits for its completion. It'll timeout after
* 90 seconds without any response.
*
* @todo Add check for texts "Transferring funds", "Collateralizing deposit".
*/
async fillAccountDepositFormAndSubmit() {
const { formTitle, proceedButton } = ACCOUNT_DEPOSIT_SELECTORS;
const { logoContainer } = LAYOUT_HEADER_SELECTORS;
await this.waitForElementToHaveText(formTitle, "Fund your account");
await this.clickOnElement(proceedButton);
await this.waitForElementToHaveText(proceedButton, "Check your wallet");
await this.confirmDeposit();
await this.waitForElement(logoContainer, 90000);
}
/**
* Returns the current screen's name according to the current URL.
*/
async getCurrentScreenName(): Promise<CounterfactualScreenName | void> {
if (this.currentContext !== TestBrowserContext.CounterfactualWallet) {
return;
}
const url = await this.browser.executeScript<string>(
"return document.location.href"
);
if (url.includes("setup/register")) {
return CounterfactualScreenName.OnboardingRegistration;
}
if (url.includes("setup/deposit")) {
return CounterfactualScreenName.OnboardingDeposit;
}
if (url.includes("channels")) {
return CounterfactualScreenName.Channels;
}
return CounterfactualScreenName.Welcome;
}
/**
* Waits for the Hub API to respond a login request by holding execution
* until the AccountContainer UI element is rendered in the screen.
*/
async waitForLoginToBeFinished() {
const { accountContainer } = LAYOUT_HEADER_SELECTORS;
await this.waitForElement(accountContainer);
}
/****************************************************************
* Browser Generic API
****************************************************************/
/**
* Closes the current window.
*/
async closeTab() {
await this.browser.close();
}
/**
* Closes the entire browser.
*/
async closeBrowser() {
await this.browser.quit();
}
/**
* Returns a list of elements found by the given selector.
*
* @param selector
*/
getElements(selector: Locator): Promise<WebElement[]> {
return new Promise(async (resolve, reject) => {
setTimeout(() => reject("Timeout"), this.locatorTimeout);
const result = await this.browser.findElements(selector);
resolve(result);
});
}
/**
* Returns a single element found by the given selector. It'll retry up to
* 5 times to get the element immediately. This retry strategy is added
* to prevent stale references failures due to DOM locks.
*
* @param selector
*/
getElement(selector: Locator): WebElementPromise {
let result: WebElementPromise = {} as WebElementPromise;
const attempts = 0;
while (attempts < 5) {
try {
result = this.browser.wait(
until.elementLocated(selector),
this.locatorTimeout,
selector.toString()
);
break;
} catch (e) {
const error = e as Error;
if (!error.message.startsWith("StaleElementReferenceError")) {
throw e;
}
}
}
return result;
}
/**
* Waits for an element to be located in the DOM tree.
*
* @param selector
*/
async waitForElement(selector: Locator, timeout = this.locatorTimeout) {
await this.browser.wait(
until.elementLocated(selector),
timeout,
selector.toString()
);
}
/**
* Clicks an element found by the selector.
*
* @param selector
*/
async clickOnElement(selector: Locator) {
await this.getElement(selector).click();
}
/**
* Types a given text into the element found by the selector.
*
* @param selector
*/
async typeOnInput(selector: Locator, value: string) {
await this.getElement(selector).sendKeys(value);
}
/**
* Returns the text contained in an element found by the selector.
*
* @param selector
*/
async getTextFromElement(selector: Locator) {
return this.getElement(selector).getText();
}
/**
* Waits for an element to contain a given text. Useful for checking, for example,
* if a button is showing a certain label to reflect state. It'll retry up to
* 5 times to get the element, with delays of 50ms. This retry strategy is added
* to prevent stale references failures due to DOM locks.
*
* @param selector
* @param text
*/
async waitForElementToHaveText(selector: Locator, expectedText: string) {
let attempts = 0;
while (attempts < 5) {
try {
const element = await this.getElement(selector);
const currentText = await element.getText();
return currentText.includes(expectedText);
} catch (e) {
const { message } = e as Error;
if (message.startsWith("StaleElementReferenceError")) {
await this.browser.sleep(50);
attempts += 1;
}
}
}
return false;
}
/**
* Finds an element in a list of nodes by a partial text match.
* For example, you have a list of networks "Main Network", "Kovan Test Network",
* "Rinkeby Test Network", etc. By passing the proper locator and
* "kovan" as partial text, you can interact with that item in particular.
*
* @param elementLocator
* @param partialText
*/
async findElementByPartialTextMatch(
elementLocator: Locator,
partialText: string
) {
return findItemByPartialTextMatch(
this.browser,
elementLocator,
partialText,
this.locatorTimeout
);
}
/**
* Finds an element in a list of nodes by an exact text match.
* For example, you have a list of networks "Main Network", "Kovan Test Network",
* "Rinkeby Test Network", etc. By passing the proper locator and
* "Main Network" as partial text, you can interact with that item in particular.
*
* @param elementLocator
* @param partialText
*/
async findElementByExactTextMatch(elementLocator: Locator, text: string) {
return findItemByExactTextMatch(
this.browser,
elementLocator,
text,
this.locatorTimeout
);
}
/**
* Extracts all LocalStorage data from Metamask.
*/
async collectMetamaskLocalStorage() {
await this.switchToMetamask();
const data = (await this.browser.executeScript(`
const collectedData = {};
const { length } = window.localStorage;
for (let index = 0; index < length; index += 1) {
const key = window.localStorage.key(index);
collectedData[key] = window.localStorage.getItem(key);
}
return collectedData;
`)) as StringHashMap;
// This will trigger a failure in the test if the LocalStorage
// data couldn't be collected.
expect(Object.keys(data)).not.toHaveLength(0);
this.stateCollector.write(data);
}
/**
* Writes each entry provided in the `data` map as a key/value
* entry into Metamask's LocalStorage.
*
* @param data
*/
async injectIntoMetamaskLocalStorage() {
const data = this.stateCollector.read();
await this.switchToMetamask();
// This will trigger a failure in the test if the LocalStorage
// data couldn't be collected.
expect(Object.keys(data).length).toBeGreaterThan(0);
for (const [key, value] of Object.entries(data)) {
await this.browser.executeScript(
`window.localStorage.setItem(arguments[0], arguments[1]);`,
key,
value
);
expect(
await this.browser.executeScript(
`return window.localStorage.getItem(arguments[0]);`,
key
)
).toEqual(value);
}
}
/****************************************************************
* Private API
****************************************************************/
/**
* Browses to a given URL in the current window.
*
* @param url
*/
private async navigateTo(url: string) {
await this.browser.navigate().to(url);
}
/**
* Redirects the browser to chrome://inspect/#extensions, to wait until
* the MetaMask extension is listed as available.
*/
private async waitForExtensionsList() {
await this.navigateTo(EXTENSION_INSPECTOR);
const extensionsList = await this.getElement(EXTENSION_LIST_SELECTOR);
await this.browser.wait(
until.elementTextContains(extensionsList, "MetaMask")
);
}
/**
* Stores a reference about the scope of further interactions.
* Used to properly switch the driver's context when orchestrating
* actions involving Metamask, popups and the Wallet UI.
*
* @param newContext
*/
private async updateContext(newContext: TestBrowserContext) {
this.currentContext = newContext;
if (newContext !== TestBrowserContext.CounterfactualWallet) {
await this.browser.switchTo().window(this.handlesByContext[newContext]);
} else {
const { pluginIframe } = MAIN_SCREEN_SELECTORS;
const iframe = await this.getElement(pluginIframe);
await this.browser.switchTo().frame(iframe);
}
}
/**
* Opens a new tab in the browser by executing `window.open()` in the
* current window's execution context, returning the new window's
* handle.
*
* By default, it'll wait for a second *before* opening the window
* and delay further execution for 100ms *after* opening the window.
*
* Whle opening a window can be done immediately, it is recommended
* to add some delay after opening the window so Selenium has enough
* time to detect the new window handle.
*
* @param millisecondsToWaitBeforeOpening
* @param millisecondsToWaitAfterOpening
*/
private async openNewTab(
millisecondsToWaitBeforeOpening = 1000,
millisecondsToWaitAfterOpening = 100
) {
await this.browser.sleep(millisecondsToWaitBeforeOpening);
await this.browser.executeScript(`window.open('','popup_${Date.now()}');`);
await this.browser.sleep(millisecondsToWaitAfterOpening);
const windowHandles = await this.browser.getAllWindowHandles();
return windowHandles.pop() as string;
}
} | the_stack |
// tslint:disable:max-func-body-length cyclomatic-complexity promise-function-async align max-line-length max-line-length no-undefined-keyword
// tslint:disable:no-non-null-assertion object-literal-key-quotes
import * as assert from "assert";
import { Uri } from "vscode";
import { Completion, DeploymentTemplateDoc, strings, TemplatePositionContext } from "../extension.bundle";
import { IPartialDeploymentTemplate } from "./support/diagnostics";
import { parseTemplate, parseTemplateWithMarkers } from "./support/parseTemplate";
import { stringify } from "./support/stringify";
import { UseNoSnippets } from "./support/TestSnippets";
import { testWithPrep } from "./support/testWithPrep";
import { allTestDataCompletionNames, allTestDataExpectedCompletions, parameterCompletion, propertyCompletion, variableCompletion } from "./TestData";
const fakeId = Uri.file("https://doc-id");
suite("TemplatePositionContext.completions", () => {
suite("completionItems", async () => {
function addCursor(documentText: string, markerIndex: number): string {
return `${documentText.slice(0, markerIndex)}<CURSOR>${documentText.slice(markerIndex)}`;
}
function completionItemsTest(documentText: string, index: number, expectedCompletionItems: Completion.Item[]): void {
const testName = `with ${strings.escapeAndQuote(addCursor(documentText, index))} at index ${index}`;
testWithPrep(
testName,
[UseNoSnippets.instance],
async () => {
let keepInClosureForEasierDebugging = testName;
keepInClosureForEasierDebugging = keepInClosureForEasierDebugging;
const dt = new DeploymentTemplateDoc(documentText, fakeId, 0);
const pc: TemplatePositionContext = dt.getContextFromDocumentCharacterIndex(index, undefined);
let completionItems: Completion.Item[] = (await pc.getCompletionItems(undefined, 2)).items;
const completionItems2: Completion.Item[] = (await pc.getCompletionItems(undefined, 2)).items;
assert.deepStrictEqual(completionItems, completionItems2, "Got different results");
compareTestableCompletionItems(completionItems, expectedCompletionItems);
});
}
function compareTestableCompletionItems(actualItems: Completion.Item[], expectedItems: Completion.Item[]): void {
let isFunctionCompletions = expectedItems.some(item => allTestDataCompletionNames.has(item.label));
// Ignore functions that aren't in our testing list
if (isFunctionCompletions) {
// Unless it's an empty list - then we want to ensure the actual list is empty, too
if (expectedItems.length > 0) {
actualItems = actualItems.filter(item => allTestDataCompletionNames.has(item.label));
}
}
// Make it easier to see missing names quickly
let actualNames = actualItems.map(item => item.label);
let expectedNames = expectedItems.map(item => typeof item === 'string' ? item : item.label);
assert.deepStrictEqual(actualNames, expectedNames);
assert.deepEqual(actualItems, expectedItems);
}
// NOTE: We are testing against test metadata, not the real data
suite("test 01", () => {
for (let i = 0; i <= 24; ++i) {
completionItemsTest(`{ 'a': "[concat('B')]" }`, i,
(i >= 9 && i <= 15) ? allTestDataExpectedCompletions(9, i - 9) :
(i === 20) ? allTestDataExpectedCompletions(20, 0) :
[]);
}
});
const repetitions = 1;
for (let repetition = 0; repetition < repetitions; ++repetition) {
suite("test 02", () => {
for (let i = 9; i <= 9; ++i) {
completionItemsTest(`{ "variables": { "v1": "value1" }, "v": "V" }`, i, []);
}
});
suite("test 03", () => {
for (let i = 0; i <= 25; ++i) {
completionItemsTest(`{ 'a': 'A', 'b': "[concat`, i,
(i >= 19 && i <= 25) ? allTestDataExpectedCompletions(19, i - 19) : []);
}
});
suite("test 04", () => {
for (let i = 0; i <= 23; ++i) {
completionItemsTest(`{ 'a': 'A', 'b': "[spif`, i,
(i >= 19 && i <= 23) ? allTestDataExpectedCompletions(19, i - 19) : []);
}
});
suite("test 05", () => {
for (let i = 0; i <= 33; ++i) {
completionItemsTest(`{ 'a': 'A', 'b': "[concat ()]" }`, i,
(i >= 19 && i <= 25) ? allTestDataExpectedCompletions(19, i - 19) :
(26 <= i && i <= 29) ? allTestDataExpectedCompletions(i, 0) :
[]);
}
});
suite("test 06", () => {
for (let i = 0; i <= 80; ++i) {
completionItemsTest(`{ 'parameters': { 'pName': { 'type': 'integer' } }, 'a': 'A', 'b': "[concat(')]"`, i,
(i >= 69 && i <= 75) ? allTestDataExpectedCompletions(69, i - 69) :
(i === 80) ? allTestDataExpectedCompletions(80, 0) :
[]);
}
});
suite("test 07", () => {
for (let i = 0; i <= 24; ++i) {
completionItemsTest(`{ 'a': "[variables()]" }`, i,
(i >= 9 && i <= 18) ? allTestDataExpectedCompletions(9, i - 9) :
(i === 20) ? allTestDataExpectedCompletions(20, 0) :
[]);
}
});
suite("test 08", () => {
for (let i = 0; i <= 56; ++i) {
completionItemsTest(`{ 'variables': { 'v1': 'value1' }, 'a': "[variables(]" }`, i,
// after the "[": all
(i >= 42 && i <= 51) ? allTestDataExpectedCompletions(42, i - 42) :
// after "[variables(": "v1" is only completion
(i === 52) ? [
variableCompletion("v1", 52, 0)
] :
[]);
}
});
suite("test 09", () => {
for (let i = 0; i <= 57; ++i) {
completionItemsTest(`{ 'variables': { 'v1': 'value1' }, 'a': "[variables()]" }`, i,
(i === 42 || i === 53) ? allTestDataExpectedCompletions(i, 0) :
(i >= 43 && i <= 51) ? allTestDataExpectedCompletions(42, i - 42) :
(i === 52) ? [
variableCompletion("v1", 52, 1)
] :
[]);
}
});
suite("test 10", () => {
for (let i = 0; i <= 52; ++i) {
completionItemsTest(`{ 'variables': { 'vName': 20 }, 'a': "[variables(')]`, i,
(i >= 39 && i <= 48) ? allTestDataExpectedCompletions(39, i - 39) :
(i === 49) ? [variableCompletion("vName", 49, 0, false)] :
(i === 50 || i === 51) ? [variableCompletion("vName", 49, 2)] :
[]);
}
});
suite("test 11", () => {
for (let i = 0; i <= 53; ++i) {
completionItemsTest(`{ 'variables': { 'vName': 20 }, 'a': "[variables('v)]`, i,
(i >= 39 && i <= 48) ? allTestDataExpectedCompletions(39, i - 39) :
(i === 49) ? [variableCompletion("vName", 49, 0, false)] :
(50 <= i && i <= 52) ? [variableCompletion("vName", 49, 3)] :
[]);
}
});
suite("test 12", () => {
for (let i = 0; i <= 56; ++i) {
completionItemsTest(`{ 'variables': { 'vName': 20 }, 'a': "[variables('')]" }`, i,
(i === 39 || i === 52) ? allTestDataExpectedCompletions(i, 0) :
(i >= 40 && i <= 48) ? allTestDataExpectedCompletions(39, i - 39) :
(i === 49) ? [variableCompletion("vName", 49, 0, false)] :
(i === 50) ? [variableCompletion("vName", 49, 3)] :
[]);
}
});
suite("test 13", () => {
for (let i = 0; i <= 140; ++i) {
// 70: ''Microsoft...
completionItemsTest(`{ "parameters": { "adminUsername": {} }, "a": "[resourceId(parameters(''Microsoft.Networks/virtualNetworks', parameters('adminUsername'))]" }`, i,
(i === 48 || i === 59 || (73 <= i && i <= 138)) ? allTestDataExpectedCompletions(i, 0) :
(49 <= i && i <= 58) ?
allTestDataExpectedCompletions(48, i - 48)
: (60 <= i && i <= 69) ?
allTestDataExpectedCompletions(59, i - 59)
:
(i === 70) ? [parameterCompletion("adminUsername", 70, 0, false)] // before the string
: (i === 71) ? [parameterCompletion("adminUsername", 70, 2)] : // in the string
[]);
}
});
suite("test 14", () => {
for (let i = 0; i <= 140; ++i) {
// 48: resourceId
// 59: parameters
// 70: 'Microsoft.Networks/virtualNetworks'
// 106: comma
// 108: parameters('adminUsername')
// 119: 'adminUsername'
completionItemsTest(`{ "parameters": { "adminUsername": {} }, "a": "[resourceId(parameters('Microsoft.Networks/virtualNetworks', parameters('adminUsername'))]" }`, i,
(48 <= i && i <= 58) ? allTestDataExpectedCompletions(48, i - 48) :
(59 <= i && i <= 69) ? allTestDataExpectedCompletions(59, i - 59) :
(i === 70) ? [parameterCompletion("adminUsername", 70, 0, false)] :
(71 <= i && i <= 105) ? [parameterCompletion("adminUsername", 70, 36, false)] :
(i === 107) ? allTestDataExpectedCompletions(107, 0) :
(108 <= i && i <= 118) ? allTestDataExpectedCompletions(108, i - 108) :
(i === 119) ? [parameterCompletion("adminUsername", 119, 0, false)] :
(i >= 120 && i <= 133) ? [parameterCompletion("adminUsername", 119, 16)] :
(i >= 135 && i <= 136) ? allTestDataExpectedCompletions(i, 0) :
[]);
}
});
suite("test 15", () => {
for (let i = 0; i <= 137; ++i) {
// 47: resourceId(
// 58: variables(
// 68: 'Microsoft...
// 104: comma
// 106: variables('adminUsername')
// 116: 'adminUsername'
completionItemsTest(`{ "variables": { "adminUsername": "" }, "a": "[resourceId(variables('Microsoft.Networks/virtualNetworks', variables('adminUsername'))]" }`, i,
(i >= 47 && i <= 57) ? allTestDataExpectedCompletions(47, i - 47) :
(i >= 58 && i <= 67) ? allTestDataExpectedCompletions(58, i - 58) :
(i === 68) ? [variableCompletion("adminUsername", 68, 0, false)] :
(i >= 69 && i <= 103) ? [variableCompletion("adminUsername", 68, 36, false)] :
(i === 105) ? allTestDataExpectedCompletions(105, 0) : // space after comma
(106 <= i && i <= 115) ? allTestDataExpectedCompletions(106, i - 106) :
(i === 116) ? [variableCompletion("adminUsername", 116, 0, false)] :
(117 <= i && i <= 130) ? [variableCompletion("adminUsername", 116, 16)] :
(i >= 132 && i <= 133) ? allTestDataExpectedCompletions(i, 0) :
[]);
}
});
suite("test 16", () => {
for (let i = 0; i <= 25; ++i) {
completionItemsTest(`{ 'a': "[parameters()]" }`, i,
(i >= 9 && i <= 19) ? allTestDataExpectedCompletions(9, i - 9) :
(i === 20) ? [] :
(i === 21) ? allTestDataExpectedCompletions(21, 0) :
[]);
}
});
suite("test 17", () => {
for (let i = 0; i <= 52; ++i) {
completionItemsTest(`{ 'parameters': { 'p1': {} }, 'a': "[parameters(]" }`, i,
(i >= 37 && i <= 47) ? allTestDataExpectedCompletions(37, i - 37) :
(i === 48) ? [parameterCompletion("p1", 48, 0)] :
[]);
}
});
suite("test 18", () => {
for (let i = 0; i <= 81; ++i) {
completionItemsTest(`{ 'parameters': { 'pName': { 'type': 'integer' } }, 'a': 'A', 'b': "[parameters('`, i,
(i >= 69 && i <= 79) ? allTestDataExpectedCompletions(69, i - 69) :
(i === 80) ? [parameterCompletion("pName", 80, 0, false)] :
[]);
}
});
suite("test 19", () => {
for (let i = 0; i <= 76; ++i) {
completionItemsTest(`{ 'parameters': { 'pName': { 'type': 'integer' } }, 'a': "[parameters(')]" }`, i,
(i >= 59 && i <= 69) ? allTestDataExpectedCompletions(59, i - 59) :
(i === 70) ? [parameterCompletion("pName", 70, 0, false)] :
(i >= 71 && i <= 72) ? [parameterCompletion("pName", 70, 2)] : // Don't replace the "]"
[]);
}
});
suite("test 20", () => {
for (let i = 0; i <= 75; ++i) {
completionItemsTest(`{ 'parameters': { 'pName': { 'type': 'integer' } }, 'a': "[parameters(']" }`, i,
(i >= 59 && i <= 69) ? allTestDataExpectedCompletions(59, i - 59) :
(i === 70) ? [parameterCompletion("pName", 70, 0, false)] :
(i === 71) ? [parameterCompletion("pName", 70, 1)] : // Don't replace the "]"
[]);
}
});
suite("test 21", () => {
for (let i = 0; i <= 53; ++i) {
completionItemsTest(`{ 'variables': { 'vName': 20 }, 'a': "[variables('p)]`, i,
(i >= 39 && i <= 48) ? allTestDataExpectedCompletions(39, i - 39) :
(i === 49) ? [variableCompletion("vName", 49, 0, false)] :
(i >= 50 && i <= 52) ? [variableCompletion("vName", 49, 3)] : // Don't replace the "]"
[]);
}
});
suite("test 22", () => {
for (let i = 0; i <= 65; ++i) {
completionItemsTest(`{ 'variables': { 'vName': 20 }, 'a': 'A', 'b': "[concat spam ('`, i,
(i >= 49 && i <= 55) ? allTestDataExpectedCompletions(49, i - 49) :
(56 <= i && i <= 63) ? allTestDataExpectedCompletions(i, 0) :
[]);
}
});
suite("test 23", () => {
for (let i = 0; i <= 28; ++i) {
completionItemsTest(`{ "a": "[resourceGroup()]" }`, i,
(i >= 9 && i <= 22) ? allTestDataExpectedCompletions(9, i - 9) :
(i === 23) ? allTestDataExpectedCompletions(23, 0) :
(i === 24) ? allTestDataExpectedCompletions(24, 0) :
[]);
}
});
suite("test 24", () => {
for (let i = 0; i <= 29; ++i) {
completionItemsTest(`{ "a": "[resourceGroup().]" }`, i,
(i >= 9 && i <= 22) ? allTestDataExpectedCompletions(9, i - 9) :
(i === 23) ? allTestDataExpectedCompletions(23, 0) :
(24 <= i && i <= 25) ? [
propertyCompletion("id", i, 0),
propertyCompletion("location", i, 0),
propertyCompletion("name", i, 0),
propertyCompletion("properties", i, 0),
propertyCompletion("tags", i, 0)
] :
[]);
}
});
suite("test 25", () => {
for (let i = 0; i <= 31; ++i) {
completionItemsTest(`{ "a": "[resourceGroup().lo]" }`, i,
(i >= 9 && i <= 22) ? allTestDataExpectedCompletions(9, i - 9) :
(i === 23) ? allTestDataExpectedCompletions(23, 0) :
(24 <= i && i <= 25) ? [
propertyCompletion("id", 25, 2),
propertyCompletion("location", 25, 2),
propertyCompletion("name", 25, 2),
propertyCompletion("properties", 25, 2),
propertyCompletion("tags", 25, 2)
] :
(26 <= i && i <= 27) ? [
propertyCompletion("location", 25, 2),
] :
[]);
}
});
suite("Variable value deep completion for objects", () => {
suite("test vvdc 01", () => {
for (let i = 0; i <= 28; ++i) {
completionItemsTest(`{ "b": "[variables('a').]" }`, i,
(9 <= i && i <= 18) ? allTestDataExpectedCompletions(9, i - 9) :
[]);
}
});
suite("test vvdc 02", () => {
for (let i = 0; i <= 55; ++i) {
completionItemsTest(`{ "variables": { "a": "A" }, "b": "[variables('a').]" }`, i,
(36 <= i && i <= 45) ? allTestDataExpectedCompletions(36, i - 36) :
(i === 46) ? [variableCompletion("a", 46, 0, false)] :
(47 <= i && i <= 48) ? [variableCompletion("a", 46, 4)] :
[]);
}
});
suite("test vvdc 03", () => {
for (let i = 0; i <= 55; ++i) {
completionItemsTest(`{ "variables": { "a": 123 }, "b": "[variables('a').]" }`, i,
(36 <= i && i <= 45) ? allTestDataExpectedCompletions(36, i - 36) :
(i === 46) ? [variableCompletion("a", 46, 0, false)] :
(47 <= i && i <= 48) ? [variableCompletion("a", 46, 4)] :
[]);
}
});
suite("test vvdc 04", () => {
for (let i = 0; i <= 56; ++i) {
completionItemsTest(`{ "variables": { "a": true }, "b": "[variables('a').]" }`, i,
(37 <= i && i <= 46) ? allTestDataExpectedCompletions(37, i - 37) :
(i === 47) ? [variableCompletion("a", 47, 0, false)] :
(48 <= i && i <= 49) ? [variableCompletion("a", 47, 4)] :
[]);
}
});
suite("test vvdc 05", () => {
for (let i = 0; i <= 56; ++i) {
completionItemsTest(`{ "variables": { "a": null }, "b": "[variables('a').]" }`, i,
(37 <= i && i <= 46) ? allTestDataExpectedCompletions(37, i - 37) :
(i === 47) ? [variableCompletion("a", 47, 0, false)] :
(48 <= i && i <= 49) ? [variableCompletion("a", 47, 4)] :
[]);
}
});
suite("test vvdc 06", () => {
for (let i = 0; i <= 54; ++i) {
completionItemsTest(`{ "variables": { "a": [] }, "b": "[variables('a').]" }`, i,
(35 <= i && i <= 44) ? allTestDataExpectedCompletions(35, i - 35) :
(i === 45) ? [variableCompletion("a", 45, 0, false)] :
(46 <= i && i <= 47) ? [variableCompletion("a", 45, 4)] :
[]);
}
});
suite("test vvdc 07", () => {
for (let i = 0; i <= 54; ++i) {
completionItemsTest(`{ "variables": { "a": {} }, "b": "[variables('a').]" }`, i,
(35 <= i && i <= 44) ? allTestDataExpectedCompletions(35, i - 35) :
(i === 45) ? [variableCompletion("a", 45, 0, false)] :
(46 <= i && i <= 47) ? [variableCompletion("a", 45, 4)] :
[]);
}
});
suite("test vvdc 08", () => {
for (let i = 0; i <= 67; ++i) {
completionItemsTest(`{ "variables": { "a": { "name": "A" } }, "b": "[variables('a').]" }`, i,
(48 <= i && i <= 57) ? allTestDataExpectedCompletions(48, i - 48) :
(i === 58) ? [variableCompletion("a", 58, 0, false)] :
(59 <= i && i <= 60) ? [variableCompletion("a", 58, 4)] :
(62 <= i && i <= 63) ? [propertyCompletion("name", i, 0)] :
[]);
}
});
suite("test vvdc 09", () => {
for (let i = 0; i <= 69; ++i) {
completionItemsTest(`{ "variables": { "a": { "name": "A" } }, "b": "[variables('a').na]" }`, i,
(48 <= i && i <= 57) ? allTestDataExpectedCompletions(48, i - 48) :
(i === 58) ? [variableCompletion("a", 58, 0, false)] :
(59 <= i && i <= 60) ? [variableCompletion("a", 58, 4)] :
(62 <= i && i <= 65) ? [propertyCompletion("name", 63, 2)] :
[]);
}
});
suite("test vvdc 10", () => {
for (let i = 0; i <= 69; ++i) {
completionItemsTest(`{ "variables": { "a": { "name": "A" } }, "b": "[variables('a').ab]" }`, i,
(48 <= i && i <= 57) ? allTestDataExpectedCompletions(48, i - 48) :
(i === 58) ? [variableCompletion("a", 58, 0, false)] :
(59 <= i && i <= 60) ? [variableCompletion("a", 58, 4)] :
(62 <= i && i <= 63) ? [propertyCompletion("name", 63, 2)] :
[]);
}
});
suite("test vvdc 11", () => {
for (let i = 0; i <= 78; ++i) {
completionItemsTest(`{ "variables": { "a": { "bb": { "cc": 200 } } }, "b": "[variables('a').bb.]" }`, i,
(56 <= i && i <= 65) ? allTestDataExpectedCompletions(56, i - 56) :
(i === 66) ? [variableCompletion("a", 66, 0, false)] :
(67 <= i && i <= 68) ? [variableCompletion("a", 66, 4)] :
(70 <= i && i <= 73) ? [propertyCompletion("bb", 71, 2)] :
(i === 74) ? [propertyCompletion("cc", 74, 0)] :
[]);
}
});
suite("test vvdc 12", () => {
// Should retain original casing when completing
for (let i = 0; i <= 78; ++i) {
completionItemsTest(`{ "variables": { "A": { "Bb": { "cC": 200 } } }, "b": "[variables('a').Bb.]" }`, i,
(56 <= i && i <= 65) ? allTestDataExpectedCompletions(56, i - 56) :
(i === 66) ? [variableCompletion("A", 66, 0, false)] :
(67 <= i && i <= 68) ? [variableCompletion("A", 66, 4)] :
(70 <= i && i <= 73) ? [propertyCompletion("Bb", 71, 2)] :
(i === 74) ? [propertyCompletion("cC", 74, 0)] :
[]);
}
});
suite("test vvdc 13", () => {
// Casing shouldn't matter for finding completions
for (let i = 0; i <= 78; ++i) {
completionItemsTest(`{ "variables": { "A": { "Bb": { "cC": 200 } } }, "b": "[variables('a').BB.Cc]" }`, i,
(56 <= i && i <= 65) ? allTestDataExpectedCompletions(56, i - 56) :
(i === 66) ? [variableCompletion("A", 66, 0, false)] :
(67 <= i && i <= 68) ? [variableCompletion("A", 66, 4)] :
(70 <= i && i <= 73) ? [propertyCompletion("Bb", 71, 2)] :
(74 <= i && i <= 76) ? [propertyCompletion("cC", 74, 2)] :
[]);
}
});
});
// CONSIDER: Use parseTemplateWithMarkers
function getDocumentAndMarkers(document: object | string): { documentText: string; tokens: number[] } {
let tokens: number[] = [];
document = typeof document === "string" ? document : JSON.stringify(document);
// tslint:disable-next-line:no-constant-condition
while (true) {
let tokenPos: number = document.indexOf("!");
if (tokenPos < 0) {
break;
}
tokens.push(tokenPos);
document = document.slice(0, tokenPos) + document.slice(tokenPos + 1);
}
return {
documentText: document,
tokens
};
}
suite("Parameter defaultValue deep completion for objects", () => {
let { documentText, tokens } = getDocumentAndMarkers({
parameters: {
a: {
type: "object",
defaultValue: {
aa: {
bb: {
cc: 200
}
}
}
}
},
variables: {
b: "[parameters('a').!aa.!bb.!]"
}
});
let [dotAa, dotBb, dot] = tokens;
completionItemsTest(
documentText,
dotAa,
[propertyCompletion("aa", dotAa, 2)]);
completionItemsTest(
documentText,
dotBb,
[propertyCompletion("bb", dotBb, 2)]);
completionItemsTest(
documentText,
dot,
[propertyCompletion("cc", dot, 0)]);
});
suite("Parameter defaultValue with array nested in object", () => {
let { documentText, tokens } = getDocumentAndMarkers({
"parameters": {
"location": {
"type": "object",
"defaultValue": {
"a": [ // array inside an object
1
]
}
}
},
"outputs": {
"output1": {
"type": "bool",
"value": "[parameters('location').a.b.!]"
}
}
});
let [dotB] = tokens;
completionItemsTest(
documentText,
dotB,
// We should get any completions because we don't handle completions
// for arrays (shouldn't throw, either)
// See https://github.com/microsoft/vscode-azurearmtools/issues/441
[]);
});
suite("Variable value with array nested in object", () => {
test("variables('v1').a.b.c", async () => {
// Shouldn't throw - see https://github.com/microsoft/vscode-azurearmtools/issues/441
parseTemplate(
{
"variables": {
"v1": {
"a": [
1
]
}
},
"outputs": {
"output1": {
"type": "bool",
"value": "[variables('v1').a.b.c]"
}
}
},
[]);
});
});
}
suite("Completion items usability", () => {
// <!replstart!> - indicates the start of the replacement range
// ! - indicates location of the cursor
function testCompletionItemsWithRange(
nameSuffix: string,
templateWithReplacement: string | IPartialDeploymentTemplate,
expression: string,
expectedExample: undefined | { // Expected representation of one of the completion items, we'll search for it by label (the others are not tested, assumed to be similar)
label: string;
insertText: string;
replaceSpanText: string;
}
): void {
// tslint:disable-next-line: prefer-template
let testName = `${expression}${nameSuffix ? ' (' + nameSuffix + ')' : ''}`;
testWithPrep(
testName,
[UseNoSnippets.instance],
async () => {
testName = testName;
templateWithReplacement = stringify(templateWithReplacement);
const template = templateWithReplacement.replace(/TESTEXPRESSION/, expression);
const { dt, markers: { cursor, replstart } } = parseTemplateWithMarkers(template);
// tslint:disable-next-line: strict-boolean-expressions
assert(!!replstart!, "Didn't find <!replstart!> in test expression");
// tslint:disable-next-line: strict-boolean-expressions
assert(!!cursor!, "Didn't find <!cursor!> in test expression");
const pc: TemplatePositionContext = dt.getContextFromDocumentCharacterIndex(cursor.index, undefined);
let completionItems: Completion.Item[] = (await pc.getCompletionItems(undefined, 2)).items;
if (!expectedExample) {
assert.equal(completionItems.length, 0, "Expected 0 completion items");
return;
}
let foundItem = completionItems.find(ci => ci.label === expectedExample.label);
assert(!!foundItem, `Did not find a completion item with the label "${expectedExample.label}"`);
const actual = {
label: foundItem.label,
insertText: foundItem.insertText,
replaceSpanStart: foundItem.span.startIndex,
replaceSpanText: dt.getDocumentText(foundItem.span),
};
const expected = {
label: expectedExample.label,
insertText: expectedExample.insertText,
replaceSpanStart: replstart.index,
replaceSpanText: expectedExample.replaceSpanText,
};
assert.deepEqual(actual, expected);
});
}
const template1: IPartialDeploymentTemplate = {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"outputs": {
"testExpression": {
"type": "string",
"value": "TESTEXPRESSION"
}
},
"parameters": {
"subnet1Name": {
"type": "object",
"defaultValue": {
"property1": "hi",
"property2": {
"property2a": "2a"
}
}
},
"sku": {
"type": "string"
}
},
"variables": {
"subnet1Name": {
"property1": "hi",
"property2": {
"property2a": "2a"
}
},
"subnet2Name": "subnet2"
},
"resources": [],
"functions": [
{
"namespace": "mixedCaseNamespace",
"members": {
"howdy": {}
}
},
{
"namespace": "udf",
"members": {
"myfunction": {
"parameters": [
{
"name": "year",
"type": "Int"
},
{
"name": "month",
"type": "int"
},
{
"name": "day",
"type": "int"
}
],
"output": {
"type": "string",
"value": "[<stringOutputValue>]"
}
},
"udf2": {},
"udf3": {},
"udf34": {},
"mixedCaseFunc": {}
}
}
]
};
suite("Simple function completions", () => {
testCompletionItemsWithRange(
"",
template1,
`[<!replstart!><!cursor!>]`,
{
label: "add",
insertText: "add",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"",
template1,
`[<!replstart!><!cursor!>param]`,
{
label: "add",
insertText: "add",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"",
template1,
`[<!replstart!>param<!cursor!>]`,
{
label: "parameters",
insertText: "parameters",
replaceSpanText: "param"
}
);
testCompletionItemsWithRange(
"Don't replace the entire function name, just what's to the left of the cursor",
template1,
`[<!replstart!>param<!cursor!>eters]`,
{
label: "parameters",
insertText: "parameters",
replaceSpanText: "param"
}
);
});
suite("User-defined function namespace completions", () => {
testCompletionItemsWithRange(
"",
template1,
`[<!replstart!><!cursor!>]`,
{
label: "udf",
insertText: "udf",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"",
template1,
`[<!replstart!><!cursor!>ud]`,
{
label: "udf",
insertText: "udf",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"",
template1,
`[<!replstart!>ud<!cursor!>]`,
{
label: "udf",
insertText: "udf",
replaceSpanText: "ud"
}
);
testCompletionItemsWithRange(
"Don't replace the entire namespace, just what's to the left of the cursor",
template1,
`[<!replstart!>ud<!cursor!>f]`,
{
label: "udf",
insertText: "udf",
replaceSpanText: "ud"
}
);
});
suite("User-defined function name completions", () => {
testCompletionItemsWithRange(
"",
template1,
`[udf.<!replstart!><!cursor!>myfunction]`,
{
label: "udf.myfunction",
insertText: "myfunction",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"",
template1,
`[udf.<!replstart!>myfunction<!cursor!>]`,
{
label: "udf.myfunction",
insertText: "myfunction",
replaceSpanText: "myfunction"
}
);
testCompletionItemsWithRange(
"Don't replace the entire function name, just what's to the left of the cursor",
template1,
`[udf.<!replstart!>myf<!cursor!>unction]`,
{
label: "udf.myfunction",
insertText: "myfunction",
replaceSpanText: "myf"
}
);
});
suite("Parameters/variables argument replacements", () => {
// Include closing parenthesis and single quote in the replacement span and insertion text,
// so that the cursor ends up after them once the replacement happens.
// This way the user can immediately start typing the rest of the expression after the parameters call.
// Also, note that we replace the entire string argument (unlike for function name replacements)
suite("empty parentheses", () => {
testCompletionItemsWithRange(
"",
template1,
`[parameters(<!replstart!><!cursor!>)]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: ")"
}
);
testCompletionItemsWithRange(
"",
template1,
`[variables(<!replstart!><!cursor!>)]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: ")"
}
);
testCompletionItemsWithRange(
"with whitespace",
template1,
`[parameters(<!replstart!><!cursor!> )]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: " )"
}
);
testCompletionItemsWithRange(
"with whitespace",
template1,
`[variables(<!replstart!><!cursor!> )]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: " )"
}
);
testCompletionItemsWithRange(
"with whitespace #2",
template1,
`[parameters( <!replstart!><!cursor!>)]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: ")"
}
);
testCompletionItemsWithRange(
"no closing paren",
template1,
`[parameters(<!replstart!><!cursor!>]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"no closing paren",
template1,
`[variables(<!replstart!><!cursor!>]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: ""
}
);
});
suite("cursor before string - insert completion, don't remove anything", () => {
testCompletionItemsWithRange(
"",
template1,
`[parameters(<!replstart!><!cursor!>'hi')]`,
{
label: "'sku'",
insertText: "'sku'",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"",
template1,
`[variables(<!replstart!><!cursor!>'hi')]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name'",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"with whitespace before string, cursor after whitespace",
template1,
`[parameters( <!replstart!><!cursor!>'hi')]`,
{
label: "'sku'",
insertText: "'sku'",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"no closing paren",
template1,
`[parameters(<!replstart!><!cursor!>'hi']`,
{
label: "'sku'",
insertText: "'sku'",
replaceSpanText: ""
}
);
});
suite("cursor inside string - replace entire string and closing paren", () => {
testCompletionItemsWithRange(
"empty string",
template1,
`[parameters(<!replstart!>'<!cursor!>')]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'')"
}
);
testCompletionItemsWithRange(
"empty string",
template1,
`[variables(<!replstart!>'<!cursor!>')]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: "'')"
}
);
testCompletionItemsWithRange(
"",
template1,
`[parameters(<!replstart!>'<!cursor!>hi')]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'hi')"
}
);
testCompletionItemsWithRange(
"",
template1,
`[variables(<!replstart!>'<!cursor!>hi')]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: "'hi')"
}
);
testCompletionItemsWithRange(
"",
template1,
`[parameters(<!replstart!>'h<!cursor!>i')]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'hi')"
}
);
testCompletionItemsWithRange(
"",
template1,
`[variables(<!replstart!>'h<!cursor!>i')]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: "'hi')"
}
);
testCompletionItemsWithRange(
"",
template1,
`[parameters(<!replstart!>'hi<!cursor!>')]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'hi')"
}
);
testCompletionItemsWithRange(
"",
template1,
`[variables(<!replstart!>'hi<!cursor!>')]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: "'hi')"
}
);
suite("Make sure we don't erase the closing ']' if the closing paren or quote are missing (perhaps Auto Closing Brackets settings if off)", () => {
testCompletionItemsWithRange(
"no closing paren",
template1,
`[parameters(<!replstart!>'hi<!cursor!>']`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'hi'"
}
);
testCompletionItemsWithRange(
"no closing quote",
template1,
`[parameters(<!replstart!>'hi<!cursor!>)]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'hi)"
}
);
testCompletionItemsWithRange(
"no closing quote or paren",
template1,
`[parameters(<!replstart!>'hi<!cursor!>]`,
{
label: "'sku'",
insertText: "'sku')",
replaceSpanText: "'hi"
}
);
testCompletionItemsWithRange(
"no closing quote or paren",
template1,
`[variables(<!replstart!>'hi<!cursor!>]`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name')",
replaceSpanText: "'hi"
}
);
});
testCompletionItemsWithRange(
"extra (invalid) args",
template1,
`[parameters(<!replstart!>'hi<!cursor!>', 'there']`,
{
label: "'sku'",
insertText: "'sku'",
replaceSpanText: "'hi'"
}
);
testCompletionItemsWithRange(
"extra (invalid) args",
template1,
`[variables(<!replstart!>'hi<!cursor!>', 'there']`,
{
label: "'subnet1Name'",
insertText: "'subnet1Name'",
replaceSpanText: "'hi'"
}
);
testCompletionItemsWithRange(
"before second (invalid) arg",
template1,
`[parameters('hi', <!cursor!><!replstart!>'there']`,
undefined
);
testCompletionItemsWithRange(
"in second (invalid) arg",
template1,
`[parameters('hi', '<!replstart!><!cursor!>there']`,
undefined
);
testCompletionItemsWithRange(
"in second (invalid) arg",
template1,
`[variables('hi', '<!cursor!><!replstart!><!cursor!>there']`,
undefined
);
});
suite("#349 tab completion of params/vars shouldn't wipe out remainder of existing string when adding new parameters call before existing string", () => {
// E.g.: "[resourceId(<CURSOR>'Microsoft.Network/virtualNetworks', parameters('subnet2Name'))]",
testCompletionItemsWithRange(
"user typed parameters( without apostrophe before completing",
template1,
`[resourceId(parameters(<!replstart!><!cursor!>'Microsoft.Network/virtualNetworks', parameters('subnet2Name'))]`,
{
label: "'sku'",
insertText: "'sku'",
replaceSpanText: ""
}
);
testCompletionItemsWithRange(
"user typed parameters(' with an apostrophe before completing",
template1,
`[resourceId(parameters(<!replstart!>'<!cursor!>''Microsoft.Network/virtualNetworks', parameters('subnet2Name'))]`,
{
label: "'sku'",
insertText: "'sku'",
replaceSpanText: "''"
}
);
});
});
});
});
}); | the_stack |
import "../styles/captureMenu.scss";
import { Observable } from "../../shared/utils/observable";
import { MVX } from "../mvx/mvx";
import { CaptureMenuComponent, ICaptureMenuComponentState } from "./captureMenuComponent";
import { CanvasListItemComponent } from "./canvasListItemComponent";
import { CaptureMenuActionsComponent } from "./captureMenuActionsComponent";
import { CanvasListComponent, ICanvasListComponentState } from "./canvasListComponent";
import { FpsCounterComponent } from "./fpsCounterComponent";
import { LogLevel } from "../../shared/utils/logger";
export interface ICanvasInformation {
id: string;
width: number;
height: number;
ref: any;
}
export interface ICaptureMenuOptions {
readonly rootPlaceHolder?: Element;
readonly canvas?: HTMLCanvasElement;
readonly hideLog?: boolean;
}
interface IArrayLike<T> {
length: number;
[index: number]: T;
}
export class CaptureMenu {
public static SelectCanvasHelpText = "Please, select a canvas in the list above.";
public static ActionsHelpText = "Record with the red button, you can also pause or continue playing the current scene.";
public static PleaseWaitHelpText = "Capturing, be patient (this can take up to 3 minutes)...";
public readonly onCanvasSelected: Observable<ICanvasInformation>;
public readonly onCaptureRequested: Observable<ICanvasInformation>;
public readonly onPauseRequested: Observable<ICanvasInformation>;
public readonly onPlayRequested: Observable<ICanvasInformation>;
public readonly onPlayNextFrameRequested: Observable<ICanvasInformation>;
private readonly rootPlaceHolder: Element;
private readonly mvx: MVX;
private readonly captureMenuComponent: CaptureMenuComponent;
private readonly canvasListItemComponent: CanvasListItemComponent;
private readonly actionsComponent: CaptureMenuActionsComponent;
private readonly canvasListComponent: CanvasListComponent;
private readonly fpsCounterComponent: FpsCounterComponent;
private readonly rootStateId: number;
private readonly fpsStateId: number;
private readonly actionsStateId: number;
private readonly canvasListStateId: number;
private isTrackingCanvas: boolean;
constructor(private readonly options: ICaptureMenuOptions = {}) {
this.rootPlaceHolder = options.rootPlaceHolder || document.body;
this.mvx = new MVX(this.rootPlaceHolder);
this.isTrackingCanvas = false;
this.onCanvasSelected = new Observable<ICanvasInformation>();
this.onCaptureRequested = new Observable<ICanvasInformation>();
this.onPauseRequested = new Observable<ICanvasInformation>();
this.onPlayRequested = new Observable<ICanvasInformation>();
this.onPlayNextFrameRequested = new Observable<ICanvasInformation>();
this.captureMenuComponent = new CaptureMenuComponent();
this.canvasListComponent = new CanvasListComponent();
this.canvasListItemComponent = new CanvasListItemComponent();
this.actionsComponent = new CaptureMenuActionsComponent();
this.fpsCounterComponent = new FpsCounterComponent();
this.rootStateId = this.mvx.addRootState({
visible: true,
logLevel: LogLevel.info,
logText: CaptureMenu.SelectCanvasHelpText,
logVisible: !this.options.hideLog,
}, this.captureMenuComponent);
this.canvasListStateId = this.mvx.addChildState(this.rootStateId, { currentCanvasInformation: null, showList: false }, this.canvasListComponent);
this.actionsStateId = this.mvx.addChildState(this.rootStateId, true, this.actionsComponent);
this.fpsStateId = this.mvx.addChildState(this.rootStateId, 0, this.fpsCounterComponent);
this.actionsComponent.onCaptureRequested.add(() => {
const currentCanvasInformation = this.getSelectedCanvasInformation();
if (currentCanvasInformation) {
this.updateMenuStateLog(LogLevel.info, CaptureMenu.PleaseWaitHelpText, true);
}
// Defer to ensure the log displays.
setTimeout(() => {
this.onCaptureRequested.trigger(currentCanvasInformation);
}, 200);
});
this.actionsComponent.onPauseRequested.add(() => {
this.onPauseRequested.trigger(this.getSelectedCanvasInformation());
this.mvx.updateState(this.actionsStateId, false);
});
this.actionsComponent.onPlayRequested.add(() => {
this.onPlayRequested.trigger(this.getSelectedCanvasInformation());
this.mvx.updateState(this.actionsStateId, true);
});
this.actionsComponent.onPlayNextFrameRequested.add(() => {
this.onPlayNextFrameRequested.trigger(this.getSelectedCanvasInformation());
});
this.canvasListComponent.onCanvasSelection.add((eventArgs) => {
this.mvx.updateState(this.canvasListStateId, {
currentCanvasInformation: null,
showList: !eventArgs.state.showList,
});
this.updateMenuStateLog(LogLevel.info, CaptureMenu.SelectCanvasHelpText);
this.onCanvasSelected.trigger(null);
if (this.isTrackingCanvas) {
this.trackPageCanvases();
}
if (eventArgs.state.showList) {
this.showMenuStateLog();
}
else {
this.hideMenuStateLog();
}
});
this.canvasListItemComponent.onCanvasSelected.add((eventArgs) => {
this.mvx.updateState(this.canvasListStateId, {
currentCanvasInformation: eventArgs.state,
showList: false,
});
this.onCanvasSelected.trigger(eventArgs.state);
this.updateMenuStateLog(LogLevel.info, CaptureMenu.ActionsHelpText);
this.showMenuStateLog();
});
}
public getSelectedCanvasInformation(): ICanvasInformation {
const canvasListState = this.mvx.getGenericState<ICanvasListComponentState>(this.canvasListStateId);
return canvasListState.currentCanvasInformation;
}
public trackPageCanvases(): void {
this.isTrackingCanvas = true;
if (document.body) {
const canvases = document.body.querySelectorAll("canvas");
this.updateCanvasesList(canvases);
}
}
public updateCanvasesList(canvases: NodeListOf<HTMLCanvasElement>): void {
this.updateCanvasesListInformationInternal(canvases, (info) => {
return {
id: info.id,
width: info.width,
height: info.height,
ref: info,
};
});
}
public updateCanvasesListInformation(canvasesInformation: ICanvasInformation[]): void {
this.updateCanvasesListInformationInternal(canvasesInformation, (info) => {
return {
id: info.id,
width: info.width,
height: info.height,
ref: info.ref,
};
});
}
public display(): void {
this.updateMenuStateVisibility(true);
}
public hide(): void {
this.updateMenuStateVisibility(false);
}
public captureComplete(errorText: string): void {
if (errorText) {
this.updateMenuStateLog(LogLevel.error, errorText);
}
else {
this.updateMenuStateLog(LogLevel.info, CaptureMenu.ActionsHelpText);
}
}
public setFPS(fps: number): void {
this.mvx.updateState(this.fpsStateId, fps);
}
private updateCanvasesListInformationInternal<T>(canvasesInformation: ArrayLike<T>, convertToListInfo: (info: T) => ICanvasInformation): void {
// Create a consumable information list for the view.
this.mvx.removeChildrenStates(this.canvasListStateId);
const canvasesInformationClone: ICanvasInformation[] = [];
for (let i = 0; i < canvasesInformation.length; i++) {
const canvas = canvasesInformation[i];
const canvasInformationClone = convertToListInfo(canvas);
canvasesInformationClone.push(canvasInformationClone);
this.mvx.addChildState(this.canvasListStateId, canvasInformationClone, this.canvasListItemComponent);
}
// Auto Select in the list if only one canvas.
const canvasesCount = canvasesInformationClone.length;
const canvasListState = this.mvx.getGenericState<ICanvasListComponentState>(this.canvasListStateId);
const visible = canvasListState.showList;
if (!visible) {
if (canvasesCount === 1) {
const canvasToSelect = canvasesInformationClone[0];
this.mvx.updateState(this.canvasListStateId, {
currentCanvasInformation: canvasToSelect,
showList: visible,
});
this.updateMenuStateLog(LogLevel.info, CaptureMenu.ActionsHelpText);
this.onCanvasSelected.trigger(canvasToSelect);
}
else {
this.updateMenuStateLog(LogLevel.info, CaptureMenu.SelectCanvasHelpText);
this.onCanvasSelected.trigger(null);
}
}
}
private hideMenuStateLog() {
const menuState = this.mvx.getGenericState<ICaptureMenuComponentState>(this.rootStateId);
this.mvx.updateState(this.rootStateId, {
visible: menuState.visible,
logLevel: menuState.logLevel,
logText: menuState.logText,
logVisible: false,
});
}
private showMenuStateLog() {
const menuState = this.mvx.getGenericState<ICaptureMenuComponentState>(this.rootStateId);
this.mvx.updateState(this.rootStateId, {
visible: menuState.visible,
logLevel: menuState.logLevel,
logText: menuState.logText,
logVisible: !this.options.hideLog,
});
}
private updateMenuStateLog(logLevel: LogLevel, logText: string, immediate = false) {
const menuState = this.mvx.getGenericState<ICaptureMenuComponentState>(this.rootStateId);
this.mvx.updateState(this.rootStateId, {
visible: menuState.visible,
logLevel,
logText,
logVisible: !this.options.hideLog,
}, immediate);
}
private updateMenuStateVisibility(visible: boolean) {
const menuState = this.mvx.getGenericState<ICaptureMenuComponentState>(this.rootStateId);
this.mvx.updateState(this.rootStateId, {
visible,
logLevel: menuState.logLevel,
logText: menuState.logText,
logVisible: menuState.logVisible,
});
}
} | the_stack |
import React, { useEffect, useState, useRef } from 'react';
import {
Animated,
Text,
StyleSheet,
StatusBar,
View,
FlatList,
SafeAreaView,
} from 'react-native';
import { layout, FlatSection, ScrollEvent, story, } from '../types/interfaces';
import PhotosChunk from './PhotosChunk';
import ThumbScroll from './ThumbScroll';
import Highlights from './Highlights';
import { BaseItemAnimator, BaseScrollView, LayoutProvider } from 'recyclerlistview';
import { LayoutUtil } from '../utils/LayoutUtil';
import FloatingFilters from './FloatingFilters';
import { useBackHandler } from '@react-native-community/hooks'
import {default as Reanimated,
useSharedValue,
useAnimatedRef,
useDerivedValue,
scrollTo as reanimatedScrollTo,
useAnimatedScrollHandler,
useAnimatedStyle,
interpolate,
runOnJS,
withDelay,
withTiming,
} from 'react-native-reanimated';
import { timestampToDate } from '../utils/functions';
import RCL from './RCL';
import {
useRecoilState,
} from 'recoil';
import {
storiesState,
} from '../states';
const notUploadedArray:Array<Animated.Value> = [];
class ItemAnimator extends React.Component implements BaseItemAnimator {
constructor(props:any) {
super(props);
}
animateWillMount(atX:number, atY:number, itemIndex:number) {
console.log(['animateWillMount',atX, atY, itemIndex]);
//This method is called before the componentWillMount of the list item in the rowrenderer
//Fill in your logic.
return undefined;
}
animateDidMount(atX:number, atY:number, itemRef:any, itemIndex:number) {
console.log(['animateDidMount',atX, atY, itemIndex]);
//This method is called after the componentDidMount of the list item in the rowrenderer
//Fill in your logic
//No return
}
animateWillUpdate(fromX:number, fromY:number, toX:number, toY:number, itemRef:any, itemIndex:number): void {
console.log(['animateWillUpdate',fromX, fromY, toX, toY, itemIndex]);
//This method is called before the componentWillUpdate of the list item in the rowrenderer. If the list item is not re-rendered,
//It is not triggered. Fill in your logic.
// A simple example can be using a native layout animation shown below - Custom animations can be implemented as required.
//LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
//No return
}
animateShift(fromX:number, fromY:number, toX:number, toY:number, itemRef:any, itemIndex:number): boolean {
console.log(['animateShift',fromX, fromY, toX, toY, itemIndex]);
//This method is called if the the props have not changed, but the view has shifted by a certain amount along either x or y axes.
//Note that, this method is not triggered if the props or size has changed and the animateWillUpdate will be triggered in that case.
//Return value is used as the return value of shouldComponentUpdate, therefore will trigger a view re-render if true.
return false;
}
animateWillUnmount(atX:number, atY:number, itemRef:any, itemIndex:number): void {
console.log('animateWillUnmount index '+itemIndex)
//This method is called before the componentWillUnmount of the list item in the rowrenderer
//No return
}
}
class ExternalScrollView extends BaseScrollView {
scrollTo(...args: any[]) {
//if ((this.props as any).scrollRefExternal?.current) {
(this.props as any).scrollRefExternal?.current?.scrollTo(...args);
//reanimatedScrollTo((this.props as any).scrollRefExternal, 0, args[0].y, true);
//(this.props as any).scroll.value = args[0].y;
//}
}
render() {
return (
<Reanimated.ScrollView {...this.props}
style={{zIndex:1}}
ref={(this.props as any).scrollRefExternal}
scrollEventThrottle={16}
nestedScrollEnabled = {true}
removeClippedSubviews={true}
showsVerticalScrollIndicator={false}
//onScroll={(this.props as any)._onScrollExternal}
//onScroll={Reanimated.event([(this.props as any).animatedEvent], {listener: this.props.onScroll, useNativeDriver: true})}
>
{this.props.children}
</Reanimated.ScrollView>
);
}
}
interface Props {
photos: FlatSection;
maxWidth: number;
minWidth: number;
numColumns: 2 | 3 | 4;
loading: boolean;
sortCondition: 'day' | 'month';
scale: Reanimated.SharedValue<number>;
numColumnsAnimated: Reanimated.SharedValue<number>;
scrollIndex2:Animated.Value;
scrollIndex3:Animated.Value;
scrollIndex4:Animated.Value;
focalY: Animated.Value;
numberOfPointers: Animated.Value;
modalShown: Reanimated.SharedValue<number>;
headerShown: Reanimated.SharedValue<number>;
storiesHeight: number;
showStory:Animated.Value;
scrollY: Reanimated.SharedValue<number>;
HEADER_HEIGHT: number;
FOOTER_HEIGHT: number;
uploadedAssets:React.MutableRefObject<{[key: string]: number;}>
lastUpload:Reanimated.SharedValue<string>;
uploadingPercent:React.MutableRefObject<Animated.Value[]>
animatedImagePositionX: Reanimated.SharedValue<number>;
animatedImagePositionY: Reanimated.SharedValue<number>;
animatedSingleMediaIndex: Reanimated.SharedValue<number>;
singleImageWidth: Reanimated.SharedValue<number>;
singleImageHeight: Reanimated.SharedValue<number>;
selectedAssets:Reanimated.SharedValue<string[]>;
lastSelectedAssetId: Reanimated.SharedValue<string>;
lastSelectedAssetAction: Reanimated.SharedValue<number>;
dragY: Reanimated.SharedValue<number>;
SCREEN_HEIGHT: number;
SCREEN_WIDTH: number;
}
const RenderPhotos: React.FC<Props> = (props) => {
const [stories, setStories] = useRecoilState(storiesState);
const headerHeight = 20;
const indicatorHeight = 50;
const [layoutProvider, setLayoutProvider] = useState<LayoutProvider>(LayoutUtil.getLayoutProvider(props.numColumns, props.sortCondition, headerHeight, props.storiesHeight, props.HEADER_HEIGHT));
layoutProvider.shouldRefreshWithAnchoring = true;
const scrollRef:any = useRef();
const scrollRefExternal = useAnimatedRef<Reanimated.ScrollView>();
const showThumbScroll = useSharedValue(0);
const showFloatingFilters = useSharedValue(0);
const animatedTimeStampString = useSharedValue('');
const layoutHeightAnimated = useSharedValue(99999999);
const [currentImageTimestamp, setCurrentImageTimestamp] = useState<number>(0);
const animatedStyle = useAnimatedStyle(()=>{
const scale = (props.numColumns===props.numColumnsAnimated.value)?interpolate(
props.scale.value,
[0,1,4],
[props.numColumns/(props.numColumns+1),1,(props.numColumns)/(props.numColumns-1)]
):((props.numColumns===props.numColumnsAnimated.value+1)?interpolate(
props.scale.value,
[0,1,4],
[1,(props.numColumns)/(props.numColumns-1),(props.numColumns)/(props.numColumns-1)]
):((props.numColumns===props.numColumnsAnimated.value-1)?interpolate(
props.scale.value,
[0,1,4],
[(props.numColumns)/(props.numColumns+1),(props.numColumns)/(props.numColumns+1),1]
):1));
return {
opacity: (props.numColumnsAnimated.value===props.numColumns)?(interpolate(
props.scale.value,
[0,1,4],
[0,1,0]
)):(props.numColumnsAnimated.value===(props.numColumns-1)?(interpolate(
props.scale.value,
[0, 1, 4],
[1, 0, 0]
)):(props.numColumnsAnimated.value===(props.numColumns+1)?(interpolate(
props.scale.value,
[0, 1, 4],
[0, 0, 1]
)):(0))),
zIndex:(props.numColumnsAnimated.value===props.numColumns)?1:0,
transform: [
{
scale: scale,
},
{
translateX: (
(
(
scale*props.SCREEN_WIDTH)-
props.SCREEN_WIDTH)
/ (2*scale))
},
{
translateY: (
(
(
scale*(props.SCREEN_HEIGHT-(StatusBar.currentHeight || 0))
) - (props.SCREEN_HEIGHT-(StatusBar.currentHeight || 0))
)
/ (2*scale))
}
],
};
});
useEffect(()=>{
console.log([Date.now()+': component RenderPhotos'+props.numColumns+' rendered']);
});
/****
* The below lines are to update the selection checkbox status in each media
*/
const clearSelection = useRef(new Animated.Value(0)).current;
const selectedAssetsRef = useRef<string[]>([]);
const setSelectedAssetsRef = (selected:string[]) => {
selectedAssetsRef.current = selected;
}
const setClearSelection = (clear:number) => {
clearSelection.setValue(clear);
}
useDerivedValue(() => {
//we need to add a dummy condition on the props.lastSelectedAssetAction.value and props.lastSelectedAssetIndex.value so that useDerivedValue does not ignore updating
if(props.lastSelectedAssetAction.value>-1 && props.lastSelectedAssetId.value!=='Thisisjustadummytext'){
runOnJS(setSelectedAssetsRef)(props.selectedAssets.value);
if(props.selectedAssets.value.length){
runOnJS(setClearSelection)(1);
}else{
console.log('erasing selection');
runOnJS(setClearSelection)(0);
}
//selectedAssetsRef.current = props.selectedAssets.value;
}
}, [props.lastSelectedAssetAction, props.lastSelectedAssetId]);
/****
* The below lines are to update the scroll position across all modes
*/
useEffect(()=>{
console.log(['component RenderPhotos mounted '+props.numColumns]);
if(props.numColumns===3 || props.numColumns===4){
//props.scrollIndex2.removeAllListeners();
props.scrollIndex2.addListener(({value})=>{
scrollRef?.current?.scrollToIndex(value, false);
});
}
if(props.numColumns===2 || props.numColumns===3){
//props.scrollIndex4.removeAllListeners();
props.scrollIndex4.addListener(({value})=>{
scrollRef?.current?.scrollToIndex(value, false);
});
}
if(props.numColumns===2 || props.numColumns===4){
//props.scrollIndex3.removeAllListeners();
props.scrollIndex3.addListener(({value})=>{
scrollRef?.current?.scrollToIndex(value, false);
});
}
return () => {
console.log(['component RenderPhotos unmounted']);
if(props.numColumns===2 || props.numColumns ===3){
props.scrollIndex4.removeAllListeners();
}
if(props.numColumns===3 || props.numColumns ===4){
props.scrollIndex2.removeAllListeners();
}
if(props.numColumns===2 || props.numColumns ===4){
props.scrollIndex3.removeAllListeners();
}
}
}, []);
/*useEffect(()=>{
console.log('photos.layout length changed');
//if(dataProvider.getAllData().length !== props.photos.layout.length){
let data = props.photos.layout;
//setLayoutProvider(LayoutUtil.getLayoutProvider(props.numColumns, props.sortCondition, headerHeight, dataProvider, props.storiesHeight, props.HEADER_HEIGHT));
//}
},[dataProvider]);*/
useBackHandler(() => {
/*if (props.showSelectionCheckbox) {
return true
}*/
// let the default thing happen
return false
})
const rowRenderer = React.useCallback((type:string | number, data:layout, index: number) => {
if(data.sortCondition !== '' && data.sortCondition !== props.sortCondition){
return (<></>)
}
switch(type){
case 'story':
return (
<SafeAreaView style={{position:'relative', zIndex:1,marginTop:props.HEADER_HEIGHT}}>
<FlatList
data={stories}
horizontal={true}
keyExtractor={(item:story, index:number) => 'StoryItem_'+index+'_'+item.text}
getItemLayout={(data, index) => {
return {
length: 15+props.storiesHeight/1.618,
offset: index*(15+props.storiesHeight/1.618),
index: index
}
}}
showsHorizontalScrollIndicator={false}
renderItem={( {item} ) => (
<View
style={{
width:15+props.storiesHeight/1.618,
height:props.storiesHeight+25,
}}>
<Highlights
story={item}
duration={1500}
numColumns={props.numColumns}
height={props.storiesHeight}
showStory={props.showStory}
headerShown={props.headerShown}
/>
</View>
)}
/>
</SafeAreaView>
);
break;
default:
props.uploadingPercent.current[index] = new Animated.Value(0);
return (
<PhotosChunk
photo={data}
index={data.index}
modalShown={props.modalShown}
headerShown={props.headerShown}
headerHeight={headerHeight}
selectedAssets={props.selectedAssets}
lastSelectedAssetId={props.lastSelectedAssetId}
lastSelectedAssetAction={props.lastSelectedAssetAction}
selectedAssetsRef={selectedAssetsRef}
clearSelection={clearSelection}
uploadedAssets={props.uploadedAssets}
lastUpload={props.lastUpload}
uploadingPercent={props.uploadingPercent.current[index]}
animatedImagePositionX={props.animatedImagePositionX}
animatedImagePositionY={props.animatedImagePositionY}
animatedSingleMediaIndex={props.animatedSingleMediaIndex}
singleImageWidth={props.singleImageWidth}
singleImageHeight={props.singleImageHeight}
imageWidth={(typeof data.value !== 'string')?data.value.width:0}
imageHeight={(typeof data.value !== 'string')?data.value.height:0}
SCREEN_HEIGHT={props.SCREEN_HEIGHT}
SCREEN_WIDTH={props.SCREEN_WIDTH}
/>
);
}
},[props.photos?.layout?.length]);
const _onMomentumScrollEnd = () => {
let currentTimeStamp = 0;
let lastIndex = (scrollRef?.current?.findApproxFirstVisibleIndex() || 0);
let currentImage = props.photos.layout[lastIndex].value;
if(typeof currentImage === 'string'){
currentImage = props.photos.layout[lastIndex+1]?.value;
if(currentImage && typeof currentImage === 'string'){
currentImage = props.photos.layout[lastIndex+2]?.value;
}
}
if(currentImage && typeof currentImage !== 'string'){
currentTimeStamp = currentImage.modificationTime;
}
let currentTimeStampString = timestampToDate(currentTimeStamp, ['month']).month;
animatedTimeStampString.value = currentTimeStampString;
if(props.numColumns===2){
props.scrollIndex2.setValue(lastIndex);
}else if(props.numColumns===3){
props.scrollIndex3.setValue(lastIndex);
}else if(props.numColumns===4){
props.scrollIndex4.setValue(lastIndex);
}
////console.log(['momentum ended', {'in':props.numColumns, 'to':lastIndex}, lastOffset]);
showThumbScroll.value = withDelay(3000, withTiming(0));
}
useDerivedValue(() => {
let approximateIndex = Math.ceil(props.dragY.value/props.numColumns);
//animatedTimeStampString.value = approximateIndex.toString();
reanimatedScrollTo(scrollRefExternal, 0, props.dragY.value, false);
}, [props.dragY]);
const scrollBarToViewSync = (value:number)=> {
let sampleHeight = scrollRef?.current?.getContentDimension().height;
//console.log('value='+value);
//console.log('ViewOffset='+ViewOffset);
//console.log('sampleHeight='+sampleHeight);
//console.log('SCREEN_HEIGHT='+SCREEN_HEIGHT);
let currentImageIndex = scrollRef.current.findApproxFirstVisibleIndex();
let currentImage = props.photos.layout[currentImageIndex].value;
let currentTimeStamp = 0;
if(typeof currentImage === 'string'){
currentImage = props.photos.layout[currentImageIndex+1]?.value;
if(currentImage && typeof currentImage === 'string'){
currentImage = props.photos.layout[currentImageIndex+2]?.value;
}
}
if(currentImage && typeof currentImage !== 'string'){
currentTimeStamp = currentImage.modificationTime;
}
setCurrentImageTimestamp(currentTimeStamp);
}
/*useEffect(()=>{
adjustScrollPosition(props.scrollOffset);
},[props.scrollOffset]);*/
const scrollHandlerReanimated = useAnimatedScrollHandler({
onScroll: (e) => {
//position.value = e.contentOffset.x;
props.scrollY.value = e.contentOffset.y;
layoutHeightAnimated.value = e.contentSize.height;
showThumbScroll.value = 1;
},
onEndDrag: (e) => {
console.log('onEndDrag');
},
onMomentumEnd: (e) => {
runOnJS(_onMomentumScrollEnd)();
//let lastIndex = scrollRef?.current?.findApproxFirstVisibleIndex();
},
});
const itemAnimator = new ItemAnimator({uploadingPercent: props.uploadingPercent});
return props.photos.layout ? (
<Reanimated.View
// eslint-disable-next-line react-native/no-inline-styles
style={[animatedStyle, {
flex: 1,
width: props.SCREEN_WIDTH,
height: props.SCREEN_HEIGHT,
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
}]}
>
<RCL
scrollRef={scrollRef}
externalScrollView={ExternalScrollView}
itemAnimator={itemAnimator}
SCREEN_WIDTH= {props.SCREEN_WIDTH}
SCREEN_HEIGHT= {props.SCREEN_HEIGHT}
layoutProvider={layoutProvider}
rowRenderer={rowRenderer}
scrollRefExternal={scrollRefExternal}
scrollHandlerReanimated={scrollHandlerReanimated}
key={"RCL_"+props.sortCondition + props.numColumns}
/>
<ThumbScroll
indicatorHeight={indicatorHeight}
flexibleIndicator={false}
shouldIndicatorHide={true}
opacity={showThumbScroll}
showFloatingFilters={showFloatingFilters}
hideTimeout={500}
dragY={props.dragY}
headerHeight={headerHeight}
FOOTER_HEIGHT={props.FOOTER_HEIGHT}
HEADER_HEIGHT={props.HEADER_HEIGHT}
scrollY={props.scrollY}
scrollIndicatorContainerStyle={{}}
scrollIndicatorStyle={{}}
layoutHeight={layoutHeightAnimated}
currentImageTimestamp={animatedTimeStampString}
/>
<FloatingFilters
headerIndexes={props.photos.headerIndexes}
floatingFiltersOpacity={showFloatingFilters}
numColumns={props.numColumns}
sortCondition={props.sortCondition}
headerHeight={headerHeight}
FOOTER_HEIGHT={props.FOOTER_HEIGHT}
HEADER_HEIGHT={props.HEADER_HEIGHT}
indicatorHeight={indicatorHeight}
layoutHeight={layoutHeightAnimated}
/>
</Reanimated.View>
) : (
<Animated.View
// eslint-disable-next-line react-native/no-inline-styles
style={{
flex: 1,
width: props.SCREEN_WIDTH,
height: props.SCREEN_HEIGHT,
position: 'absolute',
top: 0,
bottom: 0,
marginTop: StatusBar.currentHeight || 0,
right: 0,
left: 0,
}}>
<Text>Loading...</Text>
</Animated.View>
);
};
const styles = StyleSheet.create({
header: {
fontSize: 18,
backgroundColor: '#fff',
},
});
const isEqual = (prevProps:Props, nextProps:Props) => {
return (prevProps.photos.layout.length === nextProps.photos.layout.length);
}
export default React.memo(RenderPhotos, isEqual); | the_stack |
import { readFileSync } from "fs";
import { mapFromObject } from "./core";
import { CharacterCodes } from "./tokens";
/**
* Indicates the token to use for line terminators during emit.
* {@docCategory Compiler}
*/
export enum NewLineKind {
/**
* Lines should be terminated with a line-feed (Unix-style).
*/
LineFeed,
/**
* Lines should be terminted with a carriage-return followed by a line-feed (DOS-style).
*/
CarriageReturnLineFeed,
}
/**
* Indicates the emit output format.
* {@docCategory Compiler}
*/
export enum EmitFormat {
/**
* Output should be emitted in Markdown format.
*/
markdown,
/**
* Output should be emitted in HTML format.
*/
html,
/**
* Output should be emitted in ECMArkup format.
*/
ecmarkup
}
/**
* Options that control the behavior of the compiler.
* {@docCategory Compiler}
*/
export interface CompilerOptions {
/**
* Indicates the token to use for line terminators during emit.
*/
newLine?: NewLineKind;
/**
* Indicates that diagnostics should not be reported.
*/
noChecks?: boolean;
/**
* Indicates that emit output should not be produced.
*/
noEmit?: boolean;
/**
* Indicates that emit output should not be produced if any diagnostics are reported.
*/
noEmitOnError?: boolean;
/**
* Disables strict checking of production parameters.
*/
noStrictParametricProductions?: boolean;
/**
* Indicates that diagnostics should be produced if production parameters are unused.
*/
noUnusedParameters?: boolean;
/**
* Indicates the emit output format.
*/
format?: EmitFormat;
/**
* Indicates the file path for emit output.
*/
out?: string;
/**
* Indicates whether to include hyperlinks in the emit output.
*/
emitLinks?: boolean;
/**
* Indicates whether internal diagnostic information should be reported to the console.
*/
diagnostics?: boolean;
}
/**
* Gets the default options for the compiler.
*/
export function getDefaultOptions(): CompilerOptions {
return { format: EmitFormat.markdown };
}
export interface KnownOptions {
[name: string]: Partial<KnownOption>;
}
export interface KnownOption {
shortName?: string;
longName: string;
param?: string;
type?: string | Map<string, any>;
many?: boolean;
description?: string;
error?: string;
aliasFor?: string[];
hidden?: boolean;
isUsage?: boolean;
validate?: (key: string, value: string, raw: RawArguments) => boolean;
convert?: (key: string, value: string, raw: RawArguments) => any;
}
interface KnownOptionMaps {
longNames: Map<string, KnownOption>;
shortNames: Map<string, KnownOption>;
}
export interface RawArgument {
rawKey: string;
formattedKey: string;
value: any;
option: KnownOption;
}
export interface RawArguments {
args: RawArgument[];
rest: string[];
}
export interface ParsedArguments {
[key: string]: any;
argv: string[];
rest: string[];
}
export function parse<T extends ParsedArguments>(options: KnownOptions, args: string[] = process.argv.slice(2)): T | undefined {
const known = createKnownOptionMaps(mapFromObject(options));
const raw: RawArguments = { args: [], rest: [] };
const messages: string[] = [];
let result: ParseResult
result = parseArguments(args, known, raw, messages);
if (result === ParseResult.Success) {
result = expandArguments(known, raw, messages);
if (result === ParseResult.Success) {
Object.freeze(raw.rest);
Object.freeze(raw.args);
Object.freeze(raw);
const parsed: T = <T>{ argv: args.slice(0) };
result = evaluateArguments(parsed, known, raw, messages);
if (result === ParseResult.Success) {
return parsed;
}
}
}
printErrors(messages);
}
const emptyArray: any[] = [];
export class UsageWriter {
private margin: number;
private padding: number;
private remainder: number;
constructor(margin: number, padding: number) {
this.margin = margin;
this.padding = padding;
this.remainder = 120 - margin - padding;
}
public writeOption(left: string | undefined, right: string | undefined) {
const leftLines = left ? this.fit(left, this.margin) : emptyArray;
const rightLines = right ? this.fit(right, this.remainder) : emptyArray;
const lineCount = Math.max(leftLines.length, rightLines.length);
for (let i = 0; i < lineCount; ++i) {
let line = "";
if (i < leftLines.length) {
line += leftLines[i];
}
if (i < rightLines.length) {
line = padRight(line, this.margin + this.padding);
line += rightLines[i];
}
console.log(line);
}
}
public writeln(text: string = "") {
console.log(text);
}
private fit(text: string, width: number) {
const lines: string[] = [];
let pos = 0, len = text.length;
while (pos < len) {
const ch = text.charCodeAt(pos);
if (ch === CharacterCodes.CarriageReturn || ch === CharacterCodes.LineFeed) {
pos++;
if (ch === CharacterCodes.CarriageReturn && pos < len && text.charCodeAt(pos) === CharacterCodes.LineFeed) {
pos++;
}
lines.push("");
continue;
}
let end = pos + width;
if (end >= len) {
lines.push(text.substr(pos));
break;
}
while (end > pos && !isWhiteSpace(text.charCodeAt(end))) end--;
while (end > pos && isWhiteSpace(text.charCodeAt(end), true)) end--;
if (end <= pos) {
lines.push(text.substr(pos, width));
pos += width;
}
else {
lines.push(text.substring(pos, end));
pos = end;
}
while (pos < len && isWhiteSpace(text.charCodeAt(pos), true)) pos++;
}
return lines;
}
}
export function usage(options: KnownOptions, margin: number = 0, printHeader?: (writer: UsageWriter) => void) {
const optionsDictionary = mapFromObject(options);
const knownOptions: (KnownOption)[] = [];
let hasShortNames = false;
for (const [key, value] of optionsDictionary) {
const option = importKnownOption(key, value);
if (option.hidden) {
continue;
}
let size = option.longName.length + 3;
if (option.shortName) {
hasShortNames = true;
size += 4;
}
if (option.param) {
size += 1;
}
if (size > margin) {
margin = size;
}
knownOptions.push(option);
}
const writer = new UsageWriter(margin, 1);
if (printHeader) {
printHeader(writer);
}
knownOptions.sort(compareKnownOptions);
for (const option of knownOptions) {
let left = " ";
if (option.shortName) {
left += `-${option.shortName}, `;
}
else if (hasShortNames) {
left += " ";
}
left += `--${option.longName}`;
if (option.param) {
left += ` ${option.param}`;
}
left = padRight(left, margin);
writer.writeOption(left, option.description);
}
}
function padRight(text: string, size: number, char: string = " ") {
while (text.length < size) text += char;
return text;
}
function printErrors(messages: string[]) {
for (const message of messages) {
console.error(message);
}
}
function compareKnownOptions(x: KnownOption, y: KnownOption) {
const xName = x.longName.toLowerCase();
const yName = y.longName.toLowerCase();
return xName.localeCompare(yName);
}
function importTypeMap(dict: Map<string, any>) {
const copy = new Map(dict);
Object.freeze(copy);
return copy;
}
function importKnownOption(key: string, option: Partial<KnownOption>) {
const copy: KnownOption = { longName: key };
if (typeof option.longName === "string") copy.longName = option.longName;
if (typeof option.shortName === "string" && option.shortName.length > 0) copy.shortName = option.shortName.substr(0, 1);
if (typeof option.param === "string") copy.param = option.param;
if (typeof option.type === "string") copy.type = option.type;
if (typeof option.type === "object") copy.type = importTypeMap(option.type);
if (typeof option.many === "boolean") copy.many = option.many;
if (typeof option.description === "string") copy.description = option.description;
if (typeof option.error === "string") copy.error = option.error;
if (typeof option.aliasFor === "string") copy.aliasFor = option.aliasFor;
if (typeof option.hidden === "boolean" && option.hidden) copy.hidden = option.hidden;
if (typeof option.isUsage === "boolean" && option.isUsage) copy.isUsage = option.isUsage;
if (typeof option.validate === "function") copy.validate = option.validate;
if (typeof option.convert === "function") copy.convert = option.convert;
Object.freeze(copy);
return copy;
}
function createKnownOptionMaps(options: Map<string, Partial<KnownOption>>): KnownOptionMaps {
const longNames = new Map<string, KnownOption>();
const shortNames = new Map<string, KnownOption>();
for (const [key, rawOption] of options) {
if (rawOption) {
const knownOption = importKnownOption(key, rawOption);
longNames.set(knownOption.longName.toLowerCase(), knownOption);
if (knownOption.shortName) {
shortNames.set(knownOption.shortName, knownOption);
}
}
}
const maps: KnownOptionMaps = { longNames, shortNames };
Object.freeze(longNames);
Object.freeze(shortNames);
Object.freeze(maps);
return maps;
}
enum ParseResult {
Success,
Error
}
function parseArguments(args: string[], known: KnownOptionMaps, raw: RawArguments, messages: string[]): ParseResult {
let argc = args.length, argi = 0;
while (argi < argc) {
let arg = args[argi++];
let ch = arg.charCodeAt(0);
if (ch === CharacterCodes.At) {
const result = parseResponseFile(arg.substr(1), known, raw, messages)
if (result !== ParseResult.Success) {
return result;
}
}
else if (ch === CharacterCodes.Minus) {
ch = arg.charCodeAt(1);
const colonIndex = arg.indexOf(":");
const hasInlineValue = colonIndex > 0;
const shortName = ch !== CharacterCodes.Minus;
const rawKey = arg.substring(shortName ? 1 : 2, hasInlineValue ? colonIndex : arg.length);
const match = matchKnownOption(known, rawKey, shortName);
switch (match.cardinality) {
case "none":
messages.push(`Unrecognized option: ${rawKey}.`);
return ParseResult.Error;
case "many":
messages.push(`Unrecognized option: ${rawKey}. Did you mean:`);
for (const option of match.candidates) {
messages.push(` --${option.longName}`);
}
return ParseResult.Error;
}
const option = match.option;
const formattedKey = shortName ? "-" + option.shortName : "--" + option.longName;
const valueRequired = optionRequiresValue(option);
let value: string | undefined;
if (valueRequired || hasInlineValue) {
if (hasInlineValue) {
value = arg.substr(colonIndex + 1);
}
else {
if (argi >= argc) {
messages.push(`Option '${formattedKey}' expects an argument.`);
return ParseResult.Error;
}
value = args[argi++];
}
if (value.length > 0) {
ch = value.charCodeAt(0);
if (ch === CharacterCodes.DoubleQuote) {
if (value.length > 1 && value.charCodeAt(value.length - 1) === ch) {
value = value.substr(1, value.length - 2);
}
}
}
if (valueRequired) {
if (value.length === 0 || value === `""` || value === `''`) {
messages.push(`Option '${formattedKey}' expects an argument.`);
return ParseResult.Error;
}
}
}
if (option.type === "boolean") {
if (!value) {
value = "true";
}
}
const rawArgument: RawArgument = {
rawKey,
formattedKey,
value,
option
};
Object.freeze(rawArgument);
raw.args.push(rawArgument);
}
else {
if (ch === CharacterCodes.DoubleQuote) {
if (arg.length > 1 && arg.charCodeAt(arg.length - 1) === ch) {
arg = arg.substr(1, arg.length - 2);
}
}
raw.rest.push(arg);
}
}
return ParseResult.Success;
}
function parseResponseFile(file: string, known: KnownOptionMaps, raw: RawArguments, messages: string[]): ParseResult {
let text: string;
try {
text = readFileSync(file, "utf8");
}
catch (e) {
messages.push(`File '${file}'' not found.`);
return ParseResult.Error;
}
const args: string[] = [];
let pos = 0;
const len = text.length;
while (pos < len) {
let ch = text.charCodeAt(pos);
if (isWhiteSpace(ch)) {
pos++;
continue;
}
const start = pos;
if (ch === CharacterCodes.DoubleQuote) {
pos++;
while (pos < len) {
ch = text.charCodeAt(pos);
if (ch === CharacterCodes.DoubleQuote) {
break;
}
pos++;
}
args.push(text.substring(start, pos++));
}
else {
pos++;
while (pos < len) {
ch = text.charCodeAt(pos);
if (!isWhiteSpace(ch)) {
pos++;
}
}
args.push(text.substring(start, pos));
}
}
return parseArguments(args, known, raw, messages);
}
function isWhiteSpace(ch: number, excludeLineTerminator?: boolean) {
switch (ch) {
case CharacterCodes.LineFeed:
case CharacterCodes.CarriageReturn:
return !excludeLineTerminator;
case CharacterCodes.Space:
case CharacterCodes.Tab:
case CharacterCodes.VerticalTab:
case CharacterCodes.FormFeed:
return true;
}
return false;
}
function optionRequiresValue(option: KnownOption) {
switch (option.type) {
case undefined:
case "":
case "boolean":
return false;
default:
return true;
}
}
type KnownOptionMatchResult =
| { cardinality: "one", option: KnownOption }
| { cardinality: "many", candidates: KnownOption[] }
| { cardinality: "none" };
function matchKnownOption(known: KnownOptionMaps, key: string, shortName: boolean): KnownOptionMatchResult {
if (shortName) {
const option = known.shortNames.get(key);
if (option) return { cardinality: "one", option };
}
else {
const keyLower = key.toLowerCase();
let option = known.longNames.get(keyLower);
if (option) return { cardinality: "one", option };
const keyLen = keyLower.length;
let candidates: KnownOption[] | undefined;
for (const [knownKey, option] of known.longNames) {
if (option &&
knownKey.length > keyLen &&
knownKey.substr(0, keyLen) === keyLower) {
if (!candidates) {
candidates = [];
}
candidates.push(option);
}
}
if (candidates) {
if (candidates.length === 1) {
const option = candidates[0];
return { cardinality: "one", option };
}
else if (candidates.length > 1) {
return { cardinality: "many", candidates };
}
}
}
return { cardinality: "none" };
}
function expandArguments(known: KnownOptionMaps, raw: RawArguments, messages: string[]) {
for (let i = 0; i < raw.args.length; ++i) {
const arg = raw.args[i];
const option = arg.option;
if (option.aliasFor) {
let args = option.aliasFor;
if (arg.value) {
args = args.concat([arg.value]);
}
if (parseArguments(args, known, raw, messages) === ParseResult.Error) {
return ParseResult.Error;
}
}
}
return ParseResult.Success;
}
function evaluateArguments(parsed: ParsedArguments, known: KnownOptionMaps, raw: RawArguments, messages: string[]) {
for (const arg of raw.args) {
let { formattedKey, value, option } = arg;
if (option.aliasFor) {
continue;
}
let type: string = typeof option.type;
if (type === "string") {
type = <string>option.type;
}
if (option.validate && !option.validate(option.longName, value, raw)) {
if (option.error) {
messages.push(option.error);
}
else {
messages.push(`Invalid argument for option '${formattedKey}'.`)
}
return ParseResult.Error;
}
let booleanValue: boolean | undefined;
let numberValue: number | undefined;
switch (type) {
case "file":
case "string":
break;
case "boolean":
if (value) {
value = value.toLowerCase();
if (!/^(true|false)$/.test(value)) {
if (option.error) {
messages.push(option.error);
}
else {
messages.push(`Invalid argument for option '${formattedKey}'. Expected either 'true' or 'false'.`);
}
return ParseResult.Error;
}
booleanValue = value === "true";
}
else {
booleanValue = true;
}
break;
case "number":
if (value) {
numberValue = parseFloat(value);
if (isNaN(numberValue) || !isFinite(numberValue)) {
if (option.error) {
messages.push(option.error);
}
else {
messages.push(`Invalid argument for option '${formattedKey}'. Expected a finite number.`);
}
return ParseResult.Error;
}
}
break;
case "object":
if (value) {
const type = <Map<string, any>>option.type;
let result = type.get(value);
if (result === undefined) {
const valueLower = (<string>value).toLowerCase();
result = type.get(valueLower);
if (!result) {
for (const key in type) {
if (key.toLowerCase() === valueLower) {
result = type.get(key);
break;
}
}
}
}
if (result === undefined) {
if (option.error) {
messages.push(option.error);
}
else {
messages.push(`Invalid argument for option '${formattedKey}'.`);
}
return ParseResult.Error;
}
value = result;
}
break;
}
if (option.convert) {
value = option.convert(option.longName, value, raw);
}
else {
switch (option.type) {
case "boolean":
value = booleanValue;
break;
case "number":
value = numberValue;
break;
}
}
parsed[option.longName] = value;
}
parsed.rest = raw.rest.slice(0);
return ParseResult.Success;
} | the_stack |
import { assertEquals, TestHelpers } from "../deps.ts";
import { Request, Resource, Response, Server } from "../../mod.ts";
////////////////////////////////////////////////////////////////////////////////
// FILE MARKER - APP SETUP /////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class OptionalPathParamsResource extends Resource {
paths = [
"/oppWithoutRequired/:name?/:age_of_person?/:city?",
"/oppWithRequired/:name/:age_of_person?",
];
public GET(request: Request, response: Response) {
const name = request.pathParam("name");
// deno-lint-ignore camelcase
const age_of_person = request.pathParam("age_of_person");
const city = request.pathParam("city");
response.json({
message: "Successfully handled optional path params",
data: {
name,
age_of_person,
city,
},
});
}
}
const server = new Server({
resources: [
OptionalPathParamsResource,
],
protocol: "http",
hostname: "localhost",
port: 3000,
});
////////////////////////////////////////////////////////////////////////////////
// FILE MARKER - TESTS /////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Deno.test("optional_path_params_test.ts", async (t) => {
await t.step("/oppWithoutRequired", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, undefined);
assertEquals(json.data.age_of_person, undefined);
assertEquals(json.data.city, undefined);
await server.close();
});
});
await t.step("/oppWithoutRequired/", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, undefined);
assertEquals(json.data.age_of_person, undefined);
assertEquals(json.data.city, undefined);
await server.close();
});
});
await t.step("/oppWithoutRequired/:name", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, undefined);
assertEquals(json.data.city, undefined);
await server.close();
});
});
await t.step("/oppWithoutRequired/:name/", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, undefined);
assertEquals(json.data.city, undefined);
await server.close();
});
});
await t.step("/oppWithoutRequired/:name/:age_of_person", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/999",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, "999");
assertEquals(json.data.city, undefined);
await server.close();
});
});
await t.step("/oppWithoutRequired/:name/:age_of_person/", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/999/",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, "999");
assertEquals(json.data.city, undefined);
await server.close();
});
});
await t.step("/oppWithoutRequired/:name/:age_of_person/:city", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/999/UK",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, "999");
assertEquals(json.data.city, "UK");
await server.close();
});
});
await t.step("/oppWithoutRequired/:name/:age_of_person/:city/", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/999/UK/",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, "999");
assertEquals(json.data.city, "UK");
await server.close();
});
});
await t.step(
"/oppWithoutRequired/:name/:age_of_person/:city/:other",
async (t) => {
await t.step("Resource should NOT handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/999/UK/other",
{
headers: {
Accept: "application/json",
},
},
);
assertEquals(
(await response.text()).startsWith("Error: Not Found"),
true,
);
await server.close();
});
},
);
await t.step("/oppWithoutRequired/:name/", async (t) => {
await t.step(
"Resource should handle request",
async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithoutRequired/edward/",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, undefined);
assertEquals(json.data.city, undefined);
await server.close();
},
);
});
await t.step("/oppWithRequired", async (t) => {
await t.step("Resource should NOT handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired",
{
headers: {
Accept: "application/json",
},
},
);
assertEquals(
(await response.text()).startsWith("Error: Not Found"),
true,
);
await server.close();
});
});
await t.step("/oppWithRequired/", async (t) => {
await t.step("Resource should NOT handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired/",
{
headers: {
Accept: "application/json",
},
},
);
assertEquals(
(await response.text()).startsWith("Error: Not Found"),
true,
);
await server.close();
});
});
await t.step("/oppWithRequired/edward", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired/edward",
{
headers: {
Accept: "application/json",
},
},
);
await server.close();
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, undefined);
});
});
await t.step("/oppWithRequired/edward/", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired/edward/",
{
headers: {
Accept: "application/json",
},
},
);
await server.close();
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, undefined);
});
});
await t.step("/oppWithRequired/ed-123/22", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired/ed-123/22-22",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "ed-123");
assertEquals(json.data.age_of_person, "22-22");
await server.close();
});
});
await t.step("/oppWithRequired/edward/22/", async (t) => {
await t.step("Resource should handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired/edward/22/",
{
headers: {
Accept: "application/json",
},
},
);
const json = await response.json();
assertEquals(
json.message,
"Successfully handled optional path params",
);
assertEquals(json.data.name, "edward");
assertEquals(json.data.age_of_person, "22");
await server.close();
});
});
await t.step("/oppWithRequired/edward/22/other", async (t) => {
await t.step("Resource should NOT handle request", async () => {
server.run();
const response = await TestHelpers.makeRequest.get(
"http://localhost:3000/oppWithRequired/edward/22/other",
{
headers: {
Accept: "application/json",
},
},
);
assertEquals(
(await response.text()).startsWith("Error: Not Found"),
true,
);
await server.close();
});
});
}); | the_stack |
declare namespace Composer {
/**
* List of authors that contributed to the package. This is typically the main maintainers, not the full list.
*/
type Authors = {
/**
* Full name of the author.
*/
name: string
/**
* Email address of the author.
*/
email?: string
/**
* Homepage URL for the author.
*/
homepage?: string
/**
* Author's role in the project.
*/
role?: string
}[]
type Repository =
| ComposerRepository
| VcsRepository
| PathRepository
| ArtifactRepository
| PearRepository
| PackageRepository
interface Composer {
/**
* Package name, including 'vendor-name/' prefix.
*/
name: string
/**
* Package type, either 'library' for common packages, 'composer-plugin' for plugins, 'metapackage' for empty packages, or a custom type ([a-z0-9-]+) defined by whatever project this package applies to.
*/
type?: string
/**
* DEPRECATED: Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.
*/
"target-dir"?: string
/**
* Short package description.
*/
description: string
keywords?: string[]
/**
* Homepage URL for the project.
*/
homepage?: string
/**
* Relative path to the readme document.
*/
readme?: string
/**
* Package version, see https://getcomposer.org/doc/04-schema.md#version for more info on valid schemes.
*/
version?: string
/**
* Package release date, in 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS' or 'YYYY-MM-DDTHH:MM:SSZ' format.
*/
time?: string
/**
* License name. Or an array of license names.
*/
license?: string | unknown[]
authors?: Authors
/**
* This is a hash of package name (keys) and version constraints (values) that are required to run this package.
*/
require?: {
[k: string]: string
}
/**
* This is a hash of package name (keys) and version constraints (values) that can be replaced by this package.
*/
replace?: {
[k: string]: string
}
/**
* This is a hash of package name (keys) and version constraints (values) that conflict with this package.
*/
conflict?: {
[k: string]: string
}
/**
* This is a hash of package name (keys) and version constraints (values) that this package provides in addition to this package's name.
*/
provide?: {
[k: string]: string
}
/**
* This is a hash of package name (keys) and version constraints (values) that this package requires for developing it (testing tools and such).
*/
"require-dev"?: {
[k: string]: string
}
/**
* This is a hash of package name (keys) and descriptions (values) that this package suggests work well with it (this will be suggested to the user during installation).
*/
suggest?: {
[k: string]: string
}
/**
* Composer options.
*/
config?: {
/**
* The timeout in seconds for process executions, defaults to 300 (5mins).
*/
"process-timeout"?: number
/**
* If true, the Composer autoloader will also look for classes in the PHP include path.
*/
"use-include-path"?: boolean
/**
* The install method Composer will prefer to use, defaults to auto and can be any of source, dist, auto, or a hash of {"pattern": "preference"}.
*/
"preferred-install"?:
| string
| {
[k: string]: unknown
}
/**
* Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behaviour, defaults to true.
*/
"notify-on-install"?: boolean
/**
* A list of protocols to use for github.com clones, in priority order, defaults to ["git", "https", "http"].
*/
"github-protocols"?: string[]
/**
* A hash of domain name => github API oauth tokens, typically {"github.com":"<token>"}.
*/
"github-oauth"?: {
[k: string]: string
}
/**
* A hash of domain name => gitlab API oauth tokens, typically {"gitlab.com":"<token>"}.
*/
"gitlab-oauth"?: {
[k: string]: string
}
/**
* A hash of domain name => gitlab private tokens, typically {"gitlab.com":"<token>"}.
*/
"gitlab-token"?: {
[k: string]: string
}
/**
* A hash of domain name => bearer authentication token, for example {"example.com":"<token>"}.
*/
bearer?: {
[k: string]: string
}
/**
* Defaults to `false`. If set to true all HTTPS URLs will be tried with HTTP instead and no network level encryption is performed. Enabling this is a security risk and is NOT recommended. The better way is to enable the php_openssl extension in php.ini.
*/
"disable-tls"?: boolean
/**
* Defaults to `true`. If set to true only HTTPS URLs are allowed to be downloaded via Composer. If you really absolutely need HTTP access to something then you can disable it, but using "Let's Encrypt" to get a free SSL certificate is generally a better alternative.
*/
"secure-http"?: boolean
/**
* A way to set the path to the openssl CA file. In PHP 5.6+ you should rather set this via openssl.cafile in php.ini, although PHP 5.6+ should be able to detect your system CA file automatically.
*/
cafile?: string
/**
* If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.
*/
capath?: string
/**
* A hash of domain name => {"username": "...", "password": "..."}.
*/
"http-basic"?: {
[k: string]: {
/**
* The username used for HTTP Basic authentication
*/
username: string
/**
* The password used for HTTP Basic authentication
*/
password: string
[k: string]: unknown
}
}
/**
* What to do after prompting for authentication, one of: true (store), false (do not store) or "prompt" (ask every time), defaults to prompt.
*/
"store-auths"?: string | boolean
/**
* This is a hash of package name (keys) and version (values) that will be used to mock the platform packages on this machine.
*/
platform?: {
[k: string]: string
}
/**
* The location where all packages are installed, defaults to "vendor".
*/
"vendor-dir"?: string
/**
* The location where all binaries are linked, defaults to "vendor/bin".
*/
"bin-dir"?: string
/**
* The location where old phar files are stored, defaults to "$home" except on XDG Base Directory compliant unixes.
*/
"data-dir"?: string
/**
* The location where all caches are located, defaults to "~/.composer/cache" on *nix and "%LOCALAPPDATA%\Composer" on windows.
*/
"cache-dir"?: string
/**
* The location where files (zip downloads) are cached, defaults to "{$cache-dir}/files".
*/
"cache-files-dir"?: string
/**
* The location where repo (git/hg repo clones) are cached, defaults to "{$cache-dir}/repo".
*/
"cache-repo-dir"?: string
/**
* The location where vcs infos (git clones, github api calls, etc. when reading vcs repos) are cached, defaults to "{$cache-dir}/vcs".
*/
"cache-vcs-dir"?: string
/**
* The default cache time-to-live, defaults to 15552000 (6 months).
*/
"cache-ttl"?: number
/**
* The cache time-to-live for files, defaults to the value of cache-ttl.
*/
"cache-files-ttl"?: number
/**
* The cache max size for the files cache, defaults to "300MiB".
*/
"cache-files-maxsize"?: string | number
/**
* Whether to use the Composer cache in read-only mode.
*/
"cache-read-only"?: boolean
/**
* The compatibility of the binaries, defaults to "auto" (automatically guessed) and can be "full" (compatible with both Windows and Unix-based systems).
*/
"bin-compat"?: "auto" | "full"
/**
* The default style of handling dirty updates, defaults to false and can be any of true, false or "stash".
*/
"discard-changes"?: string | boolean
/**
* Optional string to be used as a suffix for the generated Composer autoloader. When null a random one will be generated.
*/
"autoloader-suffix"?: string
/**
* Always optimize when dumping the autoloader.
*/
"optimize-autoloader"?: boolean
/**
* If false, the composer autoloader will not be prepended to existing autoloaders, defaults to true.
*/
"prepend-autoloader"?: boolean
/**
* If true, the composer autoloader will not scan the filesystem for classes that are not found in the class map, defaults to false.
*/
"classmap-authoritative"?: boolean
/**
* If true, the Composer autoloader will check for APCu and use it to cache found/not-found classes when the extension is enabled, defaults to false.
*/
"apcu-autoloader"?: boolean
/**
* A list of domains to use in github mode. This is used for GitHub Enterprise setups, defaults to ["github.com"].
*/
"github-domains"?: string[]
/**
* Defaults to true. If set to false, the OAuth tokens created to access the github API will have a date instead of the machine hostname.
*/
"github-expose-hostname"?: boolean
/**
* A list of domains to use in gitlab mode. This is used for custom GitLab setups, defaults to ["gitlab.com"].
*/
"gitlab-domains"?: string[]
/**
* Defaults to true. If set to false, globally disables the use of the GitHub API for all GitHub repositories and clones the repository as it would for any other repository.
*/
"use-github-api"?: boolean
/**
* The default archiving format when not provided on cli, defaults to "tar".
*/
"archive-format"?: string
/**
* The default archive path when not provided on cli, defaults to ".".
*/
"archive-dir"?: string
/**
* Defaults to true. If set to false, Composer will not create .htaccess files in the composer home, cache, and data directories.
*/
"htaccess-protect"?: boolean
/**
* Defaults to false. If set to true, Composer will sort packages when adding/updating a new dependency.
*/
"sort-packages"?: boolean
/**
* Defaults to true. If set to false, Composer will not create a composer.lock file.
*/
lock?: boolean
/**
* Defaults to "php-only" which checks only the PHP version. Setting to true will also check the presence of required PHP extensions. If set to false, Composer will not create and require a platform_check.php file as part of the autoloader bootstrap.
*/
"platform-check"?: boolean | string
[k: string]: unknown
}
/**
* Arbitrary extra data that can be used by plugins, for example, package of type composer-plugin may have a 'class' key defining an installer class name.
*/
extra?:
| {
[k: string]: unknown
}
| unknown[]
autoload?: Autoload
/**
* Description of additional autoload rules for development purpose (eg. a test suite).
*/
"autoload-dev"?: {
/**
* This is a hash of namespaces (keys) and the directories they can be found into (values, can be arrays of paths) by the autoloader.
*/
"psr-0"?: {
[k: string]: string[]
}
/**
* This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.
*/
"psr-4"?: {
[k: string]: string[]
}
/**
* This is an array of paths that contain classes to be included in the class-map generation process.
*/
classmap?: unknown[]
/**
* This is an array of files that are always required on every request.
*/
files?: unknown[]
[k: string]: unknown
}
/**
* Options for creating package archives for distribution.
*/
archive?: {
/**
* A base name for archive.
*/
name?: string
/**
* A list of patterns for paths to exclude or include if prefixed with an exclamation mark.
*/
exclude?: unknown[]
[k: string]: unknown
}
/**
* A set of additional repositories where packages can be found.
*/
repositories?: (
| Repository
| {
[k: string]: false
}
)[]
/**
* The minimum stability the packages must have to be install-able. Possible values are: dev, alpha, beta, RC, stable.
*/
"minimum-stability"?: string
/**
* If set to true, stable packages will be preferred to dev packages when possible, even if the minimum-stability allows unstable packages.
*/
"prefer-stable"?: boolean
/**
* A set of files, or a single file, that should be treated as binaries and symlinked into bin-dir (from config).
*/
bin?: string[]
/**
* DEPRECATED: A list of directories which should get added to PHP's include path. This is only present to support legacy projects, and all new code should preferably use autoloading.
*/
"include-path"?: string[]
/**
* Script listeners that will be executed before/after some events.
*/
scripts?: {
/**
* Occurs before the install command is executed, contains one or more Class::method callables or shell commands.
*/
"pre-install-cmd"?: unknown[] | string
/**
* Occurs after the install command is executed, contains one or more Class::method callables or shell commands.
*/
"post-install-cmd"?: unknown[] | string
/**
* Occurs before the update command is executed, contains one or more Class::method callables or shell commands.
*/
"pre-update-cmd"?: unknown[] | string
/**
* Occurs after the update command is executed, contains one or more Class::method callables or shell commands.
*/
"post-update-cmd"?: unknown[] | string
/**
* Occurs before the status command is executed, contains one or more Class::method callables or shell commands.
*/
"pre-status-cmd"?: unknown[] | string
/**
* Occurs after the status command is executed, contains one or more Class::method callables or shell commands.
*/
"post-status-cmd"?: unknown[] | string
/**
* Occurs before a package is installed, contains one or more Class::method callables or shell commands.
*/
"pre-package-install"?: unknown[] | string
/**
* Occurs after a package is installed, contains one or more Class::method callables or shell commands.
*/
"post-package-install"?: unknown[] | string
/**
* Occurs before a package is updated, contains one or more Class::method callables or shell commands.
*/
"pre-package-update"?: unknown[] | string
/**
* Occurs after a package is updated, contains one or more Class::method callables or shell commands.
*/
"post-package-update"?: unknown[] | string
/**
* Occurs before a package has been uninstalled, contains one or more Class::method callables or shell commands.
*/
"pre-package-uninstall"?: unknown[] | string
/**
* Occurs after a package has been uninstalled, contains one or more Class::method callables or shell commands.
*/
"post-package-uninstall"?: unknown[] | string
/**
* Occurs before the autoloader is dumped, contains one or more Class::method callables or shell commands.
*/
"pre-autoload-dump"?: unknown[] | string
/**
* Occurs after the autoloader is dumped, contains one or more Class::method callables or shell commands.
*/
"post-autoload-dump"?: unknown[] | string
/**
* Occurs after the root-package is installed, contains one or more Class::method callables or shell commands.
*/
"post-root-package-install"?: unknown[] | string
/**
* Occurs after the create-project command is executed, contains one or more Class::method callables or shell commands.
*/
"post-create-project-cmd"?: unknown[] | string
[k: string]: unknown
}
/**
* Descriptions for custom commands, shown in console help.
*/
"scripts-descriptions"?: {
[k: string]: string
}
support?: {
/**
* Email address for support.
*/
email?: string
/**
* URL to the issue tracker.
*/
issues?: string
/**
* URL to the forum.
*/
forum?: string
/**
* URL to the wiki.
*/
wiki?: string
/**
* IRC channel for support, as irc://server/channel.
*/
irc?: string
/**
* URL to the support chat.
*/
chat?: string
/**
* URL to browse or download the sources.
*/
source?: string
/**
* URL to the documentation.
*/
docs?: string
/**
* URL to the RSS feed.
*/
rss?: string
[k: string]: unknown
}
/**
* A list of options to fund the development and maintenance of the package.
*/
funding?: {
/**
* Type of funding or platform through which funding is possible.
*/
type?: string
/**
* URL to a website with details on funding and a way to fund the package.
*/
url?: string
[k: string]: unknown
}[]
/**
* A set of string or regex patterns for non-numeric branch names that will not be handled as feature branches.
*/
"non-feature-branches"?: string[]
/**
* Internal use only, do not specify this in composer.json. Indicates whether this version is the default branch of the linked VCS repository. Defaults to false.
*/
"default-branch"?: boolean
/**
* Indicates whether this package has been abandoned, it can be boolean or a package name/URL pointing to a recommended alternative. Defaults to false.
*/
abandoned?: boolean | string
/**
* A key to store comments in
*/
_comment?: unknown[] | string
}
/**
* Description of how the package can be autoloaded.
*/
interface Autoload {
/**
* This is a hash of namespaces (keys) and the directories they can be found in (values, can be arrays of paths) by the autoloader.
*/
"psr-0"?: {
[k: string]: string[]
}
/**
* This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.
*/
"psr-4"?: {
[k: string]: string[]
}
/**
* This is an array of paths that contain classes to be included in the class-map generation process.
*/
classmap?: unknown[]
/**
* This is an array of files that are always required on every request.
*/
files?: unknown[]
/**
* This is an array of patterns to exclude from autoload classmap generation. (e.g. "exclude-from-classmap": ["/test/", "/tests/", "/Tests/"]
*/
"exclude-from-classmap"?: unknown[]
[k: string]: unknown
}
interface ComposerRepository {
type: "composer"
url: string
canonical?: boolean
only?: string[]
exclude?: string[]
options?: {
[k: string]: unknown
}
allow_ssl_downgrade?: boolean
"force-lazy-providers"?: boolean
[k: string]: unknown
}
interface VcsRepository {
type:
| "vcs"
| "github"
| "git"
| "gitlab"
| "git-bitbucket"
| "hg"
| "hg-bitbucket"
| "fossil"
| "perforce"
| "svn"
url: string
canonical?: boolean
only?: string[]
exclude?: string[]
"no-api"?: boolean
"secure-http"?: boolean
"svn-cache-credentials"?: boolean
"trunk-path"?: string | boolean
"branches-path"?: string | boolean
"tags-path"?: string | boolean
"package-path"?: string
depot?: string
branch?: string
unique_perforce_client_name?: string
p4user?: string
p4password?: string
[k: string]: unknown
}
interface PathRepository {
type: "path"
url: string
canonical?: boolean
only?: string[]
exclude?: string[]
options?: {
symlink?: boolean | null
[k: string]: unknown
}
[k: string]: unknown
}
interface ArtifactRepository {
type: "artifact"
url: string
canonical?: boolean
only?: string[]
exclude?: string[]
[k: string]: unknown
}
interface PearRepository {
type: "pear"
url: string
canonical?: boolean
only?: string[]
exclude?: string[]
"vendor-alias"?: string
[k: string]: unknown
}
interface PackageRepository {
type: "package"
canonical?: boolean
only?: string[]
exclude?: string[]
package: InlinePackage | InlinePackage[]
[k: string]: unknown
}
interface InlinePackage {
/**
* Package name, including 'vendor-name/' prefix.
*/
name: string
type?: string
/**
* DEPRECATED: Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.
*/
"target-dir"?: string
description?: string
keywords?: string[]
homepage?: string
version: string
time?: string
license?: string | unknown[]
authors?: Authors
require?: {
[k: string]: string
}
replace?: {
[k: string]: string
}
conflict?: {
[k: string]: string
}
provide?: {
[k: string]: string
}
"require-dev"?: {
[k: string]: string
}
suggest?: {
[k: string]: string
}
extra?:
| {
[k: string]: unknown
}
| unknown[]
autoload?: Autoload
archive?: {
exclude?: unknown[]
[k: string]: unknown
}
/**
* A set of files, or a single file, that should be treated as binaries and symlinked into bin-dir (from config).
*/
bin?: string[]
/**
* DEPRECATED: A list of directories which should get added to PHP's include path. This is only present to support legacy projects, and all new code should preferably use autoloading.
*/
"include-path"?: string[]
source?: {
type: string
url: string
reference: string
mirrors?: unknown[]
[k: string]: unknown
}
dist?: {
type: string
url: string
reference?: string
shasum?: string
mirrors?: unknown[]
[k: string]: unknown
}
[k: string]: unknown
}
} | the_stack |
import { Range } from 'vscode-languageserver';
import
{
computeKey, Condition, DevSkimProblem, DevskimRuleSeverity, Map, AutoFix,
Rule, DevSkimAutoFixEdit, IDevSkimSettings,
} from "./devskimObjects";
import { DevSkimSuppression, DevSkimSuppressionFinding } from "./utility_classes/suppressions";
import { PathOperations } from "./utility_classes/pathOperations";
import { DevSkimWorkerSettings } from "./devskimWorkerSettings";
import { RulesLoader } from "./utility_classes/rulesLoader";
import {DevskimLambdaEngine} from "./devskimLambda";
import {DocumentUtilities} from "./utility_classes/document";
import { DebugLogger } from "./utility_classes/logger";
/**
* The bulk of the DevSkim analysis logic. Orchestrates Loading rules in, implements and exposes functions to run rules across a file
*/
export class DevSkimWorker
{
public dswSettings: DevSkimWorkerSettings = new DevSkimWorkerSettings();
public readonly rulesDirectory: string;
private analysisRules: Rule[];
//codeActions is the object that holds all of the autofix mappings. we need to store them because
//the CodeActions are created at a different point than the diagnostics, yet we still need to be able
//to associate the action with the diagnostic. So we create a mapping between them and look up the fix
//in the map using values out of the diagnostic as a key
//
//We use nested Maps to store the fixes. The key to the first map is the document URI. This maps a
//specific file to a map of the fixes for that file. The key for this second map is created in
//the devskimObjects.ts file, in the function computeKey. the second key is in essence a combination of
//a diagnostic and a string representation of a number for a particular fix, as there may be multiple fixes associated with a single diagnostic
//i.e. we suggest both strlcpy and strcpy_s to fix strcpy
//
//it's format is essentially <document URI <diagnostic + fix#>>. We could instead have done <document <diagnostic <fix#>>>, but three deep
//map seemed a little excessive to me. Then again, I just wrote 3 paragraphs for how this works, so maybe I'm being too clever
public codeActions: Map<Map<AutoFix>> = Object.create(null);
/**
* Instantiate the DevSkim Worker
* @param logger a logger object, to decide where messages should be written (console, remote console, nowhere, etc)
* @param dsSuppressions an existing suppressions object to hold information about suppressed findings
* @param settings the settings analysis should run under (can be updated post instantiate with UpdateSettings method)
*/
constructor(private logger: DebugLogger, private dsSuppressions: DevSkimSuppression, settings: IDevSkimSettings = DevSkimWorkerSettings.defaultSettings())
{
this.rulesDirectory = DevSkimWorkerSettings.getRulesDirectory(logger);
this.dswSettings.setSettings(settings);
this.dsSuppressions.dsSettings = settings;
}
/**
* Call whenever the user updates their settings in the IDE, to ensure that the worker is using the most up to date
* version of the user's settings
* @param settings the current settings to update
*/
public UpdateSettings(settings : IDevSkimSettings)
{
this.dswSettings.setSettings(settings);
this.dsSuppressions.dsSettings = settings;
}
/**
* Must be called before analysis is effective. Loads the rules from the file system
*/
public async init(): Promise<void>
{
await this.loadRules();
}
/**
* Look for problems in the provided text. For the IDE includeSuppressions should be true so that users see details
* about what rule was suppressed in a suppression comment. When called from teh CLI the value should be false, so that
* it doesn't get included in the output
*
* @param {string} documentContents the contents of a file to analyze
* @param {string} langID the programming language for the file
* @param {string} documentURI the URI identifying the file
* @param {boolean} includeSuppressions true if the resulting problems should include information squiggles for the ruleID listed in a suppression comment
* @returns {DevSkimProblem[]} an array of all of the issues found in the text
*/
public analyzeText(documentContents: string, langID: string, documentURI: string, includeSuppressions : boolean = true): DevSkimProblem[]
{
let problems: DevSkimProblem[] = [];
//Before we do any processing, see if the file (or its directory) are in the ignore list. If so
//skip doing any analysis on the file
if (this.analysisRules && this.analysisRules.length
&& this.dswSettings && this.dswSettings.getSettings().ignoreFiles
&& !PathOperations.ignoreFile(documentURI, this.dswSettings.getSettings().ignoreFiles)
&& documentContents.length < this.dswSettings.getSettings().maxFileSizeKB * 1024)
{
//find out what issues are in the current document
problems = this.runAnalysis(documentContents, langID, documentURI, includeSuppressions);
//remove any findings from rules that have been overridden by other rules
problems = this.processOverrides(problems);
}
return problems;
}
/**
* Save a codeAction for a particular auto-fix to the codeActions map, so that it can be looked up when onCodeAction is called
* and actually communicated to the VSCode engine. Since creating a diagnostic and assigning a code action happen at different points
* its important to be able to look up what code actions should be populated at a given time
*
* @param {string} documentURI the path to the document, identifying it
* @param {number} documentVersion the current revision of the document (vs code calculates this)
* @param range @ToDo: update this document
* @param {string | number} diagnosticCode the diagnostic a fix is associated with
* @param {DevSkimAutoFixEdit} fix the actual data about the fix being applied (location, name, action, etc.)
* @param {string} ruleID an identifier for the rule that was triggered
* @returns {void}
*/
public recordCodeAction(documentURI: string, documentVersion: number, range: Range, diagnosticCode: string | number, fix: DevSkimAutoFixEdit, ruleID: string): void
{
if (!fix || !ruleID)
{
return;
}
let fixName: string = (fix.fixName !== undefined && fix.fixName.length > 0) ? fix.fixName : `Fix this ${ruleID} problem`;
let edits: Map<AutoFix> = this.codeActions[documentURI];
if (!edits)
{
edits = Object.create(null);
this.codeActions[documentURI] = edits;
}
let x = 0;
//figure out how many existing fixes are associated with a given diagnostic by checking if it exists, and incrementing until it doesn't
while (edits[computeKey(range, diagnosticCode) + x.toString(10)])
{
x++;
}
//create a new mapping, using as the key the diagnostic the fix is associated with and a number representing whether this is the 1st fix
//to associate with that diagnostic, 2nd, 3rd, and so on. This lets us map multiple fixes to one diagnostic while providing an easy way
//to iterate. we could have instead made this a three nested map <file<diagnostic<fix#>>> but this achieves the same thing
edits[computeKey(range, diagnosticCode) + x.toString(10)] =
{
label: fixName,
documentVersion: documentVersion,
ruleId: ruleID,
edit: fix,
};
}
/**
* Reload the rules from the file system. Since this right now is just a proxy for loadRules this *could* have been achieved by
* exposing loadRules as public. I chose not to, as eventually it might make sense here to check if an analysis is actively running
* and hold off until it is complete. I don't forsee that being an issue when analyzing an individual file (it's fast enough a race condition
* should exist with reloading rules), but might be if doing a full analysis of a lot of files. So in anticipation of that, I broke this
* into its own function so such a check could be added.
*/
public async refreshAnalysisRules(): Promise<void>
{
return this.loadRules();
}
/**
* Return the collection of rules currently loaded into the analysis engine
*/
public retrieveLoadedRules() : Rule[]
{
return this.analysisRules;
}
/**
* recursively load all of the JSON files in the $userhome/.vscode/extensions/vscode-devskim/rules sub directories
*
* @private
*/
private async loadRules(): Promise<void>
{
const loader = new RulesLoader(this.logger, true, this.rulesDirectory);
const rules = await loader.loadRules();
this.analysisRules = await loader.validateRules(rules)
}
/**
* Best practice and Manual Review severity rules may be turned on and off via a setting
* prior to running an analysis, verify that the rule is enabled based on its severity and the user settings
*
* @public
* @param {DevskimRuleSeverity} ruleSeverity the severity of the current rule
* @returns {boolean} true if it should be processed (its either a high severity or the severity is enabled in settings)
*
* @memberOf DevSkimWorker
*/
public RuleSeverityEnabled(ruleSeverity: DevskimRuleSeverity): boolean
{
return ruleSeverity == DevskimRuleSeverity.Critical ||
ruleSeverity == DevskimRuleSeverity.Important ||
ruleSeverity == DevskimRuleSeverity.Moderate ||
(ruleSeverity == DevskimRuleSeverity.BestPractice &&
this.dswSettings.getSettings().enableBestPracticeRules == true) ||
(ruleSeverity == DevskimRuleSeverity.ManualReview &&
this.dswSettings.getSettings().enableManualReviewRules == true) ||
(ruleSeverity == DevskimRuleSeverity.WarningInfo &&
this.dswSettings.getSettings().enableSuppressionInfo == true);
}
/**
* maps the string for severity received from the rules into the enum (there is inconsistencies with the case used
* in the rules, so this is case incentive). We convert to the enum as we do comparisons in a number of places
* and by using an enum we can get a transpiler error if we remove/change a label
*
* @public
* @param {string} severity the text severity from the rules JSON
* @returns {DevskimRuleSeverity} the enum used in code for the severity, corresponding to the text
*
* @memberOf DevSkimWorker
*/
public static MapRuleSeverity(severity: string): DevskimRuleSeverity
{
switch (severity.toLowerCase())
{
case "critical":
return DevskimRuleSeverity.Critical;
case "important":
return DevskimRuleSeverity.Important;
case "moderate":
return DevskimRuleSeverity.Moderate;
case "best-practice":
return DevskimRuleSeverity.BestPractice;
case "manual-review":
return DevskimRuleSeverity.ManualReview;
default:
return DevskimRuleSeverity.BestPractice;
}
}
/**
* the pattern type governs how we form the regex. regex-word is wrapped in \b, string is as well, but is also escaped.
* substring is not wrapped in \b, but is escaped, and regex/the default behavior is a vanilla regular expression
* @param {string} regexType regex|regex-word|string|substring
* @param {string} pattern the regex pattern from the Rules JSON
* @param {string[]} modifiers modifiers to use when creating regex. can be null. a value of "d" will be ignored if forXregExp is false
* @param {boolean} forXregExp whether this is for the XRegExp regex engine (true) or the vanilla javascript regex engine (false)
*/
public static MakeRegex(regexType: string, pattern: string, modifiers: string[], forXregExp: boolean): RegExp
{
//create any regex modifiers
let regexModifier = "";
if (modifiers != undefined && modifiers)
{
for (let mod of modifiers)
{
//xregexp implemented dotmatchall as s instead of d
if (mod == "d")
{
//also, Javascript doesn't support dotmatchall natively, so only use this if it will be used with XRegExp
if (forXregExp)
{
regexModifier = regexModifier + "s";
}
}
else
{
regexModifier = regexModifier + mod;
}
}
}
//now create a regex based on the
let XRegExp = require('xregexp');
switch (regexType.toLowerCase())
{
case 'regex-word':
return XRegExp('\\b' + pattern + '\\b', regexModifier);
case 'string':
return XRegExp('\\b' + XRegExp.escape(pattern) + '\\b', regexModifier);
case 'substring':
return XRegExp(XRegExp.escape(pattern), regexModifier);
default:
return XRegExp(pattern, regexModifier);
}
}
/**
* Perform the actual analysis of the text, using the provided rules
*
* @param {string} documentContents the full text to analyze
* @param {string} langID the programming language for the text
* @param {string} documentURI URI identifying the document
* @param {boolean} includeSuppressions true if the resulting problems should include information squiggles for the ruleID listed in a suppression comment
* @returns {DevSkimProblem[]} all of the issues identified in the analysis
*/
private runAnalysis(documentContents: string, langID: string, documentURI: string, includeSuppressions : boolean = true): DevSkimProblem[]
{
let problems: DevSkimProblem[] = [];
let XRegExp = require('xregexp');
//iterate over all of the rules, and then all of the patterns within a rule looking for a match.
for (let rule of this.analysisRules)
{
const ruleSeverity: DevskimRuleSeverity = DevSkimWorker.MapRuleSeverity(rule.severity);
//if the rule doesn't apply to whatever language we are analyzing (C++, Java, etc.) or we aren't processing
//that particular severity skip the rest
if (this.dswSettings.getSettings().ignoreRulesList.indexOf(rule.id) == -1 && /*check to see if this is a rule the user asked to ignore */
DevSkimWorker.appliesToLangOrFile(langID, rule.applies_to, rule.does_not_apply_to, documentURI) &&
this.RuleSeverityEnabled(ruleSeverity))
{
for (let patternIndex = 0; patternIndex < rule.patterns.length; patternIndex++)
{
let modifiers: string[] = (rule.patterns[patternIndex].modifiers != undefined && rule.patterns[patternIndex].modifiers.length > 0) ?
rule.patterns[patternIndex].modifiers.concat(["g"]) : ["g"];
const matchPattern: RegExp = DevSkimWorker.MakeRegex(rule.patterns[patternIndex].type, rule.patterns[patternIndex].pattern, modifiers, true);
//go through all of the text looking for a match with the given pattern
let matchPosition = 0;
let match = XRegExp.exec(documentContents, matchPattern, matchPosition);
while (match)
{
//if the rule doesn't contain any conditions, set it to an empty array to make logic later easier
if (!rule.conditions)
{
rule.conditions = [];
}
//check to see if this finding has either been suppressed or reviewed (for manual-review rules)
//the suppressionFinding object contains a flag if the finding has been suppressed as well as
//range info for the ruleID in the suppression text so that hover text can be added describing
//the finding that was suppress
let suppressionFinding: DevSkimSuppressionFinding = DevSkimSuppression.isFindingCommented(match.index, documentContents, rule.id,langID, (ruleSeverity == DevskimRuleSeverity.ManualReview));
//calculate what line we are on by grabbing the text before the match & counting the newlines in it
let lineStart: number = DocumentUtilities.GetLineNumber(documentContents, match.index);
let newlineIndex: number = (lineStart == 0) ? -1 : documentContents.substr(0, match.index).lastIndexOf("\n");
let columnStart: number = match.index - newlineIndex - 1;
//since a match may span lines (someone who broke a long function invocation into multiple lines for example)
//it's necessary to see if there are any newlines WITHIN the match so that we get the line the match ends on,
//not just the line it starts on. Also, we use the substring for the match later when making fixes
let replacementSource: string = documentContents.substr(match.index, match[0].length);
let lineEnd: number = DocumentUtilities.GetLineNumber(replacementSource, replacementSource.length) + lineStart;
let columnEnd = (lineStart == lineEnd) ?
columnStart + match[0].length :
match[0].length - documentContents.substr(match.index).indexOf("\n") - 1;
let range: Range = Range.create(lineStart, columnStart, lineEnd, columnEnd);
// Is this *not* a suppression finding (a real issue)
if (!suppressionFinding.showSuppressionFinding)
{
if (DocumentUtilities.MatchIsInScope(langID, documentContents.substr(0, match.index), newlineIndex, rule.patterns[patternIndex].scopes))
{
if (DevSkimWorker.MatchesConditions(rule.conditions, documentContents, range, langID))
{
let snippet = [];
for (let i=Math.max(0, lineStart - 2); i<=lineEnd + 2; i++)
{
const snippetLine = DocumentUtilities.GetLine(documentContents, i);
snippet.push(snippetLine.substr(0, 80));
}
//add in any fixes
let problem: DevSkimProblem = this.MakeProblem(rule, DevSkimWorker.MapRuleSeverity(rule.severity), range, snippet.join('\n'));
problem.fixes = problem.fixes.concat(DevSkimWorker.MakeFixes(rule, replacementSource, range));
problem.fixes = problem.fixes.concat(this.dsSuppressions.createActions(rule.id, documentContents, match.index, lineStart, langID, ruleSeverity));
problem.filePath = documentURI;
problems.push(problem);
}
}
}
//throw a pop up if there is a review/suppression comment with the rule id, so that people can figure out what was
//suppressed/reviewed
else {
if (!suppressionFinding.noRange && includeSuppressions && this.RuleSeverityEnabled(DevskimRuleSeverity.WarningInfo))
{
//highlight suppression finding for context
//this will look
let problem: DevSkimProblem = this.MakeProblem(rule, DevskimRuleSeverity.WarningInfo, suppressionFinding.suppressionRange,"", range);
problems.push(problem);
}
}
//advance the location we are searching in the line
matchPosition = match.index + match[0].length;
match = XRegExp.exec(documentContents, matchPattern, matchPosition);
}
}
}
}
return problems;
}
/**
* There are two conditions where this function gets called. The first is to mark the code a rule triggered on and
* in that case the rule, the severity of that rule, and the range of code for a specific finding found by that rule are
* passed in. suppressedFindingRange is ignored
*
* The second instance is when decorating the ruleID in a suppression or review comment. e.g.:
* //DevSkim ignore: DS123456 or //DevSkim reviewed:DS123456
* DevSkim will create a problem to mark the DS123456 so that when moused over so other people looking through the code
* know what was suppressed or reviewed. In this instance we still pass in the rule. a Rule severity of warningInfo should
* be passed in for warningLevel. problemRange should be the range of the "DSXXXXXX" text that should get the information squiggle
* and suppressedFindingRange should be the range of the finding that was suppressed or reviewed by the comment. This last
* is important, as we need to save that info for later to cover overrides that also should be suppressed
* @param {Rule} rule the DevSkim rule that triggered on the problem
* @param {DevskimRuleSeverity} warningLevel Error/Warning/Informational, corresponding to the IDE squiggle UI
* @param {Range} problemRange the area that should get a squiggle added in the IDE
* @param {string} snippet the text code snippet being flagged
* @param {Range} [suppressedFindingRange] (optional) when creating a suppression squiggle, it gets a special range signifier
*/
public MakeProblem(rule: Rule, warningLevel: DevskimRuleSeverity, problemRange: Range, snippet: string, suppressedFindingRange?: Range): DevSkimProblem
{
let problem: DevSkimProblem = new DevSkimProblem(rule.description, rule.name,
rule.id, warningLevel, rule.recommendation, rule.ruleInfo, problemRange, snippet);
if (suppressedFindingRange)
{
problem.suppressedFindingRange = suppressedFindingRange;
}
if (rule.overrides && rule.overrides.length > 0)
{
problem.overrides = rule.overrides;
}
return problem;
}
/**
* Check if all of the conditions within a rule are met. Called after the initial pattern finds an issue
*
* @param {Condition[]} conditions the array of conditions for the rule that triggered
* @param {string} documentContents the document we are currently looking through
* @param {Range} findingRange the span of text for the current finding
* @param {string} langID the language we are working in
*/
public static MatchesConditions(conditions: Condition[], documentContents: string, findingRange: Range, langID: string): boolean
{
if (conditions != undefined && conditions && conditions.length != 0)
{
for (let condition of conditions)
{
//i know this looks weird - there is an object called pattern, nested inside another object called
//pattern. Sorry, that was poor naming convention
if(condition.pattern != undefined && condition.pattern && condition.pattern.pattern != undefined &&
condition.pattern.pattern && condition.pattern.pattern.length > 0)
{
if(!DevSkimWorker.MatchesConditionPattern(condition, documentContents, findingRange, langID))
{
return false;
}
}
else if(condition.lambda != undefined && condition.lambda && condition.lambda.lambda_code != undefined &&
condition.lambda.lambda_code && condition.lambda.lambda_code.length > 0)
{
let lambdaWorker : DevskimLambdaEngine = new DevskimLambdaEngine(condition, documentContents, findingRange, langID);
return lambdaWorker.ExecuteLambda();
}
}
}
return true;
}
/**
* Check to see if a RegEx powered condition is met or not
*
* @param {Condition} condition the condition objects we are checking for
* @param {string} documentContents the document we are finding the conditions in
* @param {Range} findingRange the location of the finding we are looking for more conditions around
* @param {string} langID the language we are working in
*/
public static MatchesConditionPattern(condition: Condition, documentContents: string, findingRange: Range, langID: string): boolean
{
let regionRegex: RegExp = /finding-region\s*\((-*\d+),\s*(-*\d+)\s*\)/;
let XRegExp = require('xregexp');
if (condition.negate_finding == undefined)
{
condition.negate_finding = false;
}
let modifiers: string[] = (condition.pattern.modifiers != undefined && condition.pattern.modifiers.length > 0) ?
condition.pattern.modifiers.concat(["g"]) : ["g"];
let conditionRegex: RegExp = DevSkimWorker.MakeRegex(condition.pattern.type, condition.pattern.pattern, modifiers, true);
let startPos: number = findingRange.start.line;
let endPos: number = findingRange.end.line;
//calculate where to look for the condition. finding-only is just within the actual finding the original pattern flagged.
//finding-region(#,#) specifies an area around the finding. A 0 for # means the line of the finding, negative values mean
//that many lines prior to the finding, and positive values mean that many line later in the code
if (condition.search_in == undefined || condition.search_in.length == 0)
{
startPos = DocumentUtilities.GetDocumentPosition(documentContents, findingRange.start.line);
endPos = DocumentUtilities.GetDocumentPosition(documentContents, findingRange.end.line + 1);
}
else if (condition.search_in == "finding-only")
{
startPos = DocumentUtilities.GetDocumentPosition(documentContents, findingRange.start.line) + findingRange.start.character;
endPos = DocumentUtilities.GetDocumentPosition(documentContents, findingRange.end.line) + findingRange.end.character;
}
else
{
let regionMatch = XRegExp.exec(condition.search_in, regionRegex);
if (regionMatch && regionMatch.length > 2)
{
startPos = DocumentUtilities.GetDocumentPosition(documentContents, findingRange.start.line + +regionMatch[1]);
endPos = DocumentUtilities.GetDocumentPosition(documentContents, findingRange.end.line + +regionMatch[2] + 1);
}
}
//go through all of the text looking for a match with the given pattern
let subContents = documentContents.substring(startPos,endPos);
let match = XRegExp.exec(subContents, conditionRegex, 0);
while (match)
{
//calculate what line we are on by grabbing the text before the match & counting the newlines in it
let lineStart: number = DocumentUtilities.GetLineNumber(documentContents, match.index);
let newlineIndex: number = (lineStart == 0) ? -1 : documentContents.substr(0, match.index).lastIndexOf("\n");
//look for the suppression comment for that finding
if (DocumentUtilities.MatchIsInScope(langID, documentContents.substr(0, match.index), newlineIndex, condition.pattern.scopes))
{
return condition.negate_finding ? false : true;
}
match = XRegExp.exec(subContents.substr(match.index + match[0].length), conditionRegex, 0);
}
return condition.negate_finding ? true : false;
}
/**
* Create an array of fixes from the rule and the vulnerable part of the file being scanned
*
* @private
* @param {Rule} rule the rule that triggered the issue
* @param {string} replacementSource the text that should be replaced by the fixit
* @param {Range} range the range in the document that should be swapped out by the fixit
* @returns {DevSkimAutoFixEdit[]}
*
* @memberOf DevSkimWorker
*/
public static MakeFixes(rule: Rule, replacementSource: string, range: Range): DevSkimAutoFixEdit[]
{
const fixes: DevSkimAutoFixEdit[] = [];
//if there are any fixes, add them to the fix collection so they can be used in code fix commands
if (rule.fix_its !== undefined && rule.fix_its.length > 0)
{
//recordCodeAction below acts like a stack, putting the most recently added rule first.
//Since the very first fix in the rule is usually the preferred one (when there are multiples)
//we want it to be first in the fixes collection, so we go through in reverse order
for (let fixIndex = rule.fix_its.length - 1; fixIndex >= 0; fixIndex--)
{
let fix: DevSkimAutoFixEdit = Object.create(null);
let replacePattern = DevSkimWorker.MakeRegex(rule.fix_its[fixIndex].pattern.type,
rule.fix_its[fixIndex].pattern.pattern, rule.fix_its[fixIndex].pattern.modifiers, false);
try
{
fix.text = replacementSource.replace(replacePattern, rule.fix_its[fixIndex].replacement);
fix.fixName = "DevSkim: " + rule.fix_its[fixIndex].name;
fix.range = range;
fixes.push(fix);
}
catch (e)
{
//console.log(e);
}
}
}
return fixes;
}
/**
* Removes any findings from the problems array corresponding to rules that were overridden by other rules
* for example, both the Java specific MD5 rule and the generic MD5 rule will trigger on the same usage of MD5
* in Java. We should only report the Java specific finding, as it supersedes the generic rule
*
* @private
* @param {DevSkimProblem[]} problems array of findings
* @returns {DevSkimProblem[]} findings with any overridden findings removed
*/
private processOverrides(problems: DevSkimProblem[]): DevSkimProblem[]
{
let overrideRemoved = false;
for (let problem of problems)
{
//if this problem overrides other ones, THEN do the processing
if (problem.overrides.length > 0)
{
//one rule can override multiple other rules, so create a regex of all
//of the overrides so we can search all at once - i.e. override1|override2|override3
let regexString: string = problem.overrides[0];
for (let x = 1; x < problem.overrides.length; x++)
{
regexString = regexString + "|" + problem.overrides[x];
}
//now search all of the existing findings for matches on both the regex, and the line of code
//there is some assumption that both will be on the same line, and it *might* be possible that they
//aren't BUT we can't blanket say remove all instances of the overridden finding, because it might flag
//issues the rule that supersedes it does not
let x = 0;
while ( x < problems.length )
{
let matches = problems[x].ruleId.match(regexString);
let range: Range = (problem.suppressedFindingRange != null) ? problem.suppressedFindingRange : problem.range;
if ((matches !== undefined && matches != null && matches.length > 0)
&& problems[x].range.start.line == range.start.line &&
(problems[x].range.start.character <= range.end.character && /* Range overlap algorithm */
range.start.character <= problems[x].range.end.character))
{
problems.splice(x, 1);
overrideRemoved = true;
}
else
{
x++;
}
}
//clear the overrides so we don't process them on subsequent recursive calls to this
//function
problem.overrides = []
}
}
// I hate recursion - it gives me perf concerns, but because we are modifying the
//array that we are iterating over we can't trust that we don't terminate earlier than
//desired (because the length is going down while the iterator is going up), so run
//until we don't modify anymore. To make things from getting too ugly, we do clear a
//problem's overrides after we processed them, so we don't run it again in
//recursive calls
if (overrideRemoved)
{
return this.processOverrides(problems)
}
else
{
return problems;
}
}
/**
* compares the languageID against all of the languages listed in the applies_to array to check
* for a match. If it matches, then the rule/pattern applies to the language being analyzed.
*
* Also checks to see if applies_to has the specific file name for the current file
*
* Absent any value in applies_to we assume it applies to everything so return true
*
* @param {string} languageID the vscode languageID for the current document
* @param {string[]} applies_to the array of languages a rule/pattern applies to
* @param {string} documentURI the current document URI
* @returns {boolean} true if it applies, false if it doesn't
*/
public static appliesToLangOrFile(languageID: string, applies_to: string[], does_not_apply_to: string[], documentURI: string): boolean
{
var pass = false;
//if the parameters are empty, assume it applies. Also, apply all the rules to plaintext documents
if (applies_to != undefined && applies_to && applies_to.length > 0)
{
for (let applies of applies_to)
{
//if the list of languages this rule applies to matches the current lang ID
if (languageID !== undefined && languageID != null && languageID.toLowerCase() == applies.toLowerCase())
{
pass = true;
}
else if (applies.indexOf(".") != -1 /*applies to is probably a specific file name instead of a langID*/
&& documentURI.toLowerCase().indexOf(applies.toLowerCase()) != -1) /*and its in the current doc URI*/
{
pass = true;
}
if (pass){
break;
}
}
}
else
{
pass = true;
}
if (pass = true)
{
if (does_not_apply_to != undefined && does_not_apply_to && does_not_apply_to.length > 0)
{
for (let does_not_apply of does_not_apply_to)
{
//if the list of languages this rule applies to matches the current lang ID
if (languageID !== undefined && languageID != null && languageID.toLowerCase() == does_not_apply.toLowerCase())
{
pass = false;
}
else if (does_not_apply.indexOf(".") != -1 /*applies to is probably a specific file name instead of a langID*/
&& documentURI.toLowerCase().indexOf(does_not_apply.toLowerCase()) != -1) /*and its in the current doc URI*/
{
pass = false;
}
if (!pass){
break;
}
}
}
}
return pass;
}
} | the_stack |
import { EventEmitter } from 'events';
import { isAddress, toChecksumAddress } from 'web3-utils';
import { addHexPrefix, bufferToHex } from 'ethereumjs-util';
import Safe from '@rabby-wallet/gnosis-sdk';
import {
SafeTransaction,
SafeTransactionDataPartial,
} from '@gnosis.pm/safe-core-sdk-types';
import {
isTxHashSignedWithPrefix,
adjustVInSignature,
} from '@rabby-wallet/gnosis-sdk/dist/utils';
import EthSignSignature from '@gnosis.pm/safe-core-sdk/dist/src/utils/signatures/SafeSignature';
export const keyringType = 'Gnosis';
export const TransactionBuiltEvent = 'TransactionBuilt';
export const TransactionConfirmedEvent = 'TransactionConfirmed';
export const TransactionReadyForExecEvent = 'TransactionReadyForExec';
interface SignTransactionOptions {
signatures: string[];
provider: any;
}
interface DeserializeOption {
accounts?: string[];
networkIdMap?: Record<string, string>;
}
function sanitizeHex(hex: string): string {
hex = hex.substring(0, 2) === '0x' ? hex.substring(2) : hex;
if (hex === '') {
return '';
}
hex = hex.length % 2 !== 0 ? '0' + hex : hex;
return '0x' + hex;
}
class GnosisKeyring extends EventEmitter {
static type = keyringType;
type = keyringType;
accounts: string[] = [];
accountToAdd: string | null = null;
networkIdMap: Record<string, string> = {};
currentTransaction: SafeTransaction | null = null;
currentTransactionHash: string | null = null;
onExecedTransaction: ((hash: string) => void) | null = null;
safeInstance: Safe | null = null;
constructor(options: DeserializeOption = {}) {
super();
this.deserialize(options);
}
deserialize(opts: DeserializeOption) {
if (opts.accounts) {
this.accounts = opts.accounts;
}
if (opts.networkIdMap) {
this.networkIdMap = opts.networkIdMap;
}
// filter address which dont have networkId in cache
this.accounts = this.accounts.filter(
(account) => account.toLowerCase() in this.networkIdMap
);
}
serialize() {
return Promise.resolve({
accounts: this.accounts,
networkIdMap: this.networkIdMap,
});
}
setNetworkId = (address: string, networkId: string) => {
this.networkIdMap = {
...this.networkIdMap,
[address.toLowerCase()]: networkId,
};
};
setAccountToAdd = (account: string) => {
this.accountToAdd = account;
};
async getAccounts() {
return this.accounts;
}
async getTransactionHash() {
if (this.currentTransactionHash) return this.currentTransactionHash;
if (!this.safeInstance || !this.currentTransaction) return;
const safe = this.safeInstance;
const hash = await safe.getTransactionHash(this.currentTransaction);
this.currentTransactionHash = hash;
return hash;
}
addAccounts = async () => {
if (!this.accountToAdd) throw new Error('There is no address to add');
if (!isAddress(this.accountToAdd)) {
throw new Error("The address you're are trying to import is invalid");
}
const prefixedAddress = addHexPrefix(this.accountToAdd);
if (
this.accounts.find(
(acct) => acct.toLowerCase() === prefixedAddress.toLowerCase()
)
) {
throw new Error("The address you're are trying to import is duplicate");
}
this.accounts.push(prefixedAddress);
return [prefixedAddress];
};
removeAccount(address: string): void {
this.accounts = this.accounts.filter(
(account) => account.toLowerCase() !== address.toLowerCase()
);
}
async confirmTransaction({
safeAddress,
transaction,
networkId,
provider,
}: {
safeAddress: string;
transaction: SafeTransaction | null;
networkId: string;
provider?: any;
}) {
let isCurrent = false; // Confirming a stash transaction or not
if (!transaction) {
transaction = this.currentTransaction!;
isCurrent = true;
}
if (!transaction) throw new Error('No avaliable transaction');
const checksumAddress = toChecksumAddress(safeAddress);
let safe = this.safeInstance;
if (!isCurrent) {
const safeInfo = await Safe.getSafeInfo(checksumAddress, networkId);
safe = new Safe(checksumAddress, safeInfo.version, provider, networkId);
}
await safe!.confirmTransaction(transaction);
const threshold = await safe!.getThreshold();
this.emit(TransactionConfirmedEvent, {
safeAddress,
data: {
signatures: Array.from(transaction.signatures.values()).map((item) => ({
data: item.data,
signer: item.signer,
})),
threshold,
},
});
}
async addConfirmation(address: string, signature: string) {
if (!this.currentTransaction || !this.safeInstance) {
throw new Error('No transaction in Gnosis keyring');
}
const safe = this.safeInstance;
this.addSignature(address, signature);
const hash = await this.getTransactionHash();
const sig = this.currentTransaction.signatures.get(address.toLowerCase());
if (sig) {
await safe.request.confirmTransaction(hash, { signature: sig.data });
}
}
async addPureSignature(address: string, signature: string) {
if (!this.currentTransaction || !this.safeInstance) {
throw new Error('No transaction in Gnosis keyring');
}
const sig = new EthSignSignature(address, signature);
this.currentTransaction.addSignature(sig);
}
async addSignature(address: string, signature: string) {
if (!this.currentTransaction || !this.safeInstance) {
throw new Error('No transaction in Gnosis keyring');
}
const hash = await this.getTransactionHash();
const hasPrefix = isTxHashSignedWithPrefix(hash, signature, address);
signature = adjustVInSignature(signature, hasPrefix);
const sig = new EthSignSignature(address, signature);
this.currentTransaction.addSignature(sig);
}
async getOwners(address: string, version: string, provider) {
const networkId = this.networkIdMap[address.toLowerCase()];
if (!networkId) {
throw new Error(`No networkId in keyring for address ${address}`);
}
const safe = new Safe(address, version, provider, networkId);
const owners = await safe.getOwners();
return owners;
}
async execTransaction({
safeAddress,
transaction,
networkId,
provider,
}: {
safeAddress: string;
transaction: SafeTransaction | null;
networkId: string;
provider: any;
}) {
let isCurrent = false; // Confirming a stash transaction or not
if (!transaction) {
transaction = this.currentTransaction!;
isCurrent = true;
}
if (!transaction) throw new Error('No avaliable transaction');
const checksumAddress = toChecksumAddress(safeAddress);
let safe = this.safeInstance;
if (!isCurrent) {
const safeInfo = await Safe.getSafeInfo(checksumAddress, networkId);
safe = new Safe(checksumAddress, safeInfo.version, provider, networkId);
}
const result = await safe!.executeTransaction(transaction);
this.onExecedTransaction && this.onExecedTransaction(result.hash);
return result.hash;
}
async postTransaction() {
const safe = this.safeInstance;
const safeTransaction = this.currentTransaction;
if (!safe || !safeTransaction) return;
const transactionHash = await safe.getTransactionHash(safeTransaction);
try {
await safe.postTransaction(safeTransaction, transactionHash);
} catch (e) {
let errMsg = 'Post transaction to Gnosis Server failed';
if (e?.response?.data) {
const keys = Object.keys(e.response.data);
if (Array.isArray(e.response.data[keys[0]])) {
errMsg = e.response.data[keys[0]][0];
}
} else {
errMsg = e.message;
}
throw new Error(errMsg);
}
}
async buildTransaction(
address: string,
transaction: SafeTransactionDataPartial,
provider
) {
if (
!this.accounts.find(
(account) => account.toLowerCase() === address.toLowerCase()
)
) {
throw new Error('Can not find this address');
}
const checksumAddress = toChecksumAddress(address);
const tx = {
data: transaction.data,
from: address,
to: this._normalize(transaction.to),
value: this._normalize(transaction.value) || '0x0', // prevent 0x
safeTxGas: transaction.safeTxGas,
nonce: transaction.nonce ? Number(transaction.nonce) : undefined,
baseGas: transaction.baseGas,
operation: transaction.operation,
};
const networkId = this.networkIdMap[address.toLowerCase()];
const safeInfo = await Safe.getSafeInfo(checksumAddress, networkId);
const safe = new Safe(
checksumAddress,
safeInfo.version,
provider,
networkId
);
this.safeInstance = safe;
const safeTransaction = await safe.buildTransaction(tx);
this.currentTransaction = safeTransaction;
this.currentTransactionHash = await safe.getTransactionHash(
safeTransaction
);
return safeTransaction;
}
async signTransaction(
address: string,
transaction,
opts: SignTransactionOptions
) {
// eslint-disable-next-line no-async-promise-executor
if (
!this.accounts.find(
(account) => account.toLowerCase() === address.toLowerCase()
)
) {
throw new Error('Can not find this address');
}
let safeTransaction: SafeTransaction;
let transactionHash: string;
const networkId = this.networkIdMap[address.toLowerCase()];
const checksumAddress = toChecksumAddress(address);
const safeInfo = await Safe.getSafeInfo(checksumAddress, networkId);
const safe = new Safe(
checksumAddress,
safeInfo.version,
opts.provider,
networkId
);
if (this.currentTransaction) {
safeTransaction = this.currentTransaction;
transactionHash = await this.getTransactionHash();
} else {
const tx = {
data: this._normalize(transaction.data) || '0x',
from: address,
to: this._normalize(transaction.to),
value: this._normalize(transaction.value) || '0x0', // prevent 0x
};
safeTransaction = await safe.buildTransaction(tx);
this.currentTransaction = safeTransaction;
transactionHash = await this.getTransactionHash();
}
await safe.signTransaction(safeTransaction);
this.safeInstance = safe;
this.emit(TransactionBuiltEvent, {
safeAddress: address,
data: {
hash: transactionHash,
},
});
}
signTypedData() {
throw new Error('Gnosis address not support signTypedData');
}
signPersonalMessage() {
throw new Error('Gnosis address not support signPersonalMessage');
}
_normalize(buf) {
return sanitizeHex(bufferToHex(buf).toString());
}
}
export default GnosisKeyring; | the_stack |
import type { ContextInterface } from '@textile/context'
import {
privateKeyBytesToString,
publicKeyBytesToString,
} from '@textile/crypto'
import { GrpcConnection } from '@textile/grpc-connection'
import * as pb from '@textile/hub-grpc/api/hubd/pb/hubd_pb'
import { APIService } from '@textile/hub-grpc/api/hubd/pb/hubd_pb_service'
import log from 'loglevel'
const logger = log.getLogger('admin-api')
export interface SigninOrSignupResponse {
key: string
session: string
}
/**
* Creates a new user (if username is available) and returns a session.
* @param username The desired username.
* @param email The user's email address.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @note This method will block and wait for email-based verification.
* @internal
*/
export async function signUp(
api: GrpcConnection,
username: string,
email: string,
ctx?: ContextInterface,
): Promise<SigninOrSignupResponse> {
logger.debug('signup request')
const req = new pb.SignupRequest()
req.setEmail(email)
req.setUsername(username)
const res: pb.SignupResponse = await api.unary(APIService.Signup, req, ctx)
return {
key: publicKeyBytesToString(res.getKey_asU8()),
session: res.getSession(),
}
}
/**
* Returns a session for an existing username or email.
* @param usernameOrEmail An existing username or email address.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @note This method will block and wait for email-based verification.
* @internal
*/
export async function signIn(
api: GrpcConnection,
usernameOrEmail: string,
ctx?: ContextInterface,
): Promise<SigninOrSignupResponse> {
logger.debug('signin request')
const req = new pb.SigninRequest()
req.setUsernameOrEmail(usernameOrEmail)
const res: pb.SigninResponse = await api.unary(APIService.Signin, req, ctx)
return {
key: publicKeyBytesToString(res.getKey_asU8()),
session: res.getSession(),
}
}
/**
* Deletes the current session.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function signOut(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('signout request')
const req = new pb.SignoutRequest()
await api.unary(APIService.Signout, req, ctx)
return
}
export interface SessionInfoResponse {
key: string
username: string
email: string
}
/**
* Returns the current session information.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function getSessionInfo(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<SessionInfoResponse> {
logger.debug('get session info request')
const req = new pb.GetSessionInfoRequest()
const res: pb.GetSessionInfoResponse = await api.unary(
APIService.GetSessionInfo,
req,
ctx,
)
return {
key: publicKeyBytesToString(res.getKey_asU8()),
username: res.getUsername(),
email: res.getEmail(),
}
}
/**
* Returns the identity (public key string) of the current session.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function getIdentity(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<string> {
logger.debug('get identity request')
const req = new pb.GetIdentityRequest()
const res: pb.GetIdentityResponse = await api.unary(
APIService.GetIdentity,
req,
ctx,
)
return privateKeyBytesToString(res.getIdentity_asU8())
}
export enum KeyType {
UNSPECIFIED = 0,
ACCOUNT = 1,
USER = 2,
}
export interface KeyInfo {
key: string
secret: string
type: KeyType
valid: boolean
threads: number
secure: boolean
}
/**
* Creates a new key for the current session.
* @param type The key type, should be one of `USER`, `ACCOUNT`, `UNSPECIFIED`.
* @param secure Whether the key should be flagged as secure. Defaults to true.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function createKey(
api: GrpcConnection,
type: KeyType = KeyType.UNSPECIFIED,
secure = true,
ctx?: ContextInterface,
): Promise<KeyInfo> {
logger.debug('create key request')
const req = new pb.CreateKeyRequest()
req.setType(type)
req.setSecure(secure)
const res: pb.CreateKeyResponse = await api.unary(
APIService.CreateKey,
req,
ctx,
)
const { keyInfo } = res.toObject()
if (keyInfo === undefined) throw new Error('error creating key')
return keyInfo
}
/**
* Marks a key as invalid.
* @param key The session key to invalidate.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @note New Threads cannot be created with an invalid key.
* @internal
*/
export async function invalidateKey(
api: GrpcConnection,
key: string,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('invalidate key request')
const req = new pb.InvalidateKeyRequest()
req.setKey(key)
await api.unary(APIService.InvalidateKey, req, ctx)
return
}
/**
* Returns a list of keys for the current session.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function listKeys(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<Array<KeyInfo>> {
logger.debug('list keys request')
const req = new pb.ListKeysRequest()
const res: pb.ListKeysResponse = await api.unary(
APIService.ListKeys,
req,
ctx,
)
return res.getListList().map((key) => key.toObject())
}
export interface OrgMember {
key: string
username: string
role: string
}
export interface OrgInfo {
key: string
name: string
slug: string
host: string
members: Array<OrgMember>
createdAt: number
}
const pbToOrgInfo = (orgInfo?: pb.OrgInfo): OrgInfo => {
if (orgInfo === undefined) throw new Error('error getting org info')
const members = orgInfo.getMembersList().map((res) => {
return {
role: res.getRole(),
key: publicKeyBytesToString(res.getKey_asU8()),
username: res.getUsername(),
}
})
return {
key: publicKeyBytesToString(orgInfo.getKey_asU8()),
name: orgInfo.getName(),
slug: orgInfo.getSlug(),
host: orgInfo.getHost(),
members,
createdAt: orgInfo.getCreatedAt(),
}
}
/**
* Creates a new org (if name is available) by name.
* @param name The desired org name.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function createOrg(
api: GrpcConnection,
name: string,
ctx?: ContextInterface,
): Promise<OrgInfo> {
logger.debug('create org request')
const req = new pb.CreateOrgRequest()
req.setName(name)
const res: pb.CreateOrgResponse = await api.unary(
APIService.CreateOrg,
req,
ctx,
)
return pbToOrgInfo(res.getOrgInfo())
}
/**
* Returns the current org.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function getOrg(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<OrgInfo> {
logger.debug('get org request')
const req = new pb.GetOrgRequest()
const res: pb.GetOrgResponse = await api.unary(APIService.GetOrg, req, ctx)
return pbToOrgInfo(res.getOrgInfo())
}
/**
* Returns a list of orgs for the current session.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function listOrgs(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<Array<OrgInfo>> {
logger.debug('list orgs request')
const req = new pb.ListOrgsRequest()
const res: pb.ListOrgsResponse = await api.unary(
APIService.ListOrgs,
req,
ctx,
)
return res.getListList().map(pbToOrgInfo)
}
/**
* Removes the current org.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function removeOrg(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('remove org request')
const req = new pb.RemoveOrgRequest()
await api.unary(APIService.RemoveOrg, req, ctx)
return
}
/**
* Invites the given email to an org.
* @param email The email to add to an org.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function inviteToOrg(
api: GrpcConnection,
email: string,
ctx?: ContextInterface,
): Promise<string> {
logger.debug('invite to org request')
const req = new pb.InviteToOrgRequest()
req.setEmail(email)
const res: pb.InviteToOrgResponse = await api.unary(
APIService.InviteToOrg,
req,
ctx,
)
return res.getToken()
}
/**
* Removes the current session dev from an org.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function leaveOrg(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('leave org request')
const req = new pb.LeaveOrgRequest()
await api.unary(APIService.LeaveOrg, req, ctx)
return
}
/**
* (Re-)enables billing for an account, enabling usage beyond the free quotas.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function setupBilling(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('setup billing request')
const req = new pb.SetupBillingRequest()
await api.unary(APIService.SetupBilling, req, ctx)
return
}
/**
* Returns a billing portal session url.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function getBillingSession(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<string> {
logger.debug('get billing session request')
const req = new pb.GetBillingSessionRequest()
const res: pb.GetBillingSessionResponse = await api.unary(
APIService.GetBillingSession,
req,
ctx,
)
return res.getUrl()
}
export interface Usage {
description: string
units: number
total: number
free: number
grace: number
cost: number
period?: Period
}
export interface Period {
unixStart: number
unixEnd: number
}
export interface Customer {
// TODO: Have to properly unmarshall this object rather than use toObject
key: string
customerId: string
parentKey: string
email: string
accountType: number
accountStatus: string
subscriptionStatus: string
balance: number
billable: boolean
delinquent: boolean
createdAt: number
gracePeriodEnd: number
invoicePeriod?: Period
dailyUsageMap: Array<[string, Usage]>
dependents: number
}
/**
* Returns a list of users the account is responsible for.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function listBillingUsers(
api: GrpcConnection,
offset = 0,
limit = 0,
ctx?: ContextInterface,
): Promise<Array<Customer>> {
logger.debug('list billing users request')
const req = new pb.ListBillingUsersRequest()
req.setOffset(offset)
req.setLimit(limit)
const res: pb.ListBillingUsersResponse = await api.unary(
APIService.ListBillingUsers,
req,
ctx,
)
return res.getUsersList().map((user) => user.toObject())
}
/**
* Returns whether the username is valid and available.
* @param username The desired username.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function isUsernameAvailable(
api: GrpcConnection,
username: string,
ctx?: ContextInterface,
): Promise<boolean> {
logger.debug('is username available request')
const req = new pb.IsUsernameAvailableRequest()
req.setUsername(username)
return api
.unary(APIService.IsUsernameAvailable, req, ctx)
.then(() => true)
.catch(() => false)
}
export interface IsOrgNameAvailableResponse {
slug: string
host: string
}
/**
* Returns whether the org name is valid and available.
* @param name The desired org name.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @internal
*/
export async function isOrgNameAvailable(
api: GrpcConnection,
name: string,
ctx?: ContextInterface,
): Promise<IsOrgNameAvailableResponse> {
logger.debug('is org name available request')
const req = new pb.IsOrgNameAvailableRequest()
req.setName(name)
const res: pb.IsOrgNameAvailableResponse = await api.unary(
APIService.IsOrgNameAvailable,
req,
ctx,
)
return res.toObject()
}
/**
* Completely deletes an account and all associated data.
* @param ctx Context containing gRPC headers and settings.
* These will be merged with any internal ctx.
* @note Danger!!
* @internal
*/
export async function destroyAccount(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('destroy account request')
const req = new pb.DestroyAccountRequest()
await api.unary(APIService.DestroyAccount, req, ctx)
return
} | the_stack |
import * as React from 'react';
import { interval, Subscription } from 'rxjs';
import { cloneDeep } from 'lodash';
// Services
import { Injector } from '@angular/core';
import { Location } from '@angular/common';
import { ImportsService } from '../../resources/imports/imports.service';
import { AuthService } from '../../auth/auth.service';
import { PFBodyService } from '../../resources/pf-body/pf-body.service';
// Types
import { ContentFormat } from '../../enums/format';
import { PulpStatus, ImportState } from '../../enums/import-state.enum';
import { ImportList, ImporterMessage } from '../../resources/imports/import';
import { Namespace } from '../../resources/namespaces/namespace';
import { ImportMetadata } from '../shared-types/my-imports';
// Components
import { ImportListComponent } from '../components/my-imports/import-list';
import { PageHeader } from '../components/page-header';
import { ImportConsoleComponent } from '../components/my-imports/import-console';
import { ParamHelper } from '../lib/param-helper';
interface IProps {
injector: Injector;
namespaces: Namespace[];
queryParams: any;
selectedNamespace?: number;
importList?: any;
}
interface IState {
selectedNS: Namespace;
queryParams: any;
importList: ImportList[];
selectedImport: ImportList;
taskMessages: ImporterMessage[];
followMessages: boolean;
importMetadata: ImportMetadata;
noImportsExist: boolean;
resultsCount: number;
}
export class MyImportsPage extends React.Component<IProps, IState> {
importsService: ImportsService;
authService: AuthService;
location: Location;
polling: Subscription;
PFBody: PFBodyService;
constructor(props) {
super(props);
// The state of the page is mostly loaded by a series of API calls that
// need to happen in a sequential order, so we'll initialize the state
// as null and then load each piece as it comes in through the API.
// This page basically requires three pieces of information:
// - the tasks to display in the terminal, which we can't load until
// the list of imports is loaded
// - the list of imports, which can't be loaded until the namespace is
// picked
// - the namespace, which can't be loaded until the list of the user's
// namespaces is available
this.state = {
selectedNS: null,
importList: null,
selectedImport: null,
taskMessages: null,
followMessages: false,
importMetadata: {} as ImportMetadata,
noImportsExist: false,
queryParams: this.props.queryParams,
resultsCount: 0,
};
}
componentDidMount() {
this.importsService = this.props.injector.get(ImportsService);
this.authService = this.props.injector.get(AuthService);
this.location = this.props.injector.get(Location);
this.PFBody = this.props.injector.get(PFBodyService);
this.polling = interval(2000).subscribe(() => {
if (
this.state.importMetadata.state === PulpStatus.running ||
this.state.importMetadata.state === PulpStatus.waiting
) {
this.poll();
}
});
this.loadSelectedNS();
}
render() {
return (
<div className='my-imports-wrapper'>
<PageHeader
headerTitle='My Imports'
headerIcon='fa fa-upload'
/>
<div className='row'>
<div className='col-sm-4'>
<ImportListComponent
namespaces={this.props.namespaces}
selectedNS={this.state.selectedNS}
importList={this.state.importList}
selectedImport={this.state.selectedImport}
selectImport={x => this.selectImportDetail(x)}
selectNamespace={ns => this.selectedNamespace(ns)}
noImportsExist={this.state.noImportsExist}
queryParams={this.state.queryParams}
numberOfResults={this.state.resultsCount}
setQueryParams={x => this.SetQueryParams(x)}
/>
</div>
<div className='col-sm-8'>
<ImportConsoleComponent
taskMessages={this.state.taskMessages}
followMessages={this.state.followMessages}
selectedImport={this.state.selectedImport}
importMetadata={this.state.importMetadata}
noImportsExist={this.state.noImportsExist}
setFollowMessages={x => this.setFollowMessages(x)}
/>
</div>
</div>
</div>
);
}
setState(newState, callback?) {
// Update the page's URL if the queryParams or namespace state changes
super.setState(newState, callback);
if (newState.queryParams || newState.selectedNS) {
const params = newState.queryParams || this.state.queryParams;
const ns = newState.selectedNS || this.state.selectedNS;
this.location.replaceState(
`my-imports/${ns.id}`,
ParamHelper.getQueryString(params),
);
}
}
componentWillUnmount() {
if (this.polling) {
this.polling.unsubscribe();
}
}
private poll() {
this.loadTaskMessages(() => {
// Update the state of the selected import in the list if it's
// different from the one loaded from the API.
if (
this.state.selectedImport.state !==
this.state.importMetadata.state
) {
const importIndex = this.state.importList.findIndex(
x =>
x.id === this.state.selectedImport.id &&
x.type === this.state.selectedImport.type,
);
const imports = cloneDeep(this.state.importList);
const selectedImport = cloneDeep(this.state.selectedImport);
imports[importIndex].state = this.state.importMetadata.state;
imports[
importIndex
].finished_at = this.state.importMetadata.finished_date;
selectedImport.state = this.state.importMetadata.state;
selectedImport.finished_at = this.state.importMetadata.finished_date;
this.setState({
selectedImport: selectedImport,
importList: imports,
});
}
});
}
private SetQueryParams(params) {
this.setState(
{ queryParams: params, importList: null, noImportsExist: false },
() => this.loadImportList(true),
);
}
private setFollowMessages(follow) {
this.setState({ followMessages: follow });
}
private loadSelectedNS() {
if (this.props.selectedNamespace) {
const selectedNS = this.props.namespaces.find(
x => x.id === this.props.selectedNamespace,
);
this.setState({ selectedNS: selectedNS }, () =>
this.loadImportList(),
);
} else {
this.authService.me().subscribe(me => {
// If no namespace is defined by the route, load whichever one
// matches the user's username.
let selectedNS = this.props.namespaces.find(
x => x.name === me.username,
);
// If no match is found, just use the first namespace in the
// list
if (selectedNS === undefined) {
selectedNS = this.props.namespaces[0];
}
this.setState({ selectedNS: selectedNS }, () =>
this.loadImportList(),
);
});
}
}
private loadImportList(forceLoad = false) {
// If the namespace has been pre loaded via URL params then it gets
// passed to this component via props and we don't have to load it from
// the API
if (this.props.importList && !forceLoad) {
this.setState(
{
selectedImport: this.props.importList.results[0],
importList: this.props.importList.results,
resultsCount: this.props.importList.count,
},
() => this.loadTaskMessages(),
);
} else {
this.importsService
.get_import_list(
this.state.selectedNS.id,
this.state.queryParams,
)
.subscribe(importList => {
this.setState(
{
importList: importList.results,
selectedImport: importList.results[0],
resultsCount: importList.count,
},
() => this.loadTaskMessages(),
);
});
}
}
private loadTaskMessages(callback?: () => void) {
if (!this.state.selectedImport) {
this.setState({ noImportsExist: true });
} else if (
this.state.selectedImport.type === ContentFormat.collection
) {
this.importsService
.get_collection_import(this.state.selectedImport.id)
.subscribe(result => {
this.setState(
{
noImportsExist: false,
taskMessages: result.messages,
importMetadata: {
version: result.version,
error: result.error
? result.error.description
: null,
state: result.state,
} as ImportMetadata,
},
callback,
);
});
} else if (
this.state.selectedImport.type === ContentFormat.repository
) {
// Map repo import messages so that they look like collection
// messages
this.importsService
.get_repo_import(this.state.selectedImport.id)
.subscribe(result => {
this.setState(
{
taskMessages: result.summary_fields.task_messages.map(
el => {
return {
level: el.message_type,
message: el.message_text,
time: '',
};
},
),
importMetadata: {
state: this.mapStates(result.state),
branch: result.import_branch,
commit_message: result.commit_message,
travis_build_url: result.travis_build_url,
travis_status_url: result.travis_status_url,
} as ImportMetadata,
},
callback,
);
});
}
}
private mapStates(state) {
switch (state) {
case ImportState.pending:
return PulpStatus.running;
case ImportState.running:
return PulpStatus.running;
case ImportState.failed:
return PulpStatus.failed;
case ImportState.success:
return PulpStatus.completed;
}
}
private selectImportDetail(item: ImportList) {
this.PFBody.scrollToTop();
this.setState(
{
selectedImport: item,
taskMessages: null,
importMetadata: {} as ImportMetadata,
followMessages: false,
},
() => this.loadTaskMessages(),
);
}
private selectedNamespace(nsID: number) {
// For some reason the value passed back by the react component isn't
// a number
// tslint:disable-next-line:triple-equals
const ns = this.props.namespaces.find(x => x.id == nsID);
this.setState(
{
selectedNS: ns,
importList: null,
noImportsExist: false,
},
() => this.loadImportList(true),
);
}
} | the_stack |
import SlidingWindow from "swstats";
import { Logger } from "tslog";
import {
getArbitrageOpportunitiesByState,
setArbitrageOpportunityState,
isArbitrageOpportunityApproachingTradingStart,
extractTradingPairs,
TradingPairs,
swapCurrency,
PairBases,
sell,
buy,
convertBaseToBusd,
} from "./arbitrage.service";
import { LeanDocument } from "mongoose";
import { Arbitrage } from "./schemas/arbitrage.schema";
import { calculateServertimeDrift } from "../timesync/timesync.controller";
import { generateMarketsFromArbitrageOpportunities, setupBinanceMarket } from "./exchange.service";
import { binance } from "ccxt.pro";
import type { Order, Balances } from "ccxt";
const ARB_SLIDING_WINDOW_DURATION = +process.env.ARB_SLIDING_WINDOW_DURATION || 50;
const log: Logger = new Logger();
export const waitForTradingStartDate = async (): Promise<void | LeanDocument<Arbitrage>[]> => {
const availableArbitrageOpportunities = await getArbitrageOpportunitiesByState("waitingForArbitrage");
console.log(availableArbitrageOpportunities);
if (availableArbitrageOpportunities.length === 0) {
// log.debug("found no arbitrage opportunities");
return Promise.resolve();
}
return Promise.all(
availableArbitrageOpportunities
.filter((arbitrageOpportunity) => {
return isArbitrageOpportunityApproachingTradingStart(arbitrageOpportunity);
})
.map(async (arbitrageOpportunity) => {
log.debug(`${arbitrageOpportunity._id} is ready for abritrage`);
return setArbitrageOpportunityState(arbitrageOpportunity._id, "readyForArbitrage");
})
);
};
export const initiateTrade = async (): Promise<void> => {
const availableArbitrageOpportunities = await getArbitrageOpportunitiesByState("readyForArbitrage");
if (availableArbitrageOpportunities.length === 0) {
return Promise.resolve();
}
await Promise.all(
availableArbitrageOpportunities.map(async (arbitrageOpportunity) => {
return setArbitrageOpportunityState(arbitrageOpportunity._id, "inArbitrage");
})
);
availableArbitrageOpportunities.map(async (arbitrageOpportunity) => {
const tradingPairs = extractTradingPairs(arbitrageOpportunity);
log.debug("extrated trading pairs:");
log.debug(tradingPairs);
return prepareForArbing(arbitrageOpportunity._id, arbitrageOpportunity.tokenCode, tradingPairs);
});
};
const prepareForArbing = async (arbitrageId: string, tokenCode: string, tradingPairs: TradingPairs): Promise<void> => {
const exchange = setupBinanceMarket();
await exchange.loadMarkets();
try {
await bringBackToBUSD(exchange, tradingPairs);
await spreadOutToAllBasePairs(exchange, tradingPairs);
await arbTokens(arbitrageId, tokenCode, tradingPairs);
} catch (error) {
log.trace(error);
await bringBackToBUSD(exchange, tradingPairs);
}
};
function isOrder(orderResult: Order | void): orderResult is Order {
return (orderResult as Order)?.remaining !== undefined;
}
const arbTokens = async (arbitrageId: string, tokenCode: string, tradingPairs: TradingPairs): Promise<void> => {
log.debug(tokenCode);
log.debug(tradingPairs);
const currentArbitrageOpportunities = await getArbitrageOpportunitiesByState("inArbitrage");
if (currentArbitrageOpportunities.length === 0) {
return Promise.resolve();
}
const markets = await generateMarketsFromArbitrageOpportunities(currentArbitrageOpportunities);
const exchange = setupBinanceMarket(markets);
let sellLock = false;
let firstTrade = true;
let lockStatus = "none" as "none" | "bucket" | "first" | "initialBuy";
let balances = await exchange.fetchBalance();
log.debug("Measuring server latency...");
const serverTimeDrift = await calculateServertimeDrift();
log.debug(serverTimeDrift);
log.debug(`Fetching crypto prices from binance...`);
const btcUsdBuyPrice = await (await exchange.fetchTicker("BTC/BUSD")).ask;
const ethUsdBuyPrice = await (await exchange.fetchTicker("ETH/BUSD")).ask;
const bnbUsdBuyPrice = await (await exchange.fetchTicker("BNB/BUSD")).ask;
log.debug(`Waiting for events from Binance Websocket...`);
const timeBuckets = {};
Object.keys(tradingPairs).map((tradingPairBase: PairBases) => {
timeBuckets[tradingPairBase] = new SlidingWindow.TimeStats(10000, {
step: ARB_SLIDING_WINDOW_DURATION,
ops: ["avg"],
});
});
let bucketEndTime;
let consecutiveArbMisses = 0;
await Promise.all(
Object.keys(tradingPairs).map((tradingPairBase: PairBases) =>
(async () => {
const tradingPair = tradingPairs[tradingPairBase];
while (!sellLock) {
try {
const newTrades = await exchange.watchTrades(tradingPair);
newTrades.forEach(async (trade) => {
// log.debug(`new trade, lock is ${lockStatus}`);
if (sellLock) {
// log.debug(`returning, sell lock is ${sellLock}`);
return;
}
if (!trade?.price || !trade?.timestamp) {
// log.debug(
// `returning, trade price is ${trade?.price} , timestamp is ${trade?.timestamp}`
// );
return;
}
timeBuckets[tradingPairBase].push(trade.price);
if (firstTrade) {
// log.debug(`it's the first trade`);
lockStatus = "initialBuy";
firstTrade = false;
bucketEndTime = trade.timestamp + 1900;
purchaseFromAllAvailablePairs(exchange, balances, tradingPairs).then(() => {
exchange.fetchBalance().then((newBalances) => {
balances = newBalances;
lockStatus = "first";
});
});
}
if (trade.timestamp >= bucketEndTime && lockStatus === "first") {
// This is the first trade we will execute. We have an initial balance originating from the first buy, and just want to sell that.
// Force closing of arb for the $beta launch
await closeArbPosition(tradingPairs, arbitrageId, exchange);
return;
lockStatus = "bucket";
const bucketValues = calculateBucketValue(timeBuckets, tradingPairs, {
btc: btcUsdBuyPrice,
eth: ethUsdBuyPrice,
bnb: bnbUsdBuyPrice,
busd: 1,
usdt: 1,
});
const sortedBuckets = Object.keys(tradingPairs)
.map((tradingPairBase: PairBases) => {
return tradingPairs[tradingPairBase];
})
.slice()
.sort((a, b) => {
return bucketValues[b] - bucketValues[a]; // sort descending
});
// log.debug(JSON.stringify(sortedBuckets));
// log.debug(JSON.stringify(bucketValues));
const delta = Math.abs(
bucketValues[sortedBuckets[0].split("/")[1].toLowerCase()] -
bucketValues[
sortedBuckets[sortedBuckets.length - 1].split("/")[1].toLowerCase()
]
);
// log.debug(`Inspecting bucket ${sortedBuckets[0].split("/")[1].toLowerCase()}`);
// log.debug(`Current bucket delta: ${delta}`);
// log.debug(
// `Current bucket value: ${
// bucketValues[sortedBuckets[0].split("/")[1].toLowerCase()]
// }`
// );
const bucketPercentageSpread =
(delta / bucketValues[sortedBuckets[0].split("/")[1].toLowerCase()]) * 100;
// log.debug(`Current bucket percentage spread: ${bucketPercentageSpread}`);
if (bucketPercentageSpread < 0.1) {
// log.warn(`${consecutiveArbMisses} consecutive arb misses`);
consecutiveArbMisses++;
}
// Sell the most expensive pair
const tokenBalance = balances[tokenCode].free;
// log.debug(`Selling ${tokenBalance} worth of ${sortedBuckets[0]}`);
await sell(sortedBuckets[0], tokenBalance, exchange);
balances = await exchange.fetchBalance();
bucketEndTime = trade.timestamp + ARB_SLIDING_WINDOW_DURATION;
lockStatus = "none";
}
if (trade.timestamp >= bucketEndTime && lockStatus === "none") {
// This is any subsequent trade. We will have a 0 balance initially, and will go and perform a swap if it's favorable to do so.
// log.debug(
// `Bucket end time: ${bucketEndTime}, trade timestamp: ${trade.timestamp}, lockstatus: ${lockStatus}`
// );
lockStatus = "bucket";
const bucketValues = calculateBucketValue(timeBuckets, tradingPairs, {
btc: btcUsdBuyPrice,
eth: ethUsdBuyPrice,
bnb: bnbUsdBuyPrice,
busd: 1,
usdt: 1,
});
const sortedBuckets = Object.keys(tradingPairs)
.map((tradingPairBase: PairBases) => {
return tradingPairs[tradingPairBase];
})
.slice()
.sort((a, b) => {
return bucketValues[b] - bucketValues[a]; // sort descending
});
// log.debug(JSON.stringify(sortedBuckets));
// log.debug(JSON.stringify(bucketValues));
const delta = Math.abs(
bucketValues[sortedBuckets[0].split("/")[1].toLowerCase()] -
bucketValues[
sortedBuckets[sortedBuckets.length - 1].split("/")[1].toLowerCase()
]
);
// log.debug(`Inspecting bucket ${sortedBuckets[0].split("/")[1].toLowerCase()}`);
// log.debug(`Current bucket delta: ${delta}`);
// log.debug(
// `Current bucket value: ${
// bucketValues[sortedBuckets[0].split("/")[1].toLowerCase()]
// }`
// );
const bucketPercentageSpread =
(delta / bucketValues[sortedBuckets[0].split("/")[1].toLowerCase()]) * 100;
// log.debug(`Current bucket percentage spread: ${bucketPercentageSpread}`);
if (bucketPercentageSpread < 2) {
// log.warn(`${consecutiveArbMisses} consecutive arb misses`);
consecutiveArbMisses++;
}
balances = await exchange.fetchBalance();
if (consecutiveArbMisses > 5) {
log.debug(`Ending arbitrage due to 5 consecutive misses`);
sellLock = true;
await closeArbPosition(tradingPairs, arbitrageId, exchange);
return;
}
// Swap to che base unit of the cheapest pair
const counterBalance = balances[sortedBuckets[0].split("/")[1]].free;
// log.debug(
// `Swapping ${sortedBuckets[0].split("/")[1]} for ${
// sortedBuckets[sortedBuckets.length - 1].split("/")[1]
// }`
// );
const swapOrder = await swapCurrency(
sortedBuckets[0].split("/")[1].toLowerCase() as PairBases,
sortedBuckets[sortedBuckets.length - 1].split("/")[1].toLowerCase() as PairBases,
counterBalance,
exchange
);
if (isOrder(swapOrder)) {
// log.info(`Remaining: ${swapOrder.remaining}`);
// log.info(`Filled: ${swapOrder.filled}`);
}
balances = await exchange.fetchBalance();
// Buy the cheapest pair
const lowcostCounterBalance =
balances[sortedBuckets[sortedBuckets.length - 1].split("/")[1]].free;
// log.debug(
// `Buying ${lowcostCounterBalance} worth of ${
// sortedBuckets[sortedBuckets.length - 1]
// }`
// );
await buy(sortedBuckets[sortedBuckets.length - 1], lowcostCounterBalance, exchange);
balances = await exchange.fetchBalance();
// Sell the most expensive pair
const tokenBalance = balances[tokenCode].free;
// log.debug(`Selling ${tokenBalance} worth of ${sortedBuckets[0]}`);
await sell(sortedBuckets[0], tokenBalance, exchange);
bucketEndTime = trade.timestamp + ARB_SLIDING_WINDOW_DURATION;
lockStatus = "none";
}
});
} catch (e) {
log.error(tradingPair, e);
// do nothing and retry on next loop iteration
}
}
})()
)
);
log.debug("Arb process complete");
return Promise.resolve();
};
export const purchaseFromAllAvailablePairs = async (
exchange: binance,
balances: Balances,
tradingPairs: TradingPairs
): Promise<Order[]> => {
await exchange.loadMarkets(true); // attempt to reload markets so we can purchase. This might cause a blocking condition, so not sure.
return Promise.all(
Object.keys(tradingPairs).map((tradingPairBase: PairBases) => {
const tradingPair = tradingPairs[tradingPairBase];
log.debug(tradingPair);
const availableBalance = balances[tradingPair.split("/")[1].toUpperCase()].free;
log.info(JSON.stringify(balances[tradingPair.split("/")[1].toUpperCase()]));
return buy(tradingPair, availableBalance, exchange);
})
);
};
const spreadOutToAllBasePairs = async (exchange: binance, tradingPairs: TradingPairs): Promise<(void | Order)[]> => {
const balances = await exchange.fetchBalance();
const availableBusd = balances["BUSD"].free;
const UsdValueForPair = Math.floor(availableBusd / Object.keys(tradingPairs).length) - 1; //Magic number so we attempt to not run into cases where we try to buy more than we have due to usdt/busd/ustc price differences
log.debug(`Keys available for tradingpairs are: ${Object.keys(tradingPairs)}`);
return Promise.all(
Object.keys(tradingPairs).map((tradingPairBase: PairBases) => {
return swapCurrency("busd", tradingPairBase, UsdValueForPair, exchange);
})
);
};
const bringBackToBUSD = async (exchange: binance, tradingPairs: TradingPairs): Promise<(void | Order)[]> => {
const balances = await exchange.fetchBalance();
return Promise.all(
Object.keys(tradingPairs).map(async (tradingPairBase: PairBases) => {
const availableBaseAmount = balances.free[tradingPairBase.toUpperCase()];
const BusdAmount = await convertBaseToBusd(tradingPairBase, availableBaseAmount, exchange);
try {
return await swapCurrency(tradingPairBase, "busd", BusdAmount, exchange);
} catch (error) {
log.debug(`failed processing ${availableBaseAmount} worth of ${tradingPairBase}`);
log.trace(error);
}
})
);
};
export type TimeBuckets = Record<Partial<PairBases>, number>;
export const calculateBucketValue = (
timeBucket: { [x: string]: { stats: { avg: number } } },
tradingPairs: TradingPairs,
prices: { btc?: number; eth?: number; bnb?: number; busd?: number; usdt?: number }
): TimeBuckets => {
const pairs = Object.keys(tradingPairs);
const hashmap = {} as TimeBuckets;
pairs.forEach((pairbase: PairBases) => {
hashmap[pairbase] = timeBucket[pairbase].stats.avg * prices[pairbase];
});
return hashmap;
};
const closeArbPosition = async (tradingPairs: TradingPairs, arbitrageId: string, exchange: binance) => {
log.debug(`Concluding arb}`);
await bringBackToBUSD(exchange, tradingPairs);
await setArbitrageOpportunityState(arbitrageId, "soldOnBinance");
}; | the_stack |
declare module 'typescript-project-services/lib/compilerManager' {
import ts = require('typescript');
import fs = require('typescript-project-services/lib/fileSystem');
import promise = require('typescript-project-services/lib/promise');
export type TypeScriptInfo = {
path: string;
typeScript: typeof ts;
libLocation: string;
documentRegistry: ts.DocumentRegistry;
};
export function init(fs: fs.IFileSystem, libLocation: string): void;
export function getDefaultTypeScriptInfo(): TypeScriptInfo;
export function acquireCompiler(typescriptPath: string): promise.Promise<TypeScriptInfo>;
export function releaseCompiler(typeScriptInfo: TypeScriptInfo): void;
}
declare module 'typescript-project-services/lib/fileSystem' {
import promise = require('typescript-project-services/lib/promise');
import utils = require('typescript-project-services/lib/utils');
import ISignal = utils.ISignal;
/**
* A simple wrapper over brackets filesystem that provide simple function and
* typed watcher
*/
export interface IFileSystem {
/**
* return a promise resolving to the project root folder path
*/
getProjectRoot(): promise.Promise<string>;
/**
* a signal dispatching fine grained change reflecting the change that happens in the working set
*/
projectFilesChanged: ISignal<FileChangeRecord[]>;
/**
* return a promise that resolve with an array of string containing all the files of the projects
*/
getProjectFiles(): promise.Promise<string[]>;
/**
* read a file, return a promise with that resolve to the file content
*
* @param path the file to read
*/
readFile(path: string): promise.Promise<string>;
}
/**
* enum representing the kind change possible in the fileSysem
*/
export const enum FileChangeKind {
/**
* a file has been added
*/
ADD = 0,
/**
* a file has been updated
*/
UPDATE = 1,
/**
* a file has been deleted
*/
DELETE = 2,
/**
* the project files has been reset
*/
RESET = 3,
}
/**
* FileSystem change descriptor
*/
export type FileChangeRecord = {
/**
* kind of change
*/
kind: FileChangeKind;
/**
* name of the file that have changed
*/
fileName: string;
};
}
declare module 'typescript-project-services/lib/languageServiceHost' {
import ts = require('typescript');
interface LanguageServiceHost extends ts.LanguageServiceHost {
/**
* add a script to the host
*
* @param fileName the absolute path of the file
* @param content the file content
*/
addScript(fileName: string, content: string): void;
/**
* remove a script from the host
*
* @param fileName the absolute path of the file
*/
removeScript(fileName: string): void;
/**
* remove all script from the host
*
* @param fileName the absolute path of the file
*/
removeAll(): void;
/**
* update a script
*
* @param fileName the absolute path of the file
* @param content the new file content
*/
updateScript(fileName: string, content: string): void;
/**
* edit a script
*
* @param fileName the absolute path of the file
* @param minChar the index in the file content where the edition begins
* @param limChar the index in the file content where the edition ends
* @param newText the text inserted
*/
editScript(fileName: string, minChar: number, limChar: number, newText: string): void;
/**
* set 'open' status of a script
*
* @param fileName the absolute path of the file
* @param isOpen open status
*/
setScriptIsOpen(fileName: string, isOpen: boolean): void;
/**
* the the language service host compilation settings
*
* @param the settings to be applied to the host
*/
setCompilationSettings(settings: ts.CompilerOptions): void;
/**
* retrieve the content of a given script
*
* @param fileName the absolute path of the file
*/
getScriptContent(fileName: string): string;
/**
* return an index from a positon in line/char
*
* @param path the path of the file
* @param position the position
*/
getIndexFromPosition(fileName: string, position: {
ch: number;
line: number;
}): number;
/**
* return a positon in line/char from an index
*
* @param path the path of the file
* @param index the index
*/
getPositionFromIndex(fileName: string, index: number): {
ch: number;
line: number;
};
} module LanguageServiceHost {
function create(baseDir: string, defaultLibFileName: string): LanguageServiceHost;
}
export = LanguageServiceHost;
}
declare module 'typescript-project-services/lib/logger' {
export type Logger = (message?: any, ...optionalParams: any[]) => void;
export var info: (message?: any, ...optionalParams: any[]) => void;
export var warn: (message?: any, ...optionalParams: any[]) => void;
export var error: (message?: any, ...optionalParams: any[]) => void;
export function injectLogger(info: Logger, warn: Logger, error: Logger): void;
}
declare module 'typescript-project-services/lib/project' {
import ts = require('typescript');
import promise = require('typescript-project-services/lib/promise');
import fs = require('typescript-project-services/lib/fileSystem');
import ws = require('typescript-project-services/lib/workingSet');
import LanguageServiceHost = require('typescript-project-services/lib/languageServiceHost');
import compilerManager = require('typescript-project-services/lib/compilerManager');
import TypeScriptInfo = compilerManager.TypeScriptInfo;
/**
* Project Configuration
*/
export type TypeScriptProjectConfig = {
/**
* Array of minimatch pattern string representing
* sources of a project
*/
sources: string[];
/**
* Compiltation settings
*/
compilationSettings: ts.CompilerOptions;
/**
* Path to an alternative typescriptCompiler
*/
typescriptPath?: string;
};
export interface TypeScriptProject {
/**
* Initialize the project an his component
*/
init(): promise.Promise<void>;
/**
* update a project with a new config
*/
update(config: TypeScriptProjectConfig): promise.Promise<void>;
/**
* dispose the project
*/
dispose(): void;
/**
* return the language service host of the project
*/
getLanguageServiceHost(): LanguageServiceHost;
/**
* return the languageService used by the project
*/
getLanguageService(): ts.LanguageService;
/**
* return the typescript info used by the project
*/
getTypeScriptInfo(): TypeScriptInfo;
/**
* return the set of files contained in the project
*/
getProjectFilesSet(): {
[path: string]: boolean;
};
/**
* for a given path, give the relation between the project an the associated file
* @param path
*/
getProjectFileKind(fileName: string): ProjectFileKind;
}
export const enum ProjectFileKind {
/**
* the file is not a part of the project
*/
NONE = 0,
/**
* the file is a source file of the project
*/
SOURCE = 1,
/**
* the file is referenced by a source file of the project
*/
REFERENCE = 2,
}
export function createProject(baseDirectory: string, config: TypeScriptProjectConfig, fileSystem: fs.IFileSystem, workingSet: ws.IWorkingSet): TypeScriptProject;
}
declare module 'typescript-project-services/lib/projectManager' {
import promise = require('typescript-project-services/lib/promise');
import fs = require('typescript-project-services/lib/fileSystem');
import ws = require('typescript-project-services/lib/workingSet');
import project = require('typescript-project-services/lib/project');
import TypeScriptProject = project.TypeScriptProject;
import TypeScriptProjectConfig = project.TypeScriptProjectConfig;
export type ProjectManagerConfig = {
/**
* location of the default typescript compiler lib.d.ts file
*/
defaultTypeScriptLocation: string;
/**
* editor filesystem manager
*/
fileSystem: fs.IFileSystem;
/**
* ditor workingset manager
*/
workingSet: ws.IWorkingSet;
/**
* projects configurations
*/
projectConfigs: {
[projectId: string]: TypeScriptProjectConfig;
};
};
/**
* initialize the project manager
*
* @param config ProjectManager configuration
*/
export function init(config: ProjectManagerConfig): promise.Promise<void>;
/**
* dispose the project manager
*/
export function dispose(): void;
/**
* this method will try to find a project referencing the given path
* it will by priority try to retrive project that have that file as part of 'direct source'
* before returning projects that just have 'reference' to this file
*
* @param fileName the path of the typesrcript file for which project are looked fo
*/
export function getProjectForFile(fileName: string): promise.Promise<TypeScriptProject>;
export function updateProjectConfigs(configs: {
[projectId: string]: TypeScriptProjectConfig;
}): promise.Promise<void>;
}
declare module 'typescript-project-services/lib/promise' {
export interface Thenable<R> {
then<U>(onFulfill?: (value: R) => Thenable<U> | U, onReject?: (error: any) => Thenable<U> | U): Promise<U>;
}
export class Promise<R> implements Thenable<R> {
constructor(callback: (resolve: (result: R | Thenable<R>) => void, reject: (error: any) => void) => void);
then<U>(onFulfill?: (value: R) => Thenable<U> | U, onReject?: (error: any) => Thenable<U> | U): Promise<U>;
catch<U>(onReject?: (error: any) => Thenable<U> | U): Promise<U>;
static resolve<T>(object?: T | Thenable<T>): Promise<T>;
static reject<T>(error?: any): Promise<T>;
static all<T>(promises: (Thenable<T> | T)[]): Promise<T[]>;
static race<T>(promises: (Thenable<T> | T)[]): Promise<T>;
}
export function injectPromiseLibrary(promise: typeof Promise): void;
}
declare module 'typescript-project-services/lib/serviceUtils' {
import ts = require('typescript');
import SourceFile = ts.SourceFile;
import Node = ts.Node;
import SyntaxKind = ts.SyntaxKind;
export function getTouchingWord(sourceFile: SourceFile, position: number, typeScript: typeof ts): Node;
/** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */
export function getTouchingToken(sourceFile: SourceFile, position: number, typeScript: typeof ts, includeItemAtEndPosition?: (n: Node) => boolean): Node;
export function getSynTaxKind(type: string, typescript: typeof ts): any;
export function findPrecedingToken(position: number, sourceFile: SourceFile, typeScript: typeof ts, startNode?: Node): Node;
export function nodeHasTokens(n: Node): boolean;
export function isToken(n: Node, typeScript: typeof ts): boolean;
export function isWord(kind: SyntaxKind, typeScript: typeof ts): boolean;
export function isKeyword(token: SyntaxKind, typeScript: typeof ts): boolean;
}
declare module 'typescript-project-services/lib/utils' {
import promise = require('typescript-project-services/lib/promise');
export interface PromiseQueue {
then<T>(callback: () => promise.Promise<T>): promise.Promise<T>;
then<T>(callback: () => T): promise.Promise<T>;
reset<T>(item: promise.Promise<T>): promise.Promise<T>;
}
export function createPromiseQueue(): PromiseQueue;
export function mapValues<T>(map: {
[index: string]: T;
}): T[];
/**
* assign all properties of a list of object to an object
* @param target the object that will receive properties
* @param items items which properties will be assigned to a target
*/
export function assign(target: any, ...items: any[]): any;
/**
* clone an object (shallow)
* @param target the object to clone
*/
export function clone<T>(target: T): T;
export function createMap(arr: string[]): {
[string: string]: boolean;
};
/**
* browserify path.resolve is buggy on windows
*/
export function pathResolve(from: string, to: string): string;
/**
* C# like events and delegates for typed events
* dispatching
*/
export interface ISignal<T> {
/**
* Subscribes a listener for the signal.
*
* @params listener the callback to call when events are dispatched
* @params priority an optional priority for this signal
*/
add(listener: (parameter: T) => any, priority?: number): void;
/**
* unsubscribe a listener for the signal
*
* @params listener the previously subscribed listener
*/
remove(listener: (parameter: T) => any): void;
/**
* dispatch an event
*
* @params parameter the parameter attached to the event dispatching
*/
dispatch(parameter?: T): boolean;
/**
* Remove all listener from the signal
*/
clear(): void;
/**
* @return true if the listener has been subsribed to this signal
*/
hasListeners(): boolean;
}
export class Signal<T> implements ISignal<T> {
/**
* list of listeners that have been suscribed to this signal
*/
private listeners;
/**
* Priorities corresponding to the listeners
*/
private priorities;
/**
* Subscribes a listener for the signal.
*
* @params listener the callback to call when events are dispatched
* @params priority an optional priority for this signal
*/
add(listener: (parameter: T) => any, priority?: number): void;
/**
* unsubscribe a listener for the signal
*
* @params listener the previously subscribed listener
*/
remove(listener: (parameter: T) => any): void;
/**
* dispatch an event
*
* @params parameter the parameter attached to the event dispatching
*/
dispatch(parameter?: T): boolean;
/**
* Remove all listener from the signal
*/
clear(): void;
/**
* @return true if the listener has been subsribed to this signal
*/
hasListeners(): boolean;
}
export function binarySearch(array: number[], value: number): number;
}
declare module 'typescript-project-services/lib/workingSet' {
import promise = require('typescript-project-services/lib/promise');
import utils = require('typescript-project-services/lib/utils');
import ISignal = utils.ISignal;
/**
* A service that will reflect files in the working set
*/
export interface IWorkingSet {
/**
* list of files in the working set
*/
getFiles(): promise.Promise<string[]>;
/**
* a signal dispatching events when change occured in the working set
*/
workingSetChanged: ISignal<WorkingSetChangeRecord>;
/**
* a signal that provide fine grained change over edited document
*/
documentEdited: ISignal<DocumentChangeRecord>;
}
/**
* describe change in the working set
*/
export type WorkingSetChangeRecord = {
/**
* kind of change that occured in the working set
*/
kind: WorkingSetChangeKind;
/**
* list of paths that has been added or removed from the working set
*/
paths: string[];
};
/**
* enum listing the change kind that occur in a working set
*/
export const enum WorkingSetChangeKind {
ADD = 0,
REMOVE = 1,
}
/**
* describe a change in a document
*/
export type DocumentChangeDescriptor = {
/**
* start position of the change
*/
from?: {
ch: number;
line: number;
};
/**
* end positon of the change
*/
to?: {
ch: number;
line: number;
};
/**
* text that has been inserted (if any)
*/
text?: string;
/**
* text that has been removed (if any)
*/
removed?: string;
};
/**
* describe a list of change in a document
*/
export type DocumentChangeRecord = {
/**
* path of the files that has changed
*/
path: string;
/**
* list of changes
*/
changeList?: DocumentChangeDescriptor[];
/**
* documentText
*/
documentText?: string;
};
}
declare module 'typescript-project-services' {
import ts = require('typescript');
import promise = require('typescript-project-services/lib/promise');
import ProjectManager = require('typescript-project-services/lib/projectManager');
import fs = require('typescript-project-services/lib/fileSystem');
import ws = require('typescript-project-services/lib/workingSet');
import project = require('typescript-project-services/lib/project');
import console = require('typescript-project-services/lib/logger');
import utils = require('typescript-project-services/lib/utils');
export import Logger = console.Logger;
export var injectLogger: typeof console.injectLogger;
export var injectPromiseLibrary: typeof promise.injectPromiseLibrary;
export import ProjectManagerConfig = ProjectManager.ProjectManagerConfig;
export import IFileSystem = fs.IFileSystem;
export import FileChangeRecord = fs.FileChangeRecord;
export import FileChangeKind = fs.FileChangeKind;
export import IWorkingSet = ws.IWorkingSet;
export import DocumentChangeDescriptor = ws.DocumentChangeDescriptor;
export import DocumentChangeRecord = ws.DocumentChangeRecord;
export import WorkingSetChangeRecord = ws.WorkingSetChangeRecord;
export import WorkingSetChangeKind = ws.WorkingSetChangeKind;
export import TypeScriptProjectConfig = project.TypeScriptProjectConfig;
export import ISignal = utils.ISignal;
export import Signal = utils.Signal;
/**
* Initializate the service
*
* @param config the config used for the project managed
*/
export function init(config: ProjectManagerConfig): promise.Promise<void>;
/**
* Update the configurations of the projects managed by this services.
*
* @param configs
* A map project name to project config file.
* if a project previously managed by this service is not present in the map
* the project will be disposed.
* If a new project is present in the map, the project will be initialized
* Otherwise the project will be updated accordingly to the new configuration
*/
export function updateProjectConfigs(configs: {
[projectId: string]: TypeScriptProjectConfig;
}): promise.Promise<void>;
/**
* dispose the service
*/
export function dispose(): void;
export type TextSpan = {
start: number;
length: number;
};
export type Diagnostics = {
fileName: string;
start: number;
length: number;
messageText: string;
category: ts.DiagnosticCategory;
code: number;
};
/**
* Retrieve a list of errors for a given file
* return a promise resolving to a list of errors
*
* @param fileName the absolute path of the file
* @param allErrors by default errors are checked in 3 phases, options check, syntax check,
* semantic check, is allErrors is set to false, the service won't check the nex phase
* if there is error in the precedent one
*/
export function getDiagnosticsForFile(fileName: string, allErrors?: boolean): promise.Promise<Diagnostics[]>;
export type CompletionResult = {
/**
* the matched string portion
*/
match: string;
/**
* list of proposed entries for code completion
*/
entries: ts.CompletionEntryDetails[];
};
/**
* Retrieve completion proposal at a given point in a given file.
* return a promise resolving to a list of completion proposals.
*
* @param fileName the absolute path of the file
* @param position in the file where you want to retrieve completion proposal
* @param limit the max number of proposition this service shoudl return
* @param skip the number of proposition this service should skip
*
*/
export function getCompletionAtPosition(fileName: string, position: number, limit?: number, skip?: number): promise.Promise<CompletionResult>;
export type QuickInfo = {
kind: string;
kindModifiers: string;
textSpan: TextSpan;
displayParts: ts.SymbolDisplayPart[];
documentation: ts.SymbolDisplayPart[];
};
export function getQuickInfoAtPosition(fileName: string, position: number): promise.Promise<QuickInfo>;
export type SignatureHelpItems = {
items: ts.SignatureHelpItem[];
applicableSpan: TextSpan;
selectedItemIndex: number;
argumentIndex: number;
argumentCount: number;
};
export function getSignatureHelpItems(fileName: string, position: number): promise.Promise<SignatureHelpItems>;
export type RenameInfo = {
canRename: boolean;
localizedErrorMessage: string;
displayName: string;
fullDisplayName: string;
kind: string;
kindModifiers: string;
triggerSpan: TextSpan;
};
export function getRenameInfo(fileName: string, position: number): promise.Promise<RenameInfo>;
export function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): promise.Promise<{
textSpan: TextSpan;
fileName: string;
}[]>;
export type DefinitionInfo = {
fileName: string;
textSpan: TextSpan;
kind: string;
name: string;
containerKind: string;
containerName: string;
};
export function getDefinitionAtPosition(fileName: string, position: number): promise.Promise<DefinitionInfo[]>;
export type ReferenceEntry = {
textSpan: TextSpan;
fileName: string;
isWriteAccess: boolean;
};
export function getReferencesAtPosition(fileName: string, position: number): promise.Promise<ReferenceEntry[]>;
export function getOccurrencesAtPosition(fileName: string, position: number): promise.Promise<ReferenceEntry[]>;
export type NavigateToItem = {
name: string;
kind: string;
kindModifiers: string;
matchKind: string;
fileName: string;
textSpan: TextSpan;
containerName: string;
containerKind: string;
};
export function getNavigateToItems(fileName: string, search: string): promise.Promise<NavigateToItem[]>;
export type NavigationBarItem = {
text: string;
kind: string;
kindModifiers: string;
spans: {
start: number;
length: number;
}[];
childItems: NavigationBarItem[];
indent: number;
bolded: boolean;
grayed: boolean;
};
export function getNavigationBarItems(fileName: string): promise.Promise<NavigationBarItem[]>;
export type TextChange = {
span: TextSpan;
newText: string;
};
export function getFormattingEditsForFile(fileName: string, options: ts.FormatCodeOptions, start: number, end: number): promise.Promise<TextChange[]>;
export function getEmitOutput(fileName: string): promise.Promise<ts.EmitOutput>;
} | the_stack |
declare enum TableColumnProperties {
Index = 0,
IsKey = 1,
IsUnique = 2,
Name = 3,
DataType = 4,
DefaultValue = 5,
Comment = 6,
AutoIncrement = 7,
Tags = 8,
IsReadOnly = 9,
AllowNull = 10
}
declare enum TableProperties {
TableName = 0,
Tags = 1,
Comment = 2
}
declare enum TypeMemberProperties {
Name = 0,
Value = 1,
Comment = 2
}
declare enum TypeProperties {
Name = 0,
IsFlag = 1,
Comment = 2
}
// Misc
declare function addEventListener (value: string, action: (e1: { [key: string]: any; }) => void): void;
declare function log (value: any): void;
declare function sleep (millisecondsTimeout: number): void;
// DataBase
/** @returns transactionID */
declare function beginDataBaseTransaction (dataBaseName: string): string;
declare function cancelDataBaseTransaction (transactionID: string): void;
declare function containsDataBase (dataBaseName: string): boolean;
declare function containsTable (dataBaseName: string, tableName: string): boolean;
declare function containsTableItem (dataBaseName: string, tableItemPath: string): boolean;
declare function containsType (dataBaseName: string, typeName: string): boolean;
declare function containsTypeItemItem (dataBaseName: string, typeItemPath: string): boolean;
declare function deleteTable (dataBaseName: string, tableName: string): void;
declare function deleteTableItem (dataBaseName: string, tableItemPath: string): void;
declare function deleteType (dataBaseName: string, typeName: string): void;
declare function deleteTypeItem (dataBaseName: string, typeItemPath: string): void;
declare function endDataBaseTransaction (transactionID: string): void;
declare function enterDataBase (dataBaseName: string): void;
declare function getDataBaseInfo (dataBaseName: string): { [key: string]: any; };
declare function getDataBaseInfoByTags (dataBaseName: string, tags: string): { [key: string]: any; };
declare function getDataBaseList (): string[];
declare function getDataBaseLogInfo (dataBaseName: string): { [key: string]: any; }[];
declare function getTableData (dataBaseName: string, tableName: string, revision?: number): { [key: number]: any; };
declare function getTableInfo (dataBaseName: string, tableName: string): { [key: string]: any; };
declare function getTableInfoByTags (dataBaseName: string, tableName: string, tags: string): { [key: string]: any; };
declare function getTableItemList (dataBaseName: string): string[];
declare function getTableItemLogInfo (dataBaseName: string, tableItemPath: string): { [key: string]: any; }[];
declare function getTableList (dataBaseName: string): string[];
declare function getTableListByTags (dataBaseName: string, tags: string): string[];
declare function getTypeData (dataBaseName: string, typeName: string, revision?: number): { [key: number]: any; };
declare function getTypeInfo (dataBaseName: string, typeName: string): { [key: string]: any; };
declare function getTypeInfoByTags (dataBaseName: string, typeName: string, tags: string): { [key: string]: any; };
declare function getTypeItemList (dataBaseName: string): string[];
declare function getTypeList (dataBaseName: string): string[];
declare function getTypeListByTags (dataBaseName: string, tags: string): string[];
declare function isDataBaseEntered (dataBaseName: string): boolean;
declare function isDataBaseLoaded (dataBaseName: string): boolean;
declare function leaveDataBase (dataBaseName: string): void;
declare function loadDataBase (dataBaseName: string): void;
declare function moveType (dataBaseName: string, typeName: string, categoryPath: string): void;
declare function moveTypeItem (dataBaseName: string, typeItemPath: string, parentPath: string): void;
declare function renameType (dataBaseName: string, typeName: string, newTypeName: string): void;
declare function renameTypeItem (dataBaseName: string, typeItemPath: string, newName: string): void;
declare function unloadDataBase (dataBaseName: string): void;
// Domain
declare function containsDomain (domainID: string): boolean;
declare function containsDomainUser (domainID: string, userID: string): boolean;
declare function deleteDomain (domainID: string, isCancel: boolean): void;
declare function getDomainInfo (domainID: string): { [key: string]: any; };
declare function getDomainList (): string[];
declare function getDomainUserList (domainID: string): string[];
// IO
/** @returns fullName */
declare function createDirectory (path: string): string;
declare function directoryExists (path: string): boolean;
declare function fileExists (filename: string): boolean;
declare function readFile (filename: string): any;
declare function readFileText (filename: string): string;
declare function writeFile (filename: string, value: any): void;
declare function writeFileText (filename: string, text: string): void;
// Permission
declare function isTableItemLocked (dataBaseName: string, tableItemPath: string): boolean;
declare function isTableItemPrivate (dataBaseName: string, tableItemPath: string): boolean;
declare function isTypeItemLocked (dataBaseName: string, tableItemPath: string): boolean;
declare function isTypeItemPrivate (dataBaseName: string, typeItemPath: string): boolean;
declare function lockTableItem (dataBaseName: string, tableItemPath: string, comment: string): void;
declare function privateTableItem (dataBaseName: string, tableItemPath: string): void;
declare function privateTypeItem (dataBaseName: string, typeItemPath: string): void;
declare function publicTableItem (dataBaseName: string, tableItemPath: string): void;
declare function publicTypeItem (dataBaseName: string, typeItemPath: string): void;
declare function unlockTableItem (dataBaseName: string, tableItemPath: string): void;
// TableContent
/** @returns keys */
declare function addTableContentRow (domainID: string, fields: { [key: string]: any; }): any[];
/** @returns domainID */
declare function beginTableContentEdit (dataBaseName: string, tableName: string): string;
declare function cancelTableContentEdit (domainID: string): void;
declare function containsTableContentRow (domainID: string, keys: any[]): boolean;
declare function endTableContentEdit (domainID: string): void;
declare function enterTableContentEdit (domainID: string): void;
/** @returns domainID */
declare function getTableContentDomain (dataBaseName: string, tableName: string): string;
declare function getTableContentRowCount (domainID: string, keys: any[], columnName: string): any;
declare function getTableContentRowField (domainID: string, keys: any[], columnName: string): any;
declare function getTableContentRowFields (domainID: string, keys: any[]): { [key: string]: any; };
declare function leaveTableContentEdit (domainID: string): void;
declare function setTableContentRowField (domainID: string, keys: any[], columnName: string, value: any): void;
declare function setTableContentRowFields (domainID: string, keys: any[], fields: { [key: string]: any; }): void;
// TableTemplate
/** @param string boolean, string, int, float, double, dateTime, unsignedInt, long, short, unsignedLong, unsignedByte, duration, unsignedShort, byte, guid or typePath(e.g., /categoryPath/typeName) */
declare function addTableTemplateColumn (domainID: string, columnName: string, typeName: string, comment: string, isKey?: boolean): void;
/** @returns domainID */
declare function beginChildTableCreate (dataBaseName: string, tableName: string): string;
/** @returns domainID */
declare function beginTableCreate (dataBaseName: string, categoryPath: string): string;
/** @returns domainID */
declare function beginTableTemplateEdit (dataBaseName: string, tableName: string): string;
declare function cancelTableTemplateEdit (domainID: string): void;
declare function containsTableTemplateColumn (domainID: string, columName: string): boolean;
declare function deleteTableTemplateColumn (domainID: string, columnName: string): void;
/** @returns tableName */
declare function endTableTemplateEdit (domainID: string): string;
declare function getTableTemplateColumnProperties (domainID: string, columnName: string): { [key: string]: any; };
declare function getTableTemplateColumnProperty (domainID: string, columnName: string, propertyName: TableColumnProperties): any;
/** @returns domainID */
declare function getTableTemplateDomain (dataBaseName: string, tableName: string): string;
declare function getTableTemplateProperties (domainID: string, columnName: string): { [key: string]: any; };
declare function getTableTemplateProperty (domainID: string, columnName: string, propertyName: TableProperties): any;
declare function setTableTemplateColumnProperty (domainID: string, columnName: string, propertyName: TableColumnProperties, value: any): void;
declare function setTableTemplateProperty (domainID: string, propertyName: TableProperties, value: any): void;
// TypeTemplate
declare function addTypeTemplateMember (domainID: string, memberName: string, value: number, comment: string): void;
/** @returns domainID */
declare function beginTypeCreate (dataBaseName: string, categoryPath: string): string;
/** @returns domainID */
declare function beginTypeTemplateEdit (dataBaseName: string, typeName: string): string;
declare function cancelTypeTemplateEdit (domainID: string): void;
declare function containsTypeTemplateMember (domainID: string, memberName: string): boolean;
declare function deleteTypeTemplateMember (domainID: string, memberName: string): void;
/** @returns typeName */
declare function endTypeTemplateEdit (domainID: string): string;
/** @returns domainID */
declare function getTypeTemplateDomain (dataBaseName: string, typeName: string): string;
declare function getTypeTemplateMemberProperties (domainID: string, memberName: string): { [key: string]: any; };
declare function getTypeTemplateMemberProperty (domainID: string, memberName: string, propertyName: TypeMemberProperties): any;
declare function getTypeTemplateProperties (domainID: string): { [key: string]: any; };
declare function getTypeTemplateProperty (domainID: string, propertyName: TypeProperties): any;
declare function setTypeTemplateMemberProperty (domainID: string, memberName: string, propertyName: TypeMemberProperties, value: any): void;
declare function setTypeTemplateProperty (domainID: string, propertyName: TypeProperties, value: any): void;
// User
declare function banUser (userID: string, comment: string): void;
declare function containsUser (userID: string): boolean;
declare function containsUserItem (userItemPath: string): boolean;
/** @returns userID */
declare function getCurrentUser (): string;
declare function getUserBanInfo (userID: string): { [key: string]: any; };
declare function getUserInfo (userID: string): { [key: string]: any; };
declare function getUserItemList (): string[];
declare function getUserList (): string[];
declare function getUserState (userID: string): string;
declare function isUserBanned (userID: string): boolean;
declare function isUserOnline (userID: string): boolean;
declare function kickUser (userID: string, comment: string): void;
declare function login (userID: string, password: string): string;
declare function logout (token: string): void;
declare function notify (message: string): void;
declare function sendMessage (userID: string, message: string): void;
declare function unbanUser (userID: string): void; | the_stack |
import {
get_state,
set_state,
delete_state,
get_ptr_len,
alloc,
read_byte,
write_byte,
get_ptr_collection_len,
add_to_collection,
create_collection,
log_buffer,
log_level,
get_ptr_from_collection
} from "./env";
export class Void {
constructor () {}
static make(): Void {
return new Void();
}
}
export class Err {
message: string;
constructor(message: string) {
this.message = message;
}
getMessage(): string {
return this.message;
}
}
export class Result<T> {
_ok: T | null;
_err: Err | null;
constructor(ok: T | null, err: Err | null) {
this._ok = ok;
this._err = err;
}
static ok<T>(ok: T): Result<T> {
return new Result(ok, null);
}
static okVoid(): Result<Void> {
return new Result(Void.make(), null);
}
static err<T>(message: string): Result<T> {
return new Result(null, new Err(message));
}
isErr(): bool {
return this._err != null;
}
isOk(): bool {
return this._ok != null;
}
getOk<T>(): T | null {
if (this._ok != null) {
return this._ok;
} else {
throw new Error("Unreachable");
}
}
getErr(): Err | null {
if (this._err != null) {
return this._err;
} else {
throw new Error("Unreachable");
}
}
}
/**
* An entry in state containing the address and corresponding data.
*/
export class StateEntry {
address: string;
data: Uint8Array;
constructor(address: string, data: Uint8Array) {
this.address = address;
this.data = data;
}
getAddress(): string {
return this.address;
}
getData(): Uint8Array {
return this.data;
}
}
/**
* A WasmBuffer is a wrapper around a wasm pointer.
*
* It contains a raw wasm pointer to location in executor
* memory and a bytes representation of it's contents.
*
* It offers methods for accessing the data stored at the
* location referenced by the raw pointer.
*/
export class WasmBuffer {
raw: i32;
data: Uint8Array;
constructor(raw: i32, data: Uint8Array) {
this.raw = raw;
this.data = data;
}
static init(buffer: ArrayBuffer): WasmBuffer {
const data = Uint8Array.wrap(buffer);
const raw = alloc(data.length);
for (let i = 0; i < data.length; i++) {
if (write_byte(raw, i, data[i]) < 0) {
const err = "Failed to write data to host memory";
error(err);
throw new Error(err);
}
}
return new WasmBuffer(raw, data);
}
static fromRaw(raw: i32): WasmBuffer {
const data = ptrToVec(raw);
return new WasmBuffer(raw, data);
}
static fromList(ptr: i32): Array<WasmBuffer> {
const array = new Array<WasmBuffer>(0);
if (ptr >= 0) {
for (let i = 0; i < get_ptr_collection_len(ptr); i++) {
const p = get_ptr_from_collection(ptr, i);
if (p < 0) {
const err = "Pointer not found";
error(err);
throw new Error(err);
}
array.push(this.fromRaw(p));
}
}
return array;
}
getRaw(): i32 {
return this.raw;
}
getData(): Uint8Array {
return this.data;
}
toString(): string {
return String.UTF8.decode(this.data.buffer);
}
}
function ptrToVec(ptr: i32): Uint8Array {
const buffer = new Uint8Array(get_ptr_len(ptr));
for (let i = 0; i < get_ptr_len(ptr); i++) {
buffer[i] = read_byte(ptr + i);
}
return buffer;
}
export class Header {
signer: string;
constructor(signer: string) {
this.signer = signer;
}
getSignerPublicKey(): string {
return this.signer;
}
}
export class TpProcessRequest {
payload: Uint8Array;
header: Header;
signature: string;
constructor(payload: Uint8Array, header: Header, signature: string) {
this.payload = payload;
this.header = header;
this.signature = signature;
}
getPayload(): Uint8Array {
return this.payload;
}
getHeader(): Header {
return this.header;
}
getSignature(): string {
return this.signature;
}
}
export class TransactionContext {
constructor() {}
/**
* getStateEntries queries the validator state for data at each of the
* addresses in the given list. The addresses that have been set
* are returned.
*
* # Arguments
*
* * `addresses` - the addresses to fetch
*/
getStateEntries(addresses: string[]): Array<StateEntry> {
if (!addresses.length) {
const err = "No address to get";
error(err)
throw new Error(err);
}
const head = addresses[0];
const headerAddressBuffer = WasmBuffer.init(String.UTF8.encode(head));
create_collection(headerAddressBuffer.getRaw());
for (let i = 1; i < addresses.length; i++) {
const wasmBuffer = WasmBuffer.init(String.UTF8.encode(addresses[i]));
add_to_collection(headerAddressBuffer.getRaw(), wasmBuffer.getRaw());
}
const results = WasmBuffer.fromList(get_state(headerAddressBuffer.getRaw()));
if ((results.length % 2) != 0) {
const err = "Get state returned incorrect data fmt";
error(err);
throw new Error(err);
}
const resultsArray = new Array<StateEntry>(0);
for (let i = 0; i < results.length; i += 2) {
const addr = results[i].toString();
resultsArray.push(new StateEntry(addr, results[i + 1].getData()));
}
return resultsArray;
}
/**
* setStateEntries requests that each address in the provided map be
* set in validator state to its corresponding value.
*
* # Arguments
*
* * `entries` - a list of state entries
*/
setStateEntries(entries: Array<StateEntry>): void {
const head = entries[0];
const headAddressBuffer = WasmBuffer.init(String.UTF8.encode(head.getAddress()));
create_collection(headAddressBuffer.getRaw());
const wasmHeadDataBuffer = WasmBuffer.init(head.getData().buffer);
add_to_collection(headAddressBuffer.getRaw(), wasmHeadDataBuffer.getRaw());
for (let i = 1; i < entries.length; i++) {
const address = entries[i].getAddress();
const wasmAddrBuffer = WasmBuffer.init(String.UTF8.encode(address));
add_to_collection(headAddressBuffer.getRaw(), wasmAddrBuffer.getRaw());
const wasmDataBuffer = WasmBuffer.init(entries[i].getData().buffer);
add_to_collection(headAddressBuffer.getRaw(), wasmDataBuffer.getRaw());
}
const result = set_state(headAddressBuffer.getRaw());
info("State result: " + result.toString());
if (result == 0) {
const err = "Unable to set state";
error(err);
throw new Error(err);
}
}
/**
* deleteStateEntries requests that each of the provided addresses be unset
* in validator state. A list of successfully deleted addresses
* is returned.
*
* # Arguments
* * `addresses` - the addresses to delete
*/
deleteStateEntries(addresses: string[]): Array<string> {
if (!addresses.length) {
const err = "No address to delete";
error(err);
throw new Error(err);
}
const head = addresses[0];
const headerAddressBuffer = WasmBuffer.init(String.UTF8.encode(head));
create_collection(headerAddressBuffer.getRaw());
for (let i = 1; i < addresses.length; i++) {
const wasmBuffer = WasmBuffer.init(String.UTF8.encode(addresses[i]));
add_to_collection(headerAddressBuffer.getRaw(), wasmBuffer.getRaw());
}
const result = WasmBuffer.fromList(delete_state(headerAddressBuffer.getRaw()));
const resultArray = new Array<string>(0);
for (let i = 0; i < result.length; i++) {
resultArray.push(result[i].toString());
}
return resultArray;
}
}
/**
* executes entry point, returns 1 if successful and 0 otherwise.
*/
export function executeEntryPoint(
payloadPtr: i32,
signerPtr: i32,
signaturePtr: i32,
apply: (x:TpProcessRequest, y: TransactionContext) => bool
): i32 {
const payload = WasmBuffer.fromRaw(payloadPtr);
const signer = WasmBuffer.fromRaw(signerPtr);
const signature = WasmBuffer.fromRaw(signaturePtr);
const header = new Header(signer.toString());
const context = new TransactionContext();
const request = new TpProcessRequest(payload.getData(), header, signature.toString());
return apply(request, context) ? 1 : 0;
}
export class Request {
roles: Array<string>;
orgId: string;
publicKey: string;
payload: Uint8Array;
constructor(roles: Array<string>, orgId: string, publicKey: string, payload: Uint8Array) {
this.roles = roles;
this.orgId = orgId;
this.publicKey = publicKey;
this.payload = payload;
}
getRoles(): Array<string> {
return this.roles;
}
getOrgId(): string {
return this.orgId;
}
getPublicKey(): string {
return this.publicKey;
}
getState(address: string): Uint8Array {
const wasmBuffer = WasmBuffer.init(String.UTF8.encode(address));
return ptrToVec(get_state(wasmBuffer.getRaw()));
}
getPayload(): Uint8Array {
return this.payload;
}
}
/**
* executes entry point, returns 1 if successful and 0 otherwise.
*/
export function executeSmartPermissionEntryPoint(
rolesPtr: i32,
orgIdPtr: i32,
publicKeyPtr: i32,
payloadPtr: i32,
hasPermission: (x: Request) => bool
): i32 {
const roles = WasmBuffer.fromList(rolesPtr).map<string>((x) => x.toString());
const orgId = WasmBuffer.fromRaw(orgIdPtr).toString();
const publicKey = WasmBuffer.fromRaw(publicKeyPtr).toString();
const payload = WasmBuffer.fromRaw(payloadPtr).getData();
const request = new Request(roles, orgId, publicKey, payload);
return hasPermission(request) ? 1 : 0;
}
export function trace(msg: string): void {
log(LogLevel.TraceLv, msg);
}
export function debug(msg: string): void {
log(LogLevel.DebugLv, msg);
}
export function info(msg: string): void {
log(LogLevel.InfoLv, msg);
}
export function warn(msg: string): void {
log(LogLevel.WarnLv, msg);
}
export function error(msg: string): void {
log(LogLevel.ErrorLv, msg);
}
export function logLevel(): LogLevel {
switch (log_level()) {
case 4:
return LogLevel.TraceLv;
case 3:
return LogLevel.DebugLv;
case 2:
return LogLevel.InfoLv;
case 1:
return LogLevel.WarnLv;
case 0:
return LogLevel.ErrorLv;
default:
throw new Error("Invalid log level returned from environment");
};
}
export function logEnabled(lvl: LogLevel): bool {
return lvl >= logLevel();
}
/**
* Source: Chainsafe as-sha-256
*/
export function toHexString(bin: ArrayBuffer): string {
const u8Bin = Uint8Array.wrap(bin);
const bin_len = u8Bin.length;
let hex = "";
for (let i = 0; i < bin_len; i++) {
let bin_i = u8Bin[i] as u32;
// Bit shifting needed because `toString` in
// assembly script does not support radix argument
let c = bin_i & 0xf;
let b = bin_i >> 4;
// Calculate ASCII code
let x: u32 = ((87 + c + (((c - 10) >> 8) & ~38)) << 8) |
(87 + b + (((b - 10) >> 8) & ~38));
hex += String.fromCharCode(x as u8);
x >>= 8;
hex += String.fromCharCode(x as u8);
}
return hex;
}
enum LogLevel {
TraceLv = 4,
DebugLv = 3,
InfoLv = 2,
WarnLv = 1,
ErrorLv = 0,
}
function log(level: LogLevel, msg: string): void {
const wasmBuffer = WasmBuffer.init(String.UTF8.encode(msg));
const ptr = wasmBuffer.getRaw();
switch (level) {
case LogLevel.TraceLv:
log_buffer(4, ptr);
break;
case LogLevel.DebugLv:
log_buffer(3, ptr);
break;
case LogLevel.InfoLv:
log_buffer(2, ptr);
break;
case LogLevel.WarnLv:
log_buffer(1, ptr);
break;
case LogLevel.ErrorLv:
log_buffer(0, ptr);
break;
}
} | the_stack |
import { ChildProcess, spawn } from 'child_process';
import { EventEmitter } from 'events';
import { GenericShell, ILogOutput } from './GenericShell';
import { DebugProtocol } from 'vscode-debugprotocol';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
//inspired from https://github.com/WebFreak001/code-debug/blob/master/src/backend/mi2/mi2.ts for inspiration of an EventEmitter
const nonOutput = /^(?:\d*|undefined)[\*\+\=]|[\~\@\&\^]/;
export interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
cwd: string;
erlpath: string;
arguments: string;
verbose: boolean;
addEbinsToCodepath: boolean;
erlangPath : string; // path of erlang if specified in configuration
}
export class FunctionBreakpoint implements DebugProtocol.Breakpoint {
id: any;
verified: boolean;
name: string;
moduleName: string;
functionName: string;
arity: number;
constructor(i: string, n: string, mn:string, fn: string, a: number) {
this.id = i;
this.verified = false;
this.name = n;
this.moduleName = mn;
this.functionName = fn;
this.arity = a;
}
}
// export interface IErlangShellOutputForDebugging {
// show(): void;
// appendLine(value: string): void;
// append(value: string): void;
// debug(value: string): void;
// error(value: string): void;
// }
export class ErlangShellForDebugging extends GenericShell {
breakPoints: DebugProtocol.Breakpoint[];
functionBreakPoints: FunctionBreakpoint[];
started : boolean;
argsFileName: string;
argsPrecompiledFileName : string;
constructor(whichOutput: ILogOutput) {
super(whichOutput);
this.breakPoints = [];
this.functionBreakPoints = [];
}
public Start(erlPath: string, startDir: string, listen_port: number, bridgePath: string, launchArguments: LaunchRequestArguments): Promise<boolean> {
var randomSuffix:string = Math.floor(Math.random() * 10000000).toString();
this.argsFileName = path.join(os.tmpdir(), path.basename(startDir) + '_' + randomSuffix);
this.argsPrecompiledFileName = path.join(os.tmpdir(), 'bp_' + randomSuffix + ".erl");
this.argsPrecompiledFileName = this.formatPath(this.argsPrecompiledFileName);
var debugStartArgs = ["-noshell", "-pa", `"${bridgePath}"`, "-s", "int",
"-vscode_port", listen_port.toString()];
if (!launchArguments.noDebug) {
debugStartArgs.push("-compiled_args_file", `"${this.argsPrecompiledFileName}"`);
}
debugStartArgs.push("-s", "vscode_connection", "start");
var argsFile = this.createArgsFilev1(startDir, launchArguments.noDebug, launchArguments.addEbinsToCodepath, launchArguments.verbose);
var processArgs = debugStartArgs.concat(argsFile).concat([launchArguments.arguments]);
this.started = true;
var result = this.LaunchProcess(erlPath, startDir, processArgs, !launchArguments.verbose);
return result;
}
public CleanupAfterStart() {
if (this.argsFileName && fs.existsSync(this.argsFileName)) {
fs.unlinkSync(this.argsFileName);
}
if (this.argsPrecompiledFileName && fs.existsSync(this.argsPrecompiledFileName)) {
fs.unlinkSync(this.argsPrecompiledFileName);
var beamFile = path.join(path.dirname(this.argsPrecompiledFileName), path.basename(this.argsPrecompiledFileName, ".erl"))+".beam";
if (fs.existsSync(beamFile)) {
fs.unlinkSync(beamFile);
}
}
}
private uniqueBy<T>(arr: Array<T>, keySelector: (v: T)=> any): Array<T> {
var unique = {};
var distinct:Array<T> = [];
arr.forEach(function (x) {
var key = keySelector(x);
if (!unique[key]) {
distinct.push(x);
unique[key] = true;
}
});
return distinct;
}
private formatPath(filePath : string) {
if (os.platform() == 'win32') {
if (filePath == undefined) {
return filePath;
}
filePath = filePath.split("\\").join("/");
return filePath;
}
return filePath;
}
private findEbinDirs(dir: string, dirList: string[] = []) {
fs.readdirSync(dir).forEach(name => {
const fullpath = path.join(dir, name)
if (fs.existsSync(fullpath) && fs.statSync(fullpath).isDirectory()) {
if (name === 'ebin')
dirList.push(fullpath);
else
this.findEbinDirs(fullpath, dirList);
}
});
return dirList;
}
private findErlFiles(dir: string, fileList: string[] = []) {
fs.readdirSync(dir).forEach(file => {
if (file == '_build')
return;
const filePath = path.join(dir, file)
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory())
this.findErlFiles(filePath, fileList);
else if (path.extname(file) === '.erl')
fileList.push(filePath);
});
return fileList;
}
private excludeUnwantedFiles(bp: DebugProtocol.Breakpoint) : boolean {
//exclude files with specific extensions
if (path.extname(bp.source.path)==".src") {
return false;
}
return true;
}
private createArgsFilev1(startDir: string, noDebug: boolean, addEbinsToCodepath: boolean, verbose: boolean): string[] {
var result: string[] = [];
if (this.breakPoints) {
var argsFileContents = "";
if (!noDebug) {
let argsModuleName = path.basename(this.argsPrecompiledFileName, ".erl");
let argsCompiledContents = `-module(${argsModuleName}).\r\n-export([configure/0]).\r\n\r\n`;
argsCompiledContents += "configure() -> \r\n int:start()\r\n";
argsFileContents += "-eval 'int:start()";
var modulesWithoutBp: { [sourcePath: string]: boolean} = {};
this.findErlFiles(startDir).forEach(fileName => {
modulesWithoutBp[fileName] = true;
});
//first interpret source
var bps = this.uniqueBy(this.breakPoints, bp => bp.source.path).filter(this.excludeUnwantedFiles);
bps.forEach(bp => {
argsCompiledContents += ",int:ni(\"" + this.formatPath(bp.source.path) + "\")\r\n";
delete modulesWithoutBp[bp.source.path];
});
for (var fileName in modulesWithoutBp) {
argsCompiledContents += ",int:ni(\"" + this.formatPath(fileName) + "\")\r\n";
}
//then set break
this.breakPoints.filter(this.excludeUnwantedFiles).forEach(bp => {
var moduleName = path.basename(bp.source.name, ".erl");
argsCompiledContents += `,int:break(${moduleName}, ${bp.line})\r\n`;
});
this.functionBreakPoints.forEach(bp => {
argsCompiledContents += `,vscode_connection:set_breakpoint(${bp.moduleName}, {function, ${bp.functionName}, ${bp.arity}})\r\n`;
});
argsFileContents += "'";
argsCompiledContents += ",ok.";
if (verbose) {
this.debug(`erl file '${this.argsPrecompiledFileName}' was generated with content : -->\n${argsCompiledContents}\n<--`);
}
fs.writeFileSync(this.argsPrecompiledFileName, argsCompiledContents);
}
if (addEbinsToCodepath) {
this.findEbinDirs(path.join(startDir, "_build")).forEach(ebin => {
argsFileContents += " -pz \"" + this.formatPath(ebin) + "\"";
});
}
fs.writeFileSync(this.argsFileName, argsFileContents);
result.push("-args_file");
result.push("\"" + this.argsFileName + "\"");
}
return result;
}
// old
private createArgsFilev0(startDir: string, noDebug: boolean, addEbinsToCodepath: boolean): string[] {
var result: string[] = [];
if (this.breakPoints) {
var argsFileContents = "";
if (!noDebug) {
argsFileContents += "-eval 'int:start()";
var modulesWithoutBp: { [sourcePath: string]: boolean} = {};
this.findErlFiles(startDir).forEach(fileName => {
modulesWithoutBp[fileName] = true;
});
//first interpret source
var bps = this.uniqueBy(this.breakPoints, bp => bp.source.path);
bps.forEach(bp => {
argsFileContents += ",int:ni(\\\"" + this.formatPath(bp.source.path) + "\\\")";
delete modulesWithoutBp[bp.source.path];
});
for (var fileName in modulesWithoutBp) {
argsFileContents += ",int:ni(\\\"" + this.formatPath(fileName) + "\\\")";
}
//then set break
this.breakPoints.forEach(bp => {
var moduleName = path.basename(bp.source.name, ".erl");
argsFileContents += `,int:break(${moduleName}, ${bp.line})`;
});
this.functionBreakPoints.forEach(bp => {
argsFileContents += `,vscode_connection:set_breakpoint(${bp.moduleName}, {function, ${bp.functionName}, ${bp.arity}})`;
});
argsFileContents += "'";
}
if (addEbinsToCodepath) {
this.findEbinDirs(path.join(startDir, "_build")).forEach(ebin => {
argsFileContents += " -pz \"" + this.formatPath(ebin) + "\"";
});
}
fs.writeFileSync(this.argsFileName, argsFileContents);
result.push("-args_file");
result.push("\"" + this.argsFileName + "\"");
}
return result;
}
/** compile specific files */
public Compile(startDir: string, args: string[]): Promise<number> {
//if erl is used, -compile must be used
//var processArgs = ["-compile"].concat(args);
var processArgs = [].concat(args);
var result = this.RunProcess("erlc", startDir, processArgs);
return result;
}
public setBreakPointsRequest(bps: DebugProtocol.Breakpoint[], fbps: FunctionBreakpoint[]): void {
if (!this.started) {
this.breakPoints = this.breakPoints.concat(bps);
this.functionBreakPoints = this.functionBreakPoints.concat(fbps);
}
}
} | the_stack |
import {TwingErrorRuntime} from "./error/runtime";
import {TwingSource} from "./source";
import {TwingError} from "./error";
import {TwingEnvironment} from "./environment";
import {TwingOutputBuffer} from './output-buffer';
import {iteratorToMap} from "./helpers/iterator-to-map";
import {merge} from "./helpers/merge";
import {TwingExtensionInterface} from "./extension-interface";
import {TwingContext} from "./context";
import {isMap} from "./helpers/is-map";
import {TwingMarkup} from "./markup";
import {TwingSandboxSecurityError} from "./sandbox/security-error";
import {TwingSandboxSecurityNotAllowedFilterError} from "./sandbox/security-not-allowed-filter-error";
import {TwingSandboxSecurityNotAllowedFunctionError} from "./sandbox/security-not-allowed-function-error";
import {TwingSandboxSecurityNotAllowedTagError} from "./sandbox/security-not-allowed-tag-error";
import {compare} from "./helpers/compare";
import {count} from "./helpers/count";
import {isCountable} from "./helpers/is-countable";
import {isPlainObject} from "./helpers/is-plain-object";
import {iterate, IterateCallback} from "./helpers/iterate";
import {isIn} from "./helpers/is-in";
import {ensureTraversable} from "./helpers/ensure-traversable";
import {getAttribute} from "./helpers/get-attribute";
import {createRange} from "./helpers/create-range";
import {cloneMap} from "./helpers/clone-map";
import {parseRegex} from "./helpers/parse-regex";
import {constant} from "./helpers/constant";
import {get} from "./helpers/get";
import {include} from "./extension/core/functions/include";
import {isNullOrUndefined} from "util";
type TwingTemplateMacrosMap = Map<string, TwingTemplateMacroHandler>;
type TwingTemplateAliasesMap = TwingContext<string, TwingTemplate>;
type TwingTemplateTraceableMethod<T> = (...args: Array<any>) => Promise<T>;
export type TwingTemplateBlocksMap = Map<string, [TwingTemplate, string]>;
export type TwingTemplateBlockHandler = (context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap) => Promise<void>;
export type TwingTemplateMacroHandler = (outputBuffer: TwingOutputBuffer, ...args: Array<any>) => Promise<string>;
/**
* Default base class for compiled templates.
*
* @author Eric MORAND <eric.morand@gmail.com>
*/
export abstract class TwingTemplate {
static ANY_CALL = 'any';
static ARRAY_CALL = 'array';
static METHOD_CALL = 'method';
private readonly _environment: TwingEnvironment;
private _source: TwingSource;
protected parent: TwingTemplate | false;
protected parents: Map<TwingTemplate | string, TwingTemplate>;
protected blocks: TwingTemplateBlocksMap;
protected blockHandlers: Map<string, TwingTemplateBlockHandler>;
protected macroHandlers: Map<string, TwingTemplateMacroHandler>;
protected traits: TwingTemplateBlocksMap;
protected macros: TwingTemplateMacrosMap;
protected aliases: TwingTemplateAliasesMap;
constructor(environment: TwingEnvironment) {
this._environment = environment;
this.parents = new Map();
this.aliases = new TwingContext();
this.blockHandlers = new Map();
this.macroHandlers = new Map();
}
get environment(): TwingEnvironment {
return this._environment;
}
/**
* @returns {TwingSource}
*/
get source(): TwingSource {
return this._source;
}
/**
* Returns the template name.
*
* @returns {string} The template name
*/
get templateName(): string {
return this.source.getName();
}
get isTraitable(): boolean {
return true;
}
/**
* Returns the parent template.
*
* @param {any} context
*
* @returns {Promise<TwingTemplate|false>} The parent template or false if there is no parent
*/
public getParent(context: any = {}): Promise<TwingTemplate | false> {
if (this.parent) {
return Promise.resolve(this.parent);
}
return this.doGetParent(context)
.then((parent) => {
if (parent === false || parent instanceof TwingTemplate) {
if (parent instanceof TwingTemplate) {
this.parents.set(parent.source.getName(), parent);
}
return parent;
}
// parent is a string
if (!this.parents.has(parent)) {
return this.loadTemplate(parent)
.then((template: TwingTemplate) => {
this.parents.set(parent, template);
return template;
});
} else {
return this.parents.get(parent);
}
});
}
/**
* Returns template blocks.
*
* @returns {Promise<TwingTemplateBlocksMap>} A map of blocks
*/
public getBlocks(): Promise<TwingTemplateBlocksMap> {
if (this.blocks) {
return Promise.resolve(this.blocks);
} else {
return this.getTraits().then((traits) => {
this.blocks = merge(traits, new Map([...this.blockHandlers.keys()].map((key) => [key, [this, key]])));
return this.blocks;
});
}
}
/**
* Displays a block.
*
* @param {string} name The block name to display
* @param {any} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
* @param {boolean} useBlocks Whether to use the active set of blocks
*
* @returns {Promise<void>}
*/
protected displayBlock(name: string, context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap, useBlocks: boolean): Promise<void> {
return this.getBlocks().then((ownBlocks) => {
let blockHandler: TwingTemplateBlockHandler;
if (useBlocks && blocks.has(name)) {
blockHandler = blocks.get(name)[0].blockHandlers.get(blocks.get(name)[1]);
} else if (ownBlocks.has(name)) {
blockHandler = ownBlocks.get(name)[0].blockHandlers.get(ownBlocks.get(name)[1]);
}
if (blockHandler) {
return blockHandler(context, outputBuffer, blocks);
} else {
return this.getParent(context).then((parent) => {
if (parent) {
return parent.displayBlock(name, context, outputBuffer, merge(ownBlocks, blocks), false);
} else if (blocks.has(name)) {
throw new TwingErrorRuntime(`Block "${name}" should not call parent() in "${blocks.get(name)[0].templateName}" as the block does not exist in the parent template "${this.templateName}".`, -1, blocks.get(name)[0].source);
} else {
throw new TwingErrorRuntime(`Block "${name}" on template "${this.templateName}" does not exist.`, -1, this.source);
}
});
}
});
}
/**
* Displays a parent block.
*
* @param {string} name The block name to display from the parent
* @param {any} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
*
* @returns {Promise<void>}
*/
protected displayParentBlock(name: string, context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap): Promise<void> {
return this.getTraits().then((traits) => {
if (traits.has(name)) {
return traits.get(name)[0].displayBlock(traits.get(name)[1], context, outputBuffer, blocks, false);
} else {
return this.getParent(context).then((template) => {
if (template !== false) {
return template.displayBlock(name, context, outputBuffer, blocks, false);
} else {
throw new TwingErrorRuntime(`The template has no parent and no traits defining the "${name}" block.`, -1, this.source);
}
});
}
});
}
/**
* Renders a parent block.
*
* @param {string} name The block name to display from the parent
* @param {*} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
*
* @returns {Promise<string>} The rendered block
*/
protected renderParentBlock(name: string, context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap): Promise<string> {
outputBuffer.start();
return this.getBlocks().then((blocks) => {
return this.displayParentBlock(name, context, outputBuffer, blocks).then(() => {
return outputBuffer.getAndClean() as string;
})
});
}
/**
* Renders a block.
*
* @param {string} name The block name to display
* @param {any} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
* @param {boolean} useBlocks Whether to use the active set of blocks
*
* @return {Promise<string>} The rendered block
*/
protected renderBlock(name: string, context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap = new Map(), useBlocks = true): Promise<string> {
outputBuffer.start();
return this.displayBlock(name, context, outputBuffer, blocks, useBlocks).then(() => {
return outputBuffer.getAndClean() as string;
});
}
/**
* Returns whether a block exists or not in the active context of the template.
*
* This method checks blocks defined in the active template or defined in "used" traits or defined in parent templates.
*
* @param {string} name The block name
* @param {any} context The context
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
*
* @return {Promise<boolean>} true if the block exists, false otherwise
*/
public hasBlock(name: string, context: any, blocks: TwingTemplateBlocksMap = new Map()): Promise<boolean> {
if (blocks.has(name)) {
return Promise.resolve(true);
} else {
return this.getBlocks().then((blocks) => {
if (blocks.has(name)) {
return Promise.resolve(true);
} else {
return this.getParent(context).then((parent) => {
if (parent) {
return parent.hasBlock(name, context);
} else {
return false;
}
});
}
})
}
}
/**
* @param {string} name The name of the macro
*
* @return {Promise<boolean>}
*/
public hasMacro(name: string): Promise<boolean> {
// @see https://github.com/twigphp/Twig/issues/3174 as to why we don't check macro existence in parents
return Promise.resolve(this.macroHandlers.has(name));
}
/**
* @param name The name of the macro
*/
public getMacro(name: string): Promise<TwingTemplateMacroHandler> {
return this.hasMacro(name).then((hasMacro) => {
if (hasMacro) {
return this.macroHandlers.get(name);
}
else {
return null;
}
})
}
public loadTemplate(templates: TwingTemplate | Map<number, TwingTemplate> | string, line: number = null, index: number = 0): Promise<TwingTemplate> {
let promise: Promise<TwingTemplate>;
if (typeof templates === 'string') {
promise = this.environment.loadTemplate(templates, index, this.source);
} else if (templates instanceof TwingTemplate) {
promise = Promise.resolve(templates);
} else {
promise = this.environment.resolveTemplate([...templates.values()], this.source);
}
return promise.catch((e: TwingError) => {
if (e.getTemplateLine() !== -1) {
throw e;
}
if (line) {
e.setTemplateLine(line);
}
throw e;
});
}
/**
* Returns template traits.
*
* @returns {Promise<TwingTemplateBlocksMap>} A map of traits
*/
public getTraits(): Promise<TwingTemplateBlocksMap> {
if (this.traits) {
return Promise.resolve(this.traits);
} else {
return this.doGetTraits().then((traits) => {
this.traits = traits;
return traits;
});
}
}
protected doGetTraits(): Promise<TwingTemplateBlocksMap> {
return Promise.resolve(new Map());
}
public display(context: any, blocks: TwingTemplateBlocksMap = new Map(), outputBuffer?: TwingOutputBuffer): Promise<void> {
if (!outputBuffer) {
outputBuffer = new TwingOutputBuffer();
}
if (context === null) {
throw new TypeError('Argument 1 passed to TwingTemplate::display() must be an iterator, null given');
}
if (!isMap(context)) {
context = iteratorToMap(context);
}
context = new TwingContext(this.environment.mergeGlobals(context));
return this.getBlocks().then((ownBlocks) => this.displayWithErrorHandling(context, outputBuffer, merge(ownBlocks, blocks)));
}
protected displayWithErrorHandling(context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap = new Map()): Promise<void> {
return this.doDisplay(context, outputBuffer, blocks).catch((e) => {
if (e instanceof TwingError) {
if (!e.getSourceContext()) {
e.setSourceContext(this.source);
}
} else {
e = new TwingErrorRuntime(`An exception has been thrown during the rendering of a template ("${e.message}").`, -1, this.source, e);
}
throw e;
});
}
public render(context: any, outputBuffer?: TwingOutputBuffer): Promise<string> {
if (!outputBuffer) {
outputBuffer = new TwingOutputBuffer();
}
let level = outputBuffer.getLevel();
outputBuffer.start();
return this.display(context, undefined, outputBuffer)
.then(() => {
return outputBuffer.getAndClean() as string;
})
.catch((e) => {
while (outputBuffer.getLevel() > level) {
outputBuffer.endAndClean();
}
throw e;
})
}
/**
* Auto-generated method to display the template with the given context.
*
* @param {any} context An array of parameters to pass to the template
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks
*/
protected abstract doDisplay(context: any, outputBuffer: TwingOutputBuffer, blocks: TwingTemplateBlocksMap): Promise<void>;
protected doGetParent(context: any): Promise<TwingTemplate | string | false> {
return Promise.resolve(false);
}
protected callMacro(template: TwingTemplate, name: string, outputBuffer: TwingOutputBuffer, args: any[], lineno: number, context: TwingContext<any, any>, source: TwingSource): Promise<string> {
let getHandler = (template: TwingTemplate): Promise<TwingTemplateMacroHandler> => {
if (template.macroHandlers.has(name)) {
return Promise.resolve(template.macroHandlers.get(name));
} else {
return template.getParent(context).then((parent) => {
if (parent) {
return getHandler(parent);
} else {
return null;
}
});
}
};
return getHandler(template).then((handler) => {
if (handler) {
return handler(outputBuffer, ...args);
} else {
throw new TwingErrorRuntime(`Macro "${name}" is not defined in template "${template.templateName}".`, lineno, source);
}
});
}
public traceableMethod<T>(method: Function, lineno: number, source: TwingSource): TwingTemplateTraceableMethod<T> {
return function () {
return (method.apply(null, arguments) as Promise<T>).catch((e) => {
if (e instanceof TwingError) {
if (e.getTemplateLine() === -1) {
e.setTemplateLine(lineno);
e.setSourceContext(source);
}
} else {
throw new TwingErrorRuntime(`An exception has been thrown during the rendering of a template ("${e.message}").`, lineno, source, e);
}
throw e;
});
}
}
public traceableRenderBlock(lineno: number, source: TwingSource): TwingTemplateTraceableMethod<string> {
return this.traceableMethod(this.renderBlock.bind(this), lineno, source);
}
public traceableRenderParentBlock(lineno: number, source: TwingSource): TwingTemplateTraceableMethod<string> {
return this.traceableMethod(this.renderParentBlock.bind(this), lineno, source);
}
public traceableHasBlock(lineno: number, source: TwingSource): TwingTemplateTraceableMethod<boolean> {
return this.traceableMethod(this.hasBlock.bind(this), lineno, source);
}
protected concatenate(object1: any, object2: any): string {
if (isNullOrUndefined(object1)) {
object1 = '';
}
if (isNullOrUndefined(object2)) {
object2 = '';
}
return String(object1) + String(object2);
}
protected get cloneMap(): <K, V>(m: Map<K, V>) => Map<K, V> {
return cloneMap;
}
protected get compare(): (a: any, b: any) => boolean {
return compare;
}
protected get constant(): (name: string, object: any) => any {
return (name: string, object: any) => {
return constant(this, name, object);
}
}
protected get convertToMap(): (iterable: any) => Map<any, any> {
return iteratorToMap;
}
protected get count(): (a: any) => number {
return count;
}
protected get createRange(): (low: any, high: any, step: number) => Map<number, any> {
return createRange;
}
protected get ensureTraversable(): <T>(candidate: T[]) => T[] | [] {
return ensureTraversable;
}
protected get get(): (object: any, property: any) => any {
return (object, property) => {
if (isMap(object) || isPlainObject(object)) {
return get(object, property);
}
};
}
protected get getAttribute(): (env: TwingEnvironment, object: any, item: any, _arguments: Map<any, any>, type: string, isDefinedTest: boolean, ignoreStrictCheck: boolean, sandboxed: boolean) => any {
return getAttribute;
}
protected get include(): (context: any, outputBuffer: TwingOutputBuffer, templates: string | Map<number, string | TwingTemplate> | TwingTemplate, variables: any, withContext: boolean, ignoreMissing: boolean, line: number) => Promise<string> {
return (context, outputBuffer, templates, variables, withContext, ignoreMissing, line) => {
return include(this, context, outputBuffer, templates, variables, withContext, ignoreMissing).catch((e: TwingError) => {
if (e.getTemplateLine() === -1) {
e.setTemplateLine(line);
}
throw e;
});
}
}
protected get isCountable(): (candidate: any) => boolean {
return isCountable;
}
protected get isIn(): (a: any, b: any) => boolean {
return isIn;
}
protected get iterate(): (it: any, cb: IterateCallback) => Promise<void> {
return iterate;
}
protected get merge(): <V>(iterable1: Map<any, V>, iterable2: Map<any, V>) => Map<any, V> {
return merge;
}
protected get parseRegExp(): (input: string) => RegExp {
return parseRegex;
}
protected get Context(): typeof TwingContext {
return TwingContext;
}
protected get Markup(): typeof TwingMarkup {
return TwingMarkup;
}
protected get RuntimeError(): typeof TwingErrorRuntime {
return TwingErrorRuntime;
}
protected get SandboxSecurityError(): typeof TwingSandboxSecurityError {
return TwingSandboxSecurityError;
}
protected get SandboxSecurityNotAllowedFilterError(): typeof TwingSandboxSecurityNotAllowedFilterError {
return TwingSandboxSecurityNotAllowedFilterError;
}
protected get SandboxSecurityNotAllowedFunctionError(): typeof TwingSandboxSecurityNotAllowedFunctionError {
return TwingSandboxSecurityNotAllowedFunctionError;
}
protected get SandboxSecurityNotAllowedTagError(): typeof TwingSandboxSecurityNotAllowedTagError {
return TwingSandboxSecurityNotAllowedTagError;
}
protected get Source(): typeof TwingSource {
return TwingSource;
}
} | the_stack |
import ts, {
ClassDeclaration,
isClassDeclaration,
isFunctionTypeNode,
isJsxOpeningElement,
isJsxSelfClosingElement,
isJsxText,
isPropertySignature,
Node,
SourceFile,
FunctionDeclaration,
isVariableStatement,
isJsxAttribute,
isJsxAttributes,
VariableStatement,
isReturnStatement,
isIdentifier,
isJsxClosingFragment,
isJsxOpeningFragment,
isJsxElement,
isBlock,
FunctionTypeNode,
PropertySignature,
isTypeLiteralNode,
isUnionTypeNode,
isParenthesizedTypeNode,
isFunctionExpression,
Block,
} from 'typescript'
import { commands, Location, Position, TextDocument, TextEditor, SymbolInformation } from 'vscode'
import {
isInReactModule,
getDefinitionInAntdModule,
matchAntdModule,
tryMatchComponentName,
} from './utils'
import { composeHandlerString, addHandlerPrefix } from './insertion'
/**
* NOTE: https://github.com/microsoft/TypeScript/blob/master/lib/typescript.d.ts
* JsxText = 11,
* PropertySignature = 157,
* FunctionType = 169,
* ClassDeclaration = 244,
* JsxSelfClosingElement = 265,
* JsxOpeningElement = 266,
*/
/**
* Return nearest JsxElement at position, return null if not found.
*/
export async function getClosetAntdJsxElementNode(
document: TextDocument,
position: Position
): Promise<string | null> {
const offset = document.offsetAt(position)
// NOTE: change symbol to common letter as a legal JSX attribute for AST right paring
const firstHalf = document.getText().slice(0, offset - 1)
const secondHalf = document.getText().slice(offset)
const source = firstHalf + 'Q' + secondHalf // 'Q' could be any character
const sFile = ts.createSourceFile(document.uri.toString(), source, ts.ScriptTarget.Latest)
const parents: Node[] = getNodeWithParentsAt(sFile, offset - 1)
if (!parents.length) return null
const [jsxElement, jsxAttributes, jsxAttribute, identifier] = parents.slice(-4)
if (
(isJsxSelfClosingElement(jsxElement) || isJsxOpeningElement(jsxElement)) &&
isJsxAttributes(jsxAttributes) &&
isJsxAttribute(jsxAttribute) &&
isIdentifier(identifier)
) {
const definitionLoc = await getDefinitionInAntdModule(
document,
document.positionAt(jsxElement.tagName.end)
)
if (!definitionLoc) return null
const definitionPath = definitionLoc.uri.path
const antdMatched = matchAntdModule(definitionPath)
const interaceName = definitionLoc.text
if (antdMatched === null) return null // return if not from antd
const { componentFolder } = antdMatched
const fullComponentName = tryMatchComponentName(interaceName, componentFolder)
if (!fullComponentName) return null
return fullComponentName
}
return null
}
/**
* Get symbol name of given VSCode location
*/
export async function getContainerSymbolAtLocation(loc: Location) {
const { uri, range } = loc
const symbols = await commands.executeCommand<SymbolInformation[]>(
'vscode.executeDocumentSymbolProvider',
uri
)
if (!symbols) return null
const container = symbols.find((symbol) => {
// NOTE: symbol tree is not from line start and line end
return (
symbol.location.range.start.line <= range.start.line &&
symbol.location.range.end.line >= range.end.line
)
})
return container ? container.name : null
}
/**
* Return nearest userland component (class component / functional component) with condition
*/
export async function getParentsWhen<T extends Node>(
document: TextDocument,
position: Position,
condition: (parent: Node, document: TextDocument) => Promise<boolean>,
direction: 'inward' | 'outward'
): Promise<T | null> {
const sFile = ts.createSourceFile(
document.uri.toString(),
document.getText(),
ts.ScriptTarget.Latest
)
const offset = document.offsetAt(position)
// parents should starts from the closest
let parents: Node[] = getNodeWithParentsAt(sFile, offset)
if (direction === 'outward') parents = parents.reverse()
const typeComponentNodePromises = parents.map((parent) => {
return condition(parent, document)
})
const typeJudgementResult = await Promise.all(typeComponentNodePromises)
const targetNodeIndex = typeJudgementResult.findIndex(Boolean)
if (targetNodeIndex === -1) return null
const typeComponentNode = parents[targetNodeIndex] as T
return typeComponentNode
}
/**
* Insert string to class component
* This function adapt indent and fill in handler template
*/
export async function insertStringToClassComponent(args: {
editor: TextEditor
document: TextDocument
classNode: ClassDeclaration
symbolPosition: Position
fullHandlerName: string
indent: number
handlerParams: FunctionParam[]
}): Promise<Position | null> {
const {
editor,
document,
indent,
classNode,
symbolPosition,
fullHandlerName,
handlerParams,
} = args
const offset = document.offsetAt(symbolPosition)
const memberContainsSymbol = classNode.members.find((member) => {
return offsetContains(offset, member.pos, member.end)
})
if (!memberContainsSymbol) return null
// memberContainsSymbol.pos point to the previous member ending position
const insertAt = document.positionAt(memberContainsSymbol.pos)
await editor.edit((builder) => {
builder.insert(insertAt, composeHandlerString(fullHandlerName, handlerParams, indent, 'class'))
})
return insertAt
}
/**
* Insert string to functional component
* This function adapt indent and fill in handler template
*/
export async function insertStringToFunctionalComponent(args: {
editor: TextEditor
document: TextDocument
indent: number
position: Position
symbolPosition: Position
fullHandlerName: string
handlerParams: FunctionParam[]
}): Promise<Position | null> {
const {
editor,
document,
indent,
position,
symbolPosition,
fullHandlerName,
handlerParams,
} = args
const sFile = ts.createSourceFile(
document.uri.toString(),
document.getText(),
ts.ScriptTarget.Latest
)
// find outermost statement
const parents = getNodeWithParentsAt(sFile, document.offsetAt(symbolPosition))
// exclude outermost component, cause we should insert handler in it
const closetBlock = parents.slice(1).find((parent) => {
return isBlock(parent)
}) as Block
// arrow function
// function declaration
// function variable
// anonymous function
if (!closetBlock) return null
const subStatement = closetBlock.statements.find((statement) =>
offsetContains(document.offsetAt(position), statement.pos, statement.end)
)
if (!subStatement) return null
const insertAt = document.positionAt(subStatement.pos)
editor.edit((builder) => {
builder.insert(
insertAt,
composeHandlerString(fullHandlerName, handlerParams, indent, 'functional')
)
})
return insertAt
}
/**
* Get ast node at postion, return with it's parent nodes
*/
export async function isClassExtendsReactComponent(
node: Node,
document: TextDocument
): Promise<boolean> {
if (!isClassDeclaration(node)) return false
if (!node.heritageClauses?.length) return false
const isReactClassPromises = node.heritageClauses.map(async (heritage) => {
const expressions = heritage.types.map((type) => type.expression)
const isFromReactPromises = expressions.map(async (expression) => {
const position = document.positionAt(expression.pos + 1)
const typeDefinition = await commands.executeCommand<Location[]>(
'vscode.executeTypeDefinitionProvider',
document.uri,
position
)
const hasDefinitionFromReact = !!typeDefinition?.some((definition) =>
isInReactModule(definition.uri.path)
)
return hasDefinitionFromReact
})
const result = await Promise.all(isFromReactPromises)
return result.some(Boolean)
})
const isReactClassResult = await Promise.all(isReactClassPromises)
const isReactClass = isReactClassResult.some(Boolean)
return isReactClass
}
/**
* Whether offset between start and end
*/
function offsetContains(offset: number, startOrEnd: number, endOrStart: number) {
const [start, end] = startOrEnd > endOrStart ? [endOrStart, startOrEnd] : [startOrEnd, endOrStart]
return start <= offset && end >= offset
}
/**
* Get function params from dts string
*/
export interface FunctionParam {
type: string
text: string
}
export function getFunctionParams(dtsString: string): FunctionParam[] | null {
// NOTE: definition is a property, it should be wrapped in type
const dtsTypeString = `type DUMMY = {
${dtsString}
}`
const sCode: SourceFile = ts.createSourceFile('', dtsTypeString, ts.ScriptTarget.Latest)
let paramTexts: string[] = []
traverseWithParents(sCode, (node, stack) => {
if (isPropertySignature(node)) {
paramTexts = extractParamsFromPropertySignature(node, sCode)
}
})
return paramTexts.map((param) => ({ type: '', text: param }))
}
/**
* Extract function params from property signature
*/
function extractParamsFromPropertySignature(
signature: PropertySignature,
sCode: SourceFile
): string[] {
const paramTexts: string[] = []
const sigType = signature.type
if (!sigType) return paramTexts
// e.g. onChange?: (affixed?: boolean) => void;
if (isFunctionTypeNode(sigType)) {
paramTexts.push(...extractParamsFromFunctionType(sigType, sCode))
}
// e.g. tipFormatter?: null | ((value: number) => React.ReactNode);
if (isUnionTypeNode(sigType)) {
// should not can accept two function type
const functionType = sigType.types.filter(isParenthesizedTypeNode)[0].type
if (!functionType) return paramTexts
if (isFunctionTypeNode(functionType)) {
paramTexts.push(...extractParamsFromFunctionType(functionType, sCode))
}
}
return paramTexts
}
/**
* Extract parameter and its type from FunctionType node
*/
function extractParamsFromFunctionType(node: FunctionTypeNode, sCode: SourceFile): string[] {
const typeParamsText = node.parameters.map((p) => {
return p.name.getText(sCode as SourceFile)
})
return typeParamsText
}
/**
* Traverse ts ast
*/
interface TraverseActions {
enter?: (node: Node) => boolean
leave?: Function
}
const noop = () => true
export function traverseTsAst(entryNode: Node, traverseActions: TraverseActions) {
const { enter: _enter, leave: _leave } = traverseActions
const enter = typeof _enter === 'function' ? _enter : noop
const leave = typeof _leave === 'function' ? _leave : noop
const traverseNode = (node: Node) => {
const shouldVisitChildren = enter(node)
if (shouldVisitChildren) {
node.forEachChild(traverseNode)
}
leave(node)
}
traverseNode(entryNode)
}
/**
* Traverse node with parents
*/
export function traverseWithParents(
entryNode: Node,
visitor: (node: Node, stack: Node[]) => boolean | void
) {
const parentStack: Node[] = []
const enter = (node: Node) => {
parentStack.push(node)
visitor(node, parentStack)
return true
}
traverseTsAst(entryNode, {
enter: enter,
})
}
/**
* Get ast node at postion, return with it's parent nodes
*/
function getNodeWithParentsAt(entryNode: Node, offset: number) {
const parentStack: Node[] = []
const enter = (node: Node) => {
const start = node.pos
const end = node.end
const hasFind = offsetContains(offset, start, end)
if (hasFind) {
parentStack.push(node)
return true
} else {
return false
}
}
traverseTsAst(entryNode, {
enter: enter,
})
return parentStack
} | the_stack |
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Config } from '../../../environments/environment';
import { Util } from './util';
import { LogUtil } from './../log/index';
import { ShopVO, ShopUrlVO, ShopAliasVO, ShopSeoVO, ShopSupportedCurrenciesVO, ShopLanguagesVO, ShopLocationsVO, AttrValueShopVO, CategoryVO, Pair, ShopSummaryVO, SubShopVO } from '../model/index';
import { ErrorEventBus } from './error-event-bus.service';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
/**
* Shop service has all methods to work with shop.
*/
@Injectable()
export class ShopService {
private _serviceBaseUrl = Config.API + 'service/shops'; // URL to web api
/**
* Construct shop service, which has methods to work with information related to shop(s).
* @param http http client.
*/
constructor (private http: HttpClient) {
LogUtil.debug('ShopService constructed');
}
/**
* Get list of all shop, which are accesable to manage or view,
* @returns {Observable<T>}
*/
getAllShops():Observable<ShopVO[]> {
return this.http.get<ShopVO[]>(this._serviceBaseUrl, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get detail shop information by given id.
* @param id giveh shop id.
* @returns {Observable<T>}
*/
getShop(id:number):Observable<ShopVO> {
LogUtil.debug('ShopService get shop by id ' + id);
return this.http.get<ShopVO>(this._serviceBaseUrl + '/' + id, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get list of all shop, which are accesable to manage or view,
* @returns {Observable<T>}
*/
getSubShops(id:number):Observable<ShopVO[]> {
return this.http.get<ShopVO[]>(this._serviceBaseUrl + '/' + id + '/subs', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Create empty shop detail.
* @returns {Promise<ShopVO>}
*/
createShop():Promise<ShopVO> {
let shopVOTemplate : ShopVO = {'shopId': 0, 'disabled': false, 'code' : '', 'masterId': undefined, 'masterCode': null, 'name': '', 'description' : '', 'fspointer' : ''};
let newShop : ShopVO = Util.clone(shopVOTemplate);
return Promise.resolve(newShop);
}
/**
* Save or create given shop detail - the root of shop related information.
* @param shop
* @returns {Observable<T>}
*/
saveSubShop(shop:SubShopVO):Observable<ShopVO> {
LogUtil.debug('ShopService save sub shop ', shop);
let body = JSON.stringify(shop);
return this.http.post<ShopVO>(this._serviceBaseUrl + '/subs', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Save or create given shop detail - the root of shop related information.
* @param shop
* @returns {Observable<T>}
*/
saveShop(shop:ShopVO):Observable<ShopVO> {
LogUtil.debug('ShopService save shop ', shop);
let body = JSON.stringify(shop);
if (shop.shopId === 0) {
return this.http.post<ShopVO>(this._serviceBaseUrl, body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
} else {
return this.http.put<ShopVO>(this._serviceBaseUrl, body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
}
/**
* Save or create given shop detail - the root of shop related information.
* @param shop shop
* @param state enabled or disabled
* @returns {Observable<T>}
*/
updateDisabledFlag(shop:ShopVO, state:boolean):Observable<ShopVO> {
LogUtil.debug('ShopService change state shop ', shop.shopId, state);
let body = JSON.stringify({ disabled: state });
return this.http.post<ShopVO>(this._serviceBaseUrl + '/' + shop.shopId + '/status', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get summary information for given shop id.
* @param shopId given shop id
* @param lang language
* @return {Promise<ShopSummaryVO>}
*/
getShopSummary(shopId:number, lang:string):Observable<ShopSummaryVO> {
LogUtil.debug('ShopService get shop summary info ', shopId, lang);
return this.http.get<ShopSummaryVO>(this._serviceBaseUrl + '/' + shopId + '/summary?lang=' + lang, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get localization information for given shop id.
* @param shopId given shop id
* @return {Promise<ShopSeoVO>}
*/
getShopSeo(shopId:number):Observable<ShopSeoVO> {
LogUtil.debug('ShopService get shop seo info ', shopId);
return this.http.get<ShopSeoVO>(this._serviceBaseUrl + '/' + shopId + '/seo', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Save changes in localisation information
* @param shopSeoVO
* @returns {Promise<ShopSeoVO>}
*/
saveShopSeo(shopSeoVO:ShopSeoVO):Observable<ShopSeoVO> {
LogUtil.debug('ShopService save localization info', shopSeoVO);
let body = JSON.stringify(shopSeoVO);
return this.http.put<ShopSeoVO>(this._serviceBaseUrl + '/seo', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get urls for gien shop id.
* @param id
* @returns {Observable<T>}
*/
getShopUrls(id:number):Observable<ShopUrlVO> {
return this.http.get<ShopUrlVO>(this._serviceBaseUrl + '/' + id + '/urls', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Save changes in list of shop urls
* @param shopUrl
* @returns {Promise<ShopUrlVO>}
*/
saveShopUrls(shopUrl:ShopUrlVO):Observable<ShopUrlVO> {
let body = JSON.stringify(shopUrl);
return this.http.put<ShopUrlVO>(this._serviceBaseUrl + '/urls', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get aliases for gien shop id.
* @param id
* @returns {Observable<T>}
*/
getShopAliases(id:number):Observable<ShopAliasVO> {
return this.http.get<ShopAliasVO>(this._serviceBaseUrl + '/' + id + '/aliases', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Save changes in list of shop aliases
* @param shopAlias
* @returns {Promise<ShopAliasVO>}
*/
saveShopAliases(shopAlias:ShopAliasVO):Observable<ShopAliasVO> {
let body = JSON.stringify(shopAlias);
return this.http.put<ShopAliasVO>(this._serviceBaseUrl + '/aliases', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get currencies for given shop id.
* @param id
* @returns {Observable<T>}
*/
getShopCurrencies(id:number):Observable<ShopSupportedCurrenciesVO> {
return this.http.get<ShopSupportedCurrenciesVO>(this._serviceBaseUrl + '/' + id + '/currencies', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Update supported currencies.
* @param curr
* @returns {Observable<T>}
*/
saveShopCurrencies(curr:ShopSupportedCurrenciesVO):Observable<ShopSupportedCurrenciesVO> {
let body = JSON.stringify(curr);
return this.http.put<ShopSupportedCurrenciesVO>(this._serviceBaseUrl + '/currencies', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get languages for given shop id.
* @param id
* @returns {Observable<T>}
*/
getShopLanguages(id:number):Observable<ShopLanguagesVO> {
return this.http.get<ShopLanguagesVO>(this._serviceBaseUrl + '/' + id + '/languages', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Update supported languages.
* @param langs
* @returns {Observable<T>}
*/
saveShopLanguages(langs:ShopLanguagesVO):Observable<ShopLanguagesVO> {
let body = JSON.stringify(langs);
return this.http.put<ShopLanguagesVO>(this._serviceBaseUrl + '/languages', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get urls for given shop id.
* @param id
* @returns {Observable<T>}
*/
getShopLocations(id:number):Observable<ShopLocationsVO> {
return this.http.get<ShopLocationsVO>(this._serviceBaseUrl + '/' + id + '/locations', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Update supported locations.
* @param locs
* @returns {Observable<T>}
*/
saveShopLocations(locs:ShopLocationsVO):Observable<ShopLocationsVO> {
let body = JSON.stringify(locs);
return this.http.put<ShopLocationsVO>(this._serviceBaseUrl + '/locations', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get all categories assigned to given shop.
* @param id shop id
* @returns {Observable<T>}
*/
getShopCategories(id:number):Observable<CategoryVO[]> {
return this.http.get<CategoryVO[]>(this._serviceBaseUrl + '/' + id + '/categories', { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Save changes in shop categories.
* @param shopId
* @param cats
* @returns {Observable<T>}
*/
saveShopCategories(shopId:number, cats : CategoryVO[]):Observable<CategoryVO[]> {
let body = JSON.stringify(cats);
LogUtil.debug('Save assigned categories ', cats);
return this.http.put<CategoryVO[]>(this._serviceBaseUrl + '/' + shopId + '/categories', body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Get attributes for given shop id.
* @param id
* @param includeSecure
* @returns {Observable<T>}
*/
getShopAttributes(id:number, includeSecure:boolean):Observable<AttrValueShopVO[]> {
return this.http.get<AttrValueShopVO[]>(this._serviceBaseUrl + '/' + id + '/attributes?includeSecure=' + includeSecure, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
/**
* Update supported attributes.
* @param attrs
* @param includeSecure
* @returns {Observable<T>}
*/
saveShopAttributes(attrs:Array<Pair<AttrValueShopVO, boolean>>, includeSecure:boolean):Observable<AttrValueShopVO[]> {
let body = JSON.stringify(attrs);
return this.http.post<AttrValueShopVO[]>(this._serviceBaseUrl + '/attributes?includeSecure=' + includeSecure, body, { headers: Util.requestOptions() })
.pipe(catchError(this.handleError));
}
private handleError (error:any) {
LogUtil.error('ShopService Server error: ', error);
ErrorEventBus.getErrorEventBus().emit(error);
let message = Util.determineErrorMessage(error);
return throwError(message.message || 'Server error');
}
} | the_stack |
import mongoose from 'mongoose';
import { getInstance } from '../setup-crowi';
describe('UserGroupService', () => {
let crowi;
let User;
let UserGroup;
let UserGroupRelation;
const groupId1 = new mongoose.Types.ObjectId();
const groupId2 = new mongoose.Types.ObjectId();
const groupId3 = new mongoose.Types.ObjectId();
const groupId4 = new mongoose.Types.ObjectId();
const groupId5 = new mongoose.Types.ObjectId();
const groupId6 = new mongoose.Types.ObjectId();
const groupId7 = new mongoose.Types.ObjectId();
const groupId8 = new mongoose.Types.ObjectId();
const groupId9 = new mongoose.Types.ObjectId();
const groupId10 = new mongoose.Types.ObjectId();
const groupId11 = new mongoose.Types.ObjectId();
const groupId12 = new mongoose.Types.ObjectId();
const userId1 = new mongoose.Types.ObjectId();
beforeAll(async() => {
crowi = await getInstance();
User = mongoose.model('User');
UserGroup = mongoose.model('UserGroup');
UserGroupRelation = mongoose.model('UserGroupRelation');
await User.insertMany([
// ug -> User Group
{
_id: userId1, name: 'ug_test_user1', username: 'ug_test_user1', email: 'ug_test_user1@example.com',
},
]);
// Create Groups
await UserGroup.insertMany([
// No parent
{
_id: groupId1,
name: 'v5_group1',
description: 'description1',
},
// No parent
{
_id: groupId2,
name: 'v5_group2',
description: 'description2',
},
// No parent
{
_id: groupId3,
name: 'v5_group3',
description: 'description3',
},
// No parent
{
_id: groupId4,
name: 'v5_group4',
description: 'description4',
},
// No parent
{
_id: groupId5,
name: 'v5_group5',
description: 'description5',
},
// No parent
{
_id: groupId6,
name: 'v5_group6',
description: 'description6',
},
// No parent
{
_id: groupId7,
name: 'v5_group7',
description: 'description7',
parent: groupId6,
},
// No parent
{
_id: groupId8,
name: 'v5_group8',
description: 'description8',
},
{
_id: groupId9,
name: 'v5_group9',
description: 'description9',
},
{
_id: groupId10,
name: 'v5_group10',
description: 'description10',
parent: groupId9,
},
{
_id: groupId11,
name: 'v5_group11',
description: 'descriptio11',
},
{
_id: groupId12,
name: 'v5_group12',
description: 'description12',
parent: groupId11,
},
]);
// Create UserGroupRelations
await UserGroupRelation.insertMany([
{
relatedGroup: groupId4,
relatedUser: userId1,
},
{
relatedGroup: groupId6,
relatedUser: userId1,
},
{
relatedGroup: groupId8,
relatedUser: userId1,
},
{
relatedGroup: groupId9,
relatedUser: userId1,
},
{
relatedGroup: groupId10,
relatedUser: userId1,
},
{
relatedGroup: groupId11,
relatedUser: userId1,
},
{
relatedGroup: groupId12,
relatedUser: userId1,
},
]);
});
/*
* Update UserGroup
*/
test('Updated values should be reflected. (name, description, parent)', async() => {
const userGroup2 = await UserGroup.findOne({ _id: groupId2 });
const newGroupName = 'v5_group1_new';
const newGroupDescription = 'description1_new';
const newParentId = userGroup2._id;
const updatedUserGroup = await crowi.userGroupService.updateGroup(groupId1, newGroupName, newGroupDescription, newParentId);
expect(updatedUserGroup.name).toBe(newGroupName);
expect(updatedUserGroup.description).toBe(newGroupDescription);
expect(updatedUserGroup.parent).toStrictEqual(newParentId);
});
test('Should throw an error when trying to set existing group name', async() => {
const userGroup2 = await UserGroup.findOne({ _id: groupId2 });
const result = crowi.userGroupService.updateGroup(groupId1, userGroup2.name);
await expect(result).rejects.toThrow('The group name is already taken');
});
test('Parent should be null when parent group is released', async() => {
const userGroup = await UserGroup.findOne({ _id: groupId3 });
const updatedUserGroup = await crowi.userGroupService.updateGroup(userGroup._id, userGroup.name, userGroup.description, null);
expect(updatedUserGroup.parent).toBeNull();
});
/*
* forceUpdateParents: false
*/
test('Should throw an error when users in child group do not exist in parent group', async() => {
const userGroup4 = await UserGroup.findOne({ _id: groupId4, parent: null });
const result = crowi.userGroupService.updateGroup(userGroup4._id, userGroup4.name, userGroup4.description, groupId5);
await expect(result).rejects.toThrow('The parent group does not contain the users in this group.');
});
/*
* forceUpdateParents: true
*/
test('User should be included to parent group (2 groups ver)', async() => {
const userGroup4 = await UserGroup.findOne({ _id: groupId4, parent: null });
const userGroup5 = await UserGroup.findOne({ _id: groupId5, parent: null });
// userGroup4 has userId1
const userGroupRelation4BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: userGroup4, relatedUser: userId1 });
expect(userGroupRelation4BeforeUpdate).not.toBeNull();
// userGroup5 has not userId1
const userGroupRelation5BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: userGroup5, relatedUser: userId1 });
expect(userGroupRelation5BeforeUpdate).toBeNull();
// update userGroup4's parent with userGroup5 (forceUpdate: true)
const forceUpdateParents = true;
const updatedUserGroup = await crowi.userGroupService.updateGroup(
userGroup4._id, userGroup4.name, userGroup4.description, groupId5, forceUpdateParents,
);
expect(updatedUserGroup.parent).toStrictEqual(groupId5);
// userGroup5 should have userId1
const userGroupRelation5AfterUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId5, relatedUser: userGroupRelation4BeforeUpdate.relatedUser });
expect(userGroupRelation5AfterUpdate).not.toBeNull();
});
test('User should be included to parent group (3 groups ver)', async() => {
const userGroup8 = await UserGroup.findOne({ _id: groupId8, parent: null });
// userGroup7 has not userId1
const userGroupRelation6BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId6, relatedUser: userId1 });
const userGroupRelation7BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId7, relatedUser: userId1 });
const userGroupRelation8BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId8, relatedUser: userId1 });
expect(userGroupRelation6BeforeUpdate).not.toBeNull();
// userGroup7 does not have userId1
expect(userGroupRelation7BeforeUpdate).toBeNull();
expect(userGroupRelation8BeforeUpdate).not.toBeNull();
// update userGroup8's parent with userGroup7 (forceUpdate: true)
const forceUpdateParents = true;
await crowi.userGroupService.updateGroup(
userGroup8._id, userGroup8.name, userGroup8.description, groupId7, forceUpdateParents,
);
const userGroupRelation6AfterUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId6, relatedUser: userId1 });
const userGroupRelation7AfterUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId7, relatedUser: userId1 });
const userGroupRelation8AfterUpdate = await UserGroupRelation.findOne({ relatedGroup: groupId8, relatedUser: userId1 });
expect(userGroupRelation6AfterUpdate).not.toBeNull();
// userGroup7 should have userId1
expect(userGroupRelation7AfterUpdate).not.toBeNull();
expect(userGroupRelation8AfterUpdate).not.toBeNull();
});
test('Should throw an error when trying to choose parent from descendant groups.', async() => {
const userGroup9 = await UserGroup.findOne({ _id: groupId9, parent: null });
const userGroup10 = await UserGroup.findOne({ _id: groupId10, parent: groupId9 });
const userGroupRelation9BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: userGroup9._id, relatedUser: userId1 });
const userGroupRelation10BeforeUpdate = await UserGroupRelation.findOne({ relatedGroup: userGroup10._id, relatedUser: userId1 });
expect(userGroupRelation9BeforeUpdate).not.toBeNull();
expect(userGroupRelation10BeforeUpdate).not.toBeNull();
const result = crowi.userGroupService.updateGroup(
userGroup9._id, userGroup9.name, userGroup9.description, userGroup10._id,
);
await expect(result).rejects.toThrow('It is not allowed to choose parent from descendant groups.');
});
test('User should be deleted from child groups when the user excluded from the parent group', async() => {
const userGroup11 = await UserGroup.findOne({ _id: groupId11, parent: null });
const userGroup12 = await UserGroup.findOne({ _id: groupId12, parent: groupId11 });
// Both groups have user1
const userGroupRelation11BeforeRemove = await UserGroupRelation.findOne({ relatedGroup: userGroup11._id, relatedUser: userId1 });
const userGroupRelation12BeforeRemove = await UserGroupRelation.findOne({ relatedGroup: userGroup12._id, relatedUser: userId1 });
expect(userGroupRelation11BeforeRemove).not.toBeNull();
expect(userGroupRelation12BeforeRemove).not.toBeNull();
// remove user1 from the parent group
await crowi.userGroupService.removeUserByUsername(
userGroup11._id, 'ug_test_user1',
);
// Both groups have not user1
const userGroupRelation11AfterRemove = await UserGroupRelation.findOne({ relatedGroup: userGroup11._id, relatedUser: userId1 });
const userGroupRelation12AfterRemove = await UserGroupRelation.findOne({ relatedGroup: userGroup12._id, relatedUser: userId1 });
await expect(userGroupRelation11AfterRemove).toBeNull();
await expect(userGroupRelation12AfterRemove).toBeNull();
});
}); | the_stack |
import sinon from 'sinon';
import utils from './data-generator.utils';
import * as servicesModel from '../src/db/services.schema';
import { expect } from 'chai';
describe('Services Schema', async () => {
beforeEach(async () => {
await servicesModel.Services.sync({ force: true });
});
afterEach(async () => {
await servicesModel.Services.drop();
sinon.restore();
});
it('should create a new service record', async () => {
const serviceRecordData = utils.randomServiceRecord();
const result = await servicesModel.addService(serviceRecordData);
(result.values as object).should.include.keys(Object.keys(serviceRecordData));
});
it('should not create a duplicate service record', async () => {
const serviceRecordData = utils.randomServiceRecord();
let result = await servicesModel.addService(serviceRecordData);
(result.values as object).should.include.keys(Object.keys(serviceRecordData));
result = await servicesModel.addService(serviceRecordData);
result.success.should.be.false;
(result.errorMessage as string).should.contain('shortName must be unique');
});
it('should return empty array if no services are created', async () => {
let result = await servicesModel.getAllServices();
result.success.should.be.true;
(result.values as servicesModel.IServiceRecordAttributes[]).length.should.be.equal(0);
});
it('should return an array of services', async () => {
const expectedServices = utils.randomServiceRecords();
expectedServices.map(async s => {
await servicesModel.addService(s);
return s;
});
let result = await servicesModel.getAllServices();
result.success.should.be.true;
const actual = result.values as servicesModel.IServiceRecordAttributes[];
actual.length.should.be.equal(expectedServices.length);
for (let i = 0; i < expectedServices.length; ++i) {
utils.compareServiceRecords(expectedServices[i], actual[i]).should.be.true;
}
});
it('should return error in case of failure for getting all services', async () => {
const expectedServices = utils.randomServiceRecords();
expectedServices.map(async s => {
await servicesModel.addService(s);
return s;
});
sinon.stub(servicesModel.Services, 'findAll').throws({ errors: [{ message: 'Exception occurred.' }] });
let result = await servicesModel.getAllServices();
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should find an existing service record', async () => {
const serviceRecord = utils.randomServiceRecord();
let result = await servicesModel.addService(serviceRecord);
result.success.should.be.true;
result = await servicesModel.findService(serviceRecord.shortName);
result.success.should.be.true;
utils.compareServiceRecords((result.values as servicesModel.IServiceRecordAttributes), serviceRecord);
});
it('should not find a non-existing service record', async () => {
const serviceRecord = utils.randomServiceRecord();
let result = await servicesModel.findService(serviceRecord.shortName);
result.success.should.be.true;
expect(result.values).to.be.undefined;
});
it('should handle exception on find service record', async () => {
const serviceRecordData = utils.randomServiceRecord();
sinon.stub(servicesModel.Services, 'findOne').throws({ errors: [{ message: 'Exception occurred.' }] });
const result = await servicesModel.findService(serviceRecordData.shortName);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should update an existing service', async () => {
const serviceRecordData = utils.randomServiceRecord();
let result = await servicesModel.addService(serviceRecordData);
result.success.should.be.true;
let actual: servicesModel.IServiceRecordInstance = result.values as servicesModel.IServiceRecordInstance;
actual.name.should.be.equal(serviceRecordData.name);
serviceRecordData.name = 'changed-name';
result = await servicesModel.updateService(serviceRecordData);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(1);
result = await servicesModel.findService(serviceRecordData.shortName);
actual = result.values as servicesModel.IServiceRecordInstance;
actual.name.should.be.equal(serviceRecordData.name);
});
it('should not update a non-existing service', async () => {
const serviceRecordData = utils.randomServiceRecord();
const result = await servicesModel.updateService(serviceRecordData);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(0);
});
it('should handle exception on update', async () => {
const serviceRecordData = utils.randomServiceRecord();
sinon.stub(servicesModel.Services, 'update').throws({ errors: [{ message: 'Exception occurred.' }] });
const result = await servicesModel.updateService(serviceRecordData);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should delete an existing service record', async () => {
const expected = utils.randomServiceRecord();
let result = await servicesModel.addService(expected);
result.success.should.be.true;
result = await servicesModel.deleteService(expected.shortName);
result.success.should.be.true;
(result.data as { [key: string]: number; }).deletedRows.should.be.equal(1);
result = await servicesModel.findService(expected.shortName);
result.success.should.be.true;
let actual = result.values as servicesModel.IServiceRecordInstance;
expect(actual).to.be.undefined;
});
it('should not delete a non-existing service record', async () => {
const expected = utils.randomServiceRecord();
let result = await servicesModel.deleteService(expected.shortName);
result.success.should.be.true;
(result.data as { [key: string]: number; }).deletedRows.should.be.equal(0);
});
it('should handle exception on delete', async () => {
const serviceRecordData = utils.randomServiceRecord();
sinon.stub(servicesModel.Services, 'destroy').throws({ errors: [{ message: 'Exception occurred.' }] });
const result = await servicesModel.deleteService(serviceRecordData.shortName);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should update lastOnline', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
const lastOnline = new Date();
const result = await servicesModel.updateLastOnline(serviceRecordData.shortName, true, lastOnline);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(1);
const foundEntry = (await servicesModel.Services.findOne({
where: {
shortName: serviceRecordData.shortName
}
}))!.toJSON();
(foundEntry as servicesModel.IServiceRecordInstance).lastOnline!.toISOString().should.be.equal(lastOnline!.toISOString());
});
it('should not update lastOnline for invalid service', async () => {
const serviceRecordData = utils.randomServiceRecord();
const lastOnline = new Date();
const result = await servicesModel.updateLastOnline(serviceRecordData.shortName, true, lastOnline);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(0);
});
it('should handle exception for updating lastOnline', async () => {
const serviceRecordData = utils.randomServiceRecord();
sinon.stub(servicesModel.Services, 'update').throws({ errors: [{ message: 'Exception occurred.' }] });
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
const lastOnline = new Date();
const result = await servicesModel.updateLastOnline(serviceRecordData.shortName, true, lastOnline);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should get lastOnline', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
const lastOnline = new Date();
let result = await servicesModel.updateLastOnline(serviceRecordData.shortName, true, lastOnline);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(1);
result = await servicesModel.getStatus(serviceRecordData.shortName);
result.success.should.be.true;
(result.data as servicesModel.IServiceRecordInstance)!.lastOnline!.toISOString().should.be.equal(lastOnline.toISOString());
});
it('should get lastOnline as null for invalid service', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
const lastOnline = new Date();
let result = await servicesModel.updateLastOnline(serviceRecordData.shortName, true, lastOnline);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(1);
result = await servicesModel.getStatus(serviceRecordData.shortName + 'invalid');
result.success.should.be.true;
expect((result.data as servicesModel.IServiceRecordInstance).lastOnline).to.be.null;
});
it('should handle exception for get lastOnline', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
const lastOnline = new Date();
let result = await servicesModel.updateLastOnline(serviceRecordData.shortName, true, lastOnline);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(1);
sinon.stub(servicesModel.Services, 'findOne').throws({ errors: [{ message: 'Exception occurred.' }] });
result = await servicesModel.getStatus(serviceRecordData.shortName);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should get hits', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
let result = await servicesModel.incrementHits(serviceRecordData.shortName);
result.success.should.be.true;
result = await servicesModel.getHits(serviceRecordData.shortName);
result.success.should.be.true;
(result.data as servicesModel.IServiceRecordInstance)!.hits.should.be.equal(1);
});
it('should not get hits for non-existant service', async () => {
const serviceRecordData = utils.randomServiceRecord();
let result = await servicesModel.getHits(serviceRecordData.shortName);
result.success.should.be.true;
expect((result.data as servicesModel.IServiceRecordInstance)!.hits).to.be.null;
});
it('should handle exception on get hits', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
let result = await servicesModel.incrementHits(serviceRecordData.shortName);
result.success.should.be.true;
sinon.stub(servicesModel.Services, 'findOne').throws({ errors: [{ message: 'Exception occurred.' }] });
result = await servicesModel.getHits(serviceRecordData.shortName);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should increment hits', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
let result = await servicesModel.incrementHits(serviceRecordData.shortName);
result.success.should.be.true;
result = await servicesModel.getHits(serviceRecordData.shortName);
(result.data as servicesModel.IServiceRecordInstance)!.hits.should.be.equal(1);
});
it('should not increment hits for non-existent service', async () => {
const serviceRecordData = utils.randomServiceRecord();
let result = await servicesModel.incrementHits(serviceRecordData.shortName);
result.success.should.be.true;
(result.data as { [key: string]: number; }).affectedRows.should.be.equal(0);
});
it('should handle exception on increment hits', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
sinon.stub(servicesModel.Services, 'update').throws({ errors: [{ message: 'Exception occurred.' }] });
let result = await servicesModel.incrementHits(serviceRecordData.shortName);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
it('should get url by shortName', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
const result = await servicesModel.findURLByShortName(serviceRecordData.shortName);
result.success.should.be.true;
(result.data as servicesModel.IServiceRecordInstance)!.url.should.be.equal(serviceRecordData.url);
});
it('should not get url by shortName for non-existing service', async () => {
const serviceRecordData = utils.randomServiceRecord();
const result = await servicesModel.findURLByShortName(serviceRecordData.shortName);
result.success.should.be.true;
expect((result.data as servicesModel.IServiceRecordInstance)!.url).to.be.undefined;
});
it('should handle excpetion while getting url by shortName', async () => {
const serviceRecordData = utils.randomServiceRecord();
(await servicesModel.addService(serviceRecordData)).success.should.be.true;
sinon.stub(servicesModel.Services, 'findOne').throws({ errors: [{ message: 'Exception occurred.' }] });
const result = await servicesModel.findURLByShortName(serviceRecordData.shortName);
result.success.should.be.false;
result.errorMessage!.should.be.equal('Exception occurred.');
});
}); | the_stack |
import RectangleUtil from "./../../starling/utils/RectangleUtil";
import Matrix from "openfl/geom/Matrix";
import Matrix3D from "openfl/geom/Matrix3D";
import MatrixUtil from "./../../starling/utils/MatrixUtil";
import Pool from "./../../starling/utils/Pool";
import MathUtil from "./../../starling/utils/MathUtil";
import ArgumentError from "openfl/errors/ArgumentError";
import Vector from "openfl/Vector";
import Vector3D from "openfl/geom/Vector3D";
import Texture from "./../textures/Texture";
import TextureBase from "openfl/display3D/textures/TextureBase";
import Rectangle from "openfl/geom/Rectangle";
declare namespace starling.rendering
{
/** The RenderState stores a combination of settings that are currently used for rendering.
* This includes modelview and transformation matrices as well as context3D related settings.
*
* <p>Starling's Painter instance stores a reference to the current RenderState.
* Via a stack mechanism, you can always save a specific state and restore it later.
* That makes it easy to write rendering code that doesn't have any side effects.</p>
*
* <p>Beware that any context-related settings are not applied on the context
* right away, but only after calling <code>painter.prepareToDraw()</code>.
* However, the Painter recognizes changes to those settings and will finish the current
* batch right away if necessary.</p>
*
* <strong>Matrix Magic</strong>
*
* <p>On rendering, Starling traverses the display tree, constantly moving from one
* coordinate system to the next. Each display object stores its vertex coordinates
* in its local coordinate system; on rendering, they must be moved to a global,
* 2D coordinate space (the so-called "clip-space"). To handle these calculations,
* the RenderState contains a set of matrices.</p>
*
* <p>By multiplying vertex coordinates with the <code>modelviewMatrix</code>, you'll get the
* coordinates in "screen-space", or in other words: in stage coordinates. (Optionally,
* there's also a 3D version of this matrix. It comes into play when you're working with
* <code>Sprite3D</code> containers.)</p>
*
* <p>By feeding the result of the previous transformation into the
* <code>projectionMatrix</code>, you'll end up with so-called "clipping coordinates",
* which are in the range <code>[-1, 1]</code> (just as needed by the graphics pipeline).
* If you've got vertices in the 3D space, this matrix will also execute a perspective
* projection.</p>
*
* <p>Finally, there's the <code>mvpMatrix</code>, which is short for
* "modelviewProjectionMatrix". This is simply a combination of <code>modelview-</code> and
* <code>projectionMatrix</code>, combining the effects of both. Pass this matrix
* to the vertex shader and all your vertices will automatically end up at the right
* position.</p>
*
* @see Painter
* @see starling.display.Sprite3D
*/
export class RenderState
{
/** Creates a new render state with the default settings. */
public constructor();
/** Duplicates all properties of another instance on the current instance. */
public copyFrom(renderState:RenderState):void;
/** Resets the RenderState to the default settings.
* (Check each property documentation for its default value.) */
public reset():void;
// matrix methods / properties
/** Prepends the given matrix to the 2D modelview matrix. */
public transformModelviewMatrix(matrix:Matrix):void;
/** Prepends the given matrix to the 3D modelview matrix.
* The current contents of the 2D modelview matrix is stored in the 3D modelview matrix
* before doing so; the 2D modelview matrix is then reset to the identity matrix.
*/
public transformModelviewMatrix3D(matrix:Matrix3D):void;
/** Creates a perspective projection matrix suitable for 2D and 3D rendering.
*
* <p>The first 4 parameters define which area of the stage you want to view (the camera
* will 'zoom' to exactly this region). The final 3 parameters determine the perspective
* in which you're looking at the stage.</p>
*
* <p>The stage is always on the rectangle that is spawned up between x- and y-axis (with
* the given size). All objects that are exactly on that rectangle (z equals zero) will be
* rendered in their true size, without any distortion.</p>
*
* <p>If you pass only the first 4 parameters, the camera will be set up above the center
* of the stage, with a field of view of 1.0 rad.</p>
*/
public setProjectionMatrix(x:number, y:number, width:number, height:number,
stageWidth?:number, stageHeight?:number,
cameraPos?:Vector3D):void;
/** This method needs to be called whenever <code>projectionMatrix3D</code> was changed
* other than via <code>setProjectionMatrix</code>.
*/
public setProjectionMatrixChanged():void;
/** Changes the modelview matrices (2D and, if available, 3D) to identity matrices.
* An object transformed an identity matrix performs no transformation.
*/
public setModelviewMatricesToIdentity():void;
/** Returns the current 2D modelview matrix.
* CAUTION: Use with care! Each call returns the same instance.
* @default identity matrix */
public modelviewMatrix:Matrix;
protected get_modelviewMatrix():Matrix;
protected set_modelviewMatrix(value:Matrix):Matrix;
/** Returns the current 3D modelview matrix, if there have been 3D transformations.
* CAUTION: Use with care! Each call returns the same instance.
* @default null */
public modelviewMatrix3D:Matrix3D;
protected get_modelviewMatrix3D():Matrix3D;
protected set_modelviewMatrix3D(value:Matrix3D):Matrix3D;
/** Returns the current projection matrix. You can use the method 'setProjectionMatrix3D'
* to set it up in an intuitive way.
* CAUTION: Use with care! Each call returns the same instance. If you modify the matrix
* in place, you have to call <code>setProjectionMatrixChanged</code>.
* @default identity matrix */
public projectionMatrix3D:Matrix3D;
protected get_projectionMatrix3D():Matrix3D;
protected set_projectionMatrix3D(value:Matrix3D):Matrix3D;
/** Calculates the product of modelview and projection matrix and stores it in a 3D matrix.
* CAUTION: Use with care! Each call returns the same instance. */
public readonly mvpMatrix3D:Matrix3D;
protected get_mvpMatrix3D():Matrix3D;
// other methods
/** Changes the the current render target.
*
* @param target Either a texture or <code>null</code> to render into the back buffer.
* @param enableDepthAndStencil Indicates if depth and stencil testing will be available.
* This parameter affects only texture targets.
* @param antiAlias The anti-aliasing quality (range: <code>0 - 4</code>).
* This parameter affects only texture targets. Note that at the time
* of this writing, AIR supports anti-aliasing only on Desktop.
*/
public setRenderTarget(target:Texture, enableDepthAndStencil?:boolean,
antiAlias?:number):void;
// other properties
/** The current, cumulated alpha value. Beware that, in a standard 'render' method,
* this already includes the current object! The value is the product of current object's
* alpha value and all its parents. @default 1.0
*/
public alpha:number;
protected get_alpha():number;
protected set_alpha(value:number):number;
/** The blend mode to be used on rendering. A value of "auto" is ignored, since it
* means that the mode should remain unchanged.
*
* @default BlendMode.NORMAL
* @see starling.display.BlendMode
*/
public blendMode:string;
protected get_blendMode():string;
protected set_blendMode(value:string):string;
/** The texture that is currently being rendered into, or <code>null</code>
* to render into the back buffer. On assignment, calls <code>setRenderTarget</code>
* with its default parameters. */
public renderTarget:Texture;
protected get_renderTarget():Texture;
protected set_renderTarget(value:Texture):Texture;
/** @protected */
/*@:allow(starling)*/ protected readonly renderTargetBase:TextureBase;
protected get_renderTargetBase():TextureBase;
/** @protected */
/*@:allow(starling)*/ readonly protected renderTargetOptions:number;
protected get_renderTargetOptions():number;
/** Sets the triangle culling mode. Allows to exclude triangles from rendering based on
* their orientation relative to the view plane.
* @default Context3DTriangleFace.NONE
*/
public culling:string;
protected get_culling():string;
protected set_culling(value:string):string;
/** Enables or disables depth buffer writes.
* @default false
*/
public depthMask:boolean;
protected get_depthMask():boolean;
protected set_depthMask(value:boolean):boolean;
/** Sets type of comparison used for depth testing.
* @default Context3DCompareMode.ALWAYS
*/
public depthTest:string;
protected get_depthTest():string;
protected set_depthTest(value:string):string;
/** The clipping rectangle can be used to limit rendering in the current render target to
* a certain area. This method expects the rectangle in stage coordinates. To prevent
* any clipping, assign <code>null</code>.
*
* @default null
*/
public clipRect:Rectangle;
protected get_clipRect():Rectangle;
protected set_clipRect(value:Rectangle):Rectangle;
/** The anti-alias setting used when setting the current render target
* via <code>setRenderTarget</code>. */
public readonly renderTargetAntiAlias:number;
protected get_renderTargetAntiAlias():number;
/** Indicates if the render target (set via <code>setRenderTarget</code>)
* has its depth and stencil buffers enabled. */
public readonly renderTargetSupportsDepthAndStencil:boolean;
protected get_renderTargetSupportsDepthAndStencil():boolean;
/** Indicates if there have been any 3D transformations.
* Returns <code>true</code> if the 3D modelview matrix contains a value. */
public readonly is3D:boolean;
protected get_is3D():boolean;
/** @private
*
* This callback is executed whenever a state change requires a draw operation.
* This is the case if blend mode, render target, culling or clipping rectangle
* are changing. */
/*@:allow(starling)*/ protected onDrawRequired:()=>void;
protected get_onDrawRequired():()=>void;
protected set_onDrawRequired(value:()=>void):()=>void;
}
}
export default starling.rendering.RenderState; | the_stack |
import { multiplyMatrices } from './multiply-matrices';
type color = [number, number, number];
// Sample code for color conversions
// Conversion can also be done using ICC profiles and a Color Management System
// For clarity, a library is used for matrix multiplication (multiply-matrices.js)
// standard white points, defined by 4-figure CIE x,y chromaticities
export const D50 = [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585];
export const D65 = [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290];
// sRGB-related functions
export function lin_sRGB(RGB: color): color {
// convert an array of sRGB values
// where in-gamut values are in the range [0 - 1]
// to linear light (un-companded) form.
// https://en.wikipedia.org/wiki/SRGB
// Extended transfer function:
// for negative values, linear portion is extended on reflection of axis,
// then reflected power function is used.
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
if (abs < 0.04045) {
return val / 12.92;
}
return sign * (Math.pow((abs + 0.055) / 1.055, 2.4));
}) as color;
}
export function gam_sRGB(RGB: color): color {
// convert an array of linear-light sRGB values in the range 0.0-1.0
// to gamma corrected form
// https://en.wikipedia.org/wiki/SRGB
// Extended transfer function:
// For negative values, linear portion extends on reflection
// of axis, then uses reflected pow below that
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
if (abs > 0.0031308) {
return sign * (1.055 * Math.pow(abs, 1 / 2.4) - 0.055);
}
return 12.92 * val;
}) as color;
}
export function lin_sRGB_to_XYZ(rgb: color): color {
// convert an array of linear-light sRGB values to CIE XYZ
// using sRGB's own white, D65 (no chromatic adaptation)
const M = [
[0.41239079926595934, 0.357584339383878, 0.1804807884018343],
[0.21263900587151027, 0.715168678767756, 0.07219231536073371],
[0.01933081871559182, 0.11919477979462598, 0.9505321522496607],
];
return multiplyMatrices(M, rgb) as color;
}
export function XYZ_to_lin_sRGB(XYZ: color): color {
// convert XYZ to linear-light sRGB
const M = [
[3.2409699419045226, -1.537383177570094, -0.4986107602930034],
[-0.9692436362808796, 1.8759675015077202, 0.04155505740717559],
[0.05563007969699366, -0.20397695888897652, 1.0569715142428786],
];
return multiplyMatrices(M, XYZ) as color;
}
// display-p3-related functions
export function lin_P3(RGB: color): color {
// convert an array of display-p3 RGB values in the range 0.0 - 1.0
// to linear light (un-companded) form.
return lin_sRGB(RGB); // same as sRGB
}
export function gam_P3(RGB: color): color {
// convert an array of linear-light display-p3 RGB in the range 0.0-1.0
// to gamma corrected form
return gam_sRGB(RGB); // same as sRGB
}
export function lin_P3_to_XYZ(rgb: color): color {
// convert an array of linear-light display-p3 values to CIE XYZ
// using D65 (no chromatic adaptation)
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
const M = [
[0.4865709486482162, 0.26566769316909306, 0.1982172852343625],
[0.2289745640697488, 0.6917385218365064, 0.079286914093745],
[0.0000000000000000, 0.04511338185890264, 1.043944368900976],
];
// 0 was computed as -3.972075516933488e-17
return multiplyMatrices(M, rgb) as color;
}
export function XYZ_to_lin_P3(XYZ: color): color {
// convert XYZ to linear-light P3
const M = [
[2.493496911941425, -0.9313836179191239, -0.40271078445071684],
[-0.8294889695615747, 1.7626640603183463, 0.023624685841943577],
[0.03584583024378447, -0.07617238926804182, 0.9568845240076872],
];
return multiplyMatrices(M, XYZ) as color;
}
// prophoto-rgb functions
export function lin_ProPhoto(RGB: color): color {
// convert an array of prophoto-rgb values
// where in-gamut colors are in the range [0.0 - 1.0]
// to linear light (un-companded) form.
// Transfer curve is gamma 1.8 with a small linear portion
// Extended transfer function
const Et2 = 16 / 512;
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
if (abs <= Et2) {
return val / 16;
}
return sign * Math.pow(val, 1.8);
}) as color;
}
export function gam_ProPhoto(RGB: color): color {
// convert an array of linear-light prophoto-rgb in the range 0.0-1.0
// to gamma corrected form
// Transfer curve is gamma 1.8 with a small linear portion
// TODO for negative values, extend linear portion on reflection of axis, then add pow below that
const Et = 1 / 512;
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
if (abs >= Et) {
return sign * Math.pow(abs, 1 / 1.8);
}
return 16 * val;
}) as color;
}
export function lin_ProPhoto_to_XYZ(rgb: color): color {
// convert an array of linear-light prophoto-rgb values to CIE XYZ
// using D50 (so no chromatic adaptation needed afterwards)
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
const M = [
[0.7977604896723027, 0.13518583717574031, 0.0313493495815248],
[0.2880711282292934, 0.7118432178101014, 0.00008565396060525902],
[0.0, 0.0, 0.8251046025104601],
];
return multiplyMatrices(M, rgb) as color;
}
export function XYZ_to_lin_ProPhoto(XYZ: color): color {
// convert XYZ to linear-light prophoto-rgb
const M = [
[1.3457989731028281, -0.25558010007997534, -0.05110628506753401],
[-0.5446224939028347, 1.5082327413132781, 0.02053603239147973],
[0.0, 0.0, 1.2119675456389454],
];
return multiplyMatrices(M, XYZ) as color;
}
// a98-rgb functions
export function lin_a98rgb(RGB: color): color {
// convert an array of a98-rgb values in the range 0.0 - 1.0
// to linear light (un-companded) form.
// negative values are also now accepted
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
return sign * Math.pow(abs, 563 / 256);
}) as color;
}
export function gam_a98rgb(RGB: color): color {
// convert an array of linear-light a98-rgb in the range 0.0-1.0
// to gamma corrected form
// negative values are also now accepted
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
return sign * Math.pow(abs, 256 / 563);
}) as color;
}
export function lin_a98rgb_to_XYZ(rgb: color): color {
// convert an array of linear-light a98-rgb values to CIE XYZ
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
// has greater numerical precision than section 4.3.5.3 of
// https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
// but the values below were calculated from first principles
// from the chromaticity coordinates of R G B W
// see matrixmaker.html
const M = [
[0.5766690429101305, 0.1855582379065463, 0.1882286462349947],
[0.29734497525053605, 0.6273635662554661, 0.07529145849399788],
[0.02703136138641234, 0.07068885253582723, 0.9913375368376388],
];
return multiplyMatrices(M, rgb) as color;
}
export function XYZ_to_lin_a98rgb(XYZ: color): color {
// convert XYZ to linear-light a98-rgb
const M = [
[2.0415879038107465, -0.5650069742788596, -0.34473135077832956],
[-0.9692436362808795, 1.8759675015077202, 0.04155505740717557],
[0.013444280632031142, -0.11836239223101838, 1.0151749943912054],
];
return multiplyMatrices(M, XYZ) as color;
}
//Rec. 2020-related functions
export function lin_2020(RGB: color): color {
// convert an array of rec2020 RGB values in the range 0.0 - 1.0
// to linear light (un-companded) form.
// ITU-R BT.2020-2 p.4
const α = 1.09929682680944;
const β = 0.018053968510807;
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
if (abs < β * 4.5) {
return val / 4.5;
}
return sign * (Math.pow((abs + α - 1) / α, 1 / 0.45));
}) as color;
}
export function gam_2020(RGB: color): color {
// convert an array of linear-light rec2020 RGB in the range 0.0-1.0
// to gamma corrected form
// ITU-R BT.2020-2 p.4
const α = 1.09929682680944;
const β = 0.018053968510807;
return RGB.map(function (val) {
const sign = val < 0 ? -1 : 1;
const abs = Math.abs(val);
if (abs > β) {
return sign * (α * Math.pow(abs, 0.45) - (α - 1));
}
return 4.5 * val;
}) as color;
}
export function lin_2020_to_XYZ(rgb: color): color {
// convert an array of linear-light rec2020 values to CIE XYZ
// using D65 (no chromatic adaptation)
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
const M = [
[0.6369580483012914, 0.14461690358620832, 0.1688809751641721],
[0.2627002120112671, 0.6779980715188708, 0.05930171646986196],
[0.000000000000000, 0.028072693049087428, 1.060985057710791],
];
// 0 is actually calculated as 4.994106574466076e-17
return multiplyMatrices(M, rgb) as color;
}
export function XYZ_to_lin_2020(XYZ: color): color {
// convert XYZ to linear-light rec2020
const M = [
[1.7166511879712674, -0.35567078377639233, -0.25336628137365974],
[-0.6666843518324892, 1.6164812366349395, 0.01576854581391113],
[0.017639857445310783, -0.042770613257808524, 0.9421031212354738],
];
return multiplyMatrices(M, XYZ) as color;
}
// Chromatic adaptation
export function D65_to_D50(XYZ: color): color {
// Bradford chromatic adaptation from D65 to D50
// The matrix below is the result of three operations:
// - convert from XYZ to retinal cone domain
// - scale components from one reference white to another
// - convert back to XYZ
// http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
const M = [
[1.0479298208405488, 0.022946793341019088, -0.05019222954313557],
[0.029627815688159344, 0.990434484573249, -0.01707382502938514],
[-0.009243058152591178, 0.015055144896577895, 0.7518742899580008],
];
return multiplyMatrices(M, XYZ) as color;
}
export function D50_to_D65(XYZ: color): color {
// Bradford chromatic adaptation from D50 to D65
const M = [
[0.9554734527042182, -0.023098536874261423, 0.0632593086610217],
[-0.028369706963208136, 1.0099954580058226, 0.021041398966943008],
[0.012314001688319899, -0.020507696433477912, 1.3303659366080753],
];
return multiplyMatrices(M, XYZ) as color;
}
// CIE Lab and LCH
export function XYZ_to_Lab(XYZ: color): color {
// Assuming XYZ is relative to D50, convert to CIE Lab
// from CIE standard, which now defines these as a rational fraction
const ε = 216 / 24389; // 6^3/29^3
const κ = 24389 / 27; // 29^3/3^3
// compute xyz, which is XYZ scaled relative to reference white
const xyz = XYZ.map((value, i) => value / D50[i]);
// now compute f
const f = xyz.map(value => value > ε ? Math.cbrt(value) : (κ * value + 16) / 116);
return [
(116 * f[1]) - 16, // L
500 * (f[0] - f[1]), // a
200 * (f[1] - f[2]), // b
];
// L in range [0,100]. For use in CSS, add a percent
}
export function Lab_to_XYZ(Lab: color): color {
// Convert Lab to D50-adapted XYZ
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
const κ = 24389 / 27; // 29^3/3^3
const ε = 216 / 24389; // 6^3/29^3
const f = [];
// compute f, starting with the luminance-related term
f[1] = (Lab[0] + 16) / 116;
f[0] = Lab[1] / 500 + f[1];
f[2] = f[1] - Lab[2] / 200;
// compute xyz
const xyz = [
Math.pow(f[0], 3) > ε ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ,
Lab[0] > κ * ε ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ,
Math.pow(f[2], 3) > ε ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ,
];
// Compute XYZ by scaling xyz by reference white
return xyz.map((value, i) => value * D50[i]) as color;
}
export function Lab_to_LCH(Lab: color): color {
// Convert to polar form
const hue = Math.atan2(Lab[2], Lab[1]) * 180 / Math.PI;
return [
Lab[0], // L is still L
Math.sqrt(Math.pow(Lab[1], 2) + Math.pow(Lab[2], 2)), // Chroma
hue >= 0 ? hue : hue + 360, // Hue, in degrees [0 to 360)
];
}
export function LCH_to_Lab(LCH: color): color {
// Convert from polar form
return [
LCH[0], // L is still L
LCH[1] * Math.cos(LCH[2] * Math.PI / 180), // a
LCH[1] * Math.sin(LCH[2] * Math.PI / 180), // b
];
}
// OKLab and OKLCH
// https://bottosson.github.io/posts/oklab/
// XYZ <-> LMS matrices recalculated for consistent reference white
// see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
export function XYZ_to_OKLab(XYZ: color): color {
// Given XYZ relative to D65, convert to OKLab
const XYZtoLMS = [
[0.8190224432164319, 0.3619062562801221, -0.12887378261216414],
[0.0329836671980271, 0.9292868468965546, 0.03614466816999844],
[0.048177199566046255, 0.26423952494422764, 0.6335478258136937],
];
const LMStoOKLab = [
[0.2104542553, 0.7936177850, -0.0040720468],
[1.9779984951, -2.4285922050, 0.4505937099],
[0.0259040371, 0.7827717662, -0.8086757660],
];
const LMS = multiplyMatrices(XYZtoLMS, XYZ) as color;
return multiplyMatrices(LMStoOKLab, LMS.map(c => Math.cbrt(c))) as color;
// L in range [0,1]. For use in CSS, multiply by 100 and add a percent
}
export function OKLab_to_XYZ(OKLab: color): color {
// Given OKLab, convert to XYZ relative to D65
const LMStoXYZ = [
[1.2268798733741557, -0.5578149965554813, 0.28139105017721583],
[-0.04057576262431372, 1.1122868293970594, -0.07171106666151701],
[-0.07637294974672142, -0.4214933239627914, 1.5869240244272418],
];
const OKLabtoLMS = [
[0.99999999845051981432, 0.39633779217376785678, 0.21580375806075880339],
[1.0000000088817607767, -0.1055613423236563494, -0.063854174771705903402],
[1.0000000546724109177, -0.089484182094965759684, -1.2914855378640917399],
];
const LMSnl = multiplyMatrices(OKLabtoLMS, OKLab) as color;
return multiplyMatrices(LMStoXYZ, LMSnl.map(c => c ** 3)) as color;
}
export function OKLab_to_OKLCH(OKLab: color): color {
const hue = Math.atan2(OKLab[2], OKLab[1]) * 180 / Math.PI;
return [
OKLab[0], // L is still L
Math.sqrt(OKLab[1] ** 2 + OKLab[2] ** 2), // Chroma
hue >= 0 ? hue : hue + 360, // Hue, in degrees [0 to 360)
];
}
export function OKLCH_to_OKLab(OKLCH: color): color {
return [
OKLCH[0], // L is still L
OKLCH[1] * Math.cos(OKLCH[2] * Math.PI / 180), // a
OKLCH[1] * Math.sin(OKLCH[2] * Math.PI / 180), // b
];
}
// Premultiplied alpha conversions
export function rectangular_premultiply(color: color, alpha: number): color {
// given a color in a rectangular orthogonal colorspace
// and an alpha value
// return the premultiplied form
return color.map((c) => c * alpha) as color;
}
export function rectangular_un_premultiply(color: color, alpha: number): color {
// given a premultiplied color in a rectangular orthogonal colorspace
// and an alpha value
// return the actual color
if (alpha === 0) {
return color; // avoid divide by zero
}
return color.map((c) => c / alpha) as color;
}
export function polar_premultiply(color: color, alpha: number, hueIndex: number): color {
// given a color in a cylindicalpolar colorspace
// and an alpha value
// return the premultiplied form.
// the index says which entry in the color array corresponds to hue angle
// for example, in OKLCH it would be 2
// while in HSL it would be 0
return color.map((c, i) => c * (hueIndex === i ? 1 : alpha)) as color;
}
export function polar_un_premultiply(color: color, alpha: number, hueIndex: number): color {
// given a color in a cylindicalpolar colorspace
// and an alpha value
// return the actual color.
// the hueIndex says which entry in the color array corresponds to hue angle
// for example, in OKLCH it would be 2
// while in HSL it would be 0
if (alpha === 0) {
return color; // avoid divide by zero
}
return color.map((c, i) => c / (hueIndex === i ? 1 : alpha)) as color;
}
// Convenience functions can easily be defined, such as
export function hsl_premultiply(color: color, alpha: number): color {
return polar_premultiply(color, alpha, 0);
} | the_stack |
import React, { Component } from 'react';
import { Tree, List, Modal, Tabs, Radio, Input, message, Row, Col, Card, Avatar } from 'antd';
import { Entity } from 'aframe';
import Icon from 'polestar-icons';
import { AntTreeNodeSelectedEvent } from 'antd/lib/tree';
import difference from 'lodash/difference';
import { AntTreeNodeDropEvent } from 'antd/lib/tree/Tree';
import { SidebarContainer, Scrollbar, Empty } from '../common';
import { catalogs, primitives, getIcon } from '../../constants';
import { EntityTools, EventTools } from '../../tools';
import { IScene } from '../../tools/InspectorTools';
import { IEntity, IDetailEntity } from '../../models/entity';
import { IPrimitive } from '../../models/primitive';
type ViewTypes = 'card' | 'list';
interface IState {
visible: boolean;
treeNodes: IEntity[];
selectedKeys: string[];
expandedKeys: string[];
searchPrimitives?: string;
searchCatalogs?: string;
viewPrimitives?: ViewTypes;
viewCatalogs?: ViewTypes;
spinning: boolean;
}
class Entities extends Component<{}, IState> {
state: IState = {
visible: false,
treeNodes: [],
selectedKeys: ['scene'],
expandedKeys: ['scene'],
searchPrimitives: '',
searchCatalogs: '',
viewPrimitives: 'card',
viewCatalogs: 'card',
spinning: true,
};
componentDidMount() {
EventTools.on('sceneloaded', (scene: IScene) => {
const treeNodes = EntityTools.buildEntities(scene);
this.setState({
treeNodes,
spinning: false,
});
});
EventTools.on('entitycreate', (entity: Entity) => {
const treeNodes = EntityTools.buildEntities(AFRAME.INSPECTOR.sceneEl);
const diffKeys = difference([entity.parentElement.id], this.state.expandedKeys);
this.setState({
treeNodes,
expandedKeys: Array.from(this.state.expandedKeys.concat(diffKeys)),
});
});
EventTools.on('entityclone', () => {
const treeNodes = EntityTools.buildEntities(AFRAME.INSPECTOR.sceneEl);
this.setState({
treeNodes,
});
});
EventTools.on('entityselect', (entity: Entity) => {
if (entity) {
this.setState({
selectedKeys: [entity.id],
});
} else {
this.setState({
selectedKeys: [],
});
}
});
EventTools.on('objectselect', (object3D: THREE.Object3D) => {
if (!object3D) {
this.setState({
selectedKeys: [],
});
}
});
EventTools.on('objectremove', () => {
const treeNodes = EntityTools.buildEntities(AFRAME.INSPECTOR.sceneEl);
this.setState({
treeNodes,
});
});
EventTools.on('entityupdate', (detail: IDetailEntity) => {
if (detail.entity.object3D && detail.component === 'name') {
const treeNodes = EntityTools.buildEntities(AFRAME.INSPECTOR.sceneEl);
this.setState({
treeNodes,
});
}
});
}
/**
* @description Traverse to find the node
* @param {string} key
* @param {IEntity[]} [treeNodes]
* @returns {IEntity}
*/
private findTreeNode = (key: string, treeNodes?: IEntity[]): IEntity => {
let findNode;
for (let i = 0; i < treeNodes.length; i++) {
const node = treeNodes[i];
if (node.key === key) {
findNode = node;
return findNode;
}
if (node.children.length) {
findNode = this.findTreeNode(key, node.children);
if (findNode) {
return findNode;
}
}
}
return findNode;
};
/**
* @description Delete the entity
* @returns
*/
private handleDeleteEntity = () => {
if (AFRAME.INSPECTOR.selectedEntity) {
if (AFRAME.INSPECTOR.selectedEntity.tagName.toLowerCase() === 'a-scene') {
message.warn('Does not delete Scene.');
return;
}
Modal.confirm({
title: 'Delete entity',
content: 'Are you sure want to delete this entity?',
onOk: () => {
EntityTools.removeSelectedEntity();
},
});
}
};
/**
* @description Add the Entity
* @param {IPrimitive} item
*/
private handleAddEntity = (item: IPrimitive) => {
this.handleModalVisible();
EntityTools.createEntity(item);
};
/**
* @description Change to visible in Modal
*/
private handleModalVisible = () => {
this.setState((prevState: IState) => {
return {
visible: !prevState.visible,
};
});
};
/**
* @description Select the entity
* @param {string[]} selectedKeys
*/
private handleSelectEntity = (selectedKeys: string[], e: AntTreeNodeSelectedEvent) => {
this.setState(
{
selectedKeys,
},
() => {
if (selectedKeys.length) {
EntityTools.selectEntity(e.node.props.dataRef.entity);
} else {
EntityTools.selectEntity();
}
},
);
};
/**
* @description Expand tree node for the entity
* @param {string[]} expandedKeys
*/
private handleExpandEntity = (expandedKeys: string[]) => {
this.setState({
expandedKeys,
});
};
/**
* @description Search in Primitives
* @param {string} searchPrimitives
*/
private handleSearchPrimitives = (searchPrimitives: string) => {
this.setState({
searchPrimitives,
});
};
/**
* @description Search in Catalogs
* @param {string} searchCatalogs
*/
private handleSearchCatalogs = (searchCatalogs: string) => {
this.setState({
searchCatalogs,
});
};
/**
* @description Change to view type in Primitives
* @param {ViewTypes} viewPrimitives
*/
private handleViewPrimitives = (viewPrimitives: ViewTypes) => {
this.setState({
viewPrimitives,
});
};
/**
* @description Change to view type in Catalogs
* @param {ViewTypes} viewCatalogs
*/
private handleViewCatalogs = (viewCatalogs: ViewTypes) => {
this.setState({
viewCatalogs,
});
};
/**
* @description Drop the entity
* @param {AntTreeNodeDropEvent} options
* @returns
*/
private handleDropEntity = (options: AntTreeNodeDropEvent) => {
const { dragNode, node } = options;
const source = dragNode.props.dataRef.entity as Entity;
const dest = node.props.dataRef.entity as Entity;
if (dest.id === 'scene') {
message.warn('Can not insert before scene.');
return;
}
const sourceStr = EntityTools.getEntityClipboardRepresentation(source);
EntityTools.removeEntity(source);
const dropPos = node.props.pos.split('-');
const dropPosition = options.dropPosition - Number(dropPos[dropPos.length - 1]);
if (dropPosition > -1) {
dest.appendChild(document.createRange().createContextualFragment(sourceStr));
const treeNodes = EntityTools.buildEntities(AFRAME.INSPECTOR.sceneEl);
this.setState({
treeNodes,
});
} else {
const parent = dest.parentElement;
const createdSource = document.createRange().createContextualFragment(sourceStr);
parent.insertBefore(createdSource, dest);
const treeNodes = EntityTools.buildEntities(AFRAME.INSPECTOR.sceneEl);
this.setState({
treeNodes,
});
}
};
/**
* @description Render the tree node
* @param {IEntity[]} treeNodes
*/
private renderTreeNodes = (treeNodes: IEntity[]) =>
treeNodes.map(item => {
if (item.children && item.children.length) {
return (
<Tree.TreeNode
key={item.key.toString()}
title={item.title}
icon={<Icon name={item.icon} />}
dataRef={item}
>
{this.renderTreeNodes(item.children)}
</Tree.TreeNode>
);
}
return (
<Tree.TreeNode
key={item.key.toString()}
title={item.title}
icon={<Icon name={item.icon} />}
dataRef={item}
/>
);
});
/**
* @description Render the items with Card
* @param {IPrimitive[]} items
* @param {string} searchText
* @returns
*/
private renderCardItems = (items: IPrimitive[], searchText: string) => {
return (
<Scrollbar>
{items.length ? (
<Row gutter={16} style={{ margin: 0 }}>
{items
.filter(
item =>
item.title.toLowerCase().includes(searchText.toLowerCase()) ||
item.description.toLowerCase().includes(searchText.toLowerCase()),
)
.map(item => {
return (
<Col
key={item.key}
md={24}
lg={12}
xl={6}
onClick={() => this.handleAddEntity(item)}
>
<Card
hoverable={true}
title={item.title}
extra={
item.url && (
<a
className="editor-item-help-icon"
onClick={e => e.stopPropagation()}
target="_blank"
href={item.url}
>
<Icon name="question-circle-o" />
</a>
)
}
cover={item.image && <img src={item.image} />}
style={{ marginBottom: 16 }}
bodyStyle={{ padding: 12, height: 120 }}
>
<div className="editor-item-card-desc">{item.description}</div>
</Card>
</Col>
);
})}
</Row>
) : (
<Empty />
)}
</Scrollbar>
);
};
/**
* Render the items with List
*
* @param {IPrimitive[]} items
* @param {string} searchText
* @returns
*/
private renderListItems = (items: IPrimitive[], searchText: string) => {
return (
<Scrollbar>
{items.length ? (
<List
style={{ padding: '0 8px' }}
dataSource={items.filter(
item =>
item.title.includes(searchText.toLowerCase()) ||
item.description.includes(searchText.toLowerCase()),
)}
renderItem={item => (
<List.Item>
<List.Item.Meta
avatar={
<Avatar>
<Icon name={getIcon(item.type)} />
</Avatar>
}
title={
<div style={{ display: 'flex' }}>
<a
style={{ flex: 1 }}
onClick={() => {
this.handleAddEntity(item);
}}
>
{item.title}
</a>
{item.url && (
<div style={{ alignSelf: 'flex-end' }}>
<a
className="editor-item-help-icon"
target="_blank"
href={item.url}
>
<Icon name="question-circle-o" />
</a>
</div>
)}
</div>
}
description={item.description}
/>
</List.Item>
)}
/>
) : (
<Empty />
)}
</Scrollbar>
);
};
/**
* Render the search form
*
* @param {(value: string) => void} callback
* @returns
*/
private renderSearch = (callback: (value: string) => void) => {
return (
<div style={{ flex: 1, paddingRight: 16 }}>
<Input allowClear={true} placeholder="Search for Entity..." onChange={e => callback(e.target.value)} />
</div>
);
};
/**
* @description Render the view type form
* @param {ViewTypes} viewType
* @param {(value: ViewTypes) => void} callback
* @returns
*/
private renderViewType = (viewType: ViewTypes, callback: (value: ViewTypes) => void) => {
return (
<Radio.Group
buttonStyle="solid"
value={viewType}
defaultValue={viewType}
onChange={e => callback(e.target.value)}
>
<Radio.Button value="card">
<Icon name="table" />
</Radio.Button>
<Radio.Button value="list">
<Icon name="list" />
</Radio.Button>
</Radio.Group>
);
};
render() {
const {
visible,
treeNodes,
selectedKeys,
expandedKeys,
viewPrimitives,
viewCatalogs,
searchPrimitives,
searchCatalogs,
spinning,
} = this.state;
return (
<SidebarContainer
titleStyle={{ border: 0 }}
title={
<>
<div style={{ flex: 1 }}>{'Entity'}</div>
<div>
<Icon
className="editor-icon"
style={{ fontSize: '1.25rem', marginRight: 8 }}
name="plus"
onClick={this.handleModalVisible}
/>
<Icon
className="editor-icon"
style={{ fontSize: '1.25rem' }}
name="trash"
onClick={this.handleDeleteEntity}
/>
</div>
</>
}
spinning={spinning}
>
{treeNodes.length ? (
<Tree
showIcon={true}
defaultExpandParent={true}
selectedKeys={selectedKeys}
expandedKeys={expandedKeys}
onExpand={this.handleExpandEntity}
onSelect={this.handleSelectEntity}
defaultExpandedKeys={['scene']}
defaultSelectedKeys={['scene']}
draggable={true}
onDrop={this.handleDropEntity}
>
{this.renderTreeNodes(treeNodes)}
</Tree>
) : (
<Empty />
)}
<Modal
className="editor-item-modal"
title={'Add Entity'}
visible={visible}
onCancel={this.handleModalVisible}
footer={null}
width="75%"
style={{ height: '75%' }}
>
<Tabs tabPosition="left">
<Tabs.TabPane key="primitives" tab="Primitives">
<div style={{ display: 'flex', height: '100%', flexDirection: 'column' }}>
<div style={{ display: 'flex', padding: '0 8px 16px 8px' }}>
{this.renderSearch(this.handleSearchPrimitives)}
{this.renderViewType(viewPrimitives, this.handleViewPrimitives)}
</div>
<div style={{ flex: 1 }}>
{viewPrimitives === 'card'
? this.renderCardItems(primitives, searchPrimitives)
: this.renderListItems(primitives, searchPrimitives)}
</div>
</div>
</Tabs.TabPane>
<Tabs.TabPane key="catalogs" tab="Catalogs">
<div style={{ display: 'flex', height: '100%', flexDirection: 'column' }}>
<div style={{ display: 'flex', padding: '0 8px 16px 8px' }}>
{this.renderSearch(this.handleSearchCatalogs)}
{this.renderViewType(viewCatalogs, this.handleViewCatalogs)}
</div>
<div style={{ flex: 1 }}>
{viewCatalogs === 'card'
? this.renderCardItems(catalogs, searchCatalogs)
: this.renderListItems(catalogs, searchCatalogs)}
</div>
</div>
</Tabs.TabPane>
</Tabs>
</Modal>
</SidebarContainer>
);
}
}
export default Entities; | the_stack |
import {Component} from './component';
import {
isAttributeInstance,
isPrimaryIdentifierAttributeInstance,
isSecondaryIdentifierAttributeInstance,
isStringValueTypeInstance,
isNumberValueTypeInstance,
isMethodInstance
} from './properties';
import {
attribute,
primaryIdentifier,
secondaryIdentifier,
method,
expose,
provide,
consume
} from './decorators';
describe('Decorators', () => {
test('@attribute()', async () => {
class Movie extends Component {
@attribute() static limit = 100;
@attribute() static token?: string;
@attribute() title? = '';
@attribute() country?: string;
}
let attr = Movie.getAttribute('limit');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('limit');
expect(attr.getParent()).toBe(Movie);
expect(attr.getValue()).toBe(100);
expect(Movie.limit).toBe(100);
Movie.limit = 500;
expect(attr.getValue()).toBe(500);
expect(Movie.limit).toBe(500);
let descriptor = Object.getOwnPropertyDescriptor(Movie, 'limit')!;
expect(typeof descriptor.get).toBe('function');
expect(typeof descriptor.set).toBe('function');
attr = Movie.getAttribute('token');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('token');
expect(attr.getParent()).toBe(Movie);
expect(attr.getValue()).toBeUndefined();
expect(Movie.token).toBeUndefined();
let movie = new Movie();
attr = movie.getAttribute('title');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('title');
expect(attr.getParent()).toBe(movie);
expect(typeof attr.getDefault()).toBe('function');
expect(attr.evaluateDefault()).toBe('');
expect(attr.getValue()).toBe('');
expect(movie.title).toBe('');
movie.title = 'The Matrix';
expect(attr.getValue()).toBe('The Matrix');
expect(movie.title).toBe('The Matrix');
descriptor = Object.getOwnPropertyDescriptor(Movie.prototype, 'title')!;
expect(typeof descriptor.get).toBe('function');
expect(typeof descriptor.set).toBe('function');
expect(Object.getOwnPropertyDescriptor(movie, 'title')).toBe(undefined);
attr = movie.getAttribute('country');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('country');
expect(attr.getParent()).toBe(movie);
expect(attr.getDefault()).toBeUndefined();
expect(attr.evaluateDefault()).toBeUndefined();
expect(attr.getValue()).toBeUndefined();
expect(movie.country).toBeUndefined();
movie.country = 'USA';
expect(attr.getValue()).toBe('USA');
expect(movie.country).toBe('USA');
expect(Movie.hasAttribute('offset')).toBe(false);
expect(() => Movie.getAttribute('offset')).toThrow(
"The attribute 'offset' is missing (component: 'Movie')"
);
movie = new Movie({title: 'Inception', country: 'USA'});
expect(movie.title).toBe('Inception');
expect(movie.country).toBe('USA');
class Film extends Movie {
@attribute() static limit: number;
@attribute() static token = '';
@attribute() title!: string;
@attribute() country = '';
}
attr = Film.getAttribute('limit');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('limit');
expect(attr.getParent()).toBe(Film);
expect(attr.getValue()).toBe(500);
expect(Film.limit).toBe(500);
Film.limit = 1000;
expect(attr.getValue()).toBe(1000);
expect(Film.limit).toBe(1000);
expect(Movie.limit).toBe(500);
attr = Film.getAttribute('token');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('token');
expect(attr.getParent()).toBe(Film);
expect(attr.getValue()).toBe('');
expect(Film.token).toBe('');
const film = new Film();
attr = film.getAttribute('title');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('title');
expect(attr.getParent()).toBe(film);
expect(typeof attr.getDefault()).toBe('function');
expect(attr.evaluateDefault()).toBe('');
expect(attr.getValue()).toBe('');
expect(film.title).toBe('');
film.title = 'Léon';
expect(attr.getValue()).toBe('Léon');
expect(film.title).toBe('Léon');
attr = film.getAttribute('country');
expect(isAttributeInstance(attr)).toBe(true);
expect(attr.getName()).toBe('country');
expect(attr.getParent()).toBe(film);
expect(typeof attr.getDefault()).toBe('function');
expect(attr.evaluateDefault()).toBe('');
expect(attr.getValue()).toBe('');
expect(film.country).toBe('');
// --- Using getters ---
class MotionPicture extends Component {
@attribute({getter: () => 100}) static limit: number;
@attribute({getter: () => 'Untitled'}) title!: string;
}
expect(MotionPicture.limit).toBe(100);
expect(MotionPicture.prototype.title).toBe('Untitled');
expect(() => {
class MotionPicture extends Component {
@attribute({getter: () => 100}) static limit: number = 30;
}
return MotionPicture;
}).toThrow(
"An attribute cannot have both a getter or setter and an initial value (attribute: 'MotionPicture.limit')"
);
expect(() => {
class MotionPicture extends Component {
@attribute({getter: () => 'Untitled'}) title: string = '';
}
return MotionPicture;
}).toThrow(
"An attribute cannot have both a getter or setter and a default value (attribute: 'MotionPicture.prototype.title')"
);
});
test('@primaryIdentifier()', async () => {
class Movie1 extends Component {
@primaryIdentifier() id!: string;
}
let idAttribute = Movie1.prototype.getPrimaryIdentifierAttribute();
expect(isPrimaryIdentifierAttributeInstance(idAttribute)).toBe(true);
expect(idAttribute.getName()).toBe('id');
expect(idAttribute.getParent()).toBe(Movie1.prototype);
expect(isStringValueTypeInstance(idAttribute.getValueType())).toBe(true);
expect(typeof idAttribute.getDefault()).toBe('function');
class Movie2 extends Component {
@primaryIdentifier('number') id!: number;
}
idAttribute = Movie2.prototype.getPrimaryIdentifierAttribute();
expect(isPrimaryIdentifierAttributeInstance(idAttribute)).toBe(true);
expect(idAttribute.getName()).toBe('id');
expect(idAttribute.getParent()).toBe(Movie2.prototype);
expect(isNumberValueTypeInstance(idAttribute.getValueType())).toBe(true);
expect(idAttribute.getDefault()).toBeUndefined();
class Movie3 extends Component {
@primaryIdentifier('number') id = Math.random();
}
idAttribute = Movie3.prototype.getPrimaryIdentifierAttribute();
expect(isPrimaryIdentifierAttributeInstance(idAttribute)).toBe(true);
expect(idAttribute.getName()).toBe('id');
expect(idAttribute.getParent()).toBe(Movie3.prototype);
expect(isNumberValueTypeInstance(idAttribute.getValueType())).toBe(true);
expect(typeof idAttribute.getDefault()).toBe('function');
const movie = new Movie3();
expect(typeof movie.id === 'number').toBe(true);
expect(() => {
class Movie extends Component {
@primaryIdentifier() static id: string;
}
return Movie;
}).toThrow(
"Couldn't find a property class while executing @primaryIdentifier() (component: 'Movie', property: 'id')"
);
expect(() => {
class Movie {
@primaryIdentifier() id!: string;
}
return Movie;
}).toThrow("@primaryIdentifier() must be used inside a component class (property: 'id')");
expect(() => {
class Movie extends Component {
@primaryIdentifier() id!: string;
@primaryIdentifier() slug!: string;
}
return Movie;
}).toThrow("The component 'Movie' already has a primary identifier attribute");
});
test('@secondaryIdentifier()', async () => {
class User extends Component {
@secondaryIdentifier() email!: string;
@secondaryIdentifier() username!: string;
}
const emailAttribute = User.prototype.getSecondaryIdentifierAttribute('email');
expect(isSecondaryIdentifierAttributeInstance(emailAttribute)).toBe(true);
expect(emailAttribute.getName()).toBe('email');
expect(emailAttribute.getParent()).toBe(User.prototype);
expect(isStringValueTypeInstance(emailAttribute.getValueType())).toBe(true);
expect(emailAttribute.getDefault()).toBeUndefined();
const usernameAttribute = User.prototype.getSecondaryIdentifierAttribute('username');
expect(isSecondaryIdentifierAttributeInstance(usernameAttribute)).toBe(true);
expect(usernameAttribute.getName()).toBe('username');
expect(usernameAttribute.getParent()).toBe(User.prototype);
expect(isStringValueTypeInstance(usernameAttribute.getValueType())).toBe(true);
expect(usernameAttribute.getDefault()).toBeUndefined();
});
test('@method()', async () => {
class Movie extends Component {
@method() static find() {}
@method() load() {}
}
expect(typeof Movie.find).toBe('function');
const movie = new Movie();
expect(typeof movie.load).toBe('function');
let meth = Movie.getMethod('find');
expect(isMethodInstance(meth)).toBe(true);
expect(meth.getName()).toBe('find');
expect(meth.getParent()).toBe(Movie);
meth = movie.getMethod('load');
expect(isMethodInstance(meth)).toBe(true);
expect(meth.getName()).toBe('load');
expect(meth.getParent()).toBe(movie);
expect(Movie.hasMethod('delete')).toBe(false);
expect(() => Movie.getMethod('delete')).toThrow(
"The method 'delete' is missing (component: 'Movie')"
);
});
test('@expose()', async () => {
const testExposure = (componentProvider: () => typeof Component) => {
const component = componentProvider();
let prop = component.getProperty('limit');
expect(isAttributeInstance(prop)).toBe(true);
expect(prop.getName()).toBe('limit');
expect(prop.getExposure()).toStrictEqual({get: true});
prop = component.getProperty('find');
expect(isMethodInstance(prop)).toBe(true);
expect(prop.getName()).toBe('find');
expect(prop.getExposure()).toStrictEqual({call: true});
prop = component.prototype.getProperty('title');
expect(isAttributeInstance(prop)).toBe(true);
expect(prop.getName()).toBe('title');
expect(prop.getExposure()).toStrictEqual({get: true, set: true});
prop = component.prototype.getProperty('load');
expect(isMethodInstance(prop)).toBe(true);
expect(prop.getName()).toBe('load');
expect(prop.getExposure()).toStrictEqual({call: true});
};
testExposure(() => {
class Movie extends Component {
@expose({get: true}) @attribute() static limit: string;
@expose({call: true}) @method() static find() {}
@expose({get: true, set: true}) @attribute() title!: string;
@expose({call: true}) @method() load() {}
}
return Movie;
});
testExposure(() => {
@expose({
limit: {get: true},
find: {call: true},
prototype: {
title: {get: true, set: true},
load: {call: true}
}
})
class Movie extends Component {
@attribute() static limit: string;
@method() static find() {}
@attribute() title!: string;
@method() load() {}
}
return Movie;
});
testExposure(() => {
class Movie extends Component {
@attribute() static limit: string;
@method() static find() {}
@attribute() title!: string;
@method() load() {}
}
@expose({
limit: {get: true},
find: {call: true},
prototype: {
title: {get: true, set: true},
load: {call: true}
}
})
class ExposedMovie extends Movie {}
return ExposedMovie;
});
});
test('@provide()', async () => {
class Movie extends Component {}
class Backend extends Component {
@provide() static Movie = Movie;
}
expect(Backend.getProvidedComponent('Movie')).toBe(Movie);
((Backend, BackendMovie) => {
class Movie extends BackendMovie {}
class Frontend extends Backend {
@provide() static Movie = Movie;
}
expect(Frontend.getProvidedComponent('Movie')).toBe(Movie);
})(Backend, Movie);
// The backend should not be affected by the frontend
expect(Backend.getProvidedComponent('Movie')).toBe(Movie);
expect(() => {
class Movie extends Component {}
class Backend extends Component {
// @ts-expect-error
@provide() Movie = Movie;
}
return Backend;
}).toThrow(
"@provide() must be used inside a component class with as static attribute declaration (attribute: 'Movie')"
);
expect(() => {
class Movie {}
class Backend extends Component {
@provide() static Movie = Movie;
}
return Backend;
}).toThrow(
"@provide() must be used with an attribute declaration specifying a component class (attribute: 'Movie')"
);
});
test('@consume()', async () => {
class Movie extends Component {
@consume() static Director: typeof Director;
}
class Director extends Component {
@consume() static Movie: typeof Movie;
}
class Backend extends Component {
@provide() static Movie = Movie;
@provide() static Director = Director;
}
expect(Movie.getConsumedComponent('Director')).toBe(Director);
expect(Movie.Director).toBe(Director);
expect(Director.getConsumedComponent('Movie')).toBe(Movie);
expect(Director.Movie).toBe(Movie);
((Backend, BackendMovie, BackendDirector) => {
class Movie extends BackendMovie {
@consume() static Director: typeof Director;
}
class Director extends BackendDirector {
@consume() static Movie: typeof Movie;
}
class Frontend extends Backend {
@provide() static Movie = Movie;
@provide() static Director = Director;
}
expect(Movie.getConsumedComponent('Director')).toBe(Director);
expect(Movie.Director).toBe(Director);
expect(Director.getConsumedComponent('Movie')).toBe(Movie);
expect(Director.Movie).toBe(Movie);
return Frontend;
})(Backend, Movie, Director);
// The backend should not be affected by the frontend
expect(Movie.getConsumedComponent('Director')).toBe(Director);
expect(Movie.Director).toBe(Director);
expect(Director.getConsumedComponent('Movie')).toBe(Movie);
expect(Director.Movie).toBe(Movie);
expect(() => {
class Movie extends Component {
// @ts-expect-error
@consume() Director: typeof Director;
}
class Director extends Component {}
return Movie;
}).toThrow(
"@consume() must be used inside a component class with as static attribute declaration (attribute: 'Director')"
);
expect(() => {
class Director extends Component {}
class Movie extends Component {
@consume() static Director = Director;
}
return Movie;
}).toThrow(
"@consume() must be used with an attribute declaration which does not specify any value (attribute: 'Director')"
);
});
}); | the_stack |
import {AnalysisDataModel, Run} from "../models/run"
import {Status} from "../models/status"
import NETWORK from "../network"
import {IsUserLogged, User} from "../models/user"
import {RunsList} from '../models/run_list'
import {AnalysisPreference} from "../models/preferences"
import {SessionsList} from '../models/session_list'
import {Session} from '../models/session'
import {Job} from '../models/job'
const RELOAD_TIMEOUT = 60 * 1000
const FORCE_RELOAD_TIMEOUT = 5 * 1000
export function isReloadTimeout(lastUpdated: number): boolean {
return (new Date()).getTime() - lastUpdated > RELOAD_TIMEOUT
}
export function isForceReloadTimeout(lastUpdated: number): boolean {
return (new Date()).getTime() - lastUpdated > FORCE_RELOAD_TIMEOUT
}
class BroadcastPromise<T> {
// Registers a bunch of promises and broadcast to all of them
private isLoading: boolean
private resolvers: any[]
private rejectors: any[]
constructor() {
this.isLoading = false
this.resolvers = []
this.rejectors = []
}
create(load: () => Promise<T>): Promise<T> {
let promise = new Promise<T>((resolve, reject) => {
this.add(resolve, reject)
})
if (!this.isLoading) {
this.isLoading = true
// Load again only if not currently loading;
// Otherwise resolve/reject will be called when the current loading completes.
load().then((res: T) => {
this.resolve(res)
}).catch((err) => {
this.reject(err)
})
}
return promise
}
private add(resolve: (value: T) => void, reject: (err: any) => void) {
this.resolvers.push(resolve)
this.rejectors.push(reject)
}
private resolve(value: T) {
this.isLoading = false
let resolvers = this.resolvers
this.resolvers = []
this.rejectors = []
for (let r of resolvers) {
r(value)
}
}
private reject(err: any) {
this.isLoading = false
let rejectors = this.rejectors
this.resolvers = []
this.rejectors = []
for (let r of rejectors) {
r(err)
}
}
}
export abstract class CacheObject<T> {
public lastUpdated: number
protected data!: T
protected broadcastPromise = new BroadcastPromise<T>()
private lastUsed: number
constructor() {
this.lastUsed = 0
this.lastUpdated = 0
}
abstract load(...args: any[]): Promise<T>
async get(isRefresh = false, ...args: any[]): Promise<T> {
if (this.data == null || (isRefresh && isForceReloadTimeout(this.lastUpdated)) || isReloadTimeout(this.lastUpdated)) {
this.data = await this.load()
this.lastUpdated = (new Date()).getTime()
}
this.lastUsed = new Date().getTime()
return this.data
}
invalidate_cache(): void {
this.data = null
}
}
export class RunsListCache extends CacheObject<RunsList> {
async load(...args: any[]): Promise<RunsList> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getRuns(args[0])
return new RunsList(res)
})
}
async get(isRefresh = false, ...args: any[]): Promise<RunsList> {
if (args && args[0]) {
return await this.load(args[0])
}
if (this.data == null || (isRefresh && isForceReloadTimeout(this.lastUpdated)) || isReloadTimeout(this.lastUpdated)) {
this.data = await this.load(null)
this.lastUpdated = (new Date()).getTime()
}
return this.data
}
async deleteRuns(runUUIDS: Array<string>): Promise<void> {
let runs = []
// Only updating the cache manually, if the cache exists
if (this.data) {
let currentRuns = this.data.runs
for (let run of currentRuns) {
if (!runUUIDS.includes(run.run_uuid)) {
runs.push(run)
}
}
this.data.runs = runs
}
await NETWORK.deleteRuns(runUUIDS)
}
async addRun(run: Run): Promise<void> {
await NETWORK.addRun(run.run_uuid)
this.invalidate_cache()
}
async claimRun(run: Run): Promise<void> {
await NETWORK.claimRun(run.run_uuid)
this.invalidate_cache()
}
async startTensorBoard(computerUUID, runUUIDs: Array<string>): Promise<Job> {
let res = await NETWORK.startTensorBoard(computerUUID, runUUIDs)
return new Job(res)
}
async clearCheckPoints(computerUUID, runUUIDs: Array<string>): Promise<Job> {
let res = await NETWORK.clearCheckPoints(computerUUID, runUUIDs)
return new Job(res)
}
}
export class SessionsListCache extends CacheObject<SessionsList> {
async load(): Promise<SessionsList> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getSessions()
return new SessionsList(res)
})
}
async deleteSessions(sessionUUIDS: Set<string>): Promise<void> {
let sessions = []
// Only updating the cache manually, if the cache exists
if (this.data) {
let currentSessions = this.data.sessions
for (let session of currentSessions) {
if (!sessionUUIDS.has(session.session_uuid)) {
sessions.push(session)
}
}
this.data.sessions = sessions
}
await NETWORK.deleteSessions(Array.from(sessionUUIDS))
}
async addSession(session: Session): Promise<void> {
await NETWORK.addSession(session.session_uuid)
this.invalidate_cache()
}
async claimSession(session: Session): Promise<void> {
await NETWORK.claimSession(session.session_uuid)
this.invalidate_cache()
}
}
export class RunCache extends CacheObject<Run> {
private readonly uuid: string
private statusCache: RunStatusCache
constructor(uuid: string, statusCache: RunStatusCache) {
super()
this.uuid = uuid
this.statusCache = statusCache
}
async load(): Promise<Run> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getRun(this.uuid)
return new Run(res)
})
}
async get(isRefresh = false): Promise<Run> {
let status = await this.statusCache.get()
if (this.data == null || (status.isRunning && isReloadTimeout(this.lastUpdated)) || (isRefresh && isForceReloadTimeout(this.lastUpdated))) {
this.data = await this.load()
this.lastUpdated = (new Date()).getTime()
if ((status.isRunning && isReloadTimeout(this.lastUpdated)) || isRefresh) {
await this.statusCache.get(true)
}
}
return this.data
}
async setRun(run: Run): Promise<void> {
await NETWORK.setRun(this.uuid, run)
}
}
export class SessionCache extends CacheObject<Session> {
private readonly uuid: string
constructor(uuid: string) {
super()
this.uuid = uuid
}
async load(): Promise<Session> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getSession(this.uuid)
return new Session(res)
})
}
async setSession(session: Session): Promise<void> {
await NETWORK.setSession(this.uuid, session)
}
}
export abstract class StatusCache extends CacheObject<Status> {
}
export class RunStatusCache extends StatusCache {
private readonly uuid: string
constructor(uuid: string) {
super()
this.uuid = uuid
}
async load(): Promise<Status> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getRunStatus(this.uuid)
return new Status(res)
})
}
}
export class SessionStatusCache extends StatusCache {
private readonly uuid: string
constructor(uuid: string) {
super()
this.uuid = uuid
}
async load(): Promise<Status> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getSessionStatus(this.uuid)
return new Status(res)
})
}
}
export class UserCache extends CacheObject<User> {
async load(): Promise<User> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getUser()
return new User(res)
})
}
async setUser(user: User) {
await NETWORK.setUser(user)
}
}
export class IsUserLoggedCache extends CacheObject<IsUserLogged> {
set userLogged(is_user_logged: boolean) {
this.data = new IsUserLogged({is_user_logged: is_user_logged})
}
async load(): Promise<IsUserLogged> {
return this.broadcastPromise.create(async () => {
let res = await NETWORK.getIsUserLogged()
return new IsUserLogged(res)
})
}
}
export class AnalysisDataCache extends CacheObject<AnalysisDataModel> {
private readonly uuid: string
private readonly url: string
private statusCache: StatusCache
constructor(uuid: string, url: string, statusCache: StatusCache) {
super()
this.uuid = uuid
this.statusCache = statusCache
this.url = url
}
async load(): Promise<AnalysisDataModel> {
return this.broadcastPromise.create(async () => {
return await NETWORK.getAnalysis(this.url, this.uuid)
})
}
async get(isRefresh = false): Promise<AnalysisDataModel> {
let status = await this.statusCache.get()
if (this.data == null || (status.isRunning && isReloadTimeout(this.lastUpdated)) || (isRefresh && isForceReloadTimeout(this.lastUpdated))) {
this.data = await this.load()
this.lastUpdated = (new Date()).getTime()
if ((status.isRunning && isReloadTimeout(this.lastUpdated)) || isRefresh) {
await this.statusCache.get(true)
}
}
return this.data
}
async setAnalysis(data: {}): Promise<void> {
await NETWORK.setAnalysis(this.url, this.uuid, data)
}
}
export class AnalysisPreferenceCache extends CacheObject<AnalysisPreference> {
private readonly uuid: string
private readonly url: string
constructor(uuid: string, url: string) {
super()
this.uuid = uuid
this.url = url
}
async load(): Promise<AnalysisPreference> {
return this.broadcastPromise.create(async () => {
return await NETWORK.getPreferences(this.url, this.uuid)
})
}
async setPreference(preference: AnalysisPreference): Promise<void> {
await NETWORK.updatePreferences(this.url, this.uuid, preference)
}
}
class Cache {
private readonly runs: { [uuid: string]: RunCache }
private readonly sessions: { [uuid: string]: SessionCache }
private readonly runStatuses: { [uuid: string]: RunStatusCache }
private readonly sessionStatuses: { [uuid: string]: SessionStatusCache }
private user: UserCache | null
private isUserLogged: IsUserLoggedCache | null
private runsList: RunsListCache | null
private sessionsList: SessionsListCache | null
constructor() {
this.runs = {}
this.sessions = {}
this.runStatuses = {}
this.sessionStatuses = {}
this.user = null
this.runsList = null
this.sessionsList = null
this.isUserLogged = null
}
getRun(uuid: string) {
if (this.runs[uuid] == null) {
this.runs[uuid] = new RunCache(uuid, this.getRunStatus(uuid))
}
return this.runs[uuid]
}
getSession(uuid: string) {
if (this.sessions[uuid] == null) {
this.sessions[uuid] = new SessionCache(uuid)
}
return this.sessions[uuid]
}
getRunsList() {
if (this.runsList == null) {
this.runsList = new RunsListCache()
}
return this.runsList
}
getSessionsList() {
if (this.sessionsList == null) {
this.sessionsList = new SessionsListCache()
}
return this.sessionsList
}
getRunStatus(uuid: string) {
if (this.runStatuses[uuid] == null) {
this.runStatuses[uuid] = new RunStatusCache(uuid)
}
return this.runStatuses[uuid]
}
getSessionStatus(uuid: string) {
if (this.sessionStatuses[uuid] == null) {
this.sessionStatuses[uuid] = new SessionStatusCache(uuid)
}
return this.sessionStatuses[uuid]
}
getUser() {
if (this.user == null) {
this.user = new UserCache()
}
return this.user
}
getIsUserLogged() {
if (this.isUserLogged == null) {
this.isUserLogged = new IsUserLoggedCache()
}
return this.isUserLogged
}
}
let CACHE = new Cache()
export default CACHE | the_stack |
import { getPropertyValue, isTextTechnique } from "@here/harp-datasource-protocol";
import { TileKey } from "@here/harp-geoutils/lib/tiling/TileKey";
import { DataSource, TextElement, Tile } from "@here/harp-mapview";
import { debugContext } from "@here/harp-mapview/lib/DebugContext";
import { TileGeometryCreator } from "@here/harp-mapview/lib/geometry/TileGeometryCreator";
import { TextElementType } from "@here/harp-mapview/lib/text/TextElementType";
import {
ContextualArabicConverter,
FontUnit,
TextLayoutStyle,
TextRenderStyle
} from "@here/harp-text-canvas";
import * as THREE from "three";
const debugMaterial = new THREE.LineBasicMaterial({
color: 0x000000,
linewidth: 1,
depthTest: false,
depthFunc: THREE.NeverDepth
});
const debugCircleMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
depthTest: false,
depthFunc: THREE.NeverDepth
});
const debugCircleMaterialWF = new THREE.MeshBasicMaterial({
color: 0xff0000,
depthTest: false,
depthFunc: THREE.NeverDepth
});
debugCircleMaterialWF.wireframe = true;
const debugCircleMaterial2WF = new THREE.MeshBasicMaterial({
color: 0x8080ff,
depthTest: false,
depthFunc: THREE.NeverDepth
});
debugCircleMaterial2WF.wireframe = true;
const debugBlackCircleMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
depthTest: false,
depthFunc: THREE.NeverDepth
});
const debugBlueCircleMaterial = new THREE.MeshBasicMaterial({
color: 0x0000ff,
depthTest: false,
depthFunc: THREE.NeverDepth,
opacity: 0.75,
transparent: true
});
const debugOrangeCircleMaterial = new THREE.MeshBasicMaterial({
color: 0xa07000,
depthTest: false,
depthFunc: THREE.NeverDepth,
opacity: 0.75,
transparent: true
});
const textRenderStyle = new TextRenderStyle();
const textLayoutStyle = new TextLayoutStyle();
textRenderStyle.fontSize = {
unit: FontUnit.Point,
size: 9,
backgroundSize: 0
};
textRenderStyle.opacity = 0.75;
textRenderStyle.backgroundOpacity = 0.75;
textRenderStyle.color = new THREE.Color(0.8, 0.2, 0.2);
// Set maximum priority.
const PRIORITY_ALWAYS = Number.MAX_SAFE_INTEGER;
class DebugGeometry {
geometry = new THREE.BufferGeometry();
indices = new Array<number>();
positions = new Array<number>();
}
function addPoint(
xPos: number,
yPos: number,
zPos: number,
size: number,
debugGeometry: DebugGeometry
) {
debugGeometry.positions.push(xPos, yPos - size, zPos);
debugGeometry.positions.push(xPos + size, yPos, zPos);
debugGeometry.positions.push(xPos, yPos + size, zPos);
debugGeometry.positions.push(xPos - size, yPos, zPos);
const index = debugGeometry.positions.length / 3;
debugGeometry.indices.push(index - 4);
debugGeometry.indices.push(index - 3);
debugGeometry.indices.push(index - 2);
debugGeometry.indices.push(index - 4);
debugGeometry.indices.push(index - 2);
debugGeometry.indices.push(index - 1);
}
function addObject(
objects: THREE.Object3D[],
debugGeometry: DebugGeometry,
priorityOffset: number = 0,
factory: (geom: THREE.BufferGeometry) => THREE.Object3D
) {
if (debugGeometry.indices.length > 0) {
debugGeometry.geometry.addGroup(0, debugGeometry.indices.length, 0);
debugGeometry.geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(debugGeometry.positions), 3)
);
debugGeometry.geometry.setIndex(
new THREE.BufferAttribute(new Uint32Array(debugGeometry.indices), 1)
);
const mesh = factory(debugGeometry.geometry);
mesh.renderOrder = PRIORITY_ALWAYS - priorityOffset;
objects.push(mesh);
}
}
export class OmvDebugLabelsTile extends Tile {
constructor(dataSource: DataSource, tileKey: TileKey) {
super(dataSource, tileKey);
}
/**
* @override
* Create [[TextElement]] objects for label debugging.
*/
loadingFinished() {
// activate in the browser with:
// window.__debugContext.setValue("DEBUG_TEXT_PATHS", true)
const debugTextPaths = debugContext.getValue("DEBUG_TEXT_PATHS");
const debugTextPathsFull = debugContext.getValue("DEBUG_TEXT_PATHS_FULL");
const debugTextPoisFull = debugContext.getValue("DEBUG_TEXT_POIS_FULL");
const debugLineMarkers = debugContext.getValue("DEBUG_TEXT_LINE_MARKER");
if (
!(debugTextPaths || debugTextPathsFull || debugLineMarkers) ||
this.decodedTile === undefined
) {
return;
}
const tileGeometryCreator = TileGeometryCreator.instance;
const decodedTile = this.decodedTile!;
const colorMap = new Map<number, THREE.Color>();
// allow limiting to specific names and/or index. There can be many paths with the
// same text
const textFilter = debugContext.getValue("DEBUG_TEXT_PATHS.FILTER.TEXT");
const indexFilter = debugContext.getValue("DEBUG_TEXT_PATHS.FILTER.INDEX");
const env = this.mapView.env;
if (decodedTile.textPathGeometries !== undefined) {
this.preparedTextPaths = tileGeometryCreator.prepareTextPaths(
decodedTile.textPathGeometries,
decodedTile
);
}
const centerX = this.center.x;
const centerY = this.center.y;
const centerZ = this.center.z;
const pointScale = this.mapView.pixelToWorld;
const worldOffsetX = this.computeWorldOffsetX();
const zHeight = 10;
let pointLabelIndex = 0;
if (this.textElementGroups.count() > 0) {
const bluePoints = new DebugGeometry();
const orangePoints = new DebugGeometry();
const addedTextElements: TextElement[] = [];
this.textElementGroups.forEach((textElement: TextElement) => {
if (
textElement.type !== TextElementType.LineMarker &&
textElement.type !== TextElementType.PoiLabel
) {
return;
}
const isLineMarker = textElement.type === TextElementType.LineMarker;
const geometry = isLineMarker ? orangePoints : bluePoints;
const pointSize = pointScale * 5;
const addLabel = (x: number, y: number, z: number) => {
addPoint(x, y, z, pointSize, geometry);
if (debugTextPoisFull || debugLineMarkers) {
const offsetXY = pointSize * 0.5;
const label: string = `${textElement.text} [${pointLabelIndex}]`;
const labelElement = new TextElement(
ContextualArabicConverter.instance.convert(label),
new THREE.Vector3(
x + worldOffsetX + centerX + offsetXY,
y + centerY + offsetXY,
z + centerZ
),
textRenderStyle,
textLayoutStyle,
PRIORITY_ALWAYS,
0.0,
0.0
);
labelElement.minZoomLevel = 0;
labelElement.mayOverlap = true;
labelElement.reserveSpace = false;
labelElement.alwaysOnTop = true;
labelElement.ignoreDistance = true;
labelElement.priority = TextElement.HIGHEST_PRIORITY;
(labelElement as any)._isDebug = true;
addedTextElements.push(labelElement);
}
pointLabelIndex++;
};
if (textElement.path !== undefined && Array.isArray(textElement.path)) {
for (let i = 0; i < textElement.path.length; i++) {
const pos = textElement.path[i];
const x = pos.x - centerX;
const y = pos.y - centerY;
const z = zHeight + pos.z + i * 5 - centerZ;
addLabel(x, y, z);
}
} else if (debugTextPoisFull) {
const x = textElement.position.x - centerX;
const y = textElement.position.y - centerY;
const z = 5 - centerZ;
addLabel(x, y, z);
}
});
for (const labelElement of addedTextElements) {
this.addTextElement(labelElement);
}
addObject(
this.objects,
bluePoints,
0,
(geometry: THREE.BufferGeometry): THREE.Object3D => {
return new THREE.Mesh(geometry, debugBlueCircleMaterial);
}
);
addObject(
this.objects,
orangePoints,
0,
(geometry: THREE.BufferGeometry): THREE.Object3D => {
return new THREE.Mesh(geometry, debugOrangeCircleMaterial);
}
);
}
if (this.preparedTextPaths !== undefined) {
const lines = new DebugGeometry();
const redPoints = new DebugGeometry();
const blackPoints = new DebugGeometry();
let baseVertex = 0;
for (const textPath of this.preparedTextPaths) {
const technique = decodedTile.techniques[textPath.technique];
if (!isTextTechnique(technique) || (textPath as any)._isDebug !== undefined) {
continue;
}
if (technique.color !== undefined) {
colorMap.set(
textPath.technique,
new THREE.Color(getPropertyValue(technique.color, env))
);
}
baseVertex = lines.positions.length / 3;
const text = textPath.text;
const elementIndex = this.preparedTextPaths.indexOf(textPath);
const createDebugInfo =
(!textFilter || (text && text.includes(textFilter))) &&
(indexFilter === undefined || indexFilter === elementIndex);
if (createDebugInfo) {
for (let i = 0; i < textPath.path.length; i += 3) {
const pathIndex = i / 3;
const x = textPath.path[i] - centerX;
const y = textPath.path[i + 1] - centerY;
// raise it a bit, so we get identify connectivity visually by tilting
const z = zHeight + textPath.path[i + 2] + i / 3 - centerZ;
if (debugTextPaths) {
lines.positions.push(x, y, z);
}
const isRedPoint = i === 0 && debugTextPaths;
if (debugTextPathsFull || isRedPoint) {
const pointSize = pointScale * (isRedPoint ? 6 : 4);
const geometry = isRedPoint ? redPoints : blackPoints;
addPoint(x, y, z, pointSize, geometry);
if (debugTextPathsFull) {
const xOffset = technique.xOffset ?? 0.0;
const yOffset = technique.yOffset ?? 0.0;
const minZoomLevel = technique.minZoomLevel;
// give point index a label
const label: string =
pathIndex % 5 === 0
? text + ":" + pathIndex
: Number(pathIndex).toString();
const labelElement = new TextElement(
ContextualArabicConverter.instance.convert(label),
new THREE.Vector3(
x + worldOffsetX + centerX,
y + centerY,
z + centerZ
),
textRenderStyle,
textLayoutStyle,
getPropertyValue(technique.priority ?? 0, env),
xOffset,
yOffset
);
labelElement.minZoomLevel = getPropertyValue(minZoomLevel, env);
labelElement.mayOverlap = true;
labelElement.reserveSpace = false;
labelElement.alwaysOnTop = true;
labelElement.ignoreDistance = true;
labelElement.priority = TextElement.HIGHEST_PRIORITY;
this.addTextElement(labelElement);
}
}
}
// the lines of a path share a common geometry
const N = textPath.path.length / 3;
for (let i = 0; i < N; ++i) {
if (i > 0) {
lines.indices.push(baseVertex + i);
}
if (i + 1 < N) {
lines.indices.push(baseVertex + i);
}
}
}
}
addObject(
this.objects,
lines,
-2,
(geometry: THREE.BufferGeometry): THREE.Object3D => {
return new THREE.LineSegments(geometry, debugMaterial);
}
);
addObject(
this.objects,
redPoints,
0,
(geometry: THREE.BufferGeometry): THREE.Object3D => {
return new THREE.Mesh(geometry, debugCircleMaterial);
}
);
addObject(
this.objects,
blackPoints,
-1,
(geometry: THREE.BufferGeometry): THREE.Object3D => {
return new THREE.Mesh(geometry, debugBlackCircleMaterial);
}
);
}
}
} | the_stack |
import React from "react"
import { existsSync, readdir, writeFile, mkdirp, readFile } from "fs-extra"
import path from "path"
import { queryMysql } from "../db/db"
import { getBlockContent } from "../db/wpdb"
import {
EXPLORER_FILE_SUFFIX,
ExplorerProgram,
} from "../explorer/ExplorerProgram"
import { Router } from "express"
import { ExplorerPage } from "../site/ExplorerPage"
import {
EXPLORERS_GIT_CMS_FOLDER,
EXPLORERS_PREVIEW_ROUTE,
GetAllExplorersRoute,
ExplorersRouteResponse,
DefaultNewExplorerSlug,
EXPLORERS_ROUTE_FOLDER,
} from "../explorer/ExplorerConstants"
import simpleGit, { SimpleGit } from "simple-git"
import { slugify } from "../clientUtils/Util"
import { GrapherInterface } from "../grapher/core/GrapherInterface"
import { Grapher, GrapherProgrammaticInterface } from "../grapher/core/Grapher"
import { GitCommit, JsonError } from "../clientUtils/owidTypes"
import ReactDOMServer from "react-dom/server"
import {
explorerRedirectTable,
getExplorerRedirectForPath,
} from "./ExplorerRedirects"
import { explorerUrlMigrationsById } from "../explorer/urlMigrations/ExplorerUrlMigrations"
import { ExplorerPageUrlMigrationSpec } from "../explorer/urlMigrations/ExplorerPageUrlMigrationSpec"
export class ExplorerAdminServer {
constructor(gitDir: string, baseUrl: string) {
this.gitDir = gitDir
this.baseUrl = baseUrl
}
private baseUrl: string
private gitDir: string
// we store explorers in a subdir of the gitcms for now. idea is we may store other things in there later.
private get absoluteFolderPath() {
return this.gitDir + "/" + EXPLORERS_GIT_CMS_FOLDER + "/"
}
private _simpleGit?: SimpleGit
private get simpleGit() {
if (!this._simpleGit)
this._simpleGit = simpleGit({
baseDir: this.gitDir,
binary: "git",
maxConcurrentProcesses: 1,
})
return this._simpleGit
}
async getAllExplorersCommand() {
// Download all explorers for the admin index page
try {
const explorers = await this.getAllExplorers()
const branches = await this.simpleGit.branchLocal()
const gitCmsBranchName = await branches.current
const needsPull = false // todo: add
return {
success: true,
gitCmsBranchName,
needsPull,
explorers: explorers.map((explorer) => explorer.toJson()),
} as ExplorersRouteResponse
} catch (err) {
console.log(err)
return {
success: false,
errorMessage: err,
} as ExplorersRouteResponse
}
}
addMockBakedSiteRoutes(app: Router) {
app.get(`/${EXPLORERS_ROUTE_FOLDER}/:slug`, async (req, res) => {
res.set("Access-Control-Allow-Origin", "*")
const explorers = await this.getAllPublishedExplorers()
const explorerProgram = explorers.find(
(program) => program.slug === req.params.slug
)
if (explorerProgram)
res.send(await this.renderExplorerPage(explorerProgram))
else
throw new JsonError(
"A published explorer with that slug was not found",
404
)
})
app.get("/*", async (req, res, next) => {
const explorerRedirect = getExplorerRedirectForPath(req.path)
// If no explorer redirect exists, continue to next express handler
if (!explorerRedirect) return next()
const { migrationId, baseQueryStr } = explorerRedirect
const { explorerSlug } = explorerUrlMigrationsById[migrationId]
const program = await this.getExplorerFromSlug(explorerSlug)
res.send(
await this.renderExplorerPage(program, {
explorerUrlMigrationId: migrationId,
baseQueryStr,
})
)
})
}
addAdminRoutes(app: Router) {
app.get("/errorTest.csv", async (req, res) => {
// Add `table /admin/errorTest.csv?code=404` to test fetch download failures
const code =
req.query.code && !isNaN(parseInt(req.query.code))
? req.query.code
: 400
res.status(code)
return `Simulating code ${code}`
})
app.get(`/${GetAllExplorersRoute}`, async (req, res) => {
res.send(await this.getAllExplorersCommand())
})
app.get(`/${EXPLORERS_PREVIEW_ROUTE}/:slug`, async (req, res) => {
const slug = slugify(req.params.slug)
const filename = slug + EXPLORER_FILE_SUFFIX
if (slug === DefaultNewExplorerSlug)
return res.send(
await this.renderExplorerPage(
new ExplorerProgram(DefaultNewExplorerSlug, "")
)
)
if (!slug || !existsSync(this.absoluteFolderPath + filename))
return res.send(`File not found`)
const explorer = await this.getExplorerFromFile(filename)
return res.send(await this.renderExplorerPage(explorer))
})
}
// todo: make private? once we remove covid legacy stuff?
async getExplorerFromFile(filename: string) {
const fullPath = this.absoluteFolderPath + filename
const content = await readFile(fullPath, "utf8")
const commits = await this.simpleGit.log({ file: fullPath, n: 1 })
return new ExplorerProgram(
filename.replace(EXPLORER_FILE_SUFFIX, ""),
content,
commits.latest as GitCommit
)
}
async getExplorerFromSlug(slug: string) {
return this.getExplorerFromFile(`${slug}${EXPLORER_FILE_SUFFIX}`)
}
async renderExplorerPage(
program: ExplorerProgram,
urlMigrationSpec?: ExplorerPageUrlMigrationSpec
) {
const { requiredGrapherIds } = program.decisionMatrix
let grapherConfigRows: any[] = []
if (requiredGrapherIds.length)
grapherConfigRows = await queryMysql(
`SELECT id, config FROM charts WHERE id IN (?)`,
[requiredGrapherIds]
)
const wpContent = program.wpBlockId
? await getBlockContent(program.wpBlockId)
: undefined
const grapherConfigs: GrapherInterface[] = grapherConfigRows.map(
(row) => {
const config: GrapherProgrammaticInterface = JSON.parse(
row.config
)
config.id = row.id // Ensure each grapher has an id
config.manuallyProvideData = true
return new Grapher(config).toObject()
}
)
return (
`<!doctype html>` +
ReactDOMServer.renderToStaticMarkup(
<ExplorerPage
grapherConfigs={grapherConfigs}
program={program}
wpContent={wpContent}
baseUrl={this.baseUrl}
urlMigrationSpec={urlMigrationSpec}
/>
)
)
}
async bakeAllPublishedExplorers(outputFolder: string) {
const published = await this.getAllPublishedExplorers()
await this.bakeExplorersToDir(outputFolder, published)
}
private async getAllPublishedExplorers() {
const explorers = await this.getAllExplorers()
return explorers.filter((exp) => exp.isPublished)
}
private async getAllExplorers() {
if (!existsSync(this.absoluteFolderPath)) return []
const files = await readdir(this.absoluteFolderPath)
const explorerFiles = files.filter((filename) =>
filename.endsWith(EXPLORER_FILE_SUFFIX)
)
const explorers: ExplorerProgram[] = []
for (const filename of explorerFiles) {
const explorer = await this.getExplorerFromFile(filename)
explorers.push(explorer)
}
return explorers
}
private async write(outPath: string, content: string) {
await mkdirp(path.dirname(outPath))
await writeFile(outPath, content)
console.log(outPath)
}
private async bakeExplorersToDir(
directory: string,
explorers: ExplorerProgram[] = []
) {
for (const explorer of explorers) {
await this.write(
`${directory}/${explorer.slug}.html`,
await this.renderExplorerPage(explorer)
)
}
}
async bakeAllExplorerRedirects(outputFolder: string) {
const explorers = await this.getAllExplorers()
const redirects = explorerRedirectTable.rows
for (const redirect of redirects) {
const { migrationId, path: redirectPath, baseQueryStr } = redirect
const transform = explorerUrlMigrationsById[migrationId]
if (!transform) {
throw new Error(
`No explorer URL migration with id '${migrationId}'. Fix the list of explorer redirects and retry.`
)
}
const { explorerSlug } = transform
const program = explorers.find(
(program) => program.slug === explorerSlug
)
if (!program) {
throw new Error(
`No explorer with slug '${explorerSlug}'. Fix the list of explorer redirects and retry.`
)
}
const html = await this.renderExplorerPage(program, {
explorerUrlMigrationId: migrationId,
baseQueryStr,
})
await this.write(
path.join(outputFolder, `${redirectPath}.html`),
html
)
}
}
} | the_stack |
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import Tester from '../../Tester';
import { Block, Commitment, Blockchain, HardCreate, getMerkleRoot, getMerkleProof, encodeTransactions, transactionsToArray, SoftCreate, Account } from '../../../app';
import { randomHexBuffer, ProofBlockchain, randomHexString, encodeAccountProof } from '../../utils';
import { encodeTransactionStateProof } from '../../../app/modules/auditor/coder';
chai.use(chaiAsPromised);
const { expect } = chai;
export const test = () => describe("Execution Fraud Proof Tests", async () => {
let web3: any, tester: Tester, from: string, blockchain: ProofBlockchain;
async function resetBlockchain() {
const { token, tiramisuContract } = blockchain;
await tiramisuContract.methods.resetChain().send({ from, gas: 5e6 });
const state = await tester.newState();
blockchain = new ProofBlockchain({ web3, fromAddress: from, token, tiramisuContract, state });
}
async function hardDeposit(account, value) {
await blockchain.tiramisuContract.methods
.mockDeposit(account.address, account.address, value)
.send({ from, gas: 5e6 });
}
async function getBlockCount(): Promise<number> {
return blockchain.tiramisuContract.methods.getBlockCount().call().then(x => +x);
}
before(async () => {
({ blockchain, web3, tester, from } = await Tester.create({ blockchain: true }));
});
describe('Created Account Index Error', async () => {
describe('Case 1: Single hard create', async () => {
let previousHeader: Commitment;
let badBlock: Block;
let account1, account2;
before(async () => {
await resetBlockchain();
account1 = tester.randomAccount();
account2 = tester.randomAccount();
});
it("Should process, submit and confirm an initial block.", async () => {
await hardDeposit(account1, 100);
let block = await blockchain.processBlock();
await blockchain.submitBlock(block);
await blockchain.confirmBlock(block);
previousHeader = block.commitment;
expect(await getBlockCount()).to.eq(2);
});
it('Should submit a block with a hard create that has a bad `accountIndex`', async () => {
await hardDeposit(account2, 50);
const block = await blockchain.processBlock();
const transaction = block.transactions.hardCreates[0];
transaction.accountIndex += 1;
const leaf = transaction.encode(true);
block.header.transactionsRoot = getMerkleRoot([leaf]);
const transactions = { hardCreates: [transaction] }
const { transactionsData } = encodeTransactions(transactions);
block.transactionsData = transactionsData;
await blockchain.submitBlock(block);
badBlock = block;
expect(await getBlockCount()).to.eq(3);
});
it('Should prove a hard create has a bad account index by calling `createdAccountIndexError`', async () => {
await blockchain.tiramisuContract.methods.proveCreateIndexError(
previousHeader,
badBlock.commitment,
0,
badBlock.transactionsData
).send({ from, gas: 5e6 })
expect(await getBlockCount()).to.eq(2);
});
});
describe('Case 2: Failure', async () => {
let previousHeader: Commitment;
let badBlock: Block;
let account1, account2, account3;
before(async () => {
await resetBlockchain();
account1 = tester.randomAccount();
account2 = tester.randomAccount();
account3 = tester.randomAccount();
});
it("Should process, submit and confirm an initial block.", async () => {
await hardDeposit(account1, 100);
let block = await blockchain.processBlock();
await blockchain.submitBlock(block);
await blockchain.confirmBlock(block);
previousHeader = block.commitment;
expect(await getBlockCount()).to.eq(2);
});
it('Should submit a block with a hard create that has a null root.', async () => {
await hardDeposit(account2, 50);
await hardDeposit(account3, 50);
const block = await blockchain.processBlock();
await blockchain.submitBlock(block);
badBlock = block;
expect(await getBlockCount()).to.eq(3);
});
it('Should fail to revert a valid block.', async () => {
const promise = blockchain.tiramisuContract.methods.proveCreateIndexError(
previousHeader,
badBlock.commitment,
1,
badBlock.transactionsData
).send({ from })
expect(promise).to.eventually.be.rejectedWith('VM Exception while processing transaction: revert Transaction had correct index.')
expect(await getBlockCount()).to.eq(3);
});
it('Should reject a call with an out of range transaction.', async () => {
const promise = blockchain.tiramisuContract.methods.proveCreateIndexError(
previousHeader,
badBlock.commitment,
3,
badBlock.transactionsData
).send({ from })
expect(promise).to.eventually.be.rejectedWith('VM Exception while processing transaction: revert Not a create transaction.')
expect(await getBlockCount()).to.eq(3);
});
});
});
/* describe('Create Execution Error', async () => {
let account1: Account, account2: Account;
beforeEach(async () => {
await resetBlockchain();
account1 = tester.randomAccount();
account2 = tester.randomAccount();
});
async function executeFraudProof(
options: {
soft?: boolean,
accountIndex?: number,
transactionIndex?: number,
getPriorStateProof?: boolean,
proofSetup?: () => Promise<void>,
transactionMutator?: (transaction: HardCreate | SoftCreate) => Buffer,
expectFailure?: string
}
) {
let {
accountIndex, transactionIndex,
getPriorStateProof, proofSetup,
transactionMutator, soft,
expectFailure
} = options;
transactionIndex = transactionIndex || 0;
if (proofSetup) await proofSetup();
else await hardDeposit(account1, 50)
let block: Block;
let previousRootProof;
let accountProof;
let transactionProof;
let transactionData;
if (getPriorStateProof) {
({ block, transactionData, accountProof, previousStateProof: previousRootProof, transactionProof } = await blockchain.processBlockForProof({
accountIndex,
transactionIndex,
transactionMutator
}));
} else {
block = await blockchain.processBlock();
accountProof = '0x';
previousRootProof = '0x';
const transaction = block.transactions[soft ? 'softCreates' : 'hardCreates'][transactionIndex]
const leaves = transactionsToArray(block.transactions).map(tx => tx.encode(true));
if (transactionMutator) leaves[transactionIndex] = transactionMutator(transaction);
transactionProof = getMerkleProof(leaves, transactionIndex).siblings;
transactionData = leaves[transactionIndex];
block.header.transactionsRoot = getMerkleRoot(leaves);
}
const n = await getBlockCount();
await blockchain.submitBlock(block);
expect(await getBlockCount()).to.eql(n+1);
const promise = blockchain.tiramisuContract.methods.proveExecutionError(
block.commitment,
encodeTransactionStateProof({
previousRootProof,
transactionIndex,
siblings: transactionProof
}),
transactionData,
accountProof,
'0x'
)
// const promise = blockchain.tiramisuContract.methods.createExecutionError(
// block.commitment,
// transactionData,
// transactionIndex,
// transactionProof,
// previousRootProof,
// accountProof
// ).send({ from, gas: 6e6 });
if (expectFailure) {
expect(promise).to.eventually.be.rejectedWith(`VM Exception while processing transaction: revert ${expectFailure}`);
expect(await getBlockCount()).to.eql(n+1);
} else {
await promise;
expect(await getBlockCount()).to.eql(n);
}
}
it('Should prove that a hard create has a bad output root', async () => {
await executeFraudProof({
proofSetup: async () => {
await hardDeposit(account1, 20)
await hardDeposit(account2, 20);
},
getPriorStateProof: true,
transactionIndex: 1,
accountIndex: 1,
transactionMutator: (transaction: HardCreate): Buffer => {
transaction.intermediateStateRoot = randomHexString(32);
return transaction.encode(true);
}
});
});
it('Should reject a hard create with a valid output root', async () => {
await executeFraudProof({
proofSetup: async () => {
await hardDeposit(account1, 20)
await hardDeposit(account2, 20);
},
getPriorStateProof: true,
transactionIndex: 1,
accountIndex: 1,
expectFailure: `Transaction had valid output root.`,
transactionMutator: (transaction: HardCreate): Buffer => {
return transaction.encode(true);
}
});
});
it('Should prove that a soft create has a bad output root', async () => {
await executeFraudProof({
proofSetup: async () => {
await hardDeposit(account1, 20);
const transaction = new SoftCreate({
accountIndex: 0,
nonce: 0,
value: 10,
toAccountIndex: 1,
accountAddress: account2.address,
initialSigningKey: account2.signers[0],
privateKey: account1.privateKey
});
blockchain.queueTransaction(transaction);
},
getPriorStateProof: true,
transactionIndex: 1,
accountIndex: 1,
transactionMutator: (transaction: HardCreate): Buffer => {
transaction.intermediateStateRoot = randomHexString(32);
return transaction.encode(true);
}
});
});
}); */
});
if (process.env.NODE_ENV != 'all' && process.env.NODE_ENV != 'coverage') test(); | the_stack |
import {
Component,
EventEmitter,
Input,
OnDestroy,
Output,
TemplateRef,
ViewChild,
ViewEncapsulation,
ElementRef,
ChangeDetectionStrategy,
HostBinding,
NgZone
} from '@angular/core';
import { AnimationEvent } from '@angular/animations';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { ESCAPE } from '@angular/cdk/keycodes';
import { MdePopoverPositionX, MdePopoverPositionY, MdePopoverTriggerEvent, MdePopoverScrollStrategy } from './popover-types';
import { throwMdePopoverInvalidPositionX, throwMdePopoverInvalidPositionY } from './popover-errors';
import { MdePopoverPanel } from './popover-interfaces';
import { transformPopover } from './popover-animations';
@Component({
selector: 'mde-popover',
templateUrl: './popover.html',
styleUrls: ['./popover.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
animations: [
transformPopover
],
exportAs: 'mdePopover'
})
export class MdePopover implements MdePopoverPanel, OnDestroy { // tslint:disable-line:component-class-suffix
@HostBinding('attr.role') role = 'dialog';
/** Settings for popover, view setters and getters for more detail */
private _positionX: MdePopoverPositionX = 'after';
private _positionY: MdePopoverPositionY = 'below';
private _triggerEvent: MdePopoverTriggerEvent = 'hover';
private _scrollStrategy: MdePopoverScrollStrategy = 'reposition';
private _enterDelay = 200;
private _leaveDelay = 200;
private _overlapTrigger = true;
private _disableAnimation = false;
private _targetOffsetX = 0;
private _targetOffsetY = 0;
private _arrowOffsetX = 20;
private _arrowWidth = 8;
private _arrowColor = 'rgba(0, 0, 0, 0.12)';
private _closeOnClick = true;
private _focusTrapEnabled = true;
private _focusTrapAutoCaptureEnabled = true;
/** Config object to be passed into the popover's ngClass */
_classList: {[key: string]: boolean} = {};
// TODO: Write comment description
/** */
public containerPositioning = false;
/** Closing disabled on popover */
public closeDisabled = false;
/** Config object to be passed into the popover's arrow ngStyle */
public popoverPanelStyles: {};
/** Config object to be passed into the popover's arrow ngStyle */
public popoverArrowStyles: {};
/** Config object to be passed into the popover's content ngStyle */
public popoverContentStyles: {};
/** Emits the current animation state whenever it changes. */
_onAnimationStateChange = new EventEmitter<AnimationEvent>();
/** Position of the popover in the X axis. */
@Input('mdePopoverPositionX')
get positionX() { return this._positionX; }
set positionX(value: MdePopoverPositionX) {
if (value !== 'before' && value !== 'after') {
throwMdePopoverInvalidPositionX();
}
this._positionX = value;
this.setPositionClasses();
}
/** Position of the popover in the Y axis. */
@Input('mdePopoverPositionY')
get positionY() { return this._positionY; }
set positionY(value: MdePopoverPositionY) {
if (value !== 'above' && value !== 'below') {
throwMdePopoverInvalidPositionY();
}
this._positionY = value;
this.setPositionClasses();
}
/** Popover trigger event */
@Input('mdePopoverTriggerOn')
get triggerEvent(): MdePopoverTriggerEvent { return this._triggerEvent; }
set triggerEvent(value: MdePopoverTriggerEvent) { this._triggerEvent = value; }
/** Popover scroll strategy */
@Input('mdePopoverScrollStrategy')
get scrollStrategy(): MdePopoverScrollStrategy { return this._scrollStrategy; }
set scrollStrategy(value: MdePopoverScrollStrategy) { this._scrollStrategy = value; }
/** Popover enter delay */
@Input('mdePopoverEnterDelay')
get enterDelay(): number { return this._enterDelay; }
set enterDelay(value: number) { this._enterDelay = value; }
/** Popover leave delay */
@Input('mdePopoverLeaveDelay')
get leaveDelay(): number { return this._leaveDelay; }
set leaveDelay(value: number) { this._leaveDelay = value; }
/** Popover overlap trigger */
@Input('mdePopoverOverlapTrigger')
get overlapTrigger(): boolean { return this._overlapTrigger; }
set overlapTrigger(value: boolean) { this._overlapTrigger = value; }
/** Popover target offset x */
@Input('mdePopoverOffsetX')
get targetOffsetX(): number { return this._targetOffsetX; }
set targetOffsetX(value: number) { this._targetOffsetX = value; }
/** Popover target offset y */
@Input('mdePopoverOffsetY')
get targetOffsetY(): number { return this._targetOffsetY; }
set targetOffsetY(value: number) { this._targetOffsetY = value; }
/** Popover arrow offset x */
@Input('mdePopoverArrowOffsetX')
get arrowOffsetX(): number { return this._arrowOffsetX; }
set arrowOffsetX(value: number) { this._arrowOffsetX = value; }
/** Popover arrow width */
@Input('mdePopoverArrowWidth')
get arrowWidth(): number { return this._arrowWidth; }
set arrowWidth(value: number) { this._arrowWidth = value; }
/** Popover arrow color */
@Input('mdePopoverArrowColor')
get arrowColor(): string { return this._arrowColor; }
set arrowColor(value: string) { this._arrowColor = value; }
/**
* Popover container close on click
* default: true
*/
@Input('mdePopoverCloseOnClick')
get closeOnClick(): boolean { return this._closeOnClick; }
set closeOnClick(value: boolean) { this._closeOnClick = coerceBooleanProperty(value); }
/**
* Disable animations of popover and all child elements
* default: false
*/
@Input('mdePopoverDisableAnimation')
get disableAnimation(): boolean { return this._disableAnimation; }
set disableAnimation(value: boolean) { this._disableAnimation = coerceBooleanProperty(value); }
/**
* Popover focus trap using cdkTrapFocus
* default: true
*/
@Input('mdeFocusTrapEnabled')
get focusTrapEnabled(): boolean { return this._focusTrapEnabled; }
set focusTrapEnabled(value: boolean) { this._focusTrapEnabled = coerceBooleanProperty(value); }
/**
* Popover focus trap auto capture using cdkTrapFocusAutoCapture
* default: true
*/
@Input('mdeFocusTrapAutoCaptureEnabled')
get focusTrapAutoCaptureEnabled(): boolean { return this._focusTrapAutoCaptureEnabled; }
set focusTrapAutoCaptureEnabled(value: boolean) { this._focusTrapAutoCaptureEnabled = coerceBooleanProperty(value); }
/**
* This method takes classes set on the host md-popover element and applies them on the
* popover template that displays in the overlay container. Otherwise, it's difficult
* to style the containing popover from outside the component.
* @param classes list of class names
*/
@Input('class')
set panelClass(classes: string) {
if (classes && classes.length) {
this._classList = classes.split(' ').reduce((obj: any, className: string) => {
obj[className] = true;
return obj;
}, {});
this._elementRef.nativeElement.className = '';
this.setPositionClasses();
}
}
/**
* This method takes classes set on the host md-popover element and applies them on the
* popover template that displays in the overlay container. Otherwise, it's difficult
* to style the containing popover from outside the component.
* @deprecated Use `panelClass` instead.
*/
@Input()
get classList(): string { return this.panelClass; }
set classList(classes: string) { this.panelClass = classes; }
/** Event emitted when the popover is closed. */
@Output() close = new EventEmitter<void>();
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
constructor(private _elementRef: ElementRef, public zone: NgZone) {
this.setPositionClasses();
}
ngOnDestroy() {
this._emitCloseEvent();
this.close.complete();
}
/** Handle a keyboard event from the popover, delegating to the appropriate action. */
_handleKeydown(event: KeyboardEvent) {
switch (event.keyCode) {
case ESCAPE:
this._emitCloseEvent();
return;
}
}
/**
* This emits a close event to which the trigger is subscribed. When emitted, the
* trigger will close the popover.
*/
_emitCloseEvent(): void {
this.close.emit();
}
/** Close popover on click if closeOnClick is true */
onClick() {
if (this.closeOnClick) {
this._emitCloseEvent();
}
}
/**
* TODO: Refactor when @angular/cdk includes feature I mentioned on github see link below.
* https://github.com/angular/material2/pull/5493#issuecomment-313085323
*/
/** Disables close of popover when leaving trigger element and mouse over the popover */
onMouseOver() {
if (this.triggerEvent === 'hover') {
this.closeDisabled = true;
}
}
/** Enables close of popover when mouse leaving popover element */
onMouseLeave() {
if (this.triggerEvent === 'hover') {
this.closeDisabled = false;
this._emitCloseEvent();
}
}
// TODO: Refactor how styles are set and updated on the component, use best practices.
// TODO: If arrow left and right positioning is requested, see if flex direction can be used to work with order.
/** Sets the current styles for the popover to allow for dynamically changing settings */
setCurrentStyles() {
// TODO: See if arrow position can be calculated automatically and allow override.
// TODO: See if flex order is a better alternative to position arrow top or bottom.
this.popoverArrowStyles = {
'right': this.positionX === 'before' ? (this.arrowOffsetX - this.arrowWidth) + 'px' : '',
'left': this.positionX === 'after' ? (this.arrowOffsetX - this.arrowWidth) + 'px' : '',
'border-top': this.positionY === 'below' ?
this.arrowWidth + 'px solid ' + this.arrowColor : '0px solid transparent',
'border-right': 'undefined' === undefined ?
this.arrowWidth + 'px solid ' + this.arrowColor :
this.arrowWidth + 'px solid transparent',
'border-bottom': this.positionY === 'above' ?
this.arrowWidth + 'px solid ' + this.arrowColor :
this.arrowWidth + 'px solid transparent',
'border-left': 'undefined' === undefined ?
this.arrowWidth + 'px solid ' + this.arrowColor :
this.arrowWidth + 'px solid transparent',
};
// TODO: Remove if flex order is added.
this.popoverContentStyles = {
'padding-top': this.overlapTrigger === true ? '0px' : this.arrowWidth + 'px',
'padding-bottom': this.overlapTrigger === true ? '0px' : (this.arrowWidth) + 'px',
'margin-top': this.overlapTrigger === false && this.positionY === 'below' && this.containerPositioning === false ?
-(this.arrowWidth * 2) + 'px' : '0px'
};
}
/**
* It's necessary to set position-based classes to ensure the popover panel animation
* folds out from the correct direction.
*/
setPositionClasses(posX = this.positionX, posY = this.positionY): void {
this._classList['mde-popover-before'] = posX === 'before';
this._classList['mde-popover-after'] = posX === 'after';
this._classList['mde-popover-above'] = posY === 'above';
this._classList['mde-popover-below'] = posY === 'below';
}
} | the_stack |
import { uniq } from "lodash-es";
const BASESEQ = "BCEJKMRSUhik";
const _BASE64_ST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const _BASE64_RST = [].reduce.call(_BASE64_ST, (r: { [x: string]: number }, v: string, i: number) => ((r[v] = i), r), {}) as { [x: string]: number };
function ibase64(src: number): string {
if (src < 4096) return _BASE64_ST[src >> 6] + _BASE64_ST[src & 63];
}
function deibase64(src: string): number {
return (_BASE64_RST[src[0]] << 6) | _BASE64_RST[src[1]];
}
function toMidi(name: string) {
const isSemi = name.startsWith("b");
const [note, domain] = name.substr(name.length - 2, 2);
return SEMITONES[(note.charCodeAt(0) + 3) % 7] - (isSemi ? 1 : 0) + (+domain + 2) * 12;
}
/** 弦 */
const StringMap = [[], [0], [1], [0, 1], [2], [1, 2], [0, 2], [0, 1, 2]];
/** 品 */
const FretMap = [[0], [3], [6], [0, 2, 4], [9], [3, 5, 7], [0, 1, 3], [3, 4, 6]];
/** 代码映射 */
const CodeMap = (function () {
let r = {};
for (let i = 1; i < _BASE64_ST.length; i++) {
if ((i & 7) === 0) continue;
const str = StringMap[i & 7]; // 得到弦位
const fre = FretMap[i >> 3]; // 得到品位
const c = _BASE64_ST[i];
let dst = [];
str.forEach(str => {
fre.forEach(fre => {
dst.push(str + fre);
});
});
if (dst.length) r[c] = uniq(dst).sort();
}
return r as { [x: string]: number[] };
})();
const CodeMapRev = Object.keys(CodeMap).reduce((r, v) => ((r[CodeMap[v].join("_")] = v), r), {}) as { [x: string]: string };
export enum Mode {
PentatonicMinor = 1, // 五声小调 C-bE-F-G-bB
PentatonicMajor, // 五声大调 C-D-E-G-A
Chromatic, // 半音 C-bD-D-bE-E-F-bG-G-bA-A-bB-B
Hexatonic, // 六式音阶, C-D-E-G-A-B
Major, // 大调 C-D-E-F-G-A-B
Minor, // 小调 C-D-bE-F-G-bA-bB
Hirajoshi, // 平调子 C-bD-bE-F-G-bA
Phrygian, // 弗吉利亚调式 C-D-bE-F-G-A-bB
Yo, // Yo调式 bD-bE-bG-bA-bB
}
export const ModeMaps: { [key: number]: string[] } = {
[Mode.PentatonicMinor]: ["C3", "bE3", "F3", "G3", "bB3", "C4", "bE4", "F4", "G4", "bB4", "C5", "bE5"],
[Mode.PentatonicMajor]: ["C3", "D3", "E3", "G3", "A3", "C4", "D4", "E4", "G4", "A4", "C5", "D5"],
[Mode.Chromatic]: ["C3", "bD3", "D3", "bE3", "E3", "F3", "bG3", "G3", "bA3", "A3", "bB3", "B3"],
[Mode.Hexatonic]: ["C3", "bE3", "F3", "bG3", "G3", "bB3", "C4", "bE4", "F4", "bG4", "G4", "bB4"],
[Mode.Major]: ["C3", "D3", "E3", "F3", "G3", "A3", "B3", "C4", "D4", "E4", "F4", "G4"],
[Mode.Minor]: ["C3", "D3", "bE3", "F3", "G3", "bA3", "bB3", "C4", "D4", "bE4", "F4", "G4"],
[Mode.Hirajoshi]: ["C3", "bD3", "F3", "bG3", "bA3", "C4", "bD4", "F4", "bG4", "bA4", "C5", "bD5"],
[Mode.Phrygian]: ["C3", "bD3", "E3", "F3", "G3", "bA3", "bB3", "C4", "bD4", "E4", "F4", "G4"],
[Mode.Yo]: ["bD3", "bE3", "bG3", "bA3", "bB3", "bD4", "bE4", "bG4", "bA4", "bB4", "bD5", "bE5"],
};
const SEQ = "BCEJKMRSUhik";
const SEQ_REV = [].reduce.call(SEQ, (r: { [x: string]: number }, v: string, i: number) => ((r[v] = i), r), {}) as { [x: string]: number };
const SEMITONES = [0, 2, 4, 5, 7, 9, 11];
const NOTE12S = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
// const NOTE12B = ["C", "bD", "D", "bE", "E", "F", "bG", "G", "bA", "A", "bB", "B"];
const NOTE12T = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
const NUM12S = ["1", "1#", "2", "2#", "3", "4", "4#", "5", "5#", "6", "6#", "7"];
const NUM12T = ["1", "#1", "2", "#2", "3", "4", "#4", "5", "#5", "6", "#6", "7"];
const NUM12B = ["1", "b2", "2", "b3", "3", "4", "b5", "5", "b6", "6", "b7", "7"];
/** 音符 */
export class Note {
/** 位 */
seq = 0;
/** 音名 */
name: string;
/** 四分音符 = 1 二分音符 = 2 以此类推 */
duration: number;
/** 系 */
parent: Music;
/** midi */
midi = 0;
get shiftMidi() {
return this.midi + this.parent.numberShift;
}
get code() {
return SEQ[this.seq];
}
/** 简谱 */
get number() {
if (this.seq < 0) return "0";
return NUM12B[this.shiftMidi % 12];
}
/** 简谱升调 */
get sharpNumber() {
if (this.seq < 0) return "0";
return NUM12S[this.shiftMidi % 12];
}
/** 简谱升调 */
get codeNumber() {
if (this.seq < 0) return "0";
return NUM12T[this.shiftMidi % 12];
}
/** 简谱音高 */
get tone() {
return ((this.shiftMidi / 12) | 0) - 6;
}
/** 升调表示音名 */
get sharpName() {
if (this.seq < 0) return "0";
return NOTE12S[this.shiftMidi % 12] + (((this.shiftMidi / 12) | 0) - 2);
}
/** tone.js格式的降调 */
get toneName() {
if (this.seq < 0) return "0";
return NOTE12T[this.midi % 12] + (((this.midi / 12) | 0) - 2);
}
constructor(seq: string | number, parent: Music, duration = 1) {
if (typeof seq === "string") seq = SEQ_REV[seq];
this.seq = seq;
this.parent = parent;
this.duration = duration;
this.recalc();
}
recalc() {
if (this.seq < 0) {
this.name = "0";
return;
}
if (!this.parent.modeMap) return;
const name = this.parent.modeMap[this.seq];
this.name = name;
this.midi = toMidi(name);
}
}
/** 时域音符(播放用) */
export class MusicNote extends Note {
/** 位置 12bit */
position: number;
constructor(note: Note) {
super(note.seq, note.parent);
}
}
/** 歌曲 */
export class Music {
/** 曲名 */
name: string;
/** 原曲 */
original?: string;
/** 作曲 */
composer: string;
/** 编曲 */
arranger: string;
/** 拍号 [小节拍数, 几分音符为一拍] */
timeSignature: [number, number] = [4, 4];
/** 速度 */
bpm = 240;
/** 简谱转调 */
numberShift = 0;
modeMap = ModeMaps[Mode.Major];
/** 调式 */
private _mode: Mode = Mode.Major;
get mode(): Mode {
return this._mode;
}
set mode(value: Mode) {
this._mode = value;
this.modeMap = ModeMaps[value];
if (this.notes)
this.notes.forEach(note => {
note.recalc();
});
}
get midiMap() {
return this.modeMap.map(m => toMidi(m));
}
/** 音符 */
notes: Note[] = [];
get space() {
return (960 / this.bpm) | 0;
}
get musicNotes() {
const space = this.space;
let pos = 0;
let dst: MusicNote[] = [];
let zeroNoteCache: MusicNote[] = [];
for (let i = 0; i < this.notes.length; i++) {
let note = this.notes[i];
while (note.seq < 0) {
pos += space * note.duration;
note = this.notes[++i];
if (!note) return dst;
}
let mn = new MusicNote(note);
mn.position = pos;
mn.duration = note.duration;
pos += space * note.duration;
if (note.duration === 0) {
zeroNoteCache.push(mn);
} else {
zeroNoteCache.forEach(v => (v.duration = note.duration));
zeroNoteCache = [];
}
dst.push(mn);
}
// console.log(dst.map(v => `${v.code}:${v.position}`));
return dst;
}
get code() {
// 同时出现多音符按照对照表进行合并
const mn = this.musicNotes;
let stack = [],
sections = [];
for (let i = 0; i < mn.length; i++) {
const note = mn[i];
const next = mn[i + 1];
const pos = ibase64(note.position);
if (!pos) break;
if (next && note.position === next.position) {
stack.push(note.seq);
continue;
}
if (stack.length) {
const key = uniq(stack.concat(note.seq))
.sort()
.join("_");
const code = CodeMapRev[key] || BASESEQ[note.seq];
sections.push(`${code}${pos}`);
stack.length = 0;
} else {
sections.push(`${BASESEQ[note.seq]}${pos}`);
}
}
return `${this.mode}${sections.join("")}`;
}
set code(value) {
this._mode = +value[0];
this.modeMap = ModeMaps[this._mode];
const notes = value.substr(1);
let seqs: [number, number][] = [];
let space = this.space;
for (let i = 0; i < notes.length - 2;) {
const [code, pos] = [notes[i], notes.substr(i + 1, 2)];
const t = deibase64(pos);
// 自动判定BPM
if (t % space != 0 && this.bpm < 960) {
for (let j = space - 1; j > 0; --j) {
if (t % j === 0) {
this.bpm = 960 / j;
space = j;
break;
}
}
seqs = [];
i = 0;
continue;
}
const cs = CodeMap[code];
if (cs) {
cs.forEach(c => {
seqs.push([c, t / space]);
});
}
i += 3;
}
this.setSeqs(seqs);
}
setSeqs(seqs: [number, number][]) {
const notes: Note[] = [];
let lastDuration = 1;
const addPadding = (d: number) => {
if (!d) return;
const b4 = ~~(d / 4);
const b2 = ~~((d % 4) / 2);
const b1 = d % 2;
const s = (d: number) => new Note(-1, this, d);
for (let i = 0; i < b4; i++) notes.push(s(4));
if (b2) notes.push(s(2));
if (b1) notes.push(s(1));
};
if (seqs[0][1] !== 0) {
addPadding(seqs[0][1]);
}
for (let i = 0; i < seqs.length; i++) {
const [k, t] = seqs[i];
const next = seqs[i + 1];
const n = new Note(k, this);
let padding = 0;
if (next) {
const nt = next[1];
const deltaT = nt - t;
if (deltaT > 4) {
n.duration = 4;
padding = deltaT - 4;
} else if (deltaT === 3) {
n.duration = 2;
padding = 1;
} else {
// 0 1 2 4
n.duration = deltaT;
}
lastDuration = n.duration || lastDuration;
} else n.duration = lastDuration;
notes.push(n);
if (padding) addPadding(padding);
}
this.notes = notes;
}
/** 清除所有音符 */
clear() {
this.notes = [];
}
/** 添加音符 */
addNote(note: Note, duration = 1) {
const t = new Note(note ? note.seq : -1, this, duration);
this.notes.push(t);
}
removeNote(at: number = -1) {
if (at === -1) {
this.notes.pop();
} else {
this.notes.splice(at);
}
}
/** 获取简谱对应的音符 */
getNoteByMidi(num: number, duration?: number) {
const mm = this.midiMap;
let midi = mm.findIndex(v => v >= num);
if (num - mm[midi - 1] < num - mm[midi]) midi--;
return new Note(Math.max(0, midi), this, duration);
}
get totalDuration() {
let totalTime = 0;
this.musicNotes.forEach(note => {
totalTime += note.duration;
});
return totalTime;
}
get numberSeqs() {
let rst = [],
lastDuration = 2,
totalTime = 0;
for (let i = 0; i < this.notes.length; i++) {
const last = this.notes[i - 1];
const note = this.notes[i];
const toneFlag = ["_", , "^", "^^"][note.tone + 1] || "";
let durationFlag = "";
if (i === 0 || note.duration != lastDuration) durationFlag = ["(", "=", "-", , "."][note.duration];
rst.push(
`${i > 0 && totalTime % 16 === 0 ? " " : ""}${durationFlag}${toneFlag}${note.codeNumber}${
i > 0 && note.duration != last.duration && last.duration === 0 ? ")" : ""
}`
);
lastDuration = note.duration || lastDuration;
totalTime += note.duration;
}
return rst.join("");
}
set numberSeqs(value) {
let notes = [],
duration = 2,
toneOffset = 6,
point = false;
const rex = /([\.=\-\[\],{}])|((?:[_\^\/+]+)?[b#]?[0-7]|\((?:(?:[_\^\/+]+)?[b#]?[0-7])+?\))/g;
const srex = /([_\^\/+]+)?([b#])?([0-7])/g;
value.replace(rex, (m0, mdura: string, mnote: string) => {
if (mdura) {
switch (mdura) {
case ",":
notes.push(new Note(-1, this, Math.max(1, duration / 2)));
point = true;
break;
case "[":
duration = Math.max(1, duration / 2);
break;
case "]":
duration *= 2;
break;
case "{":
toneOffset++;
break;
case "}":
toneOffset--;
break;
default:
duration = { "=": 1, "-": 2, ".": 4 }[mdura];
}
}
if (mnote) {
let mnotes: Note[] = [];
mnote.replace(srex, (m, mtone, msharp, mn) => {
if (mn === "0") {
mnotes.push(new Note(-1, this, 0));
} else {
const tone = (mtone && { _: -1, "^": 1, "/": -1, "+": 1 }[mtone[0]] * mtone.length) || 0;
const semi = { "#": 1, b: -1 }[msharp] || 0;
const midi = SEMITONES[mn.charCodeAt(0) % 7] + (tone + toneOffset) * 12 + semi - this.numberShift;
mnotes.push(this.getNoteByMidi(midi, 0));
}
return m;
});
mnotes[mnotes.length - 1].duration = point ? duration / 2 : duration;
point = false;
notes = notes.concat(mnotes);
}
return m0;
});
// console.log(notes);
this.notes = notes;
}
} | the_stack |
import React from 'react'
import { Dispatch } from 'redux'
import { connect } from 'react-redux'
import {
View,
Text,
Keyboard,
ViewStyle,
TextStyle,
ImageStyle,
SectionList,
SectionListRenderItemInfo,
SectionListData,
ActivityIndicator,
TouchableOpacity,
SafeAreaView
} from 'react-native'
import { NavigationScreenProps, NavigationActions } from 'react-navigation'
import Icon from '@textile/react-native-icon'
import { IContact } from '@textile/react-native-sdk'
import { Contact } from 'react-native-contacts'
import { RootState, RootAction } from '../Redux/Types'
import { contactsActions, contactsSelectors } from '../features/contacts'
import {
SearchResultsSection,
SearchResult,
ContactSearchResult
} from '../features/contacts/models'
import { orderedContacts } from '../features/contacts/selectors'
import Button from '../Components/SmallButton'
import SearchBar from '../Components/SearchBar'
import RowSeparator from '../Components/RowSeparator'
import ListItem from '../Components/ListItem'
import CreateThreadModal from '../Components/CreateThreadModal'
import { Item, TextileHeaderButtons } from '../Components/HeaderButtons'
import Avatar from '../Components/Avatar'
import Checkbox from '../Components/Checkbox'
import { color, textStyle, fontFamily, fontSize, spacing } from '../styles'
import { contact } from '@textile/react-native-sdk/dist/account'
const CONTAINER: ViewStyle = {
flex: 1,
backgroundColor: color.screen_primary
}
const avatarStyle: ImageStyle = {
width: 50,
height: 50,
backgroundColor: color.grey_5
}
const selectingText: TextStyle = {
paddingRight: 15,
fontFamily: fontFamily.medium
}
const newGroupButton: ViewStyle = {
width: '100%',
paddingVertical: spacing._024,
borderTopColor: color.grey_4,
borderTopWidth: 1,
backgroundColor: color.screen_primary
}
const newGroupText: TextStyle = {
textAlign: 'center',
fontFamily: fontFamily.bold,
fontSize: fontSize._18
}
const leftItemsStyle: ViewStyle = {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
}
interface StateProps {
contacts: ReadonlyArray<IContact>
searchResults: SearchResultsSection[]
}
interface NavProps {
openDrawer: () => void
addContact: () => void
clearSearch: () => void
toggleSelect: () => void
selecting: boolean
}
interface DispatchProps {
search: (searchString: string) => void
clearSearch: () => void
addContact: (contact: IContact) => void
inviteContact: (contact: Contact) => void
}
type Props = StateProps & DispatchProps & NavigationScreenProps<NavProps>
// Store the addresses of currently selected contacts (for new group multi-select UI)
interface State {
searchString?: string
selected: ReadonlyArray<string>
showCreateGroupModal: boolean
}
class Contacts extends React.Component<Props, State> {
static navigationOptions = ({
navigation
}: NavigationScreenProps<NavProps>) => {
const openDrawer = navigation.getParam('openDrawer')
const selecting = navigation.getParam('selecting')
const toggleSelect = navigation.getParam('toggleSelect')
const headerLeft = (
<TextileHeaderButtons left={true}>
<Item
title="Account"
onPress={openDrawer}
ButtonElement={
<Avatar style={{ width: 24, height: 24 }} self={true} />
}
buttonWrapperStyle={{ margin: 11 }}
/>
</TextileHeaderButtons>
)
const headerRight = (
<TextileHeaderButtons>
<Item
title="New Group"
onPress={toggleSelect}
ButtonElement={
<Text style={selectingText}>
{selecting ? 'Cancel' : 'New Group'}
</Text>
}
/>
</TextileHeaderButtons>
)
return {
headerTitle: 'Contacts',
headerLeft,
headerRight
}
}
constructor(props: Props) {
super(props)
this.state = {
selected: [],
showCreateGroupModal: false
}
}
componentDidMount() {
this.props.navigation.setParams({
openDrawer: this.openDrawer,
clearSearch: this.props.clearSearch,
toggleSelect: this.toggleSelect,
selecting: false
})
}
contactsSearchResultSection = () => {
const contacts: SearchResult[] = this.props.contacts
.filter(contact => {
if (
this.state.searchString !== undefined &&
this.state.searchString.length > 0
) {
const searchKey = (contact.name || contact.address).toLowerCase()
const index = searchKey.indexOf(
this.state.searchString!.toLowerCase()
)
return index > -1
} else {
return true
}
})
.map(contact => {
const contactResult: ContactSearchResult = {
key: contact.address,
type: 'contact',
data: contact
}
return contactResult
})
return {
key: 'contacts',
title: 'Your Contacts',
data:
contacts.length > 0
? contacts
: [
{
key: 'textile_empty',
type: 'empty'
}
]
}
}
render() {
return (
<SafeAreaView style={CONTAINER}>
<SearchBar
containerStyle={{ backgroundColor: color.grey_5 }}
inputStyle={{
...textStyle.body_m,
color: color.grey_2,
backgroundColor: color.grey_6
}}
additionalInputProps={{
autoCapitalize: 'none',
autoCorrect: false,
spellCheck: false
}}
iconColor={color.grey_4}
onTextChanged={this.updateSearchString}
placeholder="Search or add new contact..."
/>
<SectionList
sections={[
this.contactsSearchResultSection(),
...this.props.searchResults
]}
renderSectionHeader={this.renderSectionHeader}
renderItem={this.renderRow}
ItemSeparatorComponent={RowSeparator}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
/>
{this.props.navigation.getParam('selecting') &&
this.state.selected.length > 0 && (
<TouchableOpacity
onPress={this.openCreateThreadModal}
style={newGroupButton}
>
<Text style={newGroupText}>
Create New Group With {this.state.selected.length}{' '}
{this.state.selected.length > 1 ? 'Contacts' : 'Contact'}
</Text>
</TouchableOpacity>
)}
<CreateThreadModal
isVisible={this.state.showCreateGroupModal}
fullScreen={false}
selectToShare={false}
navigateTo={true}
invites={this.state.selected}
cancel={this.cancelCreateThread}
complete={this.completeCreateThread}
/>
</SafeAreaView>
)
}
renderSectionHeader = ({
section: { key, title }
}: {
section: SectionListData<SearchResultsSection>
}) => {
return (
<Text
key={key}
style={{
...textStyle.header_xs,
paddingTop: spacing._008,
paddingBottom: spacing._008,
paddingLeft: spacing._012,
paddingRight: spacing._012,
color: color.grey_2,
backgroundColor: color.grey_5
}}
>
{title}
</Text>
)
}
renderRow = ({
item,
index,
section
}: SectionListRenderItemInfo<SearchResult>) => {
const selecting = this.props.navigation.getParam('selecting')
switch (item.type) {
case 'loading':
return <ActivityIndicator size="small" style={{ padding: 11 }} />
case 'contact': {
const contact = item.data
return (
<ListItem
title={contact.name || contact.address.substring(0, 10)}
leftItem={<Avatar style={avatarStyle} target={contact.avatar} />}
showDisclosure={true}
selecting={selecting}
selected={this.selected(contact.address)}
onPress={this.onPressTextile(contact)}
onSelect={() => this.toggleSelected(contact.address)}
/>
)
}
case 'textile':
return (
<ListItem
leftItem={
<Avatar style={{ width: 50 }} target={item.data.contact.avatar} />
}
title={item.data.contact.name || item.data.contact.address}
subtitle={item.data.contact.address.substr(
item.data.contact.address.length - 8,
8
)}
rightItems={[
<Button
key="add"
text={item.data.isContact ? 'added' : 'add'}
disabled={item.data.isContact || item.data.adding}
onPress={this.onAdd(item.data.contact)}
/>
]}
onPress={this.onPressTextile(item.data.contact)}
showDisclosure={true}
/>
)
case 'addressBook':
return (
<ListItem
title={`${item.data.givenName} ${item.data.familyName}`.trim()}
rightItems={[
<Button
key="invite"
text="invite"
onPress={this.onPressAddressBook(item.data)}
/>
]}
onPress={this.onPressAddressBook(item.data)}
/>
)
case 'empty':
return <ListItem title="No results" />
case 'error':
return <ListItem title="Error" subtitle={item.data} />
}
}
updateSearchString = (string?: string) => {
this.setState({
searchString: string
})
if (string !== undefined && string.length > 0) {
this.props.search(string)
} else {
this.props.clearSearch()
}
}
onPressTextile = (contactInfo: IContact) => {
return () => {
this.props.navigation.navigate('Contact', { contact: contactInfo })
}
}
onPressAddressBook = (contact: Contact) => {
return () => {
this.props.inviteContact(contact)
}
}
onAdd = (contact: IContact) => {
return () => this.props.addContact(contact)
}
openDrawer = () => {
this.props.navigation.openDrawer()
Keyboard.dismiss()
}
// Toggles whether the select UI is active
toggleSelect = () => {
// If we're canceling the multi-select action, reset the array of selected contacts to empty
if (this.props.navigation.getParam('selecting')) {
this.setState({
selected: []
})
}
this.props.navigation.setParams({
selecting: !this.props.navigation.getParam('selecting')
})
}
// Check whether a contact is currently selected
selected = (address: string) => {
return this.state.selected.indexOf(address) > -1
}
// Toggles whether a contact is selected
toggleSelected = (address: string) => {
this.setState((state, props) => {
return {
selected: this.selected(address)
? state.selected.filter(add => add !== address)
: [...state.selected, address]
}
})
}
openCreateThreadModal = () => {
this.setState({
showCreateGroupModal: true
})
}
cancelCreateThread = () => {
this.setState({
showCreateGroupModal: false
})
}
completeCreateThread = () => {
this.props.navigation.setParams({
selecting: false
})
this.setState({
showCreateGroupModal: false,
selected: []
})
}
}
const mapStateToProps = (state: RootState): StateProps => {
return {
contacts: orderedContacts(state.contacts),
searchResults: contactsSelectors.searchResults(state.contacts)
}
}
const mapDispatchToProps = (dispatch: Dispatch<RootAction>): DispatchProps => {
return {
search: (searchString: string) =>
dispatch(contactsActions.searchRequest(searchString)),
clearSearch: () => dispatch(contactsActions.clearSearch()),
addContact: (contact: IContact) =>
dispatch(contactsActions.addContactRequest(contact)),
inviteContact: (contact: Contact) =>
dispatch(contactsActions.authorInviteRequest(contact))
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Contacts) | the_stack |
import * as assert from "@esfx/internal-assert";
import { Equaler } from "@esfx/equatable";
import { HashSet } from "@esfx/collections-hashset";
import { HashMap } from "@esfx/collections-hashmap";
import { HierarchyIterable } from '@esfx/iter-hierarchy';
import { identity, isDefined } from '@esfx/fn';
import { toHashSet, toArray } from './scalars';
import { flowHierarchy } from './internal/utils';
class AppendIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _value: T;
constructor(source: Iterable<T>, value: T) {
this._source = source;
this._value = value;
}
*[Symbol.iterator](): Iterator<T> {
yield* this._source;
yield this._value;
}
}
/**
* Creates an `Iterable` for the elements of `source` with the provided `value` appended to the
* end.
*
* @param source The `Iterable` to append to.
* @param value The value to append.
* @category Subquery
*/
export function append<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, value: T): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the elements of `source` with the provided `value` appended to the
* end.
*
* @param source The `Iterable` to append to.
* @param value The value to append.
* @category Subquery
*/
export function append<T>(source: Iterable<T>, value: T): Iterable<T>;
export function append<T>(source: Iterable<T>, value: T): Iterable<T> {
assert.mustBeIterableObject(source, "source");
return flowHierarchy(new AppendIterable(source, value), source);
}
class PrependIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _value: T;
constructor(value: T, source: Iterable<T>) {
this._value = value;
this._source = source;
}
*[Symbol.iterator](): Iterator<T> {
yield this._value;
yield* this._source;
}
}
/**
* Creates a subquery for the elements of the source with the provided value prepended to the beginning.
*
* @param value The value to prepend.
* @category Subquery
*/
export function prepend<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, value: T): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the elements of the source with the provided value prepended to the beginning.
*
* @param value The value to prepend.
* @category Subquery
*/
export function prepend<T>(source: Iterable<T>, value: T): Iterable<T>;
export function prepend<T>(source: Iterable<T>, value: T): Iterable<T> {
assert.mustBeIterableObject(source, "source");
return flowHierarchy(new PrependIterable(value, source), source);
}
class ConcatIterable<T> implements Iterable<T> {
private _left: Iterable<T>;
private _right: Iterable<T>;
constructor(left: Iterable<T>, right: Iterable<T>) {
this._left = left;
this._right = right;
}
*[Symbol.iterator](): Iterator<T> {
yield* this._left;
yield* this._right;
}
}
/**
* Creates an `Iterable` that concatenates two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @category Subquery
*/
export function concat<TNode, T extends TNode>(left: HierarchyIterable<TNode, T>, right: Iterable<T>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` that concatenates two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @category Subquery
*/
export function concat<TNode, T extends TNode>(left: Iterable<T>, right: HierarchyIterable<TNode, T>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` that concatenates two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @category Subquery
*/
export function concat<T>(left: Iterable<T>, right: Iterable<T>): Iterable<T>;
export function concat<T>(left: Iterable<T>, right: Iterable<T>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
return flowHierarchy(new ConcatIterable(left, right), left, right);
}
class FilterByIterable<T, K> implements Iterable<T> {
private _source: Iterable<T>;
private _keySelector: (element: T) => K;
private _predicate: (key: K, offset: number) => boolean;
private _invert: boolean;
constructor(source: Iterable<T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean, invert: boolean) {
this._source = source;
this._keySelector = keySelector;
this._predicate = predicate;
this._invert = invert;
}
*[Symbol.iterator](): Iterator<T> {
const keySelector = this._keySelector;
const predicate = this._predicate;
const inverted = this._invert;
let offset = 0;
for (const element of this._source) {
let result = predicate(keySelector(element), offset++);
if (inverted) result = !result;
if (result) {
yield element;
}
}
}
}
/**
* Creates an `Iterable` where the selected key for each element matches the supplied predicate.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param predicate A callback used to match each key.
* @category Subquery
*/
export function filterBy<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` where the selected key for each element matches the supplied predicate.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param predicate A callback used to match each key.
* @category Subquery
*/
export function filterBy<T, K>(source: Iterable<T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): Iterable<T>;
export function filterBy<T, K>(source: Iterable<T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeFunction(predicate, "predicate");
return flowHierarchy(new FilterByIterable(source, keySelector, predicate, /*invert*/ false), source);
}
export { filterBy as whereBy };
/**
* Creates an `Iterable` whose elements match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filter<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => element is U): HierarchyIterable<TNode, U>;
/**
* Creates an `Iterable` whose elements match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filter<T, U extends T>(source: Iterable<T>, predicate: (element: T, offset: number) => element is U): Iterable<U>;
/**
* Creates an `Iterable` whose elements match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filter<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` whose elements match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filter<T>(source: Iterable<T>, predicate: (element: T, offset: number) => boolean): Iterable<T>;
export function filter<T>(source: Iterable<T>, predicate: (element: T, offset: number) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(predicate, "predicate");
return filterBy(source, identity, predicate);
}
export { filter as where };
/**
* Creates an `Iterable` whose elements are neither `null` nor `undefined`.
*
* @param source An `Iterable` object.
* @category Subquery
*/
export function filterDefined<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyIterable<TNode, NonNullable<T>>;
/**
* Creates an `Iterable` whose elements are neither `null` nor `undefined`.
*
* @param source An `Iterable` object.
* @category Subquery
*/
export function filterDefined<T>(source: Iterable<T>): Iterable<NonNullable<T>>;
export function filterDefined<T>(source: Iterable<T>): Iterable<NonNullable<T>> {
return filterBy(source, identity, isDefined) as Iterable<NonNullable<T>>;
}
export { filterDefined as whereDefined };
/**
* Creates an `Iterable` where the selected key for each element is neither `null` nor `undefined`.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @category Subquery
*/
export function filterDefinedBy<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (value: T) => K): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` where the selected key for each element is neither `null` nor `undefined`.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @category Subquery
*/
export function filterDefinedBy<T, K>(source: Iterable<T>, keySelector: (value: T) => K): Iterable<T>;
export function filterDefinedBy<T, K>(source: Iterable<T>, keySelector: (value: T) => K): Iterable<T> {
return filterBy(source, keySelector, isDefined);
}
export { filterDefinedBy as whereDefinedBy };
/**
* Creates an `Iterable` where the selected key for each element does not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param predicate A callback used to match each key.
* @category Subquery
*/
export function filterNotBy<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` where the selected key for each element does not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param predicate A callback used to match each key.
* @category Subquery
*/
export function filterNotBy<T, K>(source: Iterable<T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): Iterable<T>;
export function filterNotBy<T, K>(source: Iterable<T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeFunction(predicate, "predicate");
return flowHierarchy(new FilterByIterable(source, keySelector, predicate, /*invert*/ true), source);
}
export { filterNotBy as whereNotBy };
/**
* Creates an `Iterable` whose elements do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filterNot<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => element is U): HierarchyIterable<TNode, U>;
/**
* Creates an `Iterable` whose elements do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filterNot<T, U extends T>(source: Iterable<T>, predicate: (element: T, offset: number) => element is U): Iterable<U>;
/**
* Creates an `Iterable` whose elements do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filterNot<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` whose elements do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function filterNot<T>(source: Iterable<T>, predicate: (element: T, offset: number) => boolean): Iterable<T>;
export function filterNot<T>(source: Iterable<T>, predicate: (element: T, offset: number) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(predicate, "predicate");
return filterNotBy(source, identity, predicate);
}
export { filterNot as whereNot };
/**
* Creates an `Iterable` where the selected key for each element is either `null` or `undefined`.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @category Subquery
*/
export function filterNotDefinedBy<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (value: T) => K): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` where the selected key for each element is either `null` or `undefined`.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @category Subquery
*/
export function filterNotDefinedBy<T, K>(source: Iterable<T>, keySelector: (value: T) => K): Iterable<T>;
export function filterNotDefinedBy<T, K>(source: Iterable<T>, keySelector: (value: T) => K): Iterable<T> {
return filterNotBy(source, keySelector, isDefined);
}
export { filterNotDefinedBy as whereNotDefinedBy };
class MapIterable<T, U> implements Iterable<U> {
private _source: Iterable<T>;
private _selector: (element: T, offset: number) => U;
constructor(source: Iterable<T>, selector: (element: T, offset: number) => U) {
this._source = source;
this._selector = selector;
}
*[Symbol.iterator](): Iterator<U> {
const selector = this._selector;
let offset = 0;
for (const element of this._source) {
yield selector(element, offset++);
}
}
}
/**
* Creates an `Iterable` by applying a callback to each element of a `Iterable`.
*
* @param source An `Iterable` object.
* @param selector A callback used to map each element.
* @category Subquery
*/
export function map<T, U>(source: Iterable<T>, selector: (element: T, offset: number) => U): Iterable<U> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(selector, "selector");
return new MapIterable(source, selector);
}
export { map as select };
class FlatMapIterable<T, U, R> implements Iterable<U | R> {
private _source: Iterable<T>;
private _projection: (element: T) => Iterable<U>;
private _resultSelector?: (element: T, innerElement: U) => R;
constructor(source: Iterable<T>, projection: (element: T) => Iterable<U>, resultSelector?: (element: T, innerElement: U) => R) {
this._source = source;
this._projection = projection;
this._resultSelector = resultSelector;
}
*[Symbol.iterator](): Iterator<U | R> {
const projection = this._projection;
const resultSelector = this._resultSelector;
for (const element of this._source) {
const inner = projection(element);
if (resultSelector) {
for (const innerElement of inner) {
yield resultSelector(element, innerElement);
}
}
else {
yield* inner;
}
}
}
}
/**
* Creates an `Iterable` that iterates the results of applying a callback to each element of `source`.
*
* @param source An `Iterable` object.
* @param projection A callback used to map each element into an iterable.
* @category Subquery
*/
export function flatMap<T, U>(source: Iterable<T>, projection: (element: T) => Iterable<U>): Iterable<U>;
/**
* Creates an `Iterable` that iterates the results of applying a callback to each element of `source`.
*
* @param source An `Iterable` object.
* @param projection A callback used to map each element into an iterable.
* @param resultSelector A callback used to map an element and one of its projected values into a result.
* @category Subquery
*/
export function flatMap<T, U, R>(source: Iterable<T>, projection: (element: T) => Iterable<U>, resultSelector: (element: T, innerElement: U) => R): Iterable<R>;
export function flatMap<T, U, R>(source: Iterable<T>, projection: (element: T) => Iterable<U>, resultSelector?: (element: T, innerElement: U) => R): Iterable<U | R> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(projection, "projection");
assert.mustBeFunctionOrUndefined(resultSelector, "resultSelector");
return new FlatMapIterable(source, projection, resultSelector);
}
export { flatMap as selectMany };
class DropIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _count: number;
constructor(source: Iterable<T>, count: number) {
this._source = source;
this._count = count;
}
*[Symbol.iterator](): Iterator<T> {
let remaining = this._count;
if (remaining <= 0) {
yield* this._source;
}
else {
for (const element of this._source) {
if (remaining > 0) {
remaining--;
}
else {
yield element;
}
}
}
}
}
/**
* Creates a subquery containing all elements except the first elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to skip.
* @category Subquery
*/
export function drop<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, count: number): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing all elements except the first elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to skip.
* @category Subquery
*/
export function drop<T>(source: Iterable<T>, count: number): Iterable<T>;
export function drop<T>(source: Iterable<T>, count: number): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBePositiveFiniteNumber(count, "count");
return flowHierarchy(new DropIterable(source, count), source);
}
export { drop as skip };
class DropRightIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _count: number;
constructor(source: Iterable<T>, count: number) {
this._source = source;
this._count = count;
}
*[Symbol.iterator](): Iterator<T> {
const pending: T[] = [];
const count = this._count;
if (count <= 0) {
yield* this._source;
}
else {
for (const element of this._source) {
pending.push(element);
if (pending.length > count) {
yield pending.shift()!;
}
}
}
}
}
/**
* Creates a subquery containing all elements except the last elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to skip.
* @category Subquery
*/
export function dropRight<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, count: number): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing all elements except the last elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to skip.
* @category Subquery
*/
export function dropRight<T>(source: Iterable<T>, count: number): Iterable<T>;
export function dropRight<T>(source: Iterable<T>, count: number): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBePositiveFiniteNumber(count, "count");
return flowHierarchy(new DropRightIterable(source, count), source);
}
export { dropRight as skipRight };
class DropWhileIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _predicate: (element: T) => boolean;
private _invert: boolean;
constructor(source: Iterable<T>, predicate: (element: T) => boolean, invert: boolean) {
this._source = source;
this._predicate = predicate;
this._invert = invert;
}
*[Symbol.iterator](): Iterator<T> {
const predicate = this._predicate;
const inverted = this._invert;
let skipping = true;
for (const element of this._source) {
if (skipping) {
let result = predicate(element);
if (inverted) result = !result;
skipping = !!result;
}
if (!skipping) {
yield element;
}
}
}
}
/**
* Creates a subquery containing all elements except the first elements that match
* the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function dropWhile<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing all elements except the first elements that match
* the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function dropWhile<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T>;
export function dropWhile<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(predicate, "predicate");
return flowHierarchy(new DropWhileIterable(source, predicate, /*invert*/ false), source);
}
export { dropWhile as skipWhile };
/**
* Creates a subquery containing all elements except the first elements that do not match
* the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function dropUntil<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing all elements except the first elements that do not match
* the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function dropUntil<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T>;
export function dropUntil<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(predicate, "predicate");
return flowHierarchy(new DropWhileIterable(source, predicate, /*invert*/ true), source);
}
export { dropUntil as skipUntil };
class TakeIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _count: number;
constructor(source: Iterable<T>, count: number) {
this._source = source;
this._count = count;
}
*[Symbol.iterator](): Iterator<T> {
let remaining = this._count;
if (remaining > 0) {
for (const element of this._source) {
yield element;
if (--remaining <= 0) {
break;
}
}
}
}
}
/**
* Creates a subquery containing the first elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to take.
* @category Subquery
*/
export function take<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, count: number): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing the first elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to take.
* @category Subquery
*/
export function take<T>(source: Iterable<T>, count: number): Iterable<T>;
export function take<T>(source: Iterable<T>, count: number): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBePositiveFiniteNumber(count, "count");
return flowHierarchy(new TakeIterable(source, count), source);
}
class TakeRightIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _count: number;
constructor(source: Iterable<T>, count: number) {
this._source = source;
this._count = count;
}
*[Symbol.iterator](): Iterator<T> {
const count = this._count;
if (count <= 0) {
return;
}
else {
const pending: T[] = [];
for (const element of this._source) {
pending.push(element);
if (pending.length > count) {
pending.shift();
}
}
yield* pending;
}
}
}
/**
* Creates a subquery containing the last elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to take.
* @category Subquery
*/
export function takeRight<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, count: number): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing the last elements up to the supplied
* count.
*
* @param source An `Iterable` object.
* @param count The number of elements to take.
* @category Subquery
*/
export function takeRight<T>(source: Iterable<T>, count: number): Iterable<T>;
export function takeRight<T>(source: Iterable<T>, count: number): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBePositiveFiniteNumber(count, "count");
return flowHierarchy(new TakeRightIterable(source, count), source);
}
class TakeWhileIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _predicate: (element: T) => boolean;
private _invert: boolean;
constructor(source: Iterable<T>, predicate: (element: T) => boolean, invert: boolean) {
this._source = source;
this._predicate = predicate;
this._invert = invert;
}
*[Symbol.iterator](): Iterator<T> {
const predicate = this._predicate;
const inverted = this._invert;
for (const element of this._source) {
let result = predicate(element);
if (inverted) result = !result;
if (!result) {
break;
}
yield element;
}
}
}
/**
* Creates a subquery containing the first elements that match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeWhile<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => element is U): HierarchyIterable<TNode, U>;
/**
* Creates a subquery containing the first elements that match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeWhile<T, U extends T>(source: Iterable<T>, predicate: (element: T) => element is U): Iterable<U>;
/**
* Creates a subquery containing the first elements that match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeWhile<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing the first elements that match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeWhile<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T>;
export function takeWhile<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(predicate, "predicate");
return flowHierarchy(new TakeWhileIterable(source, predicate, /*invert*/ false), source);
}
/**
* Creates a subquery containing the first elements that do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeUntil<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => element is U): HierarchyIterable<TNode, U>;
/**
* Creates a subquery containing the first elements that do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeUntil<T, U extends T>(source: Iterable<T>, predicate: (element: T) => element is U): Iterable<U>;
/**
* Creates a subquery containing the first elements that do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeUntil<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => boolean): HierarchyIterable<TNode, T>;
/**
* Creates a subquery containing the first elements that do not match the supplied predicate.
*
* @param source An `Iterable` object.
* @param predicate A callback used to match each element.
* @category Subquery
*/
export function takeUntil<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T>;
export function takeUntil<T>(source: Iterable<T>, predicate: (element: T) => boolean): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(predicate, "predicate");
return flowHierarchy(new TakeWhileIterable(source, predicate, /*invert*/ true), source);
}
class IntersectByIterable<T, K> implements Iterable<T> {
private _left: Iterable<T>;
private _right: Iterable<T>;
private _keySelector: (element: T) => K;
private _keyEqualer?: Equaler<K>;
constructor(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) {
this._left = left;
this._right = right;
this._keySelector = keySelector;
this._keyEqualer = keyEqualer;
}
*[Symbol.iterator](): Iterator<T> {
const keySelector = this._keySelector;
const set = toHashSet(this._right, keySelector, this._keyEqualer);
if (set.size <= 0) {
return;
}
for (const element of this._left) {
if (set.delete(keySelector(element))) {
yield element;
}
}
}
}
/**
* Creates an `Iterable` for the set intersection of two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function intersectBy<TNode, T extends TNode, K>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the set intersection of two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function intersectBy<TNode, T extends TNode, K>(left: Iterable<T>, right: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the set intersection of two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function intersectBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T>;
export function intersectBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer");
return flowHierarchy(new IntersectByIterable(left, right, keySelector), left, right);
}
/**
* Creates an `Iterable` for the set intersection of two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function intersect<TNode, T extends TNode>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the set intersection of two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function intersect<TNode, T extends TNode>(left: Iterable<T>, right: HierarchyIterable<TNode, T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the set intersection of two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function intersect<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T>;
export function intersect<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler");
return intersectBy(left, right, identity, equaler);
}
class UnionByIterable<T, K> implements Iterable<T> {
private _left: Iterable<T>;
private _right: Iterable<T>;
private _keySelector: (element: T) => K;
private _keyEqualer?: Equaler<K>;
constructor(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) {
this._left = left;
this._right = right;
this._keySelector = keySelector;
this._keyEqualer = keyEqualer;
}
*[Symbol.iterator](): Iterator<T> {
const keySelector = this._keySelector;
const set = new HashSet<K>(this._keyEqualer);
for (const element of this._left) {
if (set.tryAdd(keySelector(element))) {
yield element;
}
}
for (const element of this._right) {
if (set.tryAdd(keySelector(element))) {
yield element;
}
}
}
}
/**
* Creates a subquery for the set union of two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left A `Iterable` value.
* @param right A `Iterable` value.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function unionBy<TNode, T extends TNode, K>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the set union of two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left A `Iterable` value.
* @param right A `Iterable` value.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function unionBy<TNode, T extends TNode, K>(left: Iterable<T>, right: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the set union of two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left A `Iterable` value.
* @param right A `Iterable` value.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function unionBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T>;
export function unionBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer");
return flowHierarchy(new UnionByIterable(left, right, keySelector, keyEqualer), left, right);
}
/**
* Creates a subquery for the set union of two `Iterable` objects.
*
* @param left A `Iterable` value.
* @param right A `Iterable` value.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function union<TNode, T extends TNode>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the set union of two `Iterable` objects.
*
* @param left A `Iterable` value.
* @param right A `Iterable` value.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function union<TNode, T extends TNode>(left: Iterable<T>, right: HierarchyIterable<TNode, T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the set union of two `Iterable` objects.
*
* @param left A `Iterable` value.
* @param right A `Iterable` value.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function union<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T>;
export function union<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler");
return unionBy(left, right, identity, equaler);
}
class ExceptByIterable<T, K> implements Iterable<T> {
private _left: Iterable<T>;
private _right: Iterable<T>;
private _keySelector: (element: T) => K;
private _keyEqualer?: Equaler<K>;
constructor(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) {
this._left = left;
this._right = right;
this._keySelector = keySelector;
this._keyEqualer = keyEqualer;
}
*[Symbol.iterator](): Iterator<T> {
const keySelector = this._keySelector;
const set = toHashSet(this._right, keySelector, this._keyEqualer!);
for (const element of this._left) {
if (set.tryAdd(keySelector(element))) {
yield element;
}
}
}
}
/**
* Creates an `Iterable` for the set difference between two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function exceptBy<TNode, T extends TNode, K>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the set difference between two `Iterable` objects, where set identity is determined by the selected key.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function exceptBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T>;
export function exceptBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer");
return flowHierarchy(new ExceptByIterable(left, right, keySelector, keyEqualer), left);
}
export { exceptBy as relativeComplementBy };
/**
* Creates an `Iterable` for the set difference between two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function except<TNode, T extends TNode>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the set difference between two `Iterable` objects.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function except<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T>;
export function except<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler");
return exceptBy(left, right, identity, equaler);
}
export { except as relativeComplement };
class DistinctByIterable<T, K> implements Iterable<T> {
private _source: Iterable<T>;
private _keySelector: (value: T) => K;
private _keyEqualer?: Equaler<K>;
constructor(source: Iterable<T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>) {
this._source = source;
this._keySelector = keySelector;
this._keyEqualer = keyEqualer;
}
*[Symbol.iterator](): Iterator<T> {
const set = this._keyEqualer ? new HashSet<K>(this._keyEqualer) : new Set<K>();
const keySelector = this._keySelector;
for (const element of this._source) {
const key = keySelector(element);
if (!set.has(key)) {
set.add(key);
yield element;
}
}
}
}
/**
* Creates an `Iterable` with every instance of the specified value removed.
*
* @param source An `Iterable` object.
* @param values The values to exclude.
* @category Subquery
*/
export function exclude<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, ...values: T[]): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` with every instance of the specified value removed.
*
* @param source An `Iterable` object.
* @param values The values to exclude.
* @category Subquery
*/
export function exclude<T>(source: Iterable<T>, ...values: T[]): Iterable<T>;
export function exclude<T>(source: Iterable<T>, ...values: T[]): Iterable<T> {
assert.mustBeIterableObject(source, "left");
return exceptBy(source, values, identity);
}
/**
* Creates an `Iterable` for the distinct elements of `source`.
* @category Subquery
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key to determine uniqueness.
* @param keyEqualer An `Equaler` object used to compare key equality.
*/
export function distinctBy<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the distinct elements of `source`.
* @category Subquery
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key to determine uniqueness.
* @param keyEqualer An `Equaler` object used to compare key equality.
*/
export function distinctBy<T, K>(source: Iterable<T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>): Iterable<T>;
export function distinctBy<T, K>(source: Iterable<T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer");
return flowHierarchy(new DistinctByIterable(source, keySelector, keyEqualer), source);
}
/**
* Creates an `Iterable` for the distinct elements of `source`.
* @category Subquery
*
* @param source An `Iterable` object.
* @param equaler An `Equaler` object used to compare element equality.
*/
export function distinct<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the distinct elements of `source`.
* @category Subquery
*
* @param source An `Iterable` object.
* @param equaler An `Equaler` object used to compare element equality.
*/
export function distinct<T>(source: Iterable<T>, equaler?: Equaler<T>): Iterable<T>;
export function distinct<T>(source: Iterable<T>, equaler?: Equaler<T>): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler");
return distinctBy(source, identity, equaler);
}
class DefaultIfEmptyIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _defaultValue: T;
constructor(source: Iterable<T>, defaultValue: T) {
this._source = source;
this._defaultValue = defaultValue;
}
*[Symbol.iterator](): Iterator<T> {
const source = this._source;
const defaultValue = this._defaultValue;
let hasElements = false;
for (const value of source) {
hasElements = true;
yield value;
}
if (!hasElements) {
yield defaultValue;
}
}
}
/**
* Creates an `Iterable` that contains the provided default value if `source`
* contains no elements.
*
* @param source An `Iterable` object.
* @param defaultValue The default value.
* @category Subquery
*/
export function defaultIfEmpty<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, defaultValue: T): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` that contains the provided default value if `source`
* contains no elements.
*
* @param source An `Iterable` object.
* @param defaultValue The default value.
* @category Subquery
*/
export function defaultIfEmpty<T>(source: Iterable<T>, defaultValue: T): Iterable<T>;
export function defaultIfEmpty<T>(source: Iterable<T>, defaultValue: T): Iterable<T> {
assert.mustBeIterableObject(source, "source");
return flowHierarchy(new DefaultIfEmptyIterable(source, defaultValue), source);
}
class PatchIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _start: number;
private _skipCount: number;
private _range: Iterable<T> | undefined;
constructor(source: Iterable<T>, start: number, skipCount: number, range: Iterable<T> | undefined) {
this._source = source;
this._start = start;
this._skipCount = skipCount;
this._range = range;
}
*[Symbol.iterator](): Iterator<T> {
const start = this._start;
const skipCount = this._skipCount;
let offset = 0;
let hasYieldedRange = false;
for (const value of this._source) {
if (offset < start) {
yield value;
offset++;
}
else if (offset < start + skipCount) {
offset++;
}
else {
if (!hasYieldedRange && this._range) {
yield* this._range;
hasYieldedRange = true;
}
yield value;
}
}
if (!hasYieldedRange && this._range) {
yield* this._range;
}
}
}
/**
* Creates an `Iterable` for the elements of `source` with the provided range
* patched into the results.
*
* @param source The `Iterable` to patch.
* @param start The offset at which to patch the range.
* @param skipCount The number of elements to skip from start.
* @param range The range to patch into the result.
* @category Subquery
*/
export function patch<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, start: number, skipCount?: number, range?: Iterable<T>): HierarchyIterable<TNode, T>;
/**
* Creates an `Iterable` for the elements of `source` with the provided range
* patched into the results.
*
* @param source The `Iterable` to patch.
* @param start The offset at which to patch the range.
* @param skipCount The number of elements to skip from start.
* @param range The range to patch into the result.
* @category Subquery
*/
export function patch<T>(source: Iterable<T>, start: number, skipCount?: number, range?: Iterable<T>): Iterable<T>;
export function patch<T>(source: Iterable<T>, start: number, skipCount?: number, range?: Iterable<T>): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBePositiveFiniteNumber(start, "start");
assert.mustBePositiveFiniteNumber(skipCount, "skipCount");
assert.mustBeIterableObjectOrUndefined(range, "range");
return flowHierarchy(new PatchIterable(source, start, skipCount, range), source);
}
class ScanIterable<T, U> implements Iterable<T | U> {
private _source: Iterable<T>;
private _accumulator: (current: T | U, element: T, offset: number) => T | U;
private _isSeeded: boolean;
private _seed: T | U | undefined;
constructor(source: Iterable<T>, accumulator: (current: T | U, element: T, offset: number) => T | U, isSeeded: boolean, seed: T | U | undefined) {
this._source = source;
this._accumulator = accumulator;
this._isSeeded = isSeeded;
this._seed = seed;
}
*[Symbol.iterator](): Iterator<T | U> {
const accumulator = this._accumulator;
let hasCurrent = this._isSeeded;
let current = this._seed;
let offset = 0;
for (const value of this._source) {
if (!hasCurrent) {
current = value;
hasCurrent = true;
}
else {
current = accumulator(current!, value, offset);
yield current;
}
offset++;
}
}
}
/**
* Creates a subquery containing the cumulative results of applying the provided callback to each element.
*
* @param source An `Iterable` object.
* @param accumulator The callback used to compute each result.
* @category Subquery
*/
export function scan<T>(source: Iterable<T>, accumulator: (current: T, element: T, offset: number) => T): Iterable<T>;
/**
* Creates a subquery containing the cumulative results of applying the provided callback to each element.
*
* @param source An `Iterable` object.
* @param accumulator The callback used to compute each result.
* @param seed An optional seed value.
* @category Subquery
*/
export function scan<T, U>(source: Iterable<T>, accumulator: (current: U, element: T, offset: number) => U, seed: U): Iterable<U>;
export function scan<T, U>(source: Iterable<T>, accumulator: (current: T | U, element: T, offset: number) => T | U, seed?: T | U): Iterable<T | U> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(accumulator, "accumulator");
return new ScanIterable<T, U>(source, accumulator, arguments.length > 2, seed!);
}
class ScanRightIterable<T, U> implements Iterable<T | U> {
private _source: Iterable<T>;
private _accumulator: (current: T | U, element: T, offset: number) => T | U;
private _isSeeded: boolean;
private _seed: T | U | undefined;
constructor(source: Iterable<T>, accumulator: (current: T | U, element: T, offset: number) => T | U, isSeeded: boolean, seed: T | U | undefined) {
this._source = source;
this._accumulator = accumulator;
this._isSeeded = isSeeded;
this._seed = seed;
}
*[Symbol.iterator](): Iterator<T | U> {
const source = toArray(this._source);
const accumulator = this._accumulator;
let hasCurrent = this._isSeeded;
let current = this._seed;
for (let offset = source.length - 1; offset >= 0; offset--) {
const value = source[offset];
if (!hasCurrent) {
current = value;
hasCurrent = true;
continue;
}
current = accumulator(current!, value, offset);
yield current;
}
}
}
/**
* Creates a subquery containing the cumulative results of applying the provided callback to each element in reverse.
*
* @param source An `Iterable` object.
* @param accumulator The callback used to compute each result.
* @category Subquery
*/
export function scanRight<T>(source: Iterable<T>, accumulator: (current: T, element: T, offset: number) => T): Iterable<T>;
/**
* Creates a subquery containing the cumulative results of applying the provided callback to each element in reverse.
*
* @param source An `Iterable` object.
* @param accumulator The callback used to compute each result.
* @param seed An optional seed value.
* @category Subquery
*/
export function scanRight<T, U>(source: Iterable<T>, accumulator: (current: U, element: T, offset: number) => U, seed: U): Iterable<U>;
export function scanRight<T, U>(source: Iterable<T>, accumulator: (current: T | U, element: T, offset: number) => T | U, seed?: T | U): Iterable<T | U> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(accumulator, "accumulator");
return new ScanRightIterable<T, U>(source, accumulator, arguments.length > 2, seed);
}
class SymmetricDifferenceByIterable<T, K> implements Iterable<T> {
private _left: Iterable<T>;
private _right: Iterable<T>;
private _keySelector: (element: T) => K;
private _keyEqualer?: Equaler<K>;
constructor(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) {
this._left = left;
this._right = right;
this._keySelector = keySelector;
this._keyEqualer = keyEqualer;
}
*[Symbol.iterator](): Iterator<T> {
const keySelector = this._keySelector;
const rightKeys = new HashSet<K>(this._keyEqualer);
const right = new HashMap<K, T>(this._keyEqualer);
for (const element of this._right) {
const key = keySelector(element);
if (rightKeys.tryAdd(key)) {
right.set(key, element);
}
}
const set = new HashSet<K>(this._keyEqualer);
for (const element of this._left) {
const key = keySelector(element);
if (set.tryAdd(key) && !right.has(key)) {
yield element;
}
}
for (const [key, element] of right) {
if (set.tryAdd(key)) {
yield element;
}
}
}
}
/**
* Creates a subquery for the symmetric difference between two `Iterable` objects, where set identity is determined by the selected key.
* The result is an `Iterable` containings the elements that exist in only left or right, but not
* in both.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function symmetricDifferenceBy<TNode, T extends TNode, K>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the symmetric difference between two `Iterable` objects, where set identity is determined by the selected key.
* The result is an `Iterable` containings the elements that exist in only left or right, but not
* in both.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function symmetricDifferenceBy<TNode, T extends TNode, K>(left: Iterable<T>, right: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the symmetric difference between two `Iterable` objects, where set identity is determined by the selected key.
* The result is an `Iterable` containings the elements that exist in only left or right, but not
* in both.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param keySelector A callback used to select the key for each element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function symmetricDifferenceBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T>;
export function symmetricDifferenceBy<T, K>(left: Iterable<T>, right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer");
return flowHierarchy(new SymmetricDifferenceByIterable(left, right, keySelector, keyEqualer), left, right);
}
/**
* Creates a subquery for the symmetric difference between two `Iterable` objects.
* The result is an `Iterable` containings the elements that exist in only left or right, but not
* in both.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function symmetricDifference<TNode, T extends TNode>(left: HierarchyIterable<TNode, T>, right: Iterable<T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the symmetric difference between two `Iterable` objects.
* The result is an `Iterable` containings the elements that exist in only left or right, but not
* in both.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function symmetricDifference<TNode, T extends TNode>(left: Iterable<T>, right: HierarchyIterable<TNode, T>, equaler?: Equaler<T>): HierarchyIterable<TNode, T>;
/**
* Creates a subquery for the symmetric difference between two `Iterable` objects.
* The result is an `Iterable` containings the elements that exist in only left or right, but not
* in both.
*
* @param left An `Iterable` object.
* @param right An `Iterable` object.
* @param equaler An `Equaler` object used to compare equality.
* @category Subquery
*/
export function symmetricDifference<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T>;
export function symmetricDifference<T>(left: Iterable<T>, right: Iterable<T>, equaler?: Equaler<T>): Iterable<T> {
assert.mustBeIterableObject(left, "left");
assert.mustBeIterableObject(right, "right");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler");
return symmetricDifferenceBy(left, right, identity, equaler);
}
class TapIterable<T> implements Iterable<T> {
private _source: Iterable<T>;
private _callback: (element: T, offset: number) => void;
constructor(source: Iterable<T>, callback: (element: T, offset: number) => void) {
this._source = source;
this._callback = callback;
}
*[Symbol.iterator](): Iterator<T> {
const source = this._source;
const callback = this._callback;
let offset = 0;
for (const element of source) {
callback(element, offset++);
yield element;
}
}
}
/**
* Lazily invokes a callback as each element of the iterable is iterated.
*
* @param source A `Iterable` object.
* @param callback The callback to invoke.
* @category Subquery
*/
export function tap<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, callback: (element: T, offset: number) => void): HierarchyIterable<TNode, T>;
/**
* Lazily invokes a callback as each element of the iterable is iterated.
*
* @param source A `Iterable` object.
* @param callback The callback to invoke.
* @category Subquery
*/
export function tap<T>(source: Iterable<T>, callback: (element: T, offset: number) => void): Iterable<T>;
export function tap<T>(source: Iterable<T>, callback: (element: T, offset: number) => void): Iterable<T> {
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(callback, "callback");
return flowHierarchy(new TapIterable(source, callback), source);
}
class MaterializeIterable<T> implements Iterable<T> {
private _source: readonly T[];
constructor(source: Iterable<T>) {
this._source = [...source];
}
[Symbol.iterator]() {
return this._source[Symbol.iterator]();
}
}
/**
* Eagerly evaluate the `Iterable`, returning a new `Iterable`.
* @category Subquery
*/
export function materialize<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyIterable<TNode, T>;
export function materialize<T>(source: Iterable<T>): Iterable<T>;
export function materialize<T>(source: Iterable<T>): Iterable<T> {
assert.mustBeIterableObject(source, "source");
return flowHierarchy(new MaterializeIterable(source), source);
} | the_stack |
import React from 'react'
import Wide from '../../src/components/Wide'
import styled from 'styled-components'
import { take } from 'lodash'
enum ChatState {
WaitingToSend,
Sending,
WaitingForResponse
}
interface State {
chatScriptIndex: number
chatState: ChatState
}
export class Chat extends React.Component<{}, State> {
messagesRef: React.RefObject<HTMLDivElement>
constructor(props: {}) {
super(props)
this.messagesRef = React.createRef()
this.state = {
chatScriptIndex: 0,
chatState: ChatState.WaitingToSend
}
}
showLatestMessage = () => {
const { current: messages } = this.messagesRef
if (messages) {
messages.scroll({ top: messages.scrollHeight })
}
}
submitClicked = () => {
if (this.state.chatScriptIndex < chatScript.length) {
this.setState(
{
chatState: ChatState.Sending,
chatScriptIndex: this.state.chatScriptIndex + 1
},
() => {
this.showLatestMessage()
setTimeout(
() =>
this.setState({ chatState: ChatState.WaitingForResponse }, () => {
setTimeout(() => {
this.setState({
chatState: ChatState.WaitingToSend
})
this.showLatestMessage()
}, 100)
}),
1000
)
}
)
}
}
render() {
const { chatState, chatScriptIndex } = this.state
return (
<Wide>
<Wrapper>
<div className="responsive-html5-chat">
<form className="chat" onSubmit={e => e.preventDefault()}>
<span
className={chatState === ChatState.Sending ? 'spinner' : ''}
/>
<div className="messages" ref={this.messagesRef}>
<div className="message">
<div className="ash">
<p>
Hey, want to chat about native iOS "versus" JavaScript?
</p>
</div>
</div>
{take(chatScript, chatScriptIndex).map((s, index) => (
<>
<div key={`reader${index}`} className="message">
<div className="reader">{s.response}</div>
</div>
{(chatState === ChatState.WaitingToSend ||
index < chatScriptIndex - 1) &&
s.message && (
<div key={`ash${index}`} className="message">
<div className="ash">{s.message}</div>
</div>
)}
</>
))}
</div>
<div id="input">
{chatState === ChatState.WaitingToSend && chatScriptIndex < chatScript.length && (
<p>{chatScript[chatScriptIndex].response}</p>
)}
</div>
<input type="submit" value="Send" onClick={this.submitClicked} />
</form>
</div>
</Wrapper>
</Wide>
)
}
}
const appleBlue = '#2668d0'
// TODO: This could be moved into styled-components. Meh.
const Wrapper = styled.div`
width: 100%;
height: 500px;
background-size: 100% 100%;
margin: 0 auto;
position: relative;
/* Make everything animate because animations are cool. */
form.chat * {
transition: all 0.5s;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
form.chat {
margin: 15px 0;
cursor: default;
position: absolute;
display: block;
left: 0;
right: 0;
bottom: 0;
top: 0;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE/Edge */
user-select: none;
.messages {
display: block;
overflow-x: hidden;
overflow-y: scroll;
position: relative;
height: 85%;
width: 100%;
padding: 2% 3%;
border-bottom: 1px solid #ecf0f1;
}
/* Customize the scrollbar to look like Messages.app */
::-webkit-scrollbar {
width: 3px;
height: 1px;
transition: all 0.5s;
z-index: 10;
}
::-webkit-scrollbar-track {
background-color: white;
}
::-webkit-scrollbar-thumb {
background-color: #bec4c8;
border-radius: 3px;
}
/* Basic message formatting. */
.message {
display: block;
width: 98%;
padding: 0.5%;
p {
line-height: 20px;
margin: 0;
padding: 10px 0;
}
}
.reader,
.ash {
word-wrap: break-word;
margin-bottom: 20px;
position: relative;
padding: 0px 15px;
color: white;
border-radius: 25px;
clear: both;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 15px;
max-width: 90%;
}
/* Formatting specific to "my" messages. */
.reader {
background: ${appleBlue};
color: white;
float: right;
clear: both;
border-bottom-right-radius: 20px 0px;
}
.reader:before {
content: '';
position: absolute;
z-index: 1;
bottom: -2px;
right: -8px;
height: 19px;
border-right: 20px solid ${appleBlue};
border-bottom-left-radius: 16px 14px;
-webkit-transform: translate(0, -2px);
transform: translate(0, -2px);
border-bottom-left-radius: 15px 0px;
transform: translate(-1px, -2px);
}
.reader:after {
content: '';
position: absolute;
z-index: 1;
bottom: -2px;
right: -42px;
width: 12px;
height: 20px;
background: white;
border-bottom-left-radius: 10px;
-webkit-transform: translate(-30px, -2px);
transform: translate(-30px, -2px);
}
/* Formatting specific to "their" messages */
.ash {
background: #e5e5ea;
color: black;
float: left;
clear: both;
border-bottom-left-radius: 30px 0px;
}
.ash:before {
content: '';
position: absolute;
z-index: 2;
bottom: -2px;
left: -7px;
height: 19px;
border-left: 20px solid #e5e5ea;
border-bottom-right-radius: 16px 14px;
-webkit-transform: translate(0, -2px);
transform: translate(0, -2px);
border-bottom-right-radius: 15px 0px;
transform: translate(-1px, -2px);
}
.ash:after {
content: '';
position: absolute;
z-index: 3;
bottom: -2px;
left: 4px;
width: 26px;
height: 20px;
background: white;
border-bottom-right-radius: 10px;
-webkit-transform: translate(-30px, -2px);
transform: translate(-30px, -2px);
}
/* Formatting for the input at the bottom. */
#input {
font-size: 15px;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
border: 0;
padding: 0 10px;
height: 15%;
outline: 0;
display: table;
width: calc(100% - 60px);
float: left;
p {
color: black;
display: table-cell;
vertical-align: middle;
line-height: 20px;
margin: 0;
}
}
input[type='submit'] {
font-size: 15px;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
border: 0;
padding: 0 15px;
height: 15%;
outline: 0;
width: 60px;
background: transparent;
color: #0072c6;
font-weight: 700;
text-align: right;
float: right;
}
/* "Spinner" really means "loading indicator" here. */
span.spinner {
-moz-animation: loading-bar 0.5s 1;
-webkit-animation: loading-bar 0.5s 1;
animation: loading-bar 0.5s 1;
display: block;
height: 2px;
background-color: ${appleBlue};
transition: width 0.2s;
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 4;
}
}
/* Loading bar animation */
@-moz-keyframes loading-bar {
0% {
width: 0%;
}
90% {
width: 90%;
}
100% {
width: 100%;
}
}
@-webkit-keyframes loading-bar {
0% {
width: 0%;
}
90% {
width: 90%;
}
100% {
width: 100%;
}
}
@keyframes loading-bar {
0% {
width: 0%;
}
90% {
width: 90%;
}
100% {
width: 100%;
}
}
`
interface ChatScript {
response: JSX.Element
message: JSX.Element
}
const chatScript = [
{
response: <p>Yeah. What exactly makes JavaScript so awesome?</p>,
message: (
<p>
The best thing about JavaScript is its ecosystem. It is <em>huge</em>.
And it's vibrant: JavaScript developers feel like they own their own
platform, and consequently, there's a lot of experimentation. Most ideas
are bad, but the successful ones get institutionalized as best
practices. Over time, momentum grows.
</p>
)
},
{
response: <p>What do you mean about momentum?</p>,
message: (
<p>
Think about this: JavaScript development tools are often written{' '}
<em>in</em> JavaScript. As soon as a tool gets built, it's able to be
used to build more tools.
</p>
)
},
{
response: <p>That sounds kind of dizzying. Is that why the JavaScript ecosystem seems to move so quickly?</p>,
message:<p>Aye, that's a big part of it. JavaScript itself and <a href='https://www.npmjs.com'>npm</a> also encourage the creation of many, single-purpose tools. It is overwhelming. A brand new React Native codebase has <em>hundreds</em> of dependencies.</p>,
},
{
response:
<p>That sounds pretty sketchy. What about the scaffolding metaphor from earlier? Don't all those packages collapse under their own weight?</p>,
message:
<p>Sometimes they do 😬 It's happened a few times now, and the JavaScript ecosystem is always developing new tools and practices to deal with the complexity. The community is huge, so there's a lot of impetus to make it all work. Sometimes it feels to me like a "too big to fail" kind of situation.</p>,
},
{
response: <p>That sounds awful.</p>,
message:
<p>You're right to be skeptical. The JavaScript ecosystem can't easily be decoupled from your development flow, either. It's really weird to think about building a Node.js server, for example, without using npm. In iOS, lots of folks still don't use a dependency manager. It's just a different perspective.</p>,
},
{
response: <p>I hadn't thought about that.</p>,
message:
<p>It's interesting, isn't it? I think of JavaScript as a crucible: hard constraints, like the need for absolute backwards compatibility across decades of browsers, have fostered creativity in the community.</p>,
},
{
response: <p>Don't things get really fragmented?</p>,
message:
<p>Yeah, they do. But fragmentation isn't always bad, either. JavaScript allows for specialization in a way that iOS can't: consider two core contributors to <a href='https://babeljs.io'>Babel</a> and <a href='https://prettier.io'>Prettier</a> (two important OSS projects). They might never interact at all because the two tools are so different, but they <em>do</em> both get to use the same tools. JavaScript encourages fragmentation in useful ways, too.</p>,
},
{
response: <p>But the language just moves so fast!</p>,
message: <p>Well, so does Swift.</p>,
},
{
response:
<p>Touché. Are you now going to tell me everything wrong with native iOS development?</p>,
message:
<p>No, I always like to start on a positive note. Apple's tools for common development workflows are <em>exceptionally</em> well-polished. For example, Apple's app performance instrumentation tool is the best I've ever seen.</p>,
},
{
response: <p>Yeah, Instruments.app is great.</p>,
message:
<p>And because Apple owns the platform, they can be opinionated about their tools. Opinionated software can be really good.</p>,
},
{
response: <p>That's true!</p>,
message:
<p>Unfortunately, Apple's opinions about developer tooling are often not that good.</p>,
},
{
response: <p>Wait, what do you mean?</p>,
message:
<p>Apple's tooling reflects Apple's priorities; they make Instruments.app really amazing because they care that we build performant apps. That's great! But Apple's unit testing tools are... pretty awful to compared to <a href='https://jestjs.io'>Jest</a>. Apple doesn't prioritize unit testing – that's their opinion, and if you disagree with it, that's not Apple's problem.</p>,
},
{
response: <p>What's so wrong about Xcode's unit testing tools?</p>,
message:
<p>I wrote a <a href='https://ashfurrow.com/blog/apple-releases-jive/'>whole blog post about this</a>, go check it out. It's not a fair comparison, granted: Jest benefits from being used by such a huge community in web front-ends, servers, and command-line tools. XCTest gets used by the relatively small iOS developer community. However, the blog post goes into detail about low-hanging fruit that would make a huge difference. It's got radars you can dupe.</p>,
},
{
response: <p>How else are the native iOS tools different?</p>,
message:
<p>Apple builds tools for workflows that already exist, or that Apple invents. Their tools can be difficult to build community tools on top of. Take the new Xcode extensions API: it's very limited. Compare that to Visual Studio Code's extensions API, which is so capable that it has enabled entirely <em>new kinds</em> of developer tools get built.</p>,
},
{
response: <p>Yeah, I still miss Alcatraz.</p>,
message: <p>Me too.</p>,
},
{
response:
<p>Does the size disparity mean that the JavaScript ecosystem will always have better tools?</p>,
message:
<p>"Better" is a value judgement – they are different. JavaScript development tools have to do a lot more than iOS tools, which get to be more focused and have <em>way</em> lower barriers-to-entry. We're just analyzing those differences. Next, let's think about specialization.</p>,
},
{
response: <p>Okay...</p>,
message:
<p>Specialization can be really useful. Many of Apple's APIs are so stable, and cross such a wide spectrum of levels of abstraction, that there are iOS developers who <em>just</em> focus on the AVFoundation or CoreAnimation frameworks. Specialists can create <em>incredibly</em> polished software, and that kind of deep specialization is pretty uncommon among JavaScript developers.</p>,
},
{
response: <p>Whoa, yeah.</p>,
message:
<p>However, specialized skills are difficult to apply to a broad range of tasks.</p>,
},
{
response: <p>That's bad.</p>,
message:
<p>But they enable very rich, user-centric designs to spring to life and delight users.</p>,
},
{
response: <p>That's good!</p>,
message:
<p>But when you have a problem, and Apple doesn't care about <em>that</em> problem, it really sucks.</p>,
},
{
response: <p>That's bad.</p>,
message:
<p>Despite this, open source contributors have built some very impressive iOS tools.</p>,
},
{
response: <p>That's good!</p>,
message:
<p>But Apple's mishandling of Swift Package Manager has sucked a lot of enthusiasm out of this community.</p>,
},
{
response: <p>That's bad.</p>,
message: <p>It is what it is.</p>,
},
{
response: <p>... can I go now?</p>,
message: <p>😉</p>,
},
{
response: <p>Hey, I just figured out what this bit is a reference too.</p>,
message:
<p>Yeah, I'm a sucker for early Simpsons jokes. <a href='https://youtu.be/Krbl911ZPBA?t=22'>Here's the source material</a>.</p>,
},
{
response: <p>We've gotten off-topic.</p>,
message: <p>Right, sorry.</p>,
},
{
response: <p>Any other big advantages to native iOS development?</p>,
message:
<p>Yes. I have to give huge props to Apple for using their authoritative position within the community to make it really easy to learn how to build working software.</p>,
},
{
response: <p>What kind of tools?</p>,
message:
<p>In my Core Data workshops, one of the first things we do is create a project with a Core Data Xcode template and examine it. Or take <a href='https://www.apple.com/swift/playgrounds/'>Swift Playgrounds</a> for example. They make sure it's <em>really</em> easy to build apps for their platform.</p>,
},
{
response: <p>It sounds almost... selfish, when you say it like that.</p>,
message:
<p>Life is complicated. I can recognize when Apple has an agenda which happens to align with my own.</p>,
},
{
response: <p>I guess...</p>,
message:
<p>Apple's problems aren't our problems. That's a value-neutral statement, so if you have feelings about it, interrogate them. I guarantee you'll learn something.</p>,
},
{
response: <p>Okay so what else is wrong with native iOS development?</p>,
message:
<p>It's slow. But this slowness is often only apparent when you've used something better.</p>,
},
{
response: <p>What do you mean?</p>,
message:
<p>JavaScript developer tooling is very sophisticated (if unpolished). Hot module reloading and Jest's watch mode enable software development at the speed of thought. iOS development is like a painter who makes a brush stroke and has to wait fifteen seconds to see that change to their painting.</p>,
},
{
response: <p>That's kind of harsh.</p>,
message:
<p>🤷♂️ It's how I feel. It's hard to go back from a world where I see my changes and test results <em>instantly</em>.</p>,
},
{
response: <p>Are the tools really that good?</p>,
message:
<p>Yes. 'Not-invented here syndrome' doesn't hold much purchase among JavaScript developers.</p>,
},
{
response: <p>You're saying it does with iOS developers?</p>,
message:
<p>Not nearly like it used to. I've been so happy to see the community nourish a tool-focused open source community that brings Apple's sense of polish to building their own tools. <a href='https://github.com/krzysztofzablocki/Sourcery'>Sourcery</a>, <a href='https://github.com/realm/jazzy'>Jazzy</a>, <a href='https://github.com/JohnSundell/Marathon'>Marathon</a>. I could go on – and don't forget amazing commercial tools like <a href='https://revealapp.com'>Reveal</a> or <a href='http://injectionforxcode.com'>Injection for Xcode</a>.</p>,
},
{
response: <p>It's pretty impressive, what the community has accomplished.</p>,
message:
<p>I'm proud of it. Let's move on: another reality is that native iOS programming languages can't be used much outside native iOS software development.</p>,
},
{
response: <p>But what about Swift on the server?</p>,
message:
<p>I knew this would come up, eventually 😅 Swift on the server is fighting an uphill battle against frameworks with years of momentum behind them. It can be fun to build server apps in Swift, but it's much rougher experience compared to the alternatives. You've got to approach it like an adventure; however, sometimes we don't want an adventure, we just want to be productive. iOS developers sometimes ask me for advice on building their first server, and I steer them away from using Swift. They are more likely to accomplish their goals and avoid getting discouraged and quitting if they learn Sinatra or Express.</p>,
},
{
response: <p>I guess it all depends, doesn't it?</p>,
message:
<p>That's right! Software development is all about managing trade-offs. The iOS community is way smaller. That's okay! There are advantages to being smaller, too. Knowing what the trade-offs are will only help us navigate them better.</p>,
},
{
response:
<p>Okay, so what are the disadvantages of JavaScript development? In this comparison to iOS, I mean.</p>,
message:
<p>Yeah, totally. Remember Xcode's awesome project templates? No such thing exists on JavaScript. At all. There is literally no defined starting place 😱 Since there is no platform owner, there is no default <em>anything</em>. JavaScript's infinite possibilities often lead to analysis-paralysis. It leads to developers blaming themselves when their tools don't work. Constant framework churn leaves the industry littered with codebases whose dependencies are hopelessly outdated. And let's not forget the heavy influence that corporate open source holds over the entire ecosystem.</p>,
},
{
response: <p>Wait, what?</p>,
message:
<p>Facebook makes React, React Native, Jest, Yarn, and loads more. Microsoft makes Visual Studio Code and TypeScript. Even the beloved npm is backed by venture capitalists, who are expecting a return on their investments. That's even scarier than bloated node_modules directories, personally. Any of these companies can make a decision motivated by their own agenda and cause major problems for the developer community. In some ways, it's preferable to have Apple as a single platform owner. Let's extend the rent-vs-own metaphor from earlier: JavaScript might be homeowners, but they still pay a mortgage.</p>,
},
{
response: <p>That sounds awful.</p>,
message:
<p>It is what it is. I do corporate open source for Artsy, which is also venture-backed.</p>,
},
{
response: <p>Well, Artsy isn't a backbone of the JavaScript ecosystem 😜</p>,
message:
<p>Ha, that's true. Earlier, I asked you to keep an open mind. That doesn't mean giving up critical thought, though. And I do think about this stuff.</p>,
},
{
response: <p>I think that's a good place to wrap it up.</p>,
message:
<p>Yeah, hey thanks for the discussion! It felt great to engage with such a curious interlocutor.</p>,
},
{
response: <p>Well, you're quite eloquent yourself.</p>,
message: <p>Alright, take care.</p>,
},
{
response: <p>See ya.</p>
}
] as ChatScript[] | the_stack |
import rule, {
defaultOrder,
MessageIds,
Options,
} from '../../src/rules/member-ordering';
import { RuleTester } from '../RuleTester';
import { TSESLint } from '@typescript-eslint/experimental-utils';
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});
const sortedWithoutGroupingDefaultOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// default option + interface + multiple types
{
code: `
interface Foo {
(): Foo;
a(): Foo;
b(): Foo;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// default option + interface + lower/upper case
{
code: `
interface Foo {
A : b;
a : b;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + interface + numbers
{
code: `
interface Foo {
a1 : b;
aa : b;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + interface + literal properties
{
code: `
interface Foo {
a : Foo;
'b.c' : Foo;
"b.d" : Foo;
}
`,
options: [{ default: { order: 'alphabetically' } }],
},
// default option + type literal + multiple types
{
code: `
type Foo = {
a : b;
[a: string] : number;
b() : void;
() : Baz;
new () : Bar;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + type literal + lower/upper case
{
code: `
type Foo = {
A : b;
a : b;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + type literal + numbers
{
code: `
type Foo = {
a1 : b;
aa : b;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + type + literal properties
{
code: `
type Foo = {
a : Foo;
'b.c' : Foo;
"b.d" : Foo;
}
`,
options: [{ default: { order: 'alphabetically' } }],
},
// default option + class + multiple types
{
code: `
class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
constructor() {}
@Dec() d: string;
public e : string = "";
@Dec() f : string = "";
protected g : string = "";
private h : string = "";
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + class + lower/upper case
{
code: `
class Foo {
public static A : string;
public static a : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + class + numbers
{
code: `
class Foo {
public static a1 : string;
public static aa : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + class expression + multiple types
{
code: `
const foo = class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
private f : string = "";
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + class expression + lower/upper case
{
code: `
const foo = class Foo {
public static A : string;
public static a : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + class expression + numbers
{
code: `
const foo = class Foo {
public static a1 : string;
public static aa : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + class + decorators
{
code: `
class Foo {
public static a : string;
@Dec() static b : string;
public static c : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
},
// default option + private identifiers
{
code: `
class Foo {
#a = 1;
#b = 2;
#c = 3;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
],
invalid: [
// default option + interface + wrong order
{
code: `
interface Foo {
b() : void;
a : b;
[a: string] : number;
new () : Bar;
() : Baz;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'call',
beforeMember: 'new',
},
},
],
},
// default option + interface + literal properties
{
code: `
interface Foo {
"b.d" : Foo;
'b.c' : Foo;
a : Foo;
}
`,
options: [{ default: { order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b.c',
beforeMember: 'b.d',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b.c',
},
},
],
},
// default option + interface + wrong order (multiple)
{
code: `
interface Foo {
c : string;
b : string;
a : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// default option + type literal + wrong order
{
code: `
type Foo = {
b() : void;
a : b;
[a: string] : number;
new () : Bar;
() : Baz;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'call',
beforeMember: 'new',
},
},
],
},
// default option + type + literal properties
{
code: `
type Foo = {
"b.d" : Foo;
'b.c' : Foo;
a : Foo;
}
`,
options: [{ default: { order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b.c',
beforeMember: 'b.d',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b.c',
},
},
],
},
// default option + type literal + wrong order (multiple)
{
code: `
type Foo = {
c : string;
b : string;
a : string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// default option + class + wrong order
{
code: `
class Foo {
protected static b : string = "";
public static a : string;
private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
private f : string = "";
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// default option + class + wrong order (multiple)
{
code: `
class Foo {
public static c: string;
public static b: string;
public static a: string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// default option + class expression + wrong order
{
code: `
const foo = class Foo {
protected static b : string = "";
public static a : string;
private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
private f : string = "";
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// default option + class expression + wrong order (multiple)
{
code: `
const foo = class Foo {
public static c: string;
public static b: string;
public static a: string;
}
`,
options: [{ default: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
],
};
const sortedWithoutGroupingClassesOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// classes option + interface + multiple types --> Only member group order is checked (default config)
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
c : b;
new () : Bar;
b() : void;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + interface + lower/upper case --> Only member group order is checked (default config)
{
code: `
interface Foo {
a : b;
A : b;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + interface + numbers --> Only member group order is checked (default config)
{
code: `
interface Foo {
aa : b;
a1 : b;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + type literal + multiple types --> Only member group order is checked (default config)
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
c : b;
new () : Bar;
b() : void;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + type literal + lower/upper case --> Only member group order is checked (default config)
{
code: `
type Foo = {
a : b;
A : b;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + type literal + numbers --> Only member group order is checked (default config)
{
code: `
type Foo = {
aa : b;
a1 : b;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + class + multiple types
{
code: `
class Foo {
public static a : string;
protected static b : string = "";
@Dec() private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
@Dec()
private f : string = "";
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + class + lower/upper case
{
code: `
class Foo {
public static A : string;
public static a : string;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + class + numbers
{
code: `
class Foo {
public static a1 : string;
public static aa : string;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + class expression + multiple types --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
public d : string = "";
protected e : string = "";
private f : string = "";
constructor() {}
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + class expression + lower/upper case --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static a : string;
public static A : string;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
// classes option + class expression + numbers --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static aa : string;
public static a1 : string;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
},
],
invalid: [
// classes option + class + wrong order
{
code: `
class Foo {
protected static b : string = "";
public static a : string;
private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
private f : string = "";
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// classes option + class + wrong order (multiple)
{
code: `
class Foo {
public static c: string;
public static b: string;
public static a: string;
}
`,
options: [{ classes: { memberTypes: 'never', order: 'alphabetically' } }],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
],
};
const sortedWithoutGroupingClassExpressionsOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// classExpressions option + interface + multiple types --> Only member group order is checked (default config)
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
c : b;
new () : Bar;
b() : void;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + interface + lower/upper case --> Only member group order is checked (default config)
{
code: `
interface Foo {
a : b;
A : b;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + interface + numbers --> Only member group order is checked (default config)
{
code: `
interface Foo {
aa : b;
a1 : b;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + type literal + multiple types --> Only member group order is checked (default config)
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
c : b;
new () : Bar;
b() : void;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + type literal + lower/upper case --> Only member group order is checked (default config)
{
code: `
type Foo = {
a : b;
A : b;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + type literal + numbers --> Only member group order is checked (default config)
{
code: `
type Foo = {
aa : b;
a1 : b;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + class + multiple types --> Only member group order is checked (default config)
{
code: `
class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
public d : string = "";
protected e : string = "";
private f : string = "";
constructor() {}
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + class + lower/upper case --> Only member group order is checked (default config)
{
code: `
class Foo {
public static a : string;
public static A : string;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + class + numbers --> Only member group order is checked (default config)
{
code: `
class Foo {
public static aa : string;
public static a1 : string;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + class expression + multiple types
{
code: `
const foo = class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
private f : string = "";
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + class expression + lower/upper case
{
code: `
const foo = class Foo {
public static A : string;
public static a : string;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// classExpressions option + class expression + numbers
{
code: `
const foo = class Foo {
public static a1 : string;
public static aa : string;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
},
],
invalid: [
// classExpressions option + class expression + wrong order
{
code: `
const foo = class Foo {
protected static b : string = "";
public static a : string;
private static c : string = "";
constructor() {}
public d : string = "";
protected e : string = "";
private f : string = "";
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
// classExpressions option + class expression + wrong order (multiple)
{
code: `
const foo = class Foo {
public static c: string;
public static b: string;
public static a: string;
}
`,
options: [
{ classExpressions: { memberTypes: 'never', order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
],
};
const sortedWithoutGroupingInterfacesOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// interfaces option + interface + multiple types
{
code: `
interface Foo {
[a: string] : number;
a : b;
b() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + interface + lower/upper case
{
code: `
interface Foo {
A : b;
a : b;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + interface + numbers
{
code: `
interface Foo {
a1 : b;
aa : b;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + type literal + multiple types --> Only member group order is checked (default config)
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
c : b;
new () : Bar;
b() : void;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + type literal + lower/upper case --> Only member group order is checked (default config)
{
code: `
type Foo = {
a : b;
A : b;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + type literal + numbers --> Only member group order is checked (default config)
{
code: `
type Foo = {
aa : b;
a1 : b;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + class + multiple types --> Only member group order is checked (default config)
{
code: `
class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
public d : string = "";
protected e : string = "";
private f : string = "";
constructor() {}
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + class + lower/upper case --> Only member group order is checked (default config)
{
code: `
class Foo {
public static a : string;
public static A : string;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + class + numbers --> Only member group order is checked (default config)
{
code: `
class Foo {
public static aa : string;
public static a1 : string;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + class expression + multiple types --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
public d : string = "";
protected e : string = "";
private f : string = "";
constructor() {}
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + class expression + lower/upper case --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static a : string;
public static A : string;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// interfaces option + class expression + numbers --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static aa : string;
public static a1 : string;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
},
],
invalid: [
// interfaces option + interface + wrong order
{
code: `
interface Foo {
b() : void;
a : b;
[a: string] : number;
new () : Bar;
() : Baz;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'call',
beforeMember: 'new',
},
},
],
},
// interfaces option + interface + wrong order (multiple)
{
code: `
interface Foo {
c : string;
b : string;
a : string;
}
`,
options: [
{ interfaces: { memberTypes: 'never', order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
],
};
const sortedWithoutGroupingTypeLiteralsOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// typeLiterals option + interface + multiple types --> Only member group order is checked (default config)
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
c : b;
new () : Bar;
b() : void;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + interface + lower/upper case --> Only member group order is checked (default config)
{
code: `
interface Foo {
a : b;
A : b;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + interface + numbers --> Only member group order is checked (default config)
{
code: `
interface Foo {
aa : b;
a1 : b;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + type literal + multiple types
{
code: `
type Foo = {
[a: string] : number;
a : b;
b() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + type literal + lower/upper case
{
code: `
type Foo = {
A : b;
a : b;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + type literal + numbers
{
code: `
type Foo = {
a1 : b;
aa : b;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + class + multiple types --> Only member group order is checked (default config)
{
code: `
class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
public d : string = "";
protected e : string = "";
private f : string = "";
constructor() {}
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + class + lower/upper case --> Only member group order is checked (default config)
{
code: `
class Foo {
public static a : string;
public static A : string;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + class + numbers --> Only member group order is checked (default config)
{
code: `
class Foo {
public static aa : string;
public static a1 : string;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + class expression + multiple types --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static a : string;
protected static b : string = "";
private static c : string = "";
public d : string = "";
protected e : string = "";
private f : string = "";
constructor() {}
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + class expression + lower/upper case --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static a : string;
public static A : string;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
// typeLiterals option + class expression + numbers --> Only member group order is checked (default config)
{
code: `
const foo = class Foo {
public static aa : string;
public static a1 : string;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
},
],
invalid: [
// typeLiterals option + type literal + wrong order
{
code: `
type Foo = {
b() : void;
a : b;
[a: string] : number;
new () : Bar;
() : Baz;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'call',
beforeMember: 'new',
},
},
],
},
// typeLiterals option + type literal + wrong order (multiple)
{
code: `
type Foo = {
c : string;
b : string;
a : string;
}
`,
options: [
{ typeLiterals: { memberTypes: 'never', order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'b',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'b',
},
},
],
},
],
};
const sortedWithGroupingDefaultOption: TSESLint.RunTests<MessageIds, Options> =
{
valid: [
// default option + interface + default order + alphabetically
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
a : x;
b : x;
c : x;
new () : Bar;
a() : void;
b() : void;
c() : void;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// default option + interface + custom order + alphabetically
{
code: `
interface Foo {
new () : Bar;
a() : void;
b() : void;
c() : void;
a : x;
b : x;
c : x;
[a: string] : number;
() : Baz;
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'method', 'field'],
order: 'alphabetically',
},
},
],
},
// default option + type literal + default order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
a : x;
b : x;
c : x;
new () : Bar;
a() : void;
b() : void;
c() : void;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// default option + type literal + custom order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
new () : Bar;
a() : void;
b() : void;
c() : void;
a : x;
b : x;
c : x;
() : Baz;
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'method', 'field'],
order: 'alphabetically',
},
},
],
},
// default option + class + default order + alphabetically
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// default option + class + defaultOrder + alphabetically
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
get h() {}
set g() {}
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically',
},
},
],
},
// default option + class + custom + alphabetically
{
code: `
class Foo {
get a() {}
@Bar
get b() {}
set c() {}
@Bar
set d() {}
}
`,
options: [
{
default: {
memberTypes: ['get', 'decorated-get', 'set', 'decorated-set'],
order: 'alphabetically',
},
},
],
},
// default option + class + decorators + default order + alphabetically
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
@Dec() public d: string;
@Dec() protected e: string;
@Dec() private f: string;
public g: string = "";
protected h: string = "";
private i: string = "";
constructor() {}
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// default option + class + custom order + alphabetically
{
code: `
class Foo {
constructor() {}
public d: string = "";
protected e: string = "";
private f: string = "";
public static a: string;
protected static b: string = "";
private static c: string = "";
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'instance-field', 'static-field'],
order: 'alphabetically',
},
},
],
},
// default option + class expression + default order + alphabetically
{
code: `
const foo = class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// default option + class expression + custom order + alphabetically
{
code: `
const foo = class Foo {
constructor() {}
public d: string = "";
protected e: string = "";
private f: string = "";
public static a: string;
protected static b: string = "";
private static c: string = "";
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'instance-field', 'static-field'],
order: 'alphabetically',
},
},
],
},
],
invalid: [
// default option + class + wrong order within group and wrong group order + alphabetically
{
code: `
class FooTestGetter {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
get h() {}
set g() {}
constructor() {}
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'constructor',
rank: 'public instance get',
},
},
],
},
// default option + class + custom + alphabetically
{
code: `
class Foo {
@Bar
get a() {}
get b() {}
@Bar
set c() {}
set d() {}
}
`,
options: [
{
default: {
memberTypes: ['get', 'decorated-get', 'set', 'decorated-set'],
order: 'alphabetically',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'b',
rank: 'decorated get',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'decorated set',
},
},
],
},
// default option + class + wrong order within group and wrong group order + alphabetically
{
code: `
class FooTestGetter {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
set g() {}
constructor() {}
get h() {}
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'constructor',
rank: 'public instance set',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'h',
rank: 'public instance set',
},
},
],
},
// default option + interface + wrong order within group and wrong group order + alphabetically
{
code: `
interface Foo {
[a: string] : number;
a : x;
b : x;
c : x;
c() : void;
b() : void;
a() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'call',
rank: 'field',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'new',
rank: 'method',
},
},
],
},
// default option + type literal + wrong order within group and wrong group order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
a : x;
b : x;
c : x;
c() : void;
b() : void;
a() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'call',
rank: 'field',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'new',
rank: 'method',
},
},
],
},
// default option + class + wrong order within group and wrong group order + alphabetically
{
code: `
class Foo {
public static c: string = "";
public static b: string = "";
public static a: string;
constructor() {}
public d: string = "";
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'public constructor',
},
},
],
},
// default option + class expression + wrong order within group and wrong group order + alphabetically
{
code: `
const foo = class Foo {
public static c: string = "";
public static b: string = "";
public static a: string;
constructor() {}
public d: string = "";
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'public constructor',
},
},
],
},
// default option + class + decorators + custom order + wrong order within group and wrong group order + alphabetically
{
code: `
class Foo {
@Dec() a1: string;
@Dec()
a3: string;
@Dec()
a2: string;
constructor() {}
b1: string;
b2: string;
public c(): void;
@Dec() d(): void
}
`,
options: [
{
default: {
memberTypes: [
'decorated-field',
'field',
'constructor',
'decorated-method',
],
order: 'alphabetically',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'b1',
rank: 'constructor',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'b2',
rank: 'constructor',
},
},
],
},
],
};
const sortedWithGroupingClassesOption: TSESLint.RunTests<MessageIds, Options> =
{
valid: [
// classes option + interface + alphabetically --> Default order applies
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
c : x;
b : x;
a : x;
new () : Bar;
c() : void;
b() : void;
a() : void;
}
`,
options: [{ classes: { order: 'alphabetically' } }],
},
// classes option + type literal + alphabetically --> Default order applies
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
c : x;
b : x;
a : x;
new () : Bar;
c() : void;
b() : void;
a() : void;
}
`,
options: [{ classes: { order: 'alphabetically' } }],
},
// classes option + class + default order + alphabetically
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [
{ classes: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
},
// classes option + class + custom order + alphabetically
{
code: `
class Foo {
constructor() {}
public d: string = "";
protected e: string = "";
private f: string = "";
public static a: string;
protected static b: string = "";
private static c: string = "";
}
`,
options: [
{
classes: {
memberTypes: ['constructor', 'instance-field', 'static-field'],
order: 'alphabetically',
},
},
],
},
// classes option + class expression + alphabetically --> Default order applies
{
code: `
const foo = class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [{ classes: { order: 'alphabetically' } }],
},
],
invalid: [
// default option + class + wrong order within group and wrong group order + alphabetically
{
code: `
class Foo {
public static c: string = "";
public static b: string = "";
public static a: string;
constructor() {}
public d: string = "";
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'public constructor',
},
},
],
},
],
};
const sortedWithGroupingClassExpressionsOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// classExpressions option + interface + alphabetically --> Default order applies
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
c : x;
b : x;
a : x;
new () : Bar;
c() : void;
b() : void;
a() : void;
}
`,
options: [{ classExpressions: { order: 'alphabetically' } }],
},
// classExpressions option + type literal + alphabetically --> Default order applies
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
c : x;
b : x;
a : x;
new () : Bar;
c() : void;
b() : void;
a() : void;
}
`,
options: [{ classExpressions: { order: 'alphabetically' } }],
},
// classExpressions option + class + alphabetically --> Default order applies
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [{ classExpressions: { order: 'alphabetically' } }],
},
// classExpressions option + class expression + default order + alphabetically
{
code: `
const foo = class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [
{
classExpressions: {
memberTypes: defaultOrder,
order: 'alphabetically',
},
},
],
},
// classExpressions option + class expression + custom order + alphabetically
{
code: `
const foo = class Foo {
constructor() {}
public d: string = "";
protected e: string = "";
private f: string = "";
public static a: string;
protected static b: string = "";
private static c: string = "";
}
`,
options: [
{
classExpressions: {
memberTypes: ['constructor', 'instance-field', 'static-field'],
order: 'alphabetically',
},
},
],
},
],
invalid: [
// default option + class expression + wrong order within group and wrong group order + alphabetically
{
code: `
const foo = class Foo {
public static c: string = "";
public static b: string = "";
public static a: string;
constructor() {}
public d: string = "";
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'public constructor',
},
},
],
},
],
};
const sortedWithGroupingInterfacesOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// interfaces option + interface + default order + alphabetically
{
code: `
interface Foo {
[a: string] : number;
a : x;
b : x;
c : x;
a() : void;
b() : void;
c() : void;
new () : Bar;
() : Baz;
}
`,
options: [
{
interfaces: {
memberTypes: ['signature', 'field', 'method', 'constructor'],
order: 'alphabetically',
},
},
],
},
// interfaces option + interface + custom order + alphabetically
{
code: `
interface Foo {
new () : Bar;
a() : void;
b() : void;
c() : void;
a : x;
b : x;
c : x;
[a: string] : number;
() : Baz;
}
`,
options: [
{
interfaces: {
memberTypes: ['constructor', 'method', 'field'],
order: 'alphabetically',
},
},
],
},
// interfaces option + type literal + alphabetically --> Default order applies
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
c : x;
b : x;
a : x;
new () : Bar;
c() : void;
b() : void;
a() : void;
}
`,
options: [{ interfaces: { order: 'alphabetically' } }],
},
// interfaces option + class + alphabetically --> Default order applies
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [{ interfaces: { order: 'alphabetically' } }],
},
// interfaces option + class expression + alphabetically --> Default order applies
{
code: `
const foo = class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [{ interfaces: { order: 'alphabetically' } }],
},
],
invalid: [
// default option + interface + wrong order within group and wrong group order + alphabetically
{
code: `
interface Foo {
[a: string] : number;
a : x;
b : x;
c : x;
c() : void;
b() : void;
a() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'call',
rank: 'field',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'new',
rank: 'method',
},
},
],
},
],
};
const sortedWithGroupingTypeLiteralsOption: TSESLint.RunTests<
MessageIds,
Options
> = {
valid: [
// typeLiterals option + interface + alphabetically --> Default order applies
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
c : x;
b : x;
a : x;
new () : Bar;
c() : void;
b() : void;
a() : void;
}
`,
options: [{ typeLiterals: { order: 'alphabetically' } }],
},
// typeLiterals option + type literal + default order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
a : x;
b : x;
c : x;
a() : void;
b() : void;
c() : void;
new () : Bar;
() : Baz;
}
`,
options: [
{
typeLiterals: {
memberTypes: ['signature', 'field', 'method', 'constructor'],
order: 'alphabetically',
},
},
],
},
// typeLiterals option + type literal + custom order + alphabetically
{
code: `
type Foo = {
new () : Bar;
a() : void;
b() : void;
c() : void;
a : x;
b : x;
c : x;
[a: string] : number;
() : Baz;
}
`,
options: [
{
typeLiterals: {
memberTypes: ['constructor', 'method', 'field'],
order: 'alphabetically',
},
},
],
},
// typeLiterals option + class + alphabetically --> Default order applies
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [{ typeLiterals: { order: 'alphabetically' } }],
},
// typeLiterals option + class expression + alphabetically --> Default order applies
{
code: `
const foo = class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected e: string = "";
private f: string = "";
constructor() {}
}
`,
options: [{ typeLiterals: { order: 'alphabetically' } }],
},
],
invalid: [
// default option + type literal + wrong order within group and wrong group order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
a : x;
b : x;
c : x;
c() : void;
b() : void;
a() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'call',
rank: 'field',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'new',
rank: 'method',
},
},
],
},
// default option + private identifiers
{
code: `
class Foo {
#c = 3;
#b = 2;
#a = 1;
}
`,
options: [
{ default: { memberTypes: defaultOrder, order: 'alphabetically' } },
],
errors: [
{
messageId: 'incorrectOrder',
line: 4,
column: 3,
},
{
messageId: 'incorrectOrder',
line: 5,
column: 3,
},
],
},
],
};
const sortedWithoutGrouping = {
valid: [
...sortedWithoutGroupingDefaultOption.valid,
...sortedWithoutGroupingClassesOption.valid,
...sortedWithoutGroupingClassExpressionsOption.valid,
...sortedWithoutGroupingInterfacesOption.valid,
...sortedWithoutGroupingTypeLiteralsOption.valid,
],
invalid: [
...sortedWithoutGroupingDefaultOption.invalid,
...sortedWithoutGroupingClassesOption.invalid,
...sortedWithoutGroupingClassExpressionsOption.invalid,
...sortedWithoutGroupingInterfacesOption.invalid,
...sortedWithoutGroupingTypeLiteralsOption.invalid,
],
};
const sortedWithGrouping = {
valid: [
...sortedWithGroupingDefaultOption.valid,
...sortedWithGroupingClassesOption.valid,
...sortedWithGroupingClassExpressionsOption.valid,
...sortedWithGroupingInterfacesOption.valid,
...sortedWithGroupingTypeLiteralsOption.valid,
],
invalid: [
...sortedWithGroupingDefaultOption.invalid,
...sortedWithGroupingClassesOption.invalid,
...sortedWithGroupingClassExpressionsOption.invalid,
...sortedWithGroupingInterfacesOption.invalid,
...sortedWithGroupingTypeLiteralsOption.invalid,
],
};
ruleTester.run('member-ordering-alphabetically-order', rule, {
valid: [...sortedWithoutGrouping.valid, ...sortedWithGrouping.valid],
invalid: [...sortedWithoutGrouping.invalid, ...sortedWithGrouping.invalid],
}); | the_stack |
import {
API,
AudioStreamingCodecType,
AudioStreamingSamplerate,
CameraController,
CameraControllerOptions,
CameraStreamingDelegate,
HAP,
Logging,
PrepareStreamCallback,
PrepareStreamRequest,
PrepareStreamResponse,
SnapshotRequest,
SnapshotRequestCallback,
SRTPCryptoSuites,
StartStreamRequest,
StreamingRequest,
StreamRequestCallback,
StreamRequestTypes
} from 'homebridge';
import {ImageUtils} from '../utils/image-utils';
import {Canvas} from 'canvas';
import {Unifi, UnifiCamera} from '../unifi/unifi';
import {UnifiFlows} from '../unifi/unifi-flows';
import {FfmpegProcess} from './ffmpeg-process';
import {RtpDemuxer, RtpUtils} from './rtp-splitter';
import {CameraConfig} from './camera-config';
import ffmpegPath from 'ffmpeg-for-homebridge';
type SessionInfo = {
address: string; // Address of the HAP controller.
addressVersion: string;
videoPort: number;
videoReturnPort: number;
videoCryptoSuite: SRTPCryptoSuites; // This should be saved if multiple suites are supported.
videoSRTP: Buffer; // Key and salt concatenated.
videoSSRC: number; // RTP synchronisation source.
hasLibFdk: boolean; // Does the user have a version of ffmpeg that supports AAC?
audioPort: number;
audioIncomingRtcpPort: number;
audioIncomingRtpPort: number; // Port to receive audio from the HomeKit microphone.
rtpDemuxer: RtpDemuxer | null; // RTP demuxer needed for two-way audio.
audioCryptoSuite: SRTPCryptoSuites;
audioSRTP: Buffer;
audioSSRC: number;
};
export class UnifiStreamingDelegate implements CameraStreamingDelegate {
public static uFlows: UnifiFlows;
private readonly api: API;
private readonly hap: HAP;
public readonly log: Logging;
private readonly cameraConfig;
private readonly camera: UnifiCamera;
public readonly cameraName: string;
public readonly videoProcessor: string;
private readonly ongoingSessions: { [index: string]: { ffmpeg: FfmpegProcess[], rtpDemuxer: RtpDemuxer | null } };
private readonly pendingSessions: { [index: string]: SessionInfo };
public controller: CameraController;
constructor(camera: UnifiCamera, log: Logging, api: API, cameraConfig: CameraConfig, videoProcessor: string) {
this.camera = camera;
this.cameraName = camera.name;
this.api = api;
this.hap = api.hap;
this.log = log;
this.ongoingSessions = {};
this.pendingSessions = {};
this.videoProcessor = videoProcessor || ffmpegPath || 'ffmpeg';
log.info('VIDEO PROCESSOR: ' + this.videoProcessor);
this.cameraConfig = cameraConfig;
// Setup for our camera controller.
const options: CameraControllerOptions = {
cameraStreamCount: 10, // HomeKit requires at least 2 streams, and HomeKit Secure Video requires 1.
delegate: this,
streamingOptions: {
audio: {
codecs: [
{
samplerate: AudioStreamingSamplerate.KHZ_16,
type: AudioStreamingCodecType.AAC_ELD
}
],
twoWayAudio: this.camera.supportsTwoWayAudio
},
supportedCryptoSuites: [this.hap.SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80],
video: {
codec: {
// Through admittedly anecdotal testing on various G3 and G4 models, UniFi Protect seems to support
// only the H.264 Main profile, though it does support various H.264 levels, ranging from Level 3
// through Level 5.1 (G4 Pro at maximum resolution). However, HomeKit only supports Level 3.1, 3.2,
// and 4.0 currently.
levels: [this.hap.H264Level.LEVEL3_1, this.hap.H264Level.LEVEL3_2, this.hap.H264Level.LEVEL4_0],
profiles: [ this.hap.H264Profile.MAIN ]
},
//TODO: Rework this!
resolutions: [
// Width, height, framerate.
[1920, 1080, 30],
[1280, 960, 30],
[1280, 720, 30],
[1024, 768, 30],
[640, 480, 30],
[640, 360, 30],
[480, 360, 30],
[480, 270, 30],
[320, 240, 30],
[320, 240, 15], // Apple Watch requires this configuration
[320, 180, 30]
]
}
}
};
this.controller = new this.hap.CameraController(options);
}
// HomeKit image snapshot request handler.
public async handleSnapshotRequest(request: SnapshotRequest, callback: SnapshotRequestCallback): Promise<void> {
this.log.debug('Handling snapshot request for Camera: ' + this.camera.name);
if (!this.camera || !this.camera.lastDetectionSnapshot) {
this.log.debug('Getting new snapshot');
try {
const snapshotData: Buffer = await UnifiStreamingDelegate.uFlows.getCameraSnapshot(this.camera, request.width, request.height)
callback(undefined, snapshotData);
} catch (error) {
callback(undefined, null);
}
} else {
this.log.debug('Returning annotated snapshot');
const canvas: Canvas = ImageUtils.resizeCanvas(this.camera.lastDetectionSnapshot, request.width, request.height);
callback(undefined, canvas.toBuffer('image/jpeg'));
}
}
public async handleStreamRequest(request: StreamingRequest, callback: StreamRequestCallback): Promise<void> {
switch (request.type) {
case StreamRequestTypes.START:
this.startStream(request, callback);
break;
case StreamRequestTypes.RECONFIGURE:
this.log.debug('%s: Ignoring request to reconfigure: %sx%s, %s fps, %s kbps.', this.camera.name, request.video.width, request.video.height, request.video.fps, request.video.max_bit_rate);
callback();
break;
case StreamRequestTypes.STOP:
default:
this.stopStream(request.sessionID);
callback();
break;
}
}
private startStream(request: StartStreamRequest, callback: StreamRequestCallback): void {
const sessionInfo = this.pendingSessions[request.sessionID];
const sdpIpVersion = sessionInfo.addressVersion === 'ipv6' ? 'IP6 ' : 'IP4';
// Set our packet size to be 564. Why? MPEG transport stream (TS) packets are 188 bytes in size each.
// These packets transmit the video data that you ultimately see on your screen and are transmitted using
// UDP. Each UDP packet is 1316 bytes in size, before being encapsulated in IP. We want to get as many
// TS packets as we can, within reason, in those UDP packets. This translates to 1316 / 188 = 7 TS packets
// as a limit of what can be pushed through a single UDP packet. Here's the problem...you need to have
// enough data to fill that pipe, all the time. Network latency, ffmpeg overhead, and the speed / quality of
// the original camera stream all play a role here, and as you can imagine, there's a nearly endless set of
// combinations to decide how to best fill that pipe. Set it too low, and you're incurring extra overhead by
// pushing less video data to clients in each packet, though you're increasing interactivity by getting
// whatever data you have to the end user. Set it too high, and startup latency becomes unacceptable
// when you begin a stream.
//
// For audio, you have a latency problem and a packet size that's too big will force the audio to sound choppy
// - so we opt to increase responsiveness at the risk of more overhead. This gives the end user a much better
// audio experience, at a marginal cost in bandwidth overhead.
//
// Through experimentation, I've found a sweet spot of 188 * 3 = 564 for video on Protect cameras. In my testing,
// adjusting the packet size beyond 564 did not have a material impact in improving the startup time, and often had
// a negative impact.
const videomtu: number = 188 * 3;
const audiomtu: number = 188;
// -rtsp_transport tcp: tell the RTSP stream handler that we're looking for a TCP connection.
const streamingUrl: string = Unifi.generateStreamingUrlForBestMatchingResolution(this.cameraConfig.source, this.camera.streams, request.video.width, request.video.height);
const ffmpegArgs: string[] = ['-hide_banner', '-rtsp_transport', 'tcp', '-i', streamingUrl];
this.log.info('%s: HomeKit video stream request received: %sx%s, %s fps, %s kbps.', this.camera.name, request.video.width, request.video.height, request.video.fps, request.video.max_bit_rate);
this.log.info('%s: Selected stream: %s for playback', this.camera.name, streamingUrl);
// Configure our video parameters:
// -map 0:v selects the first available video track from the stream. Protect actually maps audio
// and video tracks in opposite locations from where ffmpeg typically expects them. This
// setting is a more general solution than naming the track locations directly in case
// Protect changes this in n the future.
// -vcodec copy copy the stream withour reencoding it.
// -f rawvideo specify that we're using raw video.
// -pix_fmt yuvj420p use the yuvj420p pixel format, which is what Protect uses.
// -r fps frame rate to use for this stream. This is specified by HomeKit.
// -b:v bitrate the average bitrate to use for this stream. This is specified by HomeKit.
// -bufsize size this is the decoder buffer size, which drives the variability / quality of the output bitrate.
// -maxrate bitrate the maximum bitrate tolerance, used with -bufsize. We set this to max_bit_rate to effectively
// create a constant bitrate.
// -payload_type num payload type for the RTP stream. This is negotiated by HomeKit and is usually 99 for H.264 video.
// -ssrc synchronization source stream identifier. Random number negotiated by HomeKit to identify this stream.
// -f rtp specify that we're using the RTP protocol.
// -srtp_out_suite enc specify the output encryption encoding suites.
// -srtp_out_params params specify the output encoding parameters. This is negotiated by HomeKit.
ffmpegArgs.push(
'-map', '0:v',
'-vcodec', 'copy',
'-f', 'rawvideo',
'-pix_fmt', 'yuvj420p',
'-r', request.video.fps.toString(),
//...this.platform.config.ffmpegOptions.split(' '),
'-b:v', request.video.max_bit_rate.toString() + 'k',
'-bufsize', (2 * request.video.max_bit_rate).toString() + 'k',
'-maxrate', request.video.max_bit_rate.toString() + 'k',
'-payload_type', request.video.pt.toString(),
'-ssrc', sessionInfo.videoSSRC.toString(),
'-f', 'rtp',
'-srtp_out_suite', 'AES_CM_128_HMAC_SHA1_80',
'-srtp_out_params', sessionInfo.videoSRTP.toString('base64'),
'srtp://' + sessionInfo.address + ':' + sessionInfo.videoPort.toString() + '?rtcpport=' + sessionInfo.videoPort.toString() +
'&localrtcpport=' + sessionInfo.videoPort.toString() + '&pkt_size=' + videomtu.toString()
);
// Configure the audio portion of the command line, if we have a version of FFmpeg supports libfdk_aac. Options we use are:
//
// -map 0:a selects the first available audio track from the stream. Protect actually maps audio
// and video tracks in opposite locations from where ffmpeg typically expects them. This
// setting is a more general solution than naming the track locations directly in case
// Protect changes this in the future.
// -acodec libfdk_aac encode to AAC.
// -profile:a aac_eld specify enhanced, low-delay AAC for HomeKit.
// -flags +global_header sets the global header in the bitstream.
// -f null null filter to pass the audio unchanged without running through a muxing operation.
// -ar samplerate sample rate to use for this audio. This is specified by HomeKit.
// -b:a bitrate bitrate to use for this audio. This is specified by HomeKit.
// -bufsize size this is the decoder buffer size, which drives the variability / quality of the output bitrate.
// -ac 1 set the number of audio channels to 1.
if (sessionInfo.hasLibFdk) {
// Configure our audio parameters.
ffmpegArgs.push(
'-map', '0:a',
'-acodec', 'libfdk_aac',
'-profile:a', 'aac_eld',
'-flags', '+global_header',
'-f', 'null',
'-ar', request.audio.sample_rate.toString() + 'k',
'-b:a', request.audio.max_bit_rate.toString() + 'k',
'-bufsize', (2 * request.audio.max_bit_rate).toString() + 'k',
'-ac', '1'
);
// Add the required RTP settings and encryption for the stream:
// -payload_type num payload type for the RTP stream. This is negotiated by HomeKit and is usually 110 for AAC-ELD audio.
// -ssrc synchronization source stream identifier. Random number negotiated by HomeKit to identify this stream.
// -f rtp specify that we're using the RTP protocol.
// -srtp_out_suite enc specify the output encryption encoding suites.
// -srtp_out_params params specify the output encoding parameters. This is negotiated by HomeKit.
ffmpegArgs.push(
'-payload_type', request.audio.pt.toString(),
'-ssrc', sessionInfo.audioSSRC.toString(),
'-f', 'rtp',
'-srtp_out_suite', 'AES_CM_128_HMAC_SHA1_80',
'-srtp_out_params', sessionInfo.audioSRTP.toString('base64'),
'srtp://' + sessionInfo.address + ':' + sessionInfo.audioPort.toString() + '?rtcpport=' + sessionInfo.audioPort.toString() +
'&localrtcpport=' + sessionInfo.audioPort.toString() + '&pkt_size=' + audiomtu.toString()
);
}
// Combine everything and start an instance of FFmpeg.
const ffmpeg = new FfmpegProcess(this, request.sessionID, ffmpegArgs,
(sessionInfo.hasLibFdk && this.camera.supportsTwoWayAudio) ? undefined : {
addressVersion: sessionInfo.addressVersion,
port: sessionInfo.videoReturnPort
},
callback);
// Some housekeeping for our FFmpeg and demuxer sessions.
this.ongoingSessions[request.sessionID] = {ffmpeg: [ffmpeg], rtpDemuxer: sessionInfo.rtpDemuxer};
delete this.pendingSessions[request.sessionID];
// If we aren't doing two-way audio, we're done here. For two-way audio...we have some more plumbing to do.
if (!sessionInfo.hasLibFdk || !this.camera.supportsTwoWayAudio) {
return;
}
// Session description protocol message that FFmpeg will share with HomeKit.
// SDP messages tell the other side of the connection what we're expecting to receive.
//
// Parameters are:
// v protocol version - always 0.
// o originator and session identifier.
// s session description.
// c connection information.
// t timestamps for the start and end of the session.
// m media type - audio, adhering to RTP/AVP, payload type 110.
// b bandwidth information - application specific, 24k.
// a=rtpmap payload type 110 corresponds to an MP4 stream.
// a=fmtp for payload type 110, use these format parameters.
// a=crypto crypto suite to use for this session.
const sdpReturnAudio = [
'v=0',
'o=- 0 0 IN ' + sdpIpVersion + ' 127.0.0.1',
's=' + this.camera.name + ' Audio Talkback',
'c=IN ' + sdpIpVersion + ' ' + sessionInfo.address,
't=0 0',
'm=audio ' + sessionInfo.audioIncomingRtpPort.toString() + ' RTP/AVP 110',
'b=AS:24',
'a=rtpmap:110 MPEG4-GENERIC/16000/1',
'a=fmtp:110 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3; config=F8F0212C00BC00',
'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:' + sessionInfo.audioSRTP.toString('base64')
].join('\n');
// Configure the audio portion of the command line, if we have a version of FFmpeg supports libfdk_aac. Options we use are:
//
// -protocol_whitelist set the list of allowed protocols for this ffmpeg session.
// -f sdp specify that our input will be an SDP file.
// -acodec libfdk_aac decode AAC input.
// -i pipe:0 read input from standard input.
// -map 0:a selects the first available audio track from the stream.
// -acodec aac encode to AAC. This is set by Protect.
// -flags +global_header sets the global header in the bitstream.
// -ar samplerate sample rate to use for this audio. This is specified by Protect.
// -b:a bitrate bitrate to use for this audio. This is specified by Protect.
// -ac 1 set the number of audio channels to 1. This is specified by Protect.
// -f adts transmit an ADTS stream.
const ffmpegReturnAudioCmd = [
'-hide_banner',
'-protocol_whitelist', 'pipe,udp,rtp,file,crypto',
'-f', 'sdp',
'-acodec', 'libfdk_aac',
'-i', 'pipe:0',
'-acodec', this.camera.talkbackSettings.typeFmt,
'-flags', '+global_header',
'-ar', this.camera.talkbackSettings.samplingRate.toString(),
'-b:a', '64k',
'-ac', this.camera.talkbackSettings.channels.toString(),
'-f', 'adts',
'udp://' + this.camera.ip + ':' + this.camera.talkbackSettings.bindPort.toString()
];
const ffmpegReturnAudio = new FfmpegProcess(this, request.sessionID, ffmpegReturnAudioCmd);
// Housekeeping for the twoway FFmpeg session.
this.ongoingSessions[request.sessionID].ffmpeg.push(ffmpegReturnAudio);
// Feed the SDP session description to ffmpeg on stdin.
ffmpegReturnAudio.getStdin()?.write(sdpReturnAudio);
ffmpegReturnAudio.getStdin()?.end();
}
// Prepare to launch the video stream.
public async prepareStream(request: PrepareStreamRequest, callback: PrepareStreamCallback): Promise<void> {
// We need to check for AAC support because it's going to determine whether we support audio.
const hasLibFdk = await FfmpegProcess.codecEnabled(this.videoProcessor, 'libfdk_aac');
// Setup our audio plumbing.
const audioIncomingRtcpPort = (await RtpUtils.reservePorts())[0];
const audioIncomingPort = (hasLibFdk && this.camera.supportsTwoWayAudio) ? (await RtpUtils.reservePorts())[0] : -1;
const audioIncomingRtpPort = (hasLibFdk && this.camera.supportsTwoWayAudio) ? (await RtpUtils.reservePorts(2))[0] : -1;
const audioSSRC = this.hap.CameraController.generateSynchronisationSource();
if (!hasLibFdk) {
this.log.info('%s: Audio support disabled. A version of FFmpeg that is compiled with fdk_aac support is required to support audio.', this.camera.name);
}
// Setup the RTP demuxer for two-way audio scenarios.
const rtpDemuxer = (hasLibFdk && this.camera.supportsTwoWayAudio) ?
new RtpDemuxer(this, request.addressVersion, audioIncomingPort, audioIncomingRtcpPort, audioIncomingRtpPort) : null;
// Setup our video plumbing.
const videoReturnPort = (await RtpUtils.reservePorts())[0];
const videoSSRC = this.hap.CameraController.generateSynchronisationSource();
const sessionInfo: SessionInfo = {
address: request.targetAddress,
addressVersion: request.addressVersion,
audioCryptoSuite: request.audio.srtpCryptoSuite,
audioIncomingRtcpPort: audioIncomingRtcpPort,
audioIncomingRtpPort: audioIncomingRtpPort,
audioPort: request.audio.port,
audioSRTP: Buffer.concat([request.audio.srtp_key, request.audio.srtp_salt]),
audioSSRC: audioSSRC,
hasLibFdk: hasLibFdk,
rtpDemuxer: rtpDemuxer,
videoCryptoSuite: request.video.srtpCryptoSuite,
videoPort: request.video.port,
videoReturnPort: videoReturnPort,
videoSRTP: Buffer.concat([request.video.srtp_key, request.video.srtp_salt]),
videoSSRC: videoSSRC
};
// Prepare the response stream. Here's where we figure out if we're doing two-way audio or not. For two-way audio,
// we need to use a demuxer to separate RTP and RTCP packets. For traditional video/audio streaming, we want to keep
// it simple and don't use a demuxer.
const response: PrepareStreamResponse = {
audio: {
port: (hasLibFdk && this.camera.supportsTwoWayAudio) ? audioIncomingPort : audioIncomingRtcpPort,
srtp_key: request.audio.srtp_key,
srtp_salt: request.audio.srtp_salt,
ssrc: audioSSRC
},
video: {
port: videoReturnPort,
srtp_key: request.video.srtp_key,
srtp_salt: request.video.srtp_salt,
ssrc: videoSSRC
}
};
// Add it to the pending session queue so we're ready to start when we're called upon.
this.pendingSessions[request.sessionID] = sessionInfo;
callback(undefined, response);
}
// Close a video stream.
public stopStream(sessionId: string): void {
try {
// Stop any FFmpeg instances we have running.
if (this.ongoingSessions[sessionId]) {
for (const ffmpegProcess of this.ongoingSessions[sessionId].ffmpeg) {
ffmpegProcess.stop();
}
}
// Close the demuxer, if we have one.
this.ongoingSessions[sessionId]?.rtpDemuxer?.close();
// Delete the entries.
delete this.pendingSessions[sessionId];
delete this.ongoingSessions[sessionId];
// Inform the user.
this.log.info('%s: Stopped video streaming session.', this.camera.name);
} catch (error) {
this.log.error('%s: Error occurred while ending the FFmpeg video processes: %s.', this.camera.name, error);
}
}
// Shutdown all our video streams.
public shutdown(): void {
for (const session of Object.keys(this.ongoingSessions)) {
this.stopStream(session);
}
}
} | the_stack |
import { message } from 'antd';
import _ from 'lodash';
import { parsePage, parsePageInServer } from '@foxpage/foxpage-js-sdk';
import { Page, RelationInfo, RenderAppInfo } from '@foxpage/foxpage-types';
import { searchVariable } from '@/apis/group/application/variable';
import { REACT_COMPONENT_TYPE, WRAPPER_COMPONENT_NAME } from '@/constants/build';
import { BLANK_NODE } from '@/pages/builder/constant';
import { getBusinessI18n } from '@/pages/locale';
import { Application } from '@/types/application';
import { ConditionContentItem } from '@/types/application/condition';
import { FuncContentItem } from '@/types/application/function';
import VariableType, { VariableContent } from '@/types/application/variable';
import {
ComponentSourceMapType,
ComponentStaticSaveParams,
ComponentStructure,
ComponentType,
DslContent,
DslError,
DslType,
Extension,
RelationType,
} from '@/types/builder';
import shortId from '@/utils/short-id';
const tplReplaceReg = /\{|}|/g;
export const generateNodeId = () => {
return `stru_${shortId(15)}`;
};
const generateCopyComponent = (tree: Array<ComponentStructure>, parentId: string) => {
tree.forEach((treeItem: ComponentStructure, _index: number) => {
const id = generateNodeId();
treeItem.id = id;
treeItem.parentId = parentId;
treeItem.wrapper = treeItem.wrapper ? parentId : undefined;
if (!treeItem.extension) {
treeItem.extension = {};
}
treeItem.extension.parentId = parentId;
// delete extendId
delete treeItem.extension?.extendId;
if (treeItem.children && treeItem.children.length > 0) {
generateCopyComponent(treeItem.children, id);
}
});
return tree;
};
const getRenderStructure = (list: Array<ComponentStructure>, parentId?: string) => {
return list.filter((item: ComponentStructure) => {
if (item.parentId === parentId) {
item.children = getRenderStructure(list, item.id);
return true;
}
return false;
});
};
const generateComponentList = (
list: Array<ComponentStructure>,
tree: Array<ComponentStructure>,
parentId?: string,
) => {
tree?.forEach((treeItem: ComponentStructure, index: number) => {
treeItem.position = index;
treeItem.parentId = parentId;
if (treeItem.children && treeItem.children.length > 0) {
generateComponentList(list, treeItem.children, treeItem.id);
}
if (treeItem.name) {
list.push(treeItem);
}
});
};
/**
* generate the extension data
* @param parentId parent ID
* @param sort position
* @param extendId extend id
* @returns extension data
*/
const extensionCreator = (parentId?: string, sort?: number, extendId?: string) => {
const extension: Extension = {};
if (parentId || parentId === '') {
extension.parentId = parentId;
}
if (sort) {
extension.sort = sort;
}
if (extendId) {
extension.extendId = extendId;
}
return extension;
};
export type StructureNodeInitOptions = Partial<
Pick<
ComponentStructure,
'label' | 'parentId' | 'position' | 'props' | 'relation' | 'children' | 'useStyleEditor'
>
>;
/**
* structure node creator
* @param id node id
* @param name node name
* @param options options
* @returns new node
*/
const initStructureNode = (id: string, name: string, options: StructureNodeInitOptions = {}) => {
return {
id,
label: options.label || name,
name,
type: REACT_COMPONENT_TYPE,
props: options.props || {},
parentId: options.parentId || '',
wrapper: options.useStyleEditor ? options.parentId || '' : '',
children: options.children || [],
relation: options.relation || {},
extension: extensionCreator(options.parentId, options.position),
} as ComponentStructure;
};
const newWrapperComponent = (
registeredComponent: ComponentType[],
componentName: string,
parentId?: string,
): ComponentStructure => {
const component = registeredComponent.find((item: any) => item.name === componentName) || {};
const componentId = generateNodeId();
if (component.useStyleEditor) {
const wrapperId = generateNodeId();
const child = initStructureNode(componentId, componentName, { parentId: wrapperId });
return initStructureNode(wrapperId, WRAPPER_COMPONENT_NAME, {
parentId,
children: [child],
useStyleEditor: true,
});
} else {
return initStructureNode(componentId, componentName, { parentId });
}
};
const getPosition = (componentId: string, tree: ComponentStructure[]): number => {
let index = 0;
for (let i = 0; i < tree.length; i++) {
const treeItem = tree[i];
if (treeItem.id === componentId) {
index = i;
break;
} else if (treeItem.children && treeItem.children.length > 0) {
index = getPosition(componentId, treeItem.children);
}
}
return index;
};
const addDsl = (
dsl: ComponentStructure,
tree: ComponentStructure[],
position: number,
versionType: string,
parentId?: string,
) => {
if (!parentId || parentId === '') {
tree.splice(position, 0, dsl);
return;
}
if (tree.length > 0 && tree[0].parentId === parentId) {
tree.splice(position, 0, dsl);
return;
}
for (let i = 0; i < tree.length; i++) {
const treeItem = tree[i];
if (tree[i].id === parentId && treeItem.children) {
// append at last
const pos = position === -1 ? treeItem.children.length : position;
treeItem.children.splice(pos, 0, dsl);
return;
} else if (treeItem.children && treeItem.children.length > 0) {
addDsl(dsl, treeItem.children, position, versionType, parentId);
}
}
};
const changeDsl = (dsl: ComponentStructure, tree: ComponentStructure[]) => {
for (let i = tree.length - 1; i > -1; i--) {
const treeItem = tree[i];
if (treeItem.id === dsl.id) {
tree[i] = dsl;
return;
} else if (treeItem.children && treeItem.children.length > 0) {
changeDsl(dsl, treeItem.children);
}
}
};
const deleteDsl = (dsl: ComponentStructure, tree: ComponentStructure[]): ComponentStructure => {
let deleteItem;
for (let i = tree.length - 1; i > -1; i--) {
const treeItem = tree[i];
if (treeItem.id === dsl.id) {
deleteItem = _.cloneDeep(treeItem);
tree.splice(i, 1);
break;
} else if (treeItem.children && treeItem.children.length > 0 && !deleteItem) {
deleteItem = deleteDsl(dsl, treeItem.children);
}
}
return deleteItem;
};
const updateDsl = (version: DslType, params: ComponentStaticSaveParams, versionType: string) => {
switch (params.type) {
case 'add':
if (!params.parentId && !version.content.schemas) {
version.content.schemas = [params.content];
version.content.relation = {};
} else {
addDsl(params.content, version.content.schemas, params.position || 0, versionType, params.parentId);
}
break;
case 'update':
changeDsl(params.content, version.content.schemas);
break;
case 'delete':
deleteDsl(params.content, version.content.schemas);
break;
case 'move':
const deleteItem = deleteDsl(params.content, version.content.schemas);
if (deleteItem) {
deleteItem.parentId = params.parentId;
// deal extension parentId
if (!deleteItem.extension) {
deleteItem.extension = {};
}
deleteItem.extension.parentId = params.parentId;
addDsl(deleteItem, version.content.schemas, params.position || 0, versionType, params.parentId);
} else {
console.log(params.content, version);
}
break;
}
return version;
};
const mergeDsl = async (
application: Application,
page: DslContent,
templates: ComponentStructure[],
variables: VariableType[],
conditions: ConditionContentItem[],
functions: FuncContentItem[],
locale: string,
) => {
const appInfo = {
appId: application.id,
slug: application.slug,
configs: {},
} as RenderAppInfo;
const relationInfo = {
templates, // Template[]
variables, // Variable[]
conditions, // Condition[]
functions, //FPFunction[]
};
const {
builder: { parsePageFailed },
} = getBusinessI18n();
try {
const host = application.host[0] || '';
if (!host) {
throw new Error('no host');
}
// TODO 类型声明文件后期三端统一
const result = (await parsePageInServer(page as Page, {
host: `${host}/${application.slug}`,
appInfo,
relationInfo: (relationInfo as unknown) as RelationInfo,
locale,
})) as Record<string, any>;
if (result.status === 200) {
if (result.data.status) {
return { page: { ...page, schemas: result.data.result.parsedPage } };
} else {
message.error(parsePageFailed);
console.error(result.data.result);
return { page: { ...page, schemas: [] } };
}
}
return {};
} catch (e) {
return parsePage(page as Page, {
appInfo,
relationInfo: (relationInfo as unknown) as RelationInfo,
}) as unknown as { result: { parsedPage: DslContent }; status: boolean };
}
};
const setComponentSource = (component: ComponentStructure, componentSourceMap: ComponentSourceMapType) => {
if (!component || !component.name) {
return;
}
const source =
(component.version === '' || !component.version
? componentSourceMap[component.name]
: componentSourceMap[`${component.name}@${component.version}`]) || {};
component.resource = source.resource;
component.schema = source.schema;
component.meta = source.meta;
component.useStyleEditor = source.useStyleEditor;
component.enableChildren = source.enableChildren;
};
const setSourceToDsl = (
dsl: ComponentStructure[],
componentSourceMap: ComponentSourceMapType,
pageComponentList: ComponentStructure[],
) => {
dsl?.forEach((component: ComponentStructure) => {
setComponentSource(component, componentSourceMap);
if (!pageComponentList?.find((item) => item.id === component.id)) {
component.belongTemplate = true;
}
if (component.children && component.children.length > 0) {
setSourceToDsl(component.children, componentSourceMap, pageComponentList);
}
});
};
const setWrapperToDsl = (dsl: ComponentStructure[]) => {
dsl?.forEach((component: ComponentStructure) => {
if (component.name === WRAPPER_COMPONENT_NAME && component?.children?.length > 0) {
component.children[0].wrapper = component.id;
}
if (component.children && component.children.length > 0) {
setWrapperToDsl(component.children);
}
});
};
const getRelationFromProps = (propsString: string): RelationType => {
if (!propsString) {
return {};
}
const reg = /\{\{.*?(?=(\}\}))/g;
const matchArray = propsString.match(reg);
if (!matchArray) {
return {};
} else {
const relation: RelationType = {};
const variablePaths = matchArray
.map((item: string) => item.replaceAll(/\{\{/g, ''))
.filter((item) => !!item);
variablePaths.forEach((path: string) => {
const array = path.split(':');
if (array.length > 0 && !array[0].startsWith('__')) {
relation[path] = { type: 'variable', name: array[0], id: '' };
}
});
return relation;
}
};
const updateRelation = (oldRelation: RelationType, relation: RelationType) => {
return { ...oldRelation, ...relation };
};
const deleteDslSource = (dsl: ComponentStructure[]) => {
dsl.forEach((component) => {
delete component.meta;
delete component.resource;
delete component.schema;
delete component.belongTemplate;
delete component.position;
delete component.parentId;
delete component.useStyleEditor;
delete component.enableChildren;
delete component.wrapper;
if (component.children && component.children.length > 0) {
deleteDslSource(component.children);
}
});
};
// TODO 对于过度状态的变量保存需要优化
const searchVariableRelation = async (params: {
applicationId: string;
folderId?: string;
props: unknown;
oldRelation: RelationType;
}): Promise<{
relation: RelationType;
variables: VariableContent[];
functions: FuncContentItem[];
hasError: boolean;
}> => {
const {
variable: { notExist },
} = getBusinessI18n();
const { applicationId, folderId, props, oldRelation } = params;
const relation: RelationType = getRelationFromProps(JSON.stringify(props || {}));
const variableSearches: string[] = [];
const existRelations: RelationType = {};
for (const item in relation) {
if (!(item in oldRelation) || !oldRelation[item].id) {
variableSearches.push(relation[item].name || '');
} else {
existRelations[item] = oldRelation[item];
delete relation[item];
}
}
const variables: VariableContent[] = [];
const functions: FuncContentItem[] = [];
const result = { relation: { ...existRelations, ...relation }, variables, functions, hasError: false };
if (variableSearches.length > 0) {
const searchRes = await searchVariable({ applicationId, id: folderId, names: variableSearches });
if (searchRes.data && searchRes.code === 200) {
for (const item in relation) {
const relationItem = searchRes.data.find(
(variable: VariableType) => relation[item].name === variable.name,
);
if (relationItem) {
result.variables.push(relationItem.content);
const itemRelations = relationItem.relations;
if (itemRelations?.variables) {
result.variables = result.variables.concat(itemRelations.variables);
}
if (itemRelations?.functions) {
result.functions = result.functions.concat(itemRelations.functions);
}
relation[item].id = relationItem.content.id;
delete relation[item].name;
} else {
delete relation[item];
}
}
}
}
for (const item in result.relation) {
if (!result.relation[item].id) {
message.error(notExist.replace('${name}', item));
result.hasError = true;
delete result.relation[item];
}
}
return result;
};
const getPageTemplateId = (version: DslType) => {
const { schemas, relation } = version?.content || {};
if (!schemas || schemas.length === 0 || !relation) {
return undefined;
}
const tpl = (schemas[0]?.directive?.tpl as string) || '';
return relation[tpl.replace(tplReplaceReg, '')]?.id;
};
const getComponentTemplateId = (component: ComponentStructure, relation: RelationType) => {
if (!relation || !component) {
return undefined;
}
const tpl = (component.directive?.tpl as string) || '';
return relation[tpl.replace(tplReplaceReg, '')]?.id;
};
const getDslErrors = (dsl: ComponentStructure[], relation: RelationType) => {
let error: DslError = {};
dsl.forEach((component) => {
const componentRelation: RelationType = getRelationFromProps(JSON.stringify(component.props || {}));
if (componentRelation) {
for (const relationItem in componentRelation) {
const existRelation = relation[relationItem];
if (!existRelation?.id) {
if (error[component.id]) {
error[component.id].push(`Variable(${relationItem}) no exist!`);
} else {
error[component.id] = [`Variable(${relationItem}) no exist!`];
}
}
}
}
if (component.children && component.children.length > 0) {
error = {
...error,
...getDslErrors(component.children, relation),
};
}
});
return error;
};
/**
* ignore the structure node
* @param dsl
* @param options
*/
const filterNode = <T extends ComponentStructure>(dsl: T[], condition?: (item: T) => boolean) => {
function doFilter(list: T[]) {
const result: T[] = [];
list.forEach((item) => {
const status = condition ? condition(item) : false;
if (status) {
let childList: T[] = [];
if (item.children?.length) {
childList = doFilter(item.children as T[]);
}
result.push(Object.assign({}, item, { children: childList }));
}
});
return result;
}
return doFilter(dsl);
};
/**
* ignore blank node
* @param dsl
* @returns
*/
const ignoreNodeByBlankNode = (dsl: ComponentStructure[]) => {
return filterNode(dsl, (node: ComponentStructure) => node.name !== BLANK_NODE);
};
export {
deleteDslSource,
filterNode,
generateComponentList,
generateCopyComponent,
getComponentTemplateId,
getDslErrors,
getPageTemplateId,
getPosition,
getRelationFromProps,
getRenderStructure,
ignoreNodeByBlankNode,
mergeDsl,
newWrapperComponent,
searchVariableRelation,
setComponentSource,
setSourceToDsl,
setWrapperToDsl,
updateDsl,
updateRelation,
}; | the_stack |
module android.graphics {
import Pools = android.util.Pools;
import Log = android.util.Log;
import Rect = android.graphics.Rect;
import Color = android.graphics.Color;
import NetImage = androidui.image.NetImage;
/**
* The Canvas class holds the "draw" calls. To draw something, you need
* 4 basic components: A Bitmap to hold the pixels, a Canvas to host
* the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect,
* Path, text, Bitmap), and a paint (to describe the colors and styles for the
* drawing).
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about how to use Canvas, read the
* <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">
* Canvas and Drawables</a> developer guide.</p></div>
*/
export class Canvas {
protected mCanvasElement:HTMLCanvasElement;
private mWidth = 0;
private mHeight = 0;
private _mCanvasContent:CanvasRenderingContext2D;
private _saveCount = 0;
protected mCurrentClip:Rect;
private mClipStateMap = new Map<number, Rect>();
protected static TempMatrixValue = androidui.util.ArrayCreator.newNumberArray(9);
/**
* Flag for drawTextRun indicating left-to-right run direction.
* @hide
*/
static DIRECTION_LTR = 0;
/**
* Flag for drawTextRun indicating right-to-left run direction.
* @hide
*/
static DIRECTION_RTL = 1;
private static sRectPool = new Pools.SynchronizedPool<Rect>(20);
private static obtainRect(copy?:Rect):Rect {
let rect = Canvas.sRectPool.acquire();
if(!rect) rect = new Rect();
if(copy) rect.set(copy);
return rect;
}
private static recycleRect(rect:Rect) {
rect.setEmpty();
Canvas.sRectPool.release(rect);
}
constructor(width:number, height:number) {
this.mWidth = width;
this.mHeight = height;
this.mCurrentClip = Canvas.obtainRect();
this.mCurrentClip.set(0, 0, this.mWidth, this.mHeight);
this.initCanvasImpl();
}
protected initCanvasImpl():void {
this.mCanvasElement = document.createElement("canvas");
this.mCanvasElement.width = this.mWidth;
this.mCanvasElement.height = this.mHeight;
this._mCanvasContent = this.mCanvasElement.getContext("2d");
this.save();//is need?
}
recycle():void {
Canvas.recycleRect(this.mCurrentClip);
for(let rect of this.mClipStateMap.values()) {
Canvas.recycleRect(rect);
}
this.recycleImpl();
}
protected recycleImpl():void {
if(this.mCanvasElement) this.mCanvasElement.width = this.mCanvasElement.height = 0;
}
public getHeight():number {
return this.mHeight;
}
public getWidth():number {
return this.mWidth;
}
public isNativeAccelerated():boolean{
return false;
}
translate(dx:number, dy:number):void {
if(dx==0 && dy==0) return;
if(this.mCurrentClip) this.mCurrentClip.offset(-dx, -dy);
this.translateImpl(dx, dy);
}
protected translateImpl(dx:number, dy:number):void {
this._mCanvasContent.translate(dx, dy);
}
scale(sx:number, sy:number, px?:number, py?:number):void {
//TODO effect mCurrentClip
if (px || py) this.translate(px, py);
this.scaleImpl(sx, sy);
if (px || py) this.translate(-px, -py);
}
protected scaleImpl(sx:number, sy:number):void {
this._mCanvasContent.scale(sx, sy);
}
rotate(degrees:number, px?:number, py?:number):void {
//TODO effect mCurrentClip
if (px || py) this.translate(px, py);
this.rotateImpl(degrees);
if (px || py) this.translate(-px, -py);
}
protected rotateImpl(degrees:number):void {
this._mCanvasContent.rotate(degrees*Math.PI/180);
}
concat(m:android.graphics.Matrix):void {
//TODO effect mCurrentClip
let v = Canvas.TempMatrixValue;
m.getValues(v);
this.concatImpl(v[Matrix.MSCALE_X], v[Matrix.MSKEW_X], v[Matrix.MTRANS_X], v[Matrix.MSKEW_Y], v[Matrix.MSCALE_Y],
v[Matrix.MTRANS_Y], v[Matrix.MPERSP_0], v[Matrix.MPERSP_1], v[Matrix.MPERSP_2]);
}
protected concatImpl(MSCALE_X:number, MSKEW_X:number, MTRANS_X:number, MSKEW_Y:number, MSCALE_Y:number,
MTRANS_Y:number, MPERSP_0:number, MPERSP_1:number, MPERSP_2:number){
this._mCanvasContent.transform(MSCALE_X, -MSKEW_X, -MSKEW_Y, MSCALE_Y, MTRANS_X, MTRANS_Y);
}
drawRGB(r:number, g:number, b:number):void {
this.drawARGB(255, r, g, b);
}
drawARGB(a:number, r:number, g:number, b:number):void {
this.drawARGBImpl(a, r, g, b);
}
drawColor(color:number){
this.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
}
protected drawARGBImpl(a:number, r:number, g:number, b:number):void {
let preStyle = this._mCanvasContent.fillStyle;
this._mCanvasContent.fillStyle = `rgba(${r},${g},${b},${a/255})`;
this._mCanvasContent.fillRect(this.mCurrentClip.left, this.mCurrentClip.top, this.mCurrentClip.width(), this.mCurrentClip.height());
this._mCanvasContent.fillStyle = preStyle;
}
clearColor():void {
this.clearColorImpl();
}
protected clearColorImpl():void {
this._mCanvasContent.clearRect(this.mCurrentClip.left, this.mCurrentClip.top, this.mCurrentClip.width(), this.mCurrentClip.height());
}
save():number {
this.saveImpl();
if(this.mCurrentClip) this.mClipStateMap.set(this._saveCount, Canvas.obtainRect(this.mCurrentClip));
this._saveCount++;
return this._saveCount;
}
protected saveImpl():void {
this._mCanvasContent.save();
}
restore() {
this._saveCount--;
this.restoreImpl();
let savedClip = this.mClipStateMap.get(this._saveCount);
if(savedClip){
this.mClipStateMap.delete(this._saveCount);
this.mCurrentClip.set(savedClip);
Canvas.recycleRect(savedClip);
}
}
protected restoreImpl():void {
this._mCanvasContent.restore();
}
restoreToCount(saveCount:number) {
if (saveCount <= 0) throw Error('saveCount can\'t <= 0');
while (saveCount <= this._saveCount) {
this.restore();
}
}
getSaveCount():number {
return this._saveCount;
}
clipRect(rect:Rect):boolean;
clipRect(left:number, top:number, right:number, bottom:number):boolean;
clipRect(left:number, top:number, right:number, bottom:number, radiusTopLeft:number, radiusTopRight:number, radiusBottomRight:number, radiusBottomLeft:number):boolean;
clipRect(...args):boolean {
let rect = Canvas.obtainRect();
if (args.length === 1) {
rect.set(args[0]);
}else {
let [left=0, t=0, right=0, bottom=0] = args;
rect.set(left, t, right, bottom);
}
if(args.length === 4 || (!args[4] && !args[5] && !args[6] && !args[7])){
this.clipRectImpl(Math.floor(rect.left), Math.floor(rect.top), Math.ceil(rect.width()), Math.ceil(rect.height()));
}else if(args.length===8 && (args[4]!=0 || args[5]!= 0 || args[6]!=0 || args[7]!=0)){
this.clipRoundRectImpl(Math.floor(rect.left), Math.floor(rect.top), Math.ceil(rect.width()), Math.ceil(rect.height()),
args[4], args[5], args[6], args[7]);
}
this.mCurrentClip.intersect(rect);
let r = rect.isEmpty();
Canvas.recycleRect(rect);
return r;
}
protected clipRectImpl(left:number, top:number, width:number, height:number):void {
this._mCanvasContent.beginPath();
this._mCanvasContent.rect(left, top, width, height);
this._mCanvasContent.clip();
}
clipRoundRect(r:Rect, radiusTopLeft:number, radiusTopRight:number, radiusBottomRight:number, radiusBottomLeft:number):boolean{
let rect = Canvas.obtainRect(r);
this.clipRoundRectImpl(Math.floor(rect.left), Math.floor(rect.top), Math.ceil(rect.width()), Math.ceil(rect.height()),
radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft);
this.mCurrentClip.intersect(rect);
let empty = rect.isEmpty();
Canvas.recycleRect(rect);
return empty;
}
protected clipRoundRectImpl(left:number, top:number, width:number, height:number, radiusTopLeft:number,
radiusTopRight:number, radiusBottomRight:number, radiusBottomLeft:number):void {
this.doRoundRectPath(left, top, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft);
this._mCanvasContent.clip();
}
private doRoundRectPath(left:number, top:number, width:number, height:number, radiusTopLeft:number,
radiusTopRight:number, radiusBottomRight:number, radiusBottomLeft:number):void{
let scale1 = height / (radiusTopLeft + radiusBottomLeft);
let scale2 = height / (radiusTopRight + radiusBottomRight);
let scale3 = width / (radiusTopLeft + radiusTopRight);
let scale4 = width / (radiusBottomLeft + radiusBottomRight);
let scale = Math.min(scale1, scale2, scale3, scale4);
if(scale<1) {
radiusTopLeft *= scale;
radiusTopRight *= scale;
radiusBottomRight *= scale;
radiusBottomLeft *= scale;
}
let ctx = this._mCanvasContent;
ctx.beginPath();
ctx.moveTo(left+radiusTopLeft, top);
ctx.arcTo(left+width, top, left+width, top+radiusTopRight, radiusTopRight);
ctx.arcTo(left+width, top+height, left+width-radiusBottomRight, top+height, radiusBottomRight);
ctx.arcTo(left, top+height, left, top+height-radiusBottomLeft, radiusBottomLeft);
ctx.arcTo(left, top, left+radiusTopLeft, top, radiusTopLeft);
ctx.closePath();
}
getClipBounds(bounds?:Rect):Rect {
if (!this.mCurrentClip) this.mCurrentClip = Canvas.obtainRect();
let rect = bounds || Canvas.obtainRect();
rect.set(this.mCurrentClip);
return rect;
}
quickReject(rect:Rect):boolean;
quickReject(left:number, top:number, right:number, bottom:number):boolean;
quickReject(...args):boolean {
if (!this.mCurrentClip) return false;
if (args.length == 1) {
return !this.mCurrentClip.intersects(<Rect>args[0]);
} else {
let [left=0, t=0, right=0, bottom=0] = args;
return !this.mCurrentClip.intersects(left, t, right, bottom);
}
}
drawCanvas(canvas:Canvas, offsetX=0, offsetY=0):void {
this.drawCanvasImpl(canvas, offsetX, offsetY);
}
protected drawCanvasImpl(canvas:Canvas, offsetX:number, offsetY:number):void {
this._mCanvasContent.drawImage(canvas.mCanvasElement, offsetX, offsetY);
}
drawImage(image:NetImage, srcRect?:Rect, dstRect?:Rect, paint?:Paint):void {
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
this.drawImageImpl(image, srcRect, dstRect);
if(!paintEmpty) this.restoreImpl();
}
protected drawImageImpl(image:NetImage, srcRect?:Rect, dstRect?:Rect):void {
if(!dstRect){
if(!srcRect){
this._mCanvasContent.drawImage(image.browserImage, 0, 0);
}else{
this._mCanvasContent.drawImage(image.browserImage,
srcRect.left, srcRect.top, srcRect.width(), srcRect.height(),
0, 0, srcRect.width(), srcRect.height()
// 0, 0, image.browserImage.width, image.browserImage.height
);
}
}else{
if(dstRect.isEmpty()) return;
if(!srcRect){
this._mCanvasContent.drawImage(image.browserImage, dstRect.left, dstRect.top, dstRect.width(), dstRect.height());
}else{
this._mCanvasContent.drawImage(image.browserImage,
srcRect.left, srcRect.top, srcRect.width(), srcRect.height(),
dstRect.left, dstRect.top, dstRect.width(), dstRect.height()
);
}
}
}
drawRect(rect:Rect, paint:Paint);
drawRect(left:number, top:number, right:number, bottom:number, paint:Paint);
drawRect(...args) {
if (args.length == 2) {
let rect:Rect = args[0];
this.drawRect(rect.left, rect.top, rect.right, rect.bottom, args[1]);
} else {
let [left, top, right, bottom, paint] = args;
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
let style = paint ? paint.getStyle() : Paint.Style.FILL;
this.drawRectImpl(left, top, right-left, bottom-top, style);
if(!paintEmpty) this.restoreImpl();
}
}
protected drawRectImpl(left:number, top:number, width:number, height:number, style:Paint.Style){
switch (style){
case Paint.Style.STROKE:
this._mCanvasContent.strokeRect(left, top, width, height);
break;
case Paint.Style.FILL_AND_STROKE:
this._mCanvasContent.fillRect(left, top, width, height);
this._mCanvasContent.strokeRect(left, top, width, height);
break;
case Paint.Style.FILL:
default :
this._mCanvasContent.fillRect(left, top, width, height);
break;
}
}
private applyFillOrStrokeToContent(style:Paint.Style){
switch (style){
case Paint.Style.STROKE:
this._mCanvasContent.stroke();
break;
case Paint.Style.FILL_AND_STROKE:
this._mCanvasContent.fill();
this._mCanvasContent.stroke();
break;
case Paint.Style.FILL:
default :
this._mCanvasContent.fill();
break;
}
}
/**
* Draw the specified oval using the specified paint. The oval will be
* filled or framed based on the Style in the paint.
*
* @param oval The rectangle bounds of the oval to be drawn
*/
drawOval(oval:RectF, paint:Paint):void {
if (oval == null) {
throw Error(`new NullPointerException()`);
}
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
let style = paint ? paint.getStyle() : Paint.Style.FILL;
this.drawOvalImpl(oval, style);
if(!paintEmpty) this.restoreImpl();
}
protected drawOvalImpl(oval:RectF, style:Paint.Style):void {
let ctx = this._mCanvasContent;
ctx.beginPath();
let cx = oval.centerX();
let cy = oval.centerY();
let rx = oval.width()/2;
let ry = oval.height()/2;
ctx.save();
ctx.translate(cx-rx, cy-ry);
ctx.scale(rx, ry);
ctx.arc(1, 1, 1, 0, 2 * Math.PI, false);
ctx.restore();
this.applyFillOrStrokeToContent(style);
}
/**
* Draw the specified circle using the specified paint. If radius is <= 0,
* then nothing will be drawn. The circle will be filled or framed based
* on the Style in the paint.
*
* @param cx The x-coordinate of the center of the cirle to be drawn
* @param cy The y-coordinate of the center of the cirle to be drawn
* @param radius The radius of the cirle to be drawn
* @param paint The paint used to draw the circle
*/
drawCircle(cx:number, cy:number, radius:number, paint:Paint):void {
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
let style = paint ? paint.getStyle() : Paint.Style.FILL;
this.drawCircleImpl(cx, cy, radius, style);
if(!paintEmpty) this.restoreImpl();
}
protected drawCircleImpl(cx:number, cy:number, radius:number, style:Paint.Style):void {
let ctx = this._mCanvasContent;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
this.applyFillOrStrokeToContent(style);
}
/**
* <p>Draw the specified arc, which will be scaled to fit inside the
* specified oval.</p>
*
* <p>If the start angle is negative or >= 360, the start angle is treated
* as start angle modulo 360.</p>
*
* <p>If the sweep angle is >= 360, then the oval is drawn
* completely. Note that this differs slightly from SkPath::arcTo, which
* treats the sweep angle modulo 360. If the sweep angle is negative,
* the sweep angle is treated as sweep angle modulo 360</p>
*
* <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the
* geometric angle of 0 degrees (3 o'clock on a watch.)</p>
*
* @param oval The bounds of oval used to define the shape and size
* of the arc
* @param startAngle Starting angle (in degrees) where the arc begins
* @param sweepAngle Sweep angle (in degrees) measured clockwise
* @param useCenter If true, include the center of the oval in the arc, and
close it if it is being stroked. This will draw a wedge
* @param paint The paint used to draw the arc
*/
drawArc(oval:RectF, startAngle:number, sweepAngle:number, useCenter:boolean, paint:Paint):void {
if (oval == null) {
throw Error(`new NullPointerException()`);
}
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
let style = paint ? paint.getStyle() : Paint.Style.FILL;
this.drawArcImpl(oval, startAngle, sweepAngle, useCenter, style);
if(!paintEmpty) this.restoreImpl();
}
protected drawArcImpl(oval:RectF, startAngle:number, sweepAngle:number, useCenter:boolean, style:Paint.Style):void {
let ctx = this._mCanvasContent;
ctx.save();
ctx.beginPath();
let cx = oval.centerX();
let cy = oval.centerY();
let rx = oval.width()/2;
let ry = oval.height()/2;
ctx.translate(cx-rx, cy-ry);
ctx.scale(rx, ry);
ctx.arc(1, 1, 1, startAngle / 180 * Math.PI, (sweepAngle+startAngle) / 180 * Math.PI, false);
if(useCenter){
ctx.lineTo(1, 1);
ctx.closePath();
}
ctx.restore();
this.applyFillOrStrokeToContent(style);
}
/**
* Draw the specified round-rect using the specified paint. The roundrect
* will be filled or framed based on the Style in the paint.
*
* @param rect The rectangular bounds of the roundRect to be drawn
* @param rx The x-radius of the oval used to round the corners
* @param ry The y-radius of the oval used to round the corners
* @param paint The paint used to draw the roundRect
*/
drawRoundRect(rect:RectF, radiusTopLeft:number,
radiusTopRight:number, radiusBottomRight:number, radiusBottomLeft:number, paint:Paint):void {
if (rect == null) {
throw Error(`new NullPointerException()`);
}
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
let style = paint ? paint.getStyle() : Paint.Style.FILL;
this.drawRoundRectImpl(rect, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft, style);
if(!paintEmpty) this.restoreImpl();
}
protected drawRoundRectImpl(rect:RectF, radiusTopLeft:number,
radiusTopRight:number, radiusBottomRight:number, radiusBottomLeft:number, style:Paint.Style):void {
this.doRoundRectPath(rect.left, rect.top, rect.width(), rect.height(), radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft);
this.applyFillOrStrokeToContent(style);
}
/**
* Draw the specified path using the specified paint. The path will be
* filled or framed based on the Style in the paint.
*
* @param path The path to be drawn
* @param paint The paint used to draw the path
*/
drawPath(path:Path, paint:Paint):void {
//TODO set path
}
/**
* Draw the text, with origin at (x,y), using the specified paint. The
* origin is interpreted based on the Align setting in the paint.
*
* @param text The text to be drawn
* @param x The x-coordinate of the origin of the text being drawn
* @param y The y-coordinate of the origin of the text being drawn
* @param paint The paint used for the text (e.g. color, size, style)
*/
drawText_count(text:string, index:number, count:number, x:number, y:number, paint:Paint):void {
if ((index | count | (index + count) | (text.length - index - count)) < 0) {
throw Error(`new IndexOutOfBoundsException()`);
}
this.drawText(text.substr(index, count), x, y, paint);
}
/**
* Draw the text, with origin at (x,y), using the specified paint.
* The origin is interpreted based on the Align setting in the paint.
*
* @param text The text to be drawn
* @param start The index of the first character in text to draw
* @param end (end - 1) is the index of the last character in text to draw
* @param x The x-coordinate of the origin of the text being drawn
* @param y The y-coordinate of the origin of the text being drawn
* @param paint The paint used for the text (e.g. color, size, style)
*/
drawText_end(text:string, start:number, end:number, x:number, y:number, paint:Paint):void {
if ((start | end | (end - start) | (text.length - end)) < 0) {
throw Error(`new IndexOutOfBoundsException()`);
}
this.drawText(text.substring(start, end), x, y, paint);
}
/**
* Draw the text, with origin at (x,y), using the specified paint. The
* origin is interpreted based on the Align setting in the paint.
*
* @param text The text to be drawn
* @param x The x-coordinate of the origin of the text being drawn
* @param y The y-coordinate of the origin of the text being drawn
* @param paint The paint used for the text (e.g. color, size, style)
*/
drawText(text:string, x:number, y:number, paint:Paint):void {
let paintEmpty = !paint || paint.isEmpty();
if(!paintEmpty){
this.saveImpl();
paint.applyToCanvas(this);
}
this.drawTextImpl(text, x, y, paint ? paint.getStyle() : null);
if(!paintEmpty) this.restoreImpl();
}
protected drawTextImpl(text:string, x:number, y:number, style:Paint.Style):void {
switch (style){
case Paint.Style.STROKE:
this._mCanvasContent.strokeText(text, x, y);
break;
case Paint.Style.FILL_AND_STROKE:
this._mCanvasContent.strokeText(text, x, y);
this._mCanvasContent.fillText(text, x, y);
break;
case Paint.Style.FILL:
default :
this._mCanvasContent.fillText(text, x, y);
break;
}
}
/**
* Render a run of all LTR or all RTL text, with shaping. This does not run
* bidi on the provided text, but renders it as a uniform right-to-left or
* left-to-right run, as indicated by dir. Alignment of the text is as
* determined by the Paint's TextAlign value.
*
* @param text the text to render
* @param index the start of the text to render
* @param count the count of chars to render
* @param contextIndex the start of the context for shaping. Must be
* no greater than index.
* @param contextCount the number of characters in the context for shaping.
* ContexIndex + contextCount must be no less than index
* + count.
* @param x the x position at which to draw the text
* @param y the y position at which to draw the text
* @param dir the run direction, either {@link #DIRECTION_LTR} or
* {@link #DIRECTION_RTL}.
* @param paint the paint
* @hide
*/
drawTextRun_count(text:string, index:number, count:number, contextIndex:number, contextCount:number, x:number, y:number, dir:number, paint:Paint):void {
//if (text == null) {
// throw Error(`new NullPointerException("text is null")`);
//}
//if (paint == null) {
// throw Error(`new NullPointerException("paint is null")`);
//}
//if ((index | count | text.length - index - count) < 0) {
// throw Error(`new IndexOutOfBoundsException()`);
//}
//if (dir != Canvas.DIRECTION_LTR && dir != Canvas.DIRECTION_RTL) {
// throw Error(`new IllegalArgumentException("unknown dir: " + dir)`);
//}
this.drawText_count(text, index, count, x, y, paint);
}
/**
* Render a run of all LTR or all RTL text, with shaping. This does not run
* bidi on the provided text, but renders it as a uniform right-to-left or
* left-to-right run, as indicated by dir. Alignment of the text is as
* determined by the Paint's TextAlign value.
*
* @param text the text to render
* @param start the start of the text to render. Data before this position
* can be used for shaping context.
* @param end the end of the text to render. Data at or after this
* position can be used for shaping context.
* @param x the x position at which to draw the text
* @param y the y position at which to draw the text
* @param dir the run direction, either 0 for LTR or 1 for RTL.
* @param paint the paint
* @hide
*/
drawTextRun_end(text:string, start:number, end:number, contextStart:number, contextEnd:number, x:number, y:number, dir:number, paint:Paint):void {
//if (text == null) {
// throw Error(`new NullPointerException("text is null")`);
//}
//if (paint == null) {
// throw Error(`new NullPointerException("paint is null")`);
//}
//if ((start | end | end - start | text.length() - end) < 0) {
// throw Error(`new IndexOutOfBoundsException()`);
//}
//let flags:number = dir == 0 ? 0 : 1;
//if (text instanceof string || text instanceof SpannedString || text instanceof SpannableString) {
// Canvas.native_drawTextRun(this.mNativeCanvas, text.toString(), start, end, contextStart, contextEnd, x, y, flags, paint.mNativePaint);
//} else if (text instanceof GraphicsOperations) {
// (<GraphicsOperations> text).drawTextRun(this, start, end, contextStart, contextEnd, x, y, flags, paint);
//} else {
// let contextLen:number = contextEnd - contextStart;
// let len:number = end - start;
// let buf:char[] = TemporaryBuffer.obtain(contextLen);
// TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
// Canvas.native_drawTextRun(this.mNativeCanvas, buf, start - contextStart, len, 0, contextLen, x, y, flags, paint.mNativePaint);
// TemporaryBuffer.recycle(buf);
//}
this.drawText_end(text, start, end, x, y, paint);
}
static measureText(text:string, textSize:number):number {
if(textSize==null || textSize===0) return 0;
return Canvas.measureTextImpl(text, textSize);
}
private static _measureTextContext:CanvasRenderingContext2D = document.createElement('canvas').getContext('2d');
private static _measureCacheTextSize = 1000;
private static _static = (()=>{
Canvas._measureTextContext.font = Canvas._measureCacheTextSize + 'px ' + Canvas.getMeasureTextFontFamily();
})();
private static _measureCacheMap = new Map<number, number>();//<char, width>;
protected static measureTextImpl(text:string, textSize:number):number {
let width = 0;
for(let i=0,length=text.length; i<length; i++){
let c = text.charCodeAt(i);
let cWidth:number = Canvas._measureCacheMap.get(c);
if(cWidth == null){
cWidth = Canvas._measureTextContext.measureText(text[i]).width;
Canvas._measureCacheMap.set(c, cWidth);
}
width += (cWidth * textSize / Canvas._measureCacheTextSize);
}
return width;
}
protected static getMeasureTextFontFamily():string {
let fontParts = Canvas._measureTextContext.font.split(' ');
return fontParts[fontParts.length - 1];
}
setColor(color:number, style?:Paint.Style):void {
if(color != null){
this.setColorImpl(color, style);
}
}
protected setColorImpl(color:number, style?:Paint.Style):void {
let colorS = Color.toRGBAFunc(color);
switch (style){
case Paint.Style.STROKE:
if(Color.parseColor(this._mCanvasContent.strokeStyle+'', 0)!=color){
this._mCanvasContent.strokeStyle = colorS;
}
break;
case Paint.Style.FILL:
if(Color.parseColor(this._mCanvasContent.fillStyle+'', 0)!=color){
this._mCanvasContent.fillStyle = colorS;
}
break;
default :
case Paint.Style.FILL_AND_STROKE:
if(Color.parseColor(this._mCanvasContent.fillStyle+'', 0)!=color){
this._mCanvasContent.fillStyle = colorS;
}
if(Color.parseColor(this._mCanvasContent.strokeStyle+'', 0)!=color){
this._mCanvasContent.strokeStyle = colorS;
}
break;
}
}
/**
* @param alpha [0, 1]
*/
multiplyGlobalAlpha(alpha:number):void {
if(typeof alpha === 'number' && alpha < 1){
this.multiplyGlobalAlphaImpl(alpha);
}
}
protected multiplyGlobalAlphaImpl(alpha:number):void {
this._mCanvasContent.globalAlpha *= alpha;
}
/**
* @param alpha [0, 1]
*/
setGlobalAlpha(alpha:number):void {
if(typeof alpha === 'number'){
this.setGlobalAlphaImpl(alpha);
}
}
protected setGlobalAlphaImpl(alpha:number):void {
this._mCanvasContent.globalAlpha = alpha;
}
setTextAlign(align:string):void {
if(align!=null) this.setTextAlignImpl(align);
}
protected setTextAlignImpl(align:string):void {
this._mCanvasContent.textAlign = align;
}
setLineWidth(width:number):void {
if(width!=null) this.setLineWidthImpl(width);
}
protected setLineWidthImpl(width:number):void {
this._mCanvasContent.lineWidth = width;
}
setLineCap(lineCap:string):void {
if(lineCap!=null) this.setLineCapImpl(lineCap);
}
protected setLineCapImpl(lineCap:string):void {
this._mCanvasContent.lineCap = lineCap;
}
setLineJoin(lineJoin:string):void {
if(lineJoin!=null) this.setLineJoinImpl(lineJoin);
}
protected setLineJoinImpl(lineJoin:string):void {
this._mCanvasContent.lineJoin = lineJoin;
}
setShadow(radius:number, dx:number, dy:number, color:number):void {
if(radius>0){
this.setShadowImpl(radius, dx, dy, color);
}
}
protected setShadowImpl(radius:number, dx:number, dy:number, color:number):void {
this._mCanvasContent.shadowBlur = radius;
this._mCanvasContent.shadowOffsetX = dx;
this._mCanvasContent.shadowOffsetY = dy;
this._mCanvasContent.shadowColor = Color.toRGBAFunc(color);
}
setFontSize(size:number):void {
if(size != null){
this.setFontSizeImpl(size);
}
}
protected setFontSizeImpl(size:number):void {
let cFont = this._mCanvasContent.font;
let fontParts = cFont.split(' ');
if(Number.parseFloat(fontParts[fontParts.length-2]) == size) return;
fontParts[fontParts.length-2] = size + 'px';
this._mCanvasContent.font = fontParts.join(' ');
}
setFont(fontName:string):void {
if(fontName!=null){
this.setFontImpl(fontName);
}
}
protected setFontImpl(fontName:string):void {
let cFont = this._mCanvasContent.font;
let fontParts = cFont.split(' ');
fontParts[fontParts.length - 1] = fontName;//font family
let font = fontParts.join(' ');
if(font!=cFont) this._mCanvasContent.font = font;
}
isImageSmoothingEnabled():boolean {
return this.isImageSmoothingEnabledImpl();
}
protected isImageSmoothingEnabledImpl():boolean {
return this._mCanvasContent['imageSmoothingEnabled'] || this._mCanvasContent['webkitImageSmoothingEnabled'];
}
setImageSmoothingEnabled(enable:boolean):void {
this.setImageSmoothingEnabledImpl(enable);
}
protected setImageSmoothingEnabledImpl(enable:boolean):void {
if('imageSmoothingEnabled' in this._mCanvasContent){
this._mCanvasContent['imageSmoothingEnabled'] = enable;
}else if('webkitImageSmoothingEnabled' in this._mCanvasContent){
this._mCanvasContent['webkitImageSmoothingEnabled'] = enable;
}
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.