text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
'use strict';
import * as path from 'path'
import {
IPCMessageReader, IPCMessageWriter,
createConnection, IConnection, TextDocumentSyncKind,
TextDocuments, TextDocument, Diagnostic, DiagnosticSeverity,
InitializeParams, InitializeResult, TextDocumentPositionParams,
CompletionItem, CompletionItemKind, InsertTextFormat,
DocumentFormattingParams, TextDocumentIdentifier, TextEdit,
Hover, MarkedString,
Definition,
Files, FileChangeType
} from 'vscode-languageserver'
import * as fs from 'fs'
import * as sourcekitProtocol from './sourcekites'
export const spawn = require('child_process').spawn
// Create a connection for the server. The connection uses Node's IPC as a transport
let connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process));
// Create a simple text document manager. The text document manager
// supports full document sync only
let documents: TextDocuments = new TextDocuments();
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
let allModulePaths: Map<string, string>;
let allModuleSources: Map<string, Set<string>>;
export function initializeModuleMeta() {
trace('***initializeModuleMeta***')
allModulePaths = new Map()
allModuleSources = new Map()
const shPath = getShellExecPath()
trace('***getShellExecPath: ', shPath)
const sp = spawn(shPath, ["-c",
`cd ${workspaceRoot} && ${swiftDiverBinPath} package describe --type json`,
])
sp.stdout.on('data', (data) => {
if (isTracingOn) {
trace('***swift package describe stdout*** ', '' + data)
}
//TODO more here
const pkgDesc = JSON.parse(data)
for (const m of <Object[]>pkgDesc['modules']) {
const mn = m['name']
const mp = m['path']
const ss = <string[]>m['sources']
const set = new Set()
ss.forEach(f => set.add(path.join(mp, f)))
allModuleSources.set(mn, set)
allModulePaths.set(mn, mp)
}
})
sp.stderr.on('data', (data) => {
if (isTracingOn) {
trace('***swift package describe stderr*** ', '' + data)
}
})
// sp.on('exit', function (code, signal) {
// trace('***swift package describe***', `code: ${code}, signal: ${signal}`)
// })
sp.on('error', function (err) {
trace('***swift package describe error*** ', (<Error>err).message)
if ((<Error>err).message.indexOf("ENOENT") > 0) {
const msg = "The '" + swiftDiverBinPath +
"' command is not available." +
" Please check your swift executable user setting and ensure it is installed.";
trace('***swift executable not found***', msg)
}
throw err//FIXME more friendly prompt
});
}
export function getAllSourcePaths(srcPath: string): string[] {
const sp = path.dirname(srcPath)
for (let [m, p] of allModulePaths) {
if (p === sp) {
let ss = allModuleSources.get(m)
// trace("**getAllDocumentPaths** ", Array.from(ss).join(","))
return Array.from(ss)
}
}
return null//can not find?
}
// After the server has started the client sends an initilize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilites.
export let workspaceRoot: string;
export let isTracingOn: boolean;
connection.onInitialize((params: InitializeParams, cancellationToken): InitializeResult => {
isTracingOn = params.initializationOptions.isLSPServerTracingOn
skProtocolPath = params.initializationOptions.skProtocolProcess
skProtocolProcessAsShellCmd = params.initializationOptions.skProtocolProcessAsShellCmd
trace("-->onInitialize ", `isTracingOn=[${isTracingOn}],
skProtocolProcess=[${skProtocolPath}],skProtocolProcessAsShellCmd=[${skProtocolProcessAsShellCmd}]`)
workspaceRoot = params.rootPath
return {
capabilities: {
// Tell the client that the server works in FULL text document sync mode
textDocumentSync: documents.syncKind,
definitionProvider: true,
hoverProvider: true,
// referencesProvider: false,
// documentSymbolProvider: false,
// signatureHelpProvider: {
// triggerCharacters: ['[', ',']
// },
// We're prividing completions.
completionProvider: {
resolveProvider: false,
triggerCharacters: [
'.', ':', '(', //' ', '<', //TODO
]
},
documentFormattingProvider: true,
documentRangeFormattingProvider: true
}
};
});
// The settings interface describe the server relevant settings part
interface Settings {
swift: any;
}
//external
export let sdeSettings: any;
export let swiftDiverBinPath: string = null;
export let maxBytesAllowedForCodeCompletionResponse: number = 0;
//internal
export let skProtocolPath = null
export let skProtocolProcessAsShellCmd = false
let maxNumProblems = null
let shellPath = null
// The settings have changed. Is send on server activation
// as well.
connection.onDidChangeConfiguration((change) => {
trace("-->onDidChangeConfiguration")
const settings = <Settings>change.settings
sdeSettings = settings.swift;//FIXME configs only accessed via the language id?
//FIXME does LS client support on-the-fly change?
maxNumProblems = sdeSettings.diagnosis.max_num_problems
swiftDiverBinPath = sdeSettings.path.swift_driver_bin
shellPath = sdeSettings.path.shell
trace(`-->onDidChangeConfiguration tracing:
swiftDiverBinPath=[${swiftDiverBinPath}],
shellPath=[${shellPath}]`)
//FIXME reconfigure when configs haved
sourcekitProtocol.initializeSourcekite()
if (!allModuleSources) {//FIXME oneshot?
initializeModuleMeta()
}
// Revalidate any open text documents
documents.all().forEach(validateTextDocument);
});
function validateTextDocument(textDocument: TextDocument): void {
// let diagnostics: Diagnostic[] = [];
// let lines = textDocument.getText().split(/\r?\n/g);
// let problems = 0;
// for (var i = 0; i < lines.length && problems < maxNumProblems; i++) {
// let line = lines[i];
// let index = line.indexOf('typescript');
// if (index >= 0) {
// problems++;
// diagnostics.push({
// severity: DiagnosticSeverity.Warning,
// range: {
// start: { line: i, character: index },
// end: { line: i, character: index + 10 }
// },
// message: `${line.substr(index, 10)} should be spelled TypeScript`,
// source: 'ex'
// });
// }
// }
// Send the computed diagnostics to VSCode.
// connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent((change) => {
validateTextDocument(change.document);
trace('---onDidChangeContent');
});
connection.onDidChangeWatchedFiles((watched) => {
// trace('---','onDidChangeWatchedFiles');
watched.changes.forEach(e => {
let file;
switch (e.type) {
case FileChangeType.Created:
file = fromUriString(e.uri)
for (const [m, p] of allModulePaths) {
if (file.startsWith(m)) {
allModuleSources.get(m).add(file)
}
}
break
case FileChangeType.Deleted:
file = fromUriString(e.uri)
for (const [m, p] of allModulePaths) {
if (file.startsWith(m)) {
allModuleSources.get(m).delete(file)
}
}
break
default:
//do nothing
}
})
});
// This handler provides the initial list of the completion items.
connection.onCompletion(({textDocument, position}): Thenable<CompletionItem[]> => {
const document: TextDocument = documents.get(textDocument.uri)
const srcPath = document.uri.substring(7, document.uri.length)
const srcText: string = document.getText() //NOTE needs on-the-fly buffer
const offset = document.offsetAt(position) //FIXME
return sourcekitProtocol
.codeComplete(srcText, srcPath, offset)
.then(function (completions) {
let items = [];
for (let c of <Array<Object>>completions) {
let item = CompletionItem.create(c["key.description"])
item.kind = toCompletionItemKind(c["key.kind"])
item.detail = `${c["key.modulename"]}.${c["key.name"]}`
item.insertText = createSuggest(c["key.sourcetext"])
item.insertTextFormat = InsertTextFormat.Snippet
items.push(item)
}
return items
}, function (err) {
//FIXME
return err
});
});
/**
* ref: https://github.com/facebook/nuclide/blob/master/pkg/nuclide-swift/lib/sourcekitten/Complete.js#L57
*/
function createSuggest(sourcetext: string): string {
// trace("---createSuggest--- ",sourcetext)
let index = 1
let snp = sourcetext.replace(/<#T##(.+?)#>/g, (m, g) => {
return "${" + (index++) + ":" + g.split('##')[0] + "}"
})
return snp.replace('<#code#>', `\${${index++}}`)
};
//TODO more meanful CompletionItemKinds...
function toCompletionItemKind(keyKind: string): CompletionItemKind {
switch (keyKind) {
case "source.lang.swift.decl.function.free":
case "source.lang.swift.ref.function.free":
return CompletionItemKind.Function;
case "source.lang.swift.decl.function.method.instance":
case "source.lang.swift.ref.function.method.instance":
case "source.lang.swift.decl.function.method.static":
case "source.lang.swift.ref.function.method.static":
return CompletionItemKind.Method;
case "source.lang.swift.decl.function.operator":
case "source.lang.swift.ref.function.operator":
case "source.lang.swift.decl.function.subscript":
case "source.lang.swift.ref.function.subscript":
return CompletionItemKind.Keyword;
case "source.lang.swift.decl.function.constructor":
case "source.lang.swift.ref.function.constructor":
case "source.lang.swift.decl.function.destructor":
case "source.lang.swift.ref.function.destructor":
return CompletionItemKind.Constructor;
case "source.lang.swift.decl.function.accessor.getter":
case "source.lang.swift.ref.function.accessor.getter":
case "source.lang.swift.decl.function.accessor.setter":
case "source.lang.swift.ref.function.accessor.setter":
return CompletionItemKind.Property;
case "source.lang.swift.decl.class":
case "source.lang.swift.ref.class":
case "source.lang.swift.decl.struct":
case "source.lang.swift.ref.struct":
return CompletionItemKind.Class;
case "source.lang.swift.decl.enum":
case "source.lang.swift.ref.enum":
return CompletionItemKind.Enum;
case "source.lang.swift.decl.enumelement":
case "source.lang.swift.ref.enumelement":
return CompletionItemKind.Value;
case "source.lang.swift.decl.protocol":
case "source.lang.swift.ref.protocol":
return CompletionItemKind.Interface;
case "source.lang.swift.decl.typealias":
case "source.lang.swift.ref.typealias":
return CompletionItemKind.Reference;
case "source.lang.swift.decl.var.instance":
case "source.lang.swift.ref.var.instance":
return CompletionItemKind.Field;
case "source.lang.swift.decl.var.global":
case "source.lang.swift.ref.var.global":
case "source.lang.swift.decl.var.static":
case "source.lang.swift.ref.var.static":
case "source.lang.swift.decl.var.local":
case "source.lang.swift.ref.var.local":
return CompletionItemKind.Variable;
case "source.lang.swift.decl.extension.struct":
case "source.lang.swift.decl.extension.class":
return CompletionItemKind.Class;
case "source.lang.swift.decl.extension.enum":
return CompletionItemKind.Enum;
default:
return CompletionItemKind.Text;//FIXME
}
}
// This handler resolve additional information for the item selected in
// the completion list.
// connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
// if (item.data === 1) {
// item.detail = 'TypeScript details',
// item.documentation = 'TypeScript documentation'
// } else if (item.data === 2) {
// item.detail = 'JavaScript details',
// item.documentation = 'JavaScript documentation'
// }
// return item;
// });
connection.onHover(({textDocument, position}): Promise<Hover> => {
const document: TextDocument = documents.get(textDocument.uri);
const srcPath = document.uri.substring(7, document.uri.length);
const srcText: string = document.getText();//NOTE needs on-the-fly buffer
const offset = document.offsetAt(position);//FIXME
return sourcekitProtocol
.cursorInfo(srcText, srcPath, offset)
.then(function (cursorInfo) {
return extractHoverHelp(cursorInfo)
.then(mks => { return { contents: mks } })
}, function (err) {
//FIXME
return err;
});
})
async function extractHoverHelp(cursorInfo: Object): Promise<MarkedString[]> {
//local helper
function extractText(
elementName: string, full_as_xml: string) {
let s = full_as_xml.indexOf(`<${elementName}>`)
let e = full_as_xml.indexOf(`</${elementName}>`)
let rt = full_as_xml.substring(s + elementName.length + 2, e)
return rt
}
//TODO wait vscode to support full html rendering...
//stripe all sub elements
function stripeOutTags(str) {
return str.replace(/(<.[^(><.)]+>)/g, (m, c) => '')
}
const keyKind = cursorInfo['key.kind']
const keyName = cursorInfo['key.name']
if (!keyName) {
return null
}
const full_as_xml = cursorInfo['key.doc.full_as_xml']
const annotated_decl = cursorInfo['key.annotated_decl']
const moduleName = cursorInfo['key.modulename']
const containerTypeUSR = cursorInfo['key.containertypeusr']
let containerType = null
if (containerTypeUSR) {
const res: Array<Object> = await sourcekitProtocol.demangle(containerTypeUSR)
containerType = res ? res.map(t => t["key.name"]).join(",") : null
}
const t = { language: 'markdown', value: keyName }
const snippet = annotated_decl ?
"**Declaration:**\n```swift\n" +
decode(
stripeOutTags(
extractText('Declaration',
full_as_xml ? full_as_xml : annotated_decl))) + "\n```\n"
+ (containerType ? `**Declared In**: ${containerType}\n\n` : '')
+ (moduleName ? `**Module**: ${moduleName}` : '')
: keyName
return [t, snippet];//FIXME clickable keyTypename
}
connection.onDefinition(({textDocument, position}): Promise<Definition> => {
const document: TextDocument = documents.get(textDocument.uri);
const srcPath = document.uri.substring(7, document.uri.length);
const srcText: string = document.getText();//NOTE needs on-the-fly buffer
const offset = document.offsetAt(position);//FIXME
return sourcekitProtocol
.cursorInfo(srcText, srcPath, offset)
.then(function (cursorInfo) {
const filepath = cursorInfo['key.filepath']
if (filepath) {
const offset = cursorInfo['key.offset']
const len = cursorInfo['key.length']
const fileUri = `file://${filepath}`
let document: TextDocument = documents.get(fileUri);//FIXME
//FIXME more here: https://github.com/Microsoft/language-server-protocol/issues/96
if (!document) {//FIXME just make a temp doc to let vscode help us
const content = fs.readFileSync(filepath, "utf8");
document = TextDocument.create(fileUri, "swift", 0, content);
}
return {
uri: fileUri,
range: {
start: document.positionAt(offset),
end: document.positionAt(offset + len)
}
}
} else {
return null
}
}, function (err) {//FIXME
return err;
});
})
connection.onDocumentFormatting(({textDocument, options}): Promise<TextEdit[]> => {
const document: TextDocument = documents.get(textDocument.uri);
const srcPath = fromDocumentUri(document);
const srcText = document.getText();//NOTE here needs on-the-fly buffer
return sourcekitProtocol.editorFormatText(document, srcText, srcPath, 1, document.lineCount);
});
connection.onDocumentRangeFormatting(({textDocument, options, range}): Promise<TextEdit[]> => {
const document: TextDocument = documents.get(textDocument.uri);
const srcPath = fromDocumentUri(document);
const srcText = document.getText();//NOTE here needs on-the-fly buffer
return sourcekitProtocol.editorFormatText(
document,
srcText, srcPath,
range.start.line + 1,
range.end.line + 1);//NOTE format req is 1-based
});
function fromDocumentUri(document: { uri: string; }): string {
// return Files.uriToFilePath(document.uri);
return fromUriString(document.uri)
}
function fromUriString(uri: string): string {
return uri.substring(7, uri.length)
}
/*
connection.onDidOpenTextDocument((params) => {
// A text document got opened in VSCode.
// params.uri uniquely identifies the document. For documents store on disk this is a file URI.
// params.text the initial full content of the document.
connection.console.log(`${params.uri} opened.`);
});
connection.onDidChangeTextDocument((params) => {
// The content of a text document did change in VSCode.
// params.uri uniquely identifies the document.
// params.contentChanges describe the content changes to the document.
connection.console.log(`${params.uri} changed: ${JSON.stringify(params.contentChanges)}`);
});
connection.onDidCloseTextDocument((params) => {
// A text document got closed in VSCode.
// params.uri uniquely identifies the document.
connection.console.log(`${params.uri} closed.`);
});
*/
// Listen on the connection
connection.listen();
//=== helper
const xmlEntities = {
'&': '&',
'"': '"',
'<': '<',
'>': '>'
};
function decode(str) {
return str.replace(/("|<|>|&)/g, (m, c) => xmlEntities[c])
}
//FIX issue#15
export function getShellExecPath() {
return fs.existsSync(shellPath) ? shellPath : "/usr/bin/sh"
}
/**
* NOTE:
* now the SDE only support the convention based build
*
* TODO: to use build yaml?
*/
let argsImportPaths: string[] = null
export function loadArgsImportPaths(): string[] {
if (!argsImportPaths) {
argsImportPaths = []
argsImportPaths.push("-I")
argsImportPaths.push(path.join(workspaceRoot, '.build', 'debug'))
//FIXME system paths can not be available automatically?
// rt += " -I"+"/usr/lib/swift/linux/x86_64"
argsImportPaths.push("-I")
argsImportPaths.push("/usr/lib/swift/pm/")
return argsImportPaths
} else {
return argsImportPaths
}
}
export function trace(prefix: string, msg?: string) {
if (isTracingOn) {
if (msg) {
connection.console.log(prefix + msg)
} else {
connection.console.log(prefix)
}
}
} | the_stack |
import { Vector3 } from "./Vector3";
export const M00 = 0;
export const M01 = 4;
export const M02 = 8;
export const M03 = 12;
export const M10 = 1;
export const M11 = 5;
export const M12 = 9;
export const M13 = 13;
export const M20 = 2;
export const M21 = 6;
export const M22 = 10;
export const M23 = 14;
export const M30 = 3;
export const M31 = 7;
export const M32 = 11;
export const M33 = 15;
export class Matrix4 {
temp: Float32Array = new Float32Array(16);
values: Float32Array = new Float32Array(16);
private static xAxis: Vector3 = null;
private static yAxis: Vector3 = null;
private static zAxis: Vector3 = null;
private static tmpMatrix = new Matrix4();
constructor () {
let v = this.values;
v[M00] = 1;
v[M11] = 1;
v[M22] = 1;
v[M33] = 1;
}
set (values: ArrayLike<number>): Matrix4 {
this.values.set(values);
return this;
}
transpose (): Matrix4 {
let t = this.temp;
let v = this.values;
t[M00] = v[M00];
t[M01] = v[M10];
t[M02] = v[M20];
t[M03] = v[M30];
t[M10] = v[M01];
t[M11] = v[M11];
t[M12] = v[M21];
t[M13] = v[M31];
t[M20] = v[M02];
t[M21] = v[M12];
t[M22] = v[M22];
t[M23] = v[M32];
t[M30] = v[M03];
t[M31] = v[M13];
t[M32] = v[M23];
t[M33] = v[M33];
return this.set(t);
}
identity (): Matrix4 {
let v = this.values;
v[M00] = 1;
v[M01] = 0;
v[M02] = 0;
v[M03] = 0;
v[M10] = 0;
v[M11] = 1;
v[M12] = 0;
v[M13] = 0;
v[M20] = 0;
v[M21] = 0;
v[M22] = 1;
v[M23] = 0;
v[M30] = 0;
v[M31] = 0;
v[M32] = 0;
v[M33] = 1;
return this;
}
invert (): Matrix4 {
let v = this.values;
let t = this.temp;
let l_det = v[M30] * v[M21] * v[M12] * v[M03] - v[M20] * v[M31] * v[M12] * v[M03] - v[M30] * v[M11] * v[M22] * v[M03]
+ v[M10] * v[M31] * v[M22] * v[M03] + v[M20] * v[M11] * v[M32] * v[M03] - v[M10] * v[M21] * v[M32] * v[M03]
- v[M30] * v[M21] * v[M02] * v[M13] + v[M20] * v[M31] * v[M02] * v[M13] + v[M30] * v[M01] * v[M22] * v[M13]
- v[M00] * v[M31] * v[M22] * v[M13] - v[M20] * v[M01] * v[M32] * v[M13] + v[M00] * v[M21] * v[M32] * v[M13]
+ v[M30] * v[M11] * v[M02] * v[M23] - v[M10] * v[M31] * v[M02] * v[M23] - v[M30] * v[M01] * v[M12] * v[M23]
+ v[M00] * v[M31] * v[M12] * v[M23] + v[M10] * v[M01] * v[M32] * v[M23] - v[M00] * v[M11] * v[M32] * v[M23]
- v[M20] * v[M11] * v[M02] * v[M33] + v[M10] * v[M21] * v[M02] * v[M33] + v[M20] * v[M01] * v[M12] * v[M33]
- v[M00] * v[M21] * v[M12] * v[M33] - v[M10] * v[M01] * v[M22] * v[M33] + v[M00] * v[M11] * v[M22] * v[M33];
if (l_det == 0) throw new Error("non-invertible matrix");
let inv_det = 1.0 / l_det;
t[M00] = v[M12] * v[M23] * v[M31] - v[M13] * v[M22] * v[M31] + v[M13] * v[M21] * v[M32]
- v[M11] * v[M23] * v[M32] - v[M12] * v[M21] * v[M33] + v[M11] * v[M22] * v[M33];
t[M01] = v[M03] * v[M22] * v[M31] - v[M02] * v[M23] * v[M31] - v[M03] * v[M21] * v[M32]
+ v[M01] * v[M23] * v[M32] + v[M02] * v[M21] * v[M33] - v[M01] * v[M22] * v[M33];
t[M02] = v[M02] * v[M13] * v[M31] - v[M03] * v[M12] * v[M31] + v[M03] * v[M11] * v[M32]
- v[M01] * v[M13] * v[M32] - v[M02] * v[M11] * v[M33] + v[M01] * v[M12] * v[M33];
t[M03] = v[M03] * v[M12] * v[M21] - v[M02] * v[M13] * v[M21] - v[M03] * v[M11] * v[M22]
+ v[M01] * v[M13] * v[M22] + v[M02] * v[M11] * v[M23] - v[M01] * v[M12] * v[M23];
t[M10] = v[M13] * v[M22] * v[M30] - v[M12] * v[M23] * v[M30] - v[M13] * v[M20] * v[M32]
+ v[M10] * v[M23] * v[M32] + v[M12] * v[M20] * v[M33] - v[M10] * v[M22] * v[M33];
t[M11] = v[M02] * v[M23] * v[M30] - v[M03] * v[M22] * v[M30] + v[M03] * v[M20] * v[M32]
- v[M00] * v[M23] * v[M32] - v[M02] * v[M20] * v[M33] + v[M00] * v[M22] * v[M33];
t[M12] = v[M03] * v[M12] * v[M30] - v[M02] * v[M13] * v[M30] - v[M03] * v[M10] * v[M32]
+ v[M00] * v[M13] * v[M32] + v[M02] * v[M10] * v[M33] - v[M00] * v[M12] * v[M33];
t[M13] = v[M02] * v[M13] * v[M20] - v[M03] * v[M12] * v[M20] + v[M03] * v[M10] * v[M22]
- v[M00] * v[M13] * v[M22] - v[M02] * v[M10] * v[M23] + v[M00] * v[M12] * v[M23];
t[M20] = v[M11] * v[M23] * v[M30] - v[M13] * v[M21] * v[M30] + v[M13] * v[M20] * v[M31]
- v[M10] * v[M23] * v[M31] - v[M11] * v[M20] * v[M33] + v[M10] * v[M21] * v[M33];
t[M21] = v[M03] * v[M21] * v[M30] - v[M01] * v[M23] * v[M30] - v[M03] * v[M20] * v[M31]
+ v[M00] * v[M23] * v[M31] + v[M01] * v[M20] * v[M33] - v[M00] * v[M21] * v[M33];
t[M22] = v[M01] * v[M13] * v[M30] - v[M03] * v[M11] * v[M30] + v[M03] * v[M10] * v[M31]
- v[M00] * v[M13] * v[M31] - v[M01] * v[M10] * v[M33] + v[M00] * v[M11] * v[M33];
t[M23] = v[M03] * v[M11] * v[M20] - v[M01] * v[M13] * v[M20] - v[M03] * v[M10] * v[M21]
+ v[M00] * v[M13] * v[M21] + v[M01] * v[M10] * v[M23] - v[M00] * v[M11] * v[M23];
t[M30] = v[M12] * v[M21] * v[M30] - v[M11] * v[M22] * v[M30] - v[M12] * v[M20] * v[M31]
+ v[M10] * v[M22] * v[M31] + v[M11] * v[M20] * v[M32] - v[M10] * v[M21] * v[M32];
t[M31] = v[M01] * v[M22] * v[M30] - v[M02] * v[M21] * v[M30] + v[M02] * v[M20] * v[M31]
- v[M00] * v[M22] * v[M31] - v[M01] * v[M20] * v[M32] + v[M00] * v[M21] * v[M32];
t[M32] = v[M02] * v[M11] * v[M30] - v[M01] * v[M12] * v[M30] - v[M02] * v[M10] * v[M31]
+ v[M00] * v[M12] * v[M31] + v[M01] * v[M10] * v[M32] - v[M00] * v[M11] * v[M32];
t[M33] = v[M01] * v[M12] * v[M20] - v[M02] * v[M11] * v[M20] + v[M02] * v[M10] * v[M21]
- v[M00] * v[M12] * v[M21] - v[M01] * v[M10] * v[M22] + v[M00] * v[M11] * v[M22];
v[M00] = t[M00] * inv_det;
v[M01] = t[M01] * inv_det;
v[M02] = t[M02] * inv_det;
v[M03] = t[M03] * inv_det;
v[M10] = t[M10] * inv_det;
v[M11] = t[M11] * inv_det;
v[M12] = t[M12] * inv_det;
v[M13] = t[M13] * inv_det;
v[M20] = t[M20] * inv_det;
v[M21] = t[M21] * inv_det;
v[M22] = t[M22] * inv_det;
v[M23] = t[M23] * inv_det;
v[M30] = t[M30] * inv_det;
v[M31] = t[M31] * inv_det;
v[M32] = t[M32] * inv_det;
v[M33] = t[M33] * inv_det;
return this;
}
determinant (): number {
let v = this.values;
return v[M30] * v[M21] * v[M12] * v[M03] - v[M20] * v[M31] * v[M12] * v[M03] - v[M30] * v[M11] * v[M22] * v[M03]
+ v[M10] * v[M31] * v[M22] * v[M03] + v[M20] * v[M11] * v[M32] * v[M03] - v[M10] * v[M21] * v[M32] * v[M03]
- v[M30] * v[M21] * v[M02] * v[M13] + v[M20] * v[M31] * v[M02] * v[M13] + v[M30] * v[M01] * v[M22] * v[M13]
- v[M00] * v[M31] * v[M22] * v[M13] - v[M20] * v[M01] * v[M32] * v[M13] + v[M00] * v[M21] * v[M32] * v[M13]
+ v[M30] * v[M11] * v[M02] * v[M23] - v[M10] * v[M31] * v[M02] * v[M23] - v[M30] * v[M01] * v[M12] * v[M23]
+ v[M00] * v[M31] * v[M12] * v[M23] + v[M10] * v[M01] * v[M32] * v[M23] - v[M00] * v[M11] * v[M32] * v[M23]
- v[M20] * v[M11] * v[M02] * v[M33] + v[M10] * v[M21] * v[M02] * v[M33] + v[M20] * v[M01] * v[M12] * v[M33]
- v[M00] * v[M21] * v[M12] * v[M33] - v[M10] * v[M01] * v[M22] * v[M33] + v[M00] * v[M11] * v[M22] * v[M33];
}
translate (x: number, y: number, z: number): Matrix4 {
let v = this.values;
v[M03] += x;
v[M13] += y;
v[M23] += z;
return this;
}
copy (): Matrix4 {
return new Matrix4().set(this.values);
}
projection (near: number, far: number, fovy: number, aspectRatio: number): Matrix4 {
this.identity();
let l_fd = (1.0 / Math.tan((fovy * (Math.PI / 180)) / 2.0));
let l_a1 = (far + near) / (near - far);
let l_a2 = (2 * far * near) / (near - far);
let v = this.values;
v[M00] = l_fd / aspectRatio;
v[M10] = 0;
v[M20] = 0;
v[M30] = 0;
v[M01] = 0;
v[M11] = l_fd;
v[M21] = 0;
v[M31] = 0;
v[M02] = 0;
v[M12] = 0;
v[M22] = l_a1;
v[M32] = -1;
v[M03] = 0;
v[M13] = 0;
v[M23] = l_a2;
v[M33] = 0;
return this;
}
ortho2d (x: number, y: number, width: number, height: number): Matrix4 {
return this.ortho(x, x + width, y, y + height, 0, 1);
}
ortho (left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4 {
this.identity();
let x_orth = 2 / (right - left);
let y_orth = 2 / (top - bottom);
let z_orth = -2 / (far - near);
let tx = -(right + left) / (right - left);
let ty = -(top + bottom) / (top - bottom);
let tz = -(far + near) / (far - near);
let v = this.values;
v[M00] = x_orth;
v[M10] = 0;
v[M20] = 0;
v[M30] = 0;
v[M01] = 0;
v[M11] = y_orth;
v[M21] = 0;
v[M31] = 0;
v[M02] = 0;
v[M12] = 0;
v[M22] = z_orth;
v[M32] = 0;
v[M03] = tx;
v[M13] = ty;
v[M23] = tz;
v[M33] = 1;
return this;
}
multiply (matrix: Matrix4): Matrix4 {
let t = this.temp;
let v = this.values;
let m = matrix.values;
t[M00] = v[M00] * m[M00] + v[M01] * m[M10] + v[M02] * m[M20] + v[M03] * m[M30];
t[M01] = v[M00] * m[M01] + v[M01] * m[M11] + v[M02] * m[M21] + v[M03] * m[M31];
t[M02] = v[M00] * m[M02] + v[M01] * m[M12] + v[M02] * m[M22] + v[M03] * m[M32];
t[M03] = v[M00] * m[M03] + v[M01] * m[M13] + v[M02] * m[M23] + v[M03] * m[M33];
t[M10] = v[M10] * m[M00] + v[M11] * m[M10] + v[M12] * m[M20] + v[M13] * m[M30];
t[M11] = v[M10] * m[M01] + v[M11] * m[M11] + v[M12] * m[M21] + v[M13] * m[M31];
t[M12] = v[M10] * m[M02] + v[M11] * m[M12] + v[M12] * m[M22] + v[M13] * m[M32];
t[M13] = v[M10] * m[M03] + v[M11] * m[M13] + v[M12] * m[M23] + v[M13] * m[M33];
t[M20] = v[M20] * m[M00] + v[M21] * m[M10] + v[M22] * m[M20] + v[M23] * m[M30];
t[M21] = v[M20] * m[M01] + v[M21] * m[M11] + v[M22] * m[M21] + v[M23] * m[M31];
t[M22] = v[M20] * m[M02] + v[M21] * m[M12] + v[M22] * m[M22] + v[M23] * m[M32];
t[M23] = v[M20] * m[M03] + v[M21] * m[M13] + v[M22] * m[M23] + v[M23] * m[M33];
t[M30] = v[M30] * m[M00] + v[M31] * m[M10] + v[M32] * m[M20] + v[M33] * m[M30];
t[M31] = v[M30] * m[M01] + v[M31] * m[M11] + v[M32] * m[M21] + v[M33] * m[M31];
t[M32] = v[M30] * m[M02] + v[M31] * m[M12] + v[M32] * m[M22] + v[M33] * m[M32];
t[M33] = v[M30] * m[M03] + v[M31] * m[M13] + v[M32] * m[M23] + v[M33] * m[M33];
return this.set(this.temp);
}
multiplyLeft (matrix: Matrix4): Matrix4 {
let t = this.temp;
let v = this.values;
let m = matrix.values;
t[M00] = m[M00] * v[M00] + m[M01] * v[M10] + m[M02] * v[M20] + m[M03] * v[M30];
t[M01] = m[M00] * v[M01] + m[M01] * v[M11] + m[M02] * v[M21] + m[M03] * v[M31];
t[M02] = m[M00] * v[M02] + m[M01] * v[M12] + m[M02] * v[M22] + m[M03] * v[M32];
t[M03] = m[M00] * v[M03] + m[M01] * v[M13] + m[M02] * v[M23] + m[M03] * v[M33];
t[M10] = m[M10] * v[M00] + m[M11] * v[M10] + m[M12] * v[M20] + m[M13] * v[M30];
t[M11] = m[M10] * v[M01] + m[M11] * v[M11] + m[M12] * v[M21] + m[M13] * v[M31];
t[M12] = m[M10] * v[M02] + m[M11] * v[M12] + m[M12] * v[M22] + m[M13] * v[M32];
t[M13] = m[M10] * v[M03] + m[M11] * v[M13] + m[M12] * v[M23] + m[M13] * v[M33];
t[M20] = m[M20] * v[M00] + m[M21] * v[M10] + m[M22] * v[M20] + m[M23] * v[M30];
t[M21] = m[M20] * v[M01] + m[M21] * v[M11] + m[M22] * v[M21] + m[M23] * v[M31];
t[M22] = m[M20] * v[M02] + m[M21] * v[M12] + m[M22] * v[M22] + m[M23] * v[M32];
t[M23] = m[M20] * v[M03] + m[M21] * v[M13] + m[M22] * v[M23] + m[M23] * v[M33];
t[M30] = m[M30] * v[M00] + m[M31] * v[M10] + m[M32] * v[M20] + m[M33] * v[M30];
t[M31] = m[M30] * v[M01] + m[M31] * v[M11] + m[M32] * v[M21] + m[M33] * v[M31];
t[M32] = m[M30] * v[M02] + m[M31] * v[M12] + m[M32] * v[M22] + m[M33] * v[M32];
t[M33] = m[M30] * v[M03] + m[M31] * v[M13] + m[M32] * v[M23] + m[M33] * v[M33];
return this.set(this.temp);
}
lookAt (position: Vector3, direction: Vector3, up: Vector3) {
Matrix4.initTemps();
let xAxis = Matrix4.xAxis, yAxis = Matrix4.yAxis, zAxis = Matrix4.zAxis;
zAxis.setFrom(direction).normalize();
xAxis.setFrom(direction).normalize();
xAxis.cross(up).normalize();
yAxis.setFrom(xAxis).cross(zAxis).normalize();
this.identity();
let val = this.values;
val[M00] = xAxis.x;
val[M01] = xAxis.y;
val[M02] = xAxis.z;
val[M10] = yAxis.x;
val[M11] = yAxis.y;
val[M12] = yAxis.z;
val[M20] = -zAxis.x;
val[M21] = -zAxis.y;
val[M22] = -zAxis.z;
Matrix4.tmpMatrix.identity();
Matrix4.tmpMatrix.values[M03] = -position.x;
Matrix4.tmpMatrix.values[M13] = -position.y;
Matrix4.tmpMatrix.values[M23] = -position.z;
this.multiply(Matrix4.tmpMatrix)
return this;
}
static initTemps () {
if (Matrix4.xAxis === null) Matrix4.xAxis = new Vector3();
if (Matrix4.yAxis === null) Matrix4.yAxis = new Vector3();
if (Matrix4.zAxis === null) Matrix4.zAxis = new Vector3();
}
} | the_stack |
import { Directive, Optional, Input, NgModule, Host, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { ISortingExpression } from '../data-operations/sorting-expression.interface';
import { FilteringExpressionsTree, IFilteringExpressionsTree } from '../data-operations/filtering-expressions-tree';
import { IFilteringExpression } from '../data-operations/filtering-expression.interface';
import { IgxColumnComponent } from './columns/column.component';
import { IgxColumnGroupComponent } from './columns/column-group.component';
import { IGroupingExpression } from '../data-operations/grouping-expression.interface';
import { IPagingState } from '../data-operations/paging-state.interface';
import { GridColumnDataType } from '../data-operations/data-util';
import { IgxBooleanFilteringOperand, IgxNumberFilteringOperand, IgxDateFilteringOperand,
IgxStringFilteringOperand, IFilteringOperation} from '../data-operations/filtering-condition';
import { GridSelectionRange } from './selection/selection.service';
import { IGroupByExpandState } from '../data-operations/groupby-expand-state.interface';
import { IGroupingState } from '../data-operations/groupby-state.interface';
import { IgxGridBaseDirective } from './grid-base.directive';
import { IgxGridComponent } from './grid/grid.component';
import { IgxHierarchicalGridComponent } from './hierarchical-grid/hierarchical-grid.component';
import { IPinningConfig } from './grid.common';
import { delay, take } from 'rxjs/operators';
export interface IGridState {
columns?: IColumnState[];
filtering?: IFilteringExpressionsTree;
advancedFiltering?: IFilteringExpressionsTree;
paging?: IPagingState;
sorting?: ISortingExpression[];
groupBy?: IGroupingState;
cellSelection?: GridSelectionRange[];
rowSelection?: any[];
columnSelection?: string[];
rowPinning?: any[];
pinningConfig?: IPinningConfig;
expansion?: any[];
rowIslands?: IGridStateCollection[];
id?: string;
}
export interface IGridStateCollection {
id: string;
parentRowID: any;
state: IGridState;
}
export interface IGridStateOptions {
columns?: boolean;
filtering?: boolean;
advancedFiltering?: boolean;
sorting?: boolean;
groupBy?: boolean;
paging?: boolean;
cellSelection?: boolean;
rowSelection?: boolean;
columnSelection?: boolean;
rowPinning?: boolean;
pinningConfig?: boolean;
expansion?: boolean;
rowIslands?: boolean;
}
export interface IColumnState {
pinned: boolean;
sortable: boolean;
filterable: boolean;
editable: boolean;
sortingIgnoreCase: boolean;
filteringIgnoreCase: boolean;
headerClasses: string;
headerGroupClasses: string;
maxWidth: string;
groupable: boolean;
movable: boolean;
hidden: boolean;
dataType: GridColumnDataType;
hasSummary: boolean;
field: string;
width: any;
header: string;
resizable: boolean;
searchable: boolean;
columnGroup: boolean;
parent: any;
disableHiding: boolean;
}
export type GridFeatures = keyof IGridStateOptions;
interface Feature {
getFeatureState: (context: IgxGridStateDirective) => IGridState;
restoreFeatureState: (context: IgxGridStateDirective, state: IColumnState[] | IPagingState | ISortingExpression[] |
IGroupingState | IFilteringExpressionsTree | GridSelectionRange[] | IPinningConfig | any[]) => void;
}
@Directive({
selector: '[igxGridState]'
})
export class IgxGridStateDirective {
private static ngAcceptInputType_options: IGridStateOptions | '';
private featureKeys: GridFeatures[] = [];
private state: IGridState;
private currGrid: IgxGridBaseDirective;
private _options: IGridStateOptions = {
columns: true,
filtering: true,
advancedFiltering: true,
sorting: true,
groupBy: true,
paging: true,
cellSelection: true,
rowSelection: true,
columnSelection: true,
rowPinning: true,
expansion: true,
rowIslands: true
};
private FEATURES = {
sorting: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const sortingState = context.currGrid.sortingExpressions;
sortingState.forEach(s => {
delete s.strategy;
delete s.owner;
});
return { sorting: sortingState };
},
restoreFeatureState: (context: IgxGridStateDirective, state: ISortingExpression[]): void => {
context.currGrid.sortingExpressions = state;
}
},
filtering: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const filteringState = context.currGrid.filteringExpressionsTree;
if (filteringState) {
delete filteringState.owner;
for (const item of filteringState.filteringOperands) {
delete (item as IFilteringExpressionsTree).owner;
}
}
return { filtering: filteringState };
},
restoreFeatureState: (context: IgxGridStateDirective, state: FilteringExpressionsTree): void => {
const filterTree = context.createExpressionsTreeFromObject(state);
context.currGrid.filteringExpressionsTree = filterTree as FilteringExpressionsTree;
}
},
advancedFiltering: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const filteringState = context.currGrid.advancedFilteringExpressionsTree;
let advancedFiltering: any;
if (filteringState) {
delete filteringState.owner;
for (const item of filteringState.filteringOperands) {
delete (item as IFilteringExpressionsTree).owner;
}
advancedFiltering = filteringState;
} else {
advancedFiltering = {};
}
return { advancedFiltering };
},
restoreFeatureState: (context: IgxGridStateDirective, state: FilteringExpressionsTree): void => {
const filterTree = context.createExpressionsTreeFromObject(state);
context.currGrid.advancedFilteringExpressionsTree = filterTree as FilteringExpressionsTree;
}
},
columns: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const gridColumns: IColumnState[] = context.currGrid.columns.map((c) => ({
pinned: c.pinned,
sortable: c.sortable,
filterable: c.filterable,
editable: c.editable,
sortingIgnoreCase: c.sortingIgnoreCase,
filteringIgnoreCase: c.filteringIgnoreCase,
headerClasses: c.headerClasses,
headerGroupClasses: c.headerGroupClasses,
maxWidth: c.maxWidth,
groupable: c.groupable,
movable: c.movable,
hidden: c.hidden,
dataType: c.dataType,
hasSummary: c.hasSummary,
field: c.field,
width: c.width,
header: c.header,
resizable: c.resizable,
searchable: c.searchable,
selectable: c.selectable,
parent: c.parent ? c.parent.header : null,
columnGroup: c.columnGroup,
disableHiding: c.disableHiding
}));
return { columns: gridColumns };
},
restoreFeatureState: (context: IgxGridStateDirective, state: IColumnState[]): void => {
const newColumns = [];
const factory = context.resolver.resolveComponentFactory(IgxColumnComponent);
const groupFactory = context.resolver.resolveComponentFactory(IgxColumnGroupComponent);
state.forEach((colState) => {
const hasColumnGroup = colState.columnGroup;
delete colState.columnGroup;
if (hasColumnGroup) {
const ref1 = groupFactory.create(context.viewRef.injector);
Object.assign(ref1.instance, colState);
if (ref1.instance.parent) {
const columnGroup: IgxColumnGroupComponent = newColumns.find(e => e.header === ref1.instance.parent);
columnGroup.children.reset([...columnGroup.children.toArray(), ref1.instance]);
ref1.instance.parent = columnGroup;
}
ref1.changeDetectorRef.detectChanges();
newColumns.push(ref1.instance);
} else {
const ref = factory.create(context.viewRef.injector);
Object.assign(ref.instance, colState);
if (ref.instance.parent) {
const columnGroup: IgxColumnGroupComponent = newColumns.find(e => e.header === ref.instance.parent);
if (columnGroup) {
ref.instance.parent = columnGroup;
columnGroup.children.reset([...columnGroup.children.toArray(), ref.instance]);
}
}
ref.changeDetectorRef.detectChanges();
newColumns.push(ref.instance);
}
});
context.currGrid.columnList.reset(newColumns);
context.currGrid.columnList.notifyOnChanges();
}
},
groupBy: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const grid = context.currGrid as IgxGridComponent;
const groupingExpressions = grid.groupingExpressions;
groupingExpressions.forEach(expr => {
delete expr.strategy;
});
const expansionState = grid.groupingExpansionState;
const groupsExpanded = grid.groupsExpanded;
return { groupBy: { expressions: groupingExpressions, expansion: expansionState, defaultExpanded: groupsExpanded} };
},
restoreFeatureState: (context: IgxGridStateDirective, state: IGroupingState): void => {
const grid = context.currGrid as IgxGridComponent;
grid.groupingExpressions = state.expressions as IGroupingExpression[];
if (grid.groupsExpanded !== state.defaultExpanded) {
grid.toggleAllGroupRows();
} else {
grid.groupingExpansionState = state.expansion as IGroupByExpandState[];
}
}
},
paging: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const pagingState = context.currGrid.pagingState;
return { paging: pagingState };
},
restoreFeatureState: (context: IgxGridStateDirective, state: IPagingState): void => {
if (!context.currGrid.paginator) {
return;
}
if (context.currGrid.paginator.perPage !== state.recordsPerPage) {
context.currGrid.paginator.perPage = state.recordsPerPage;
context.currGrid.cdr.detectChanges();
}
context.currGrid.paginator.page = state.index;
}
},
rowSelection: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const selection = context.currGrid.selectedRows;
return { rowSelection: selection };
},
restoreFeatureState: (context: IgxGridStateDirective, state: any[]): void => {
context.currGrid.selectRows(state, true);
}
},
cellSelection: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const selection = context.currGrid.getSelectedRanges().map(range =>
({ rowStart: range.rowStart, rowEnd: range.rowEnd, columnStart: range.columnStart, columnEnd: range.columnEnd }));
return { cellSelection: selection };
},
restoreFeatureState: (context: IgxGridStateDirective, state: GridSelectionRange[]): void => {
state.forEach(r => {
const range = { rowStart: r.rowStart, rowEnd: r.rowEnd, columnStart: r.columnStart, columnEnd: r.columnEnd};
context.currGrid.selectRange(range);
});
}
},
columnSelection: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const selection = context.currGrid.selectedColumns().map(c => c.field);
return { columnSelection: selection };
},
restoreFeatureState: (context: IgxGridStateDirective, state: string[]): void => {
context.currGrid.deselectAllColumns();
context.currGrid.selectColumns(state);
}
},
rowPinning: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const pinned = context.currGrid.pinnedRows.map(x => x.rowID);
return { rowPinning: pinned };
},
restoreFeatureState: (context: IgxGridStateDirective, state: any[]): void => {
// clear current state.
context.currGrid.pinnedRows.forEach(row => row.unpin());
state.forEach(rowID => context.currGrid.pinRow(rowID));
}
},
pinningConfig: {
getFeatureState: (context: IgxGridStateDirective): IGridState => ({ pinningConfig: context.currGrid.pinning }),
restoreFeatureState: (context: IgxGridStateDirective, state: IPinningConfig): void => {
context.currGrid.pinning = state;
}
},
expansion: {
getFeatureState: (context: IgxGridStateDirective): IGridState => {
const expansionStates = Array.from(context.currGrid.expansionStates);
return { expansion: expansionStates };
},
restoreFeatureState: (context: IgxGridStateDirective, state: any[]): void => {
const expansionStates = new Map<any, boolean>(state);
context.currGrid.expansionStates = expansionStates;
}
},
rowIslands: {
getFeatureState(context: IgxGridStateDirective): IGridState {
const childGridStates: IGridStateCollection[] = [];
const rowIslands = (context.currGrid as any).allLayoutList;
if (rowIslands) {
rowIslands.forEach(rowIsland => {
const childGrids = rowIsland.rowIslandAPI.getChildGrids();
childGrids.forEach(chGrid => {
const parentRowID = this.getParentRowID(chGrid);
context.currGrid = chGrid;
if (context.currGrid) {
const childGridState = context.buildState(context.featureKeys) as IGridState;
childGridStates.push({ id: `${rowIsland.id}`, parentRowID, state: childGridState });
}
});
});
}
context.currGrid = context.grid;
return { rowIslands: childGridStates };
},
restoreFeatureState(context: IgxGridStateDirective, state: any): void {
const rowIslands = (context.currGrid as any).allLayoutList;
if (rowIslands) {
rowIslands.forEach(rowIsland => {
const childGrids = rowIsland.rowIslandAPI.getChildGrids();
childGrids.forEach(chGrid => {
const parentRowID = this.getParentRowID(chGrid);
context.currGrid = chGrid;
const childGridState = state.find(st => st.id === rowIsland.id && st.parentRowID === parentRowID);
if (childGridState && context.currGrid) {
context.restoreGridState(childGridState.state, context.featureKeys);
}
});
});
}
context.currGrid = context.grid;
},
/**
* Traverses the hierarchy up to the root grid to return the ID of the expanded row.
*/
getParentRowID: (grid: IgxHierarchicalGridComponent) => {
let childGrid;
while (grid.parent) {
childGrid = grid;
grid = grid.parent;
}
return grid.hgridAPI.getParentRowId(childGrid);
}
}
};
/**
* An object with options determining if a certain feature state should be saved.
* ```html
* <igx-grid [igxGridState]="options"></igx-grid>
* ```
* ```typescript
* public options = {selection: false, advancedFiltering: false};
* ```
*/
@Input('igxGridState')
public get options(): IGridStateOptions {
return this._options;
}
public set options(value: IGridStateOptions) {
Object.assign(this._options, value);
if (!(this.grid instanceof IgxGridComponent)) {
delete this._options.groupBy;
} else {
delete this._options.rowIslands;
}
}
/**
* @hidden
*/
constructor(
@Host() @Optional() public grid: IgxGridBaseDirective,
private resolver: ComponentFactoryResolver,
private viewRef: ViewContainerRef) { }
/**
* Gets the state of a feature or states of all grid features, unless a certain feature is disabled through the `options` property.
*
* @param `serialize` determines whether the returned object will be serialized to JSON string. Default value is true.
* @param `feature` string or array of strings determining the features to be added in the state. If skipped, all features are added.
* @returns Returns the serialized to JSON string IGridState object, or the non-serialized IGridState object.
* ```html
* <igx-grid [igxGridState]="options"></igx-grid>
* ```
* ```typescript
* @ViewChild(IgxGridStateDirective, { static: true }) public state;
* let state = this.state.getState(); // returns string
* let state = this.state(false) // returns `IGridState` object
* ```
*/
public getState(serialize = true, features?: GridFeatures | GridFeatures[]): IGridState | string {
let state: IGridState | string;
this.currGrid = this.grid;
this.state = state = this.buildState(features) as IGridState;
if (serialize) {
state = JSON.stringify(state, this.stringifyCallback) as string;
}
return state;
}
/**
* Restores grid features' state based on the IGridState object passed as an argument.
*
* @param IGridState object to restore state from.
* @returns
* ```html
* <igx-grid [igxGridState]="options"></igx-grid>
* ```
* ```typescript
* @ViewChild(IgxGridStateDirective, { static: true }) public state;
* this.state.setState(gridState);
* ```
*/
public setState(state: IGridState | string, features?: GridFeatures | GridFeatures[]) {
if (typeof state === 'string') {
state = JSON.parse(state) as IGridState;
}
this.state = state;
this.currGrid = this.grid;
this.restoreGridState(state, features);
this.grid.cdr.detectChanges(); // TODO
}
/**
* Builds an IGridState object.
*/
private buildState(keys?: GridFeatures | GridFeatures[]): IGridState {
this.applyFeatures(keys);
let gridState = {} as IGridState;
this.featureKeys.forEach(f => {
if (this.options[f]) {
if (!(this.grid instanceof IgxGridComponent) && f === 'groupBy') {
return;
}
const feature = this.getFeature(f);
const featureState: IGridState = feature.getFeatureState(this);
gridState = Object.assign(gridState, featureState);
}
});
return gridState;
}
/**
* The method that calls corresponding methods to restore features from the passed IGridState object.
*/
private restoreGridState(state: IGridState, features?: GridFeatures | GridFeatures[]) {
// TODO Notify the grid that columnList.changes is triggered by the state directive
// instead of piping it like below
const columns = 'columns';
this.grid.columnList.changes.pipe(delay(0), take(1)).subscribe(() => {
this.featureKeys = this.featureKeys.filter(f => f !== columns);
this.restoreFeatures(state);
});
this.applyFeatures(features);
if (this.featureKeys.includes(columns) && this.options[columns] && state[columns]) {
this.getFeature(columns).restoreFeatureState(this, state[columns]);
} else {
this.restoreFeatures(state);
}
}
private restoreFeatures(state: IGridState) {
this.featureKeys.forEach(f => {
if (this.options[f]) {
const featureState = state[f];
if (featureState) {
const feature = this.getFeature(f);
feature.restoreFeatureState(this, featureState);
}
}
});
}
/**
* Returns a collection of all grid features.
*/
private applyFeatures(keys?: GridFeatures | GridFeatures[]) {
this.featureKeys = [];
if (!keys) {
for (const key of Object.keys(this.options)) {
this.featureKeys.push(key as GridFeatures);
}
} else if (Array.isArray(keys)) {
this.featureKeys = [...keys as GridFeatures[]];
} else {
this.featureKeys.push(keys);
}
}
/**
* This method builds a FilteringExpressionsTree from a provided object.
*/
private createExpressionsTreeFromObject(exprTreeObject: FilteringExpressionsTree): FilteringExpressionsTree {
if (!exprTreeObject || !exprTreeObject.filteringOperands) {
return null;
}
const expressionsTree = new FilteringExpressionsTree(exprTreeObject.operator, exprTreeObject.fieldName);
for (const item of exprTreeObject.filteringOperands) {
// Check if item is an expressions tree or a single expression.
if ((item as FilteringExpressionsTree).filteringOperands) {
const subTree = this.createExpressionsTreeFromObject((item as FilteringExpressionsTree));
expressionsTree.filteringOperands.push(subTree);
} else {
const expr = item as IFilteringExpression;
let dataType: string;
if (this.currGrid.columnList.length > 0) {
dataType = this.currGrid.columnList.find(c => c.field === expr.fieldName).dataType;
} else {
dataType = this.state.columns.find(c => c.field === expr.fieldName).dataType;
}
// when ESF, values are stored in Set.
// First those values are converted to an array before returning string in the stringifyCallback
// now we need to convert those back to Set
if (Array.isArray(expr.searchVal)) {
expr.searchVal = new Set(expr.searchVal);
} else {
expr.searchVal = (dataType === 'date') ? new Date(Date.parse(expr.searchVal)) : expr.searchVal;
}
expr.condition = this.generateFilteringCondition(dataType, expr.condition.name);
expressionsTree.filteringOperands.push(expr);
}
}
return expressionsTree;
}
/**
* Returns the filtering logic function for a given dataType and condition (contains, greaterThan, etc.)
*/
private generateFilteringCondition(dataType: string, name: string): IFilteringOperation {
let filters;
switch (dataType) {
case GridColumnDataType.Boolean:
filters = IgxBooleanFilteringOperand.instance();
break;
case GridColumnDataType.Number:
filters = IgxNumberFilteringOperand.instance();
break;
case GridColumnDataType.Date:
filters = IgxDateFilteringOperand.instance();
break;
case GridColumnDataType.String:
default:
filters = IgxStringFilteringOperand.instance();
break;
}
return filters.condition(name);
}
private stringifyCallback(key: string, val: any) {
if (key === 'searchVal' && val instanceof Set) {
return Array.from(val);
}
return val;
}
private getFeature(key: string): Feature {
const feature: Feature = this.FEATURES[key];
return feature;
}
}
/**
* @hidden
*/
@NgModule({
declarations: [IgxGridStateDirective],
exports: [IgxGridStateDirective]
})
export class IgxGridStateModule { } | the_stack |
import {
User,
getAuth,
onAuthStateChanged,
onIdTokenChanged,
signInWithPopup,
GoogleAuthProvider,
GithubAuthProvider,
OAuthProvider,
signInWithEmailAndPassword as signInWithEmailAndPass,
isSignInWithEmailLink as isSignInWithEmailLinkFB,
fetchSignInMethodsForEmail,
sendSignInLinkToEmail,
signInWithEmailLink as signInWithEmailLinkFB,
ActionCodeSettings,
signOut,
linkWithCredential,
AuthCredential,
UserCredential,
updateProfile,
updateEmail,
sendEmailVerification,
reauthenticateWithCredential,
} from "firebase/auth"
import {
onSnapshot,
getFirestore,
setDoc,
doc,
updateDoc,
} from "firebase/firestore"
import {
BehaviorSubject,
distinctUntilChanged,
filter,
map,
Subject,
Subscription,
} from "rxjs"
import { onBeforeUnmount, onMounted } from "@nuxtjs/composition-api"
import {
setLocalConfig,
getLocalConfig,
removeLocalConfig,
} from "~/newstore/localpersistence"
export type HoppUser = User & {
provider?: string
accessToken?: string
}
type AuthEvents =
| { event: "probable_login"; user: HoppUser } // We have previous login state, but the app is waiting for authentication
| { event: "login"; user: HoppUser } // We are authenticated
| { event: "logout" } // No authentication and we have no previous state
| { event: "authTokenUpdate"; user: HoppUser; newToken: string | null } // Token has been updated
/**
* A BehaviorSubject emitting the currently logged in user (or null if not logged in)
*/
export const currentUser$ = new BehaviorSubject<HoppUser | null>(null)
/**
* A BehaviorSubject emitting the current idToken
*/
export const authIdToken$ = new BehaviorSubject<string | null>(null)
/**
* A subject that emits events related to authentication flows
*/
export const authEvents$ = new Subject<AuthEvents>()
/**
* Like currentUser$ but also gives probable user value
*/
export const probableUser$ = new BehaviorSubject<HoppUser | null>(null)
/**
* Resolves when the probable login resolves into proper login
*/
export const waitProbableLoginToConfirm = () =>
new Promise<void>((resolve, reject) => {
if (authIdToken$.value) resolve()
if (!probableUser$.value) reject(new Error("no_probable_user"))
const sub = authIdToken$.pipe(filter((token) => !!token)).subscribe(() => {
sub?.unsubscribe()
resolve()
})
})
/**
* Initializes the firebase authentication related subjects
*/
export function initAuth() {
const auth = getAuth()
const firestore = getFirestore()
let extraSnapshotStop: (() => void) | null = null
probableUser$.next(JSON.parse(getLocalConfig("login_state") ?? "null"))
onAuthStateChanged(auth, (user) => {
/** Whether the user was logged in before */
const wasLoggedIn = currentUser$.value !== null
if (user) {
probableUser$.next(user)
} else {
probableUser$.next(null)
removeLocalConfig("login_state")
}
if (!user && extraSnapshotStop) {
extraSnapshotStop()
extraSnapshotStop = null
} else if (user) {
// Merge all the user info from all the authenticated providers
user.providerData.forEach((profile) => {
if (!profile) return
const us = {
updatedOn: new Date(),
provider: profile.providerId,
name: profile.displayName,
email: profile.email,
photoUrl: profile.photoURL,
uid: profile.uid,
}
setDoc(doc(firestore, "users", user.uid), us, { merge: true }).catch(
(e) => console.error("error updating", us, e)
)
})
extraSnapshotStop = onSnapshot(
doc(firestore, "users", user.uid),
(doc) => {
const data = doc.data()
const userUpdate: HoppUser = user
if (data) {
// Write extra provider data
userUpdate.provider = data.provider
userUpdate.accessToken = data.accessToken
}
currentUser$.next(userUpdate)
}
)
}
currentUser$.next(user)
// User wasn't found before, but now is there (login happened)
if (!wasLoggedIn && user) {
authEvents$.next({
event: "login",
user: currentUser$.value!!,
})
} else if (wasLoggedIn && !user) {
// User was found before, but now is not there (logout happened)
authEvents$.next({
event: "logout",
})
}
})
onIdTokenChanged(auth, async (user) => {
if (user) {
authIdToken$.next(await user.getIdToken())
authEvents$.next({
event: "authTokenUpdate",
newToken: authIdToken$.value,
user: currentUser$.value!!, // Force not-null because user is defined
})
setLocalConfig("login_state", JSON.stringify(user))
} else {
authIdToken$.next(null)
}
})
}
export function getAuthIDToken(): string | null {
return authIdToken$.getValue()
}
/**
* Sign user in with a popup using Google
*/
export async function signInUserWithGoogle() {
return await signInWithPopup(getAuth(), new GoogleAuthProvider())
}
/**
* Sign user in with a popup using Github
*/
export async function signInUserWithGithub() {
return await signInWithPopup(
getAuth(),
new GithubAuthProvider().addScope("gist")
)
}
/**
* Sign user in with a popup using Microsoft
*/
export async function signInUserWithMicrosoft() {
return await signInWithPopup(getAuth(), new OAuthProvider("microsoft.com"))
}
/**
* Sign user in with email and password
*/
export async function signInWithEmailAndPassword(
email: string,
password: string
) {
return await signInWithEmailAndPass(getAuth(), email, password)
}
/**
* Gets the sign in methods for a given email address
*
* @param email - Email to get the methods of
*
* @returns Promise for string array of the auth provider methods accessible
*/
export async function getSignInMethodsForEmail(email: string) {
return await fetchSignInMethodsForEmail(getAuth(), email)
}
export async function linkWithFBCredential(
user: User,
credential: AuthCredential
) {
return await linkWithCredential(user, credential)
}
/**
* Sends an email with the signin link to the user
*
* @param email - Email to send the email to
* @param actionCodeSettings - The settings to apply to the link
*/
export async function signInWithEmail(
email: string,
actionCodeSettings: ActionCodeSettings
) {
return await sendSignInLinkToEmail(getAuth(), email, actionCodeSettings)
}
/**
* Checks and returns whether the sign in link is an email link
*
* @param url - The URL to look in
*/
export function isSignInWithEmailLink(url: string) {
return isSignInWithEmailLinkFB(getAuth(), url)
}
/**
* Sends an email with sign in with email link
*
* @param email - Email to log in to
* @param url - The action URL which is used to validate login
*/
export async function signInWithEmailLink(email: string, url: string) {
return await signInWithEmailLinkFB(getAuth(), email, url)
}
/**
* Signs out the user
*/
export async function signOutUser() {
if (!currentUser$.value) throw new Error("No user has logged in")
await signOut(getAuth())
}
/**
* Sets the provider id and relevant provider auth token
* as user metadata
*
* @param id - The provider ID
* @param token - The relevant auth token for the given provider
*/
export async function setProviderInfo(id: string, token: string) {
if (!currentUser$.value) throw new Error("No user has logged in")
const us = {
updatedOn: new Date(),
provider: id,
accessToken: token,
}
try {
await updateDoc(
doc(getFirestore(), "users", currentUser$.value.uid),
us
).catch((e) => console.error("error updating", us, e))
} catch (e) {
console.error("error updating", e)
throw e
}
}
/**
* Sets the user's display name
*
* @param name - The new display name
*/
export async function setDisplayName(name: string) {
if (!currentUser$.value) throw new Error("No user has logged in")
const us = {
displayName: name,
}
try {
await updateProfile(currentUser$.value, us)
} catch (e) {
console.error("error updating", e)
throw e
}
}
/**
* Send user's email address verification mail
*/
export async function verifyEmailAddress() {
if (!currentUser$.value) throw new Error("No user has logged in")
try {
await sendEmailVerification(currentUser$.value)
} catch (e) {
console.error("error updating", e)
throw e
}
}
/**
* Sets the user's email address
*
* @param email - The new email address
*/
export async function setEmailAddress(email: string) {
if (!currentUser$.value) throw new Error("No user has logged in")
try {
await updateEmail(currentUser$.value, email)
} catch (e) {
await reauthenticateUser()
console.error("error updating", e)
throw e
}
}
/**
* Reauthenticate the user with the given credential
*/
async function reauthenticateUser() {
if (!currentUser$.value) throw new Error("No user has logged in")
const currentAuthMethod = currentUser$.value.provider
let credential
if (currentAuthMethod === "google.com") {
const result = await signInUserWithGithub()
credential = GithubAuthProvider.credentialFromResult(result)
} else if (currentAuthMethod === "github.com") {
const result = await signInUserWithGoogle()
credential = GoogleAuthProvider.credentialFromResult(result)
} else if (currentAuthMethod === "microsoft.com") {
const result = await signInUserWithMicrosoft()
credential = OAuthProvider.credentialFromResult(result)
} else if (currentAuthMethod === "password") {
const email = prompt(
"Reauthenticate your account using your current email:"
)
const actionCodeSettings = {
url: `${process.env.BASE_URL}/enter`,
handleCodeInApp: true,
}
await signInWithEmail(email as string, actionCodeSettings)
.then(() =>
alert(
`Check your inbox - we sent an email to ${email}. It contains a magic link that will reauthenticate your account.`
)
)
.catch((e) => {
alert(`Error: ${e.message}`)
console.error(e)
})
return
}
try {
await reauthenticateWithCredential(
currentUser$.value,
credential as AuthCredential
)
} catch (e) {
console.error("error updating", e)
throw e
}
}
export function getGithubCredentialFromResult(result: UserCredential) {
return GithubAuthProvider.credentialFromResult(result)
}
/**
* A Vue composable function that is called when the auth status
* is being updated to being logged in (fired multiple times),
* this is also called on component mount if the login
* was already resolved before mount.
*/
export function onLoggedIn(exec: (user: HoppUser) => void) {
let sub: Subscription | null = null
onMounted(() => {
sub = currentUser$
.pipe(
map((user) => !!user), // Get a logged in status (true or false)
distinctUntilChanged(), // Don't propagate unless the status updates
filter((x) => x) // Don't propagate unless it is logged in
)
.subscribe(() => {
exec(currentUser$.value!)
})
})
onBeforeUnmount(() => {
sub?.unsubscribe()
})
} | the_stack |
import {isValue} from '../values';
import type {Type} from '../types';
import {BooleanType} from '../types';
import type {Expression} from '../expression';
import type ParsingContext from '../parsing_context';
import type EvaluationContext from '../evaluation_context';
import type {CanonicalTileID} from '../../../source/tile_id';
type GeoJSONPolygons = GeoJSON.Polygon | GeoJSON.MultiPolygon;
// minX, minY, maxX, maxY
type BBox = [number, number, number, number];
const EXTENT = 8192;
function updateBBox(bbox: BBox, coord: [number, number]) {
bbox[0] = Math.min(bbox[0], coord[0]);
bbox[1] = Math.min(bbox[1], coord[1]);
bbox[2] = Math.max(bbox[2], coord[0]);
bbox[3] = Math.max(bbox[3], coord[1]);
}
function mercatorXfromLng(lng: number) {
return (180 + lng) / 360;
}
function mercatorYfromLat(lat: number) {
return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;
}
function boxWithinBox(bbox1: BBox, bbox2: BBox) {
if (bbox1[0] <= bbox2[0]) return false;
if (bbox1[2] >= bbox2[2]) return false;
if (bbox1[1] <= bbox2[1]) return false;
if (bbox1[3] >= bbox2[3]) return false;
return true;
}
function getTileCoordinates(p, canonical: CanonicalTileID): [number, number] {
const x = mercatorXfromLng(p[0]);
const y = mercatorYfromLat(p[1]);
const tilesAtZoom = Math.pow(2, canonical.z);
return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];
}
function onBoundary(p, p1, p2) {
const x1 = p[0] - p1[0];
const y1 = p[1] - p1[1];
const x2 = p[0] - p2[0];
const y2 = p[1] - p2[1];
return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0);
}
function rayIntersect(p, p1, p2) {
return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]);
}
// ray casting algorithm for detecting if point is in polygon
function pointWithinPolygon(point, rings) {
let inside = false;
for (let i = 0, len = rings.length; i < len; i++) {
const ring = rings[i];
for (let j = 0, len2 = ring.length; j < len2 - 1; j++) {
if (onBoundary(point, ring[j], ring[j + 1])) return false;
if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside;
}
}
return inside;
}
function pointWithinPolygons(point, polygons) {
for (let i = 0; i < polygons.length; i++) {
if (pointWithinPolygon(point, polygons[i])) return true;
}
return false;
}
function perp(v1, v2) {
return (v1[0] * v2[1] - v1[1] * v2[0]);
}
// check if p1 and p2 are in different sides of line segment q1->q2
function twoSided(p1, p2, q1, q2) {
// q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)
const x1 = p1[0] - q1[0];
const y1 = p1[1] - q1[1];
const x2 = p2[0] - q1[0];
const y2 = p2[1] - q1[1];
const x3 = q2[0] - q1[0];
const y3 = q2[1] - q1[1];
const det1 = (x1 * y3 - x3 * y1);
const det2 = (x2 * y3 - x3 * y2);
if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) return true;
return false;
}
// a, b are end points for line segment1, c and d are end points for line segment2
function lineIntersectLine(a, b, c, d) {
// check if two segments are parallel or not
// precondition is end point a, b is inside polygon, if line a->b is
// parallel to polygon edge c->d, then a->b won't intersect with c->d
const vectorP = [b[0] - a[0], b[1] - a[1]];
const vectorQ = [d[0] - c[0], d[1] - c[1]];
if (perp(vectorQ, vectorP) === 0) return false;
// If lines are intersecting with each other, the relative location should be:
// a and b lie in different sides of segment c->d
// c and d lie in different sides of segment a->b
if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true;
return false;
}
function lineIntersectPolygon(p1, p2, polygon) {
for (const ring of polygon) {
// loop through every edge of the ring
for (let j = 0; j < ring.length - 1; ++j) {
if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) {
return true;
}
}
}
return false;
}
function lineStringWithinPolygon(line, polygon) {
// First, check if geometry points of line segments are all inside polygon
for (let i = 0; i < line.length; ++i) {
if (!pointWithinPolygon(line[i], polygon)) {
return false;
}
}
// Second, check if there is line segment intersecting polygon edge
for (let i = 0; i < line.length - 1; ++i) {
if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {
return false;
}
}
return true;
}
function lineStringWithinPolygons(line, polygons) {
for (let i = 0; i < polygons.length; i++) {
if (lineStringWithinPolygon(line, polygons[i])) return true;
}
return false;
}
function getTilePolygon(coordinates, bbox, canonical) {
const polygon = [];
for (let i = 0; i < coordinates.length; i++) {
const ring = [];
for (let j = 0; j < coordinates[i].length; j++) {
const coord = getTileCoordinates(coordinates[i][j], canonical);
updateBBox(bbox, coord);
ring.push(coord);
}
polygon.push(ring);
}
return polygon;
}
function getTilePolygons(coordinates, bbox, canonical) {
const polygons = [];
for (let i = 0; i < coordinates.length; i++) {
const polygon = getTilePolygon(coordinates[i], bbox, canonical);
polygons.push(polygon);
}
return polygons;
}
function updatePoint(p, bbox, polyBBox, worldSize) {
if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {
const halfWorldSize = worldSize * 0.5;
let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0;
if (shift === 0) {
shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0;
}
p[0] += shift;
}
updateBBox(bbox, p);
}
function resetBBox(bbox) {
bbox[0] = bbox[1] = Infinity;
bbox[2] = bbox[3] = -Infinity;
}
function getTilePoints(geometry, pointBBox, polyBBox, canonical) {
const worldSize = Math.pow(2, canonical.z) * EXTENT;
const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];
const tilePoints = [];
for (const points of geometry) {
for (const point of points) {
const p = [point.x + shifts[0], point.y + shifts[1]];
updatePoint(p, pointBBox, polyBBox, worldSize);
tilePoints.push(p);
}
}
return tilePoints;
}
function getTileLines(geometry, lineBBox, polyBBox, canonical) {
const worldSize = Math.pow(2, canonical.z) * EXTENT;
const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];
const tileLines = [];
for (const line of geometry) {
const tileLine = [];
for (const point of line) {
const p = [point.x + shifts[0], point.y + shifts[1]] as [number, number];
updateBBox(lineBBox, p);
tileLine.push(p);
}
tileLines.push(tileLine);
}
if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {
resetBBox(lineBBox);
for (const line of tileLines) {
for (const p of line) {
updatePoint(p, lineBBox, polyBBox, worldSize);
}
}
}
return tileLines;
}
function pointsWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {
const pointBBox: BBox = [Infinity, Infinity, -Infinity, -Infinity];
const polyBBox: BBox = [Infinity, Infinity, -Infinity, -Infinity];
const canonical = ctx.canonicalID();
if (polygonGeometry.type === 'Polygon') {
const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
if (!boxWithinBox(pointBBox, polyBBox)) return false;
for (const point of tilePoints) {
if (!pointWithinPolygon(point, tilePolygon)) return false;
}
}
if (polygonGeometry.type === 'MultiPolygon') {
const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
if (!boxWithinBox(pointBBox, polyBBox)) return false;
for (const point of tilePoints) {
if (!pointWithinPolygons(point, tilePolygons)) return false;
}
}
return true;
}
function linesWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {
const lineBBox: BBox = [Infinity, Infinity, -Infinity, -Infinity];
const polyBBox: BBox = [Infinity, Infinity, -Infinity, -Infinity];
const canonical = ctx.canonicalID();
if (polygonGeometry.type === 'Polygon') {
const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
if (!boxWithinBox(lineBBox, polyBBox)) return false;
for (const line of tileLines) {
if (!lineStringWithinPolygon(line, tilePolygon)) return false;
}
}
if (polygonGeometry.type === 'MultiPolygon') {
const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
if (!boxWithinBox(lineBBox, polyBBox)) return false;
for (const line of tileLines) {
if (!lineStringWithinPolygons(line, tilePolygons)) return false;
}
}
return true;
}
class Within implements Expression {
type: Type;
geojson: GeoJSON.GeoJSON;
geometries: GeoJSONPolygons;
constructor(geojson: GeoJSON.GeoJSON, geometries: GeoJSONPolygons) {
this.type = BooleanType;
this.geojson = geojson;
this.geometries = geometries;
}
static parse(args: ReadonlyArray<unknown>, context: ParsingContext): Expression {
if (args.length !== 2)
return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`) as null;
if (isValue(args[1])) {
const geojson = (args[1] as any);
if (geojson.type === 'FeatureCollection') {
for (let i = 0; i < geojson.features.length; ++i) {
const type = geojson.features[i].geometry.type;
if (type === 'Polygon' || type === 'MultiPolygon') {
return new Within(geojson, geojson.features[i].geometry);
}
}
} else if (geojson.type === 'Feature') {
const type = geojson.geometry.type;
if (type === 'Polygon' || type === 'MultiPolygon') {
return new Within(geojson, geojson.geometry);
}
} else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {
return new Within(geojson, geojson);
}
}
return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.') as null;
}
evaluate(ctx: EvaluationContext) {
if (ctx.geometry() != null && ctx.canonicalID() != null) {
if (ctx.geometryType() === 'Point') {
return pointsWithinPolygons(ctx, this.geometries);
} else if (ctx.geometryType() === 'LineString') {
return linesWithinPolygons(ctx, this.geometries);
}
}
return false;
}
eachChild() {}
outputDefined(): boolean {
return true;
}
serialize(): Array<unknown> {
return ['within', this.geojson];
}
}
export default Within; | the_stack |
import fs = require('fs');
import http = require('http');
import path = require('path');
import url = require('url');
import logging = require('./logging');
import settings = require('./settings');
import userManager = require('./userManager');
let appSettings: common.AppSettings;
const CONTENT_TYPES: common.Map<string> = {
'.css': 'text/css',
'.html': 'text/html',
'.ico': 'image/x-icon',
'.js': 'text/javascript',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
};
const CUSTOM_THEME_FILE = 'custom.css';
const DEFAULT_THEME_FILE = 'light.css';
const contentCache: common.Map<Buffer> = {};
const watchedDynamicContent: common.Map<boolean> = {};
// Path to use for fetching static resources provided by Jupyter.
function jupyterDir(): string {
const prefix = appSettings.datalabRoot || '/usr/local/envs/py3env/lib/python3.5';
return path.join(prefix, '/site-packages/notebook');
}
function getContent(filePath: string, cb: common.Callback<Buffer>, isDynamic: boolean = false): void {
const content = contentCache[filePath];
if (content != null) {
process.nextTick(() => {
cb(null, content);
});
} else {
fs.readFile(filePath, (error, fileContent) => {
if (error) {
cb(error, null);
} else {
if (isDynamic && !watchedDynamicContent[filePath]) {
fs.watch(filePath, (eventType, filename) => {
logging.getLogger().info('Clearing cache for updated file: %s', filePath);
contentCache[filePath] = null;
if (eventType === 'rename') {
watchedDynamicContent[filePath] = false;
}
});
watchedDynamicContent[filePath] = true;
}
contentCache[filePath] = fileContent;
cb(null, fileContent);
}
});
}
}
/**
* Sends a static file as the response.
* @param filePath the full path of the static file to send.
* @param response the out-going response associated with the current HTTP request.
* @param alternatePath the path to a static Datalab file to send if the given file is missing.
* @param isDynamic indication of whether or not the file contents might change.
*/
function sendFile(filePath: string, response: http.ServerResponse,
alternatePath = '', isDynamic = false,
replaceBasepath = false): void {
const extension = path.extname(filePath);
const contentType = CONTENT_TYPES[extension.toLowerCase()] || 'application/octet-stream';
getContent(filePath, (error, content) => {
if (error) {
logging.getLogger().error(error, 'Unable to send static file: %s', filePath);
if (alternatePath !== '') {
sendDataLabFile(alternatePath, response);
} else {
response.writeHead(500);
response.end();
}
} else {
if (isDynamic) {
response.removeHeader('Cache-Control');
response.setHeader('Cache-Control', 'no-cache');
}
response.writeHead(200, { 'Content-Type': contentType });
if (replaceBasepath) {
const contentStr = content.toString().replace(
/\{base_url}/g, appSettings.datalabBasePath);
response.end(contentStr);
} else {
response.end(content);
}
}
}, isDynamic);
}
/**
* Sends a static file located within the DataLab static directory.
* @param filePath the relative file path of the static file to send.
* @param response the out-going response associated with the current HTTP request.
* @param isDynamic indication of whether or not the file contents might change.
*/
function sendDataLabFile(filePath: string, response: http.ServerResponse,
isDynamic = false, replaceBasepath = false): void {
let live = isDynamic;
let staticDir = path.join(__dirname, 'static');
// Set this env var to point to source directory for live updates without restart.
const liveStaticDir = process.env.DATALAB_LIVE_STATIC_DIR;
if (liveStaticDir) {
live = true;
staticDir = liveStaticDir;
}
sendFile(path.join(staticDir, filePath), response, '', live, replaceBasepath);
}
/**
* Sends a static file located within the Jupyter install.
* @param filePath the relative file path of the static file within the Jupyter directory to send.
* @param response the out-going response associated with the current HTTP request.
*/
function sendJupyterFile(relativePath: string, response: http.ServerResponse): void {
const filePath = path.join(jupyterDir(), relativePath);
fs.stat(filePath, (e, stats) => {
if (e || !stats.isFile()) {
response.writeHead(404);
response.end();
return;
}
sendFile(filePath, response);
});
}
/**
* Checks whether a requested static file exists in DataLab.
* @param filePath the relative path of the file.
*/
export function datalabFileExists(filePath: string): boolean {
return fs.existsSync(path.join(__dirname, 'static', filePath));
}
/**
* Sends a static 'custom.css' file located within the user's config directory.
*
* @param userId the ID of the current user.
* @param response the out-going response associated with the current HTTP request.
*/
function sendUserCustomTheme(userId: string, response: http.ServerResponse): void {
const customThemePath = path.join(settings.getUserConfigDir(userId), CUSTOM_THEME_FILE);
sendFile(customThemePath, response, DEFAULT_THEME_FILE, true);
}
/**
* Returns true if this path should return an experimental UI resource
* @param path the incoming request path
*/
export function isExperimentalResource(pathname: string, search: string): boolean {
if (pathname.indexOf('/exp/') === 0) {
return true;
}
const experimentalUiEnabled = process.env.DATALAB_EXPERIMENTAL_UI;
return experimentalUiEnabled === 'true' && (
firstComponent(pathname) === 'data' ||
// /files/path?download=true is used to download files from Jupyter
// TODO: use a different API to download files when we have a content service.
(firstComponent(pathname) === 'files' && search !== '?download=true') ||
firstComponent(pathname) === 'sessions' ||
firstComponent(pathname) === 'terminal' ||
firstComponent(pathname) === 'docs' ||
firstComponent(pathname) === 'editor' ||
firstComponent(pathname) === 'notebook' ||
pathname.indexOf('/notebook.js') === 0 ||
firstComponent(pathname) === 'bower_components' ||
firstComponent(pathname) === 'components' ||
firstComponent(pathname) === 'images' ||
pathname.indexOf('/index.css') === 0 ||
firstComponent(pathname) === 'modules' ||
firstComponent(pathname) === 'templates' ||
pathname === '/'
);
}
/**
* Parses the given url path and returns the first component.
*/
function firstComponent(pathname: string): string {
return pathname.split('/')[1];
}
/**
* Implements static file handling.
* @param request the incoming file request.
* @param response the outgoing file response.
*/
function requestHandler(request: http.ServerRequest, response: http.ServerResponse): void {
let pathname = url.parse(request.url).pathname;
const search = url.parse(request.url).search;
// -------------------------------- start of experimental UI resources
let replaceBasepath = false;
// List of page names that resolve to index.html
const indexPageNames = ['data', 'files', 'docs', 'sessions', 'terminal'];
if (isExperimentalResource(pathname, search)) {
logging.getLogger().debug('Serving experimental UI resource: ' + pathname);
let rootRedirect = 'files';
if (pathname.indexOf('/exp/') === 0) {
pathname = pathname.substr('/exp'.length);
rootRedirect = 'exp/files';
}
if (pathname === '/') {
response.statusCode = 302;
response.setHeader('Location', path.join(appSettings.datalabBasePath, rootRedirect));
response.end();
return;
} else if (indexPageNames.indexOf(firstComponent(pathname)) > -1) {
pathname = '/index.html';
replaceBasepath = true;
} else if (firstComponent(pathname) === 'editor') {
pathname = '/editor.html';
replaceBasepath = true;
} else if (firstComponent(pathname) === 'notebook') {
pathname = '/notebook.html';
replaceBasepath = true;
} else if (pathname === '/index.css') {
const userSettings: common.UserSettings =
settings.loadUserSettings(userManager.getUserId(request));
pathname = '/index.' + (userSettings.theme || 'light') + '.css';
}
pathname = 'experimental' + pathname;
logging.getLogger().debug('sending experimental file: ' + pathname);
sendDataLabFile(pathname, response, undefined, replaceBasepath);
return;
}
// -------------------------------- end of experimental resources
console.log('static request: ' + pathname);
// List of resources that are passed through with the same name.
const staticResourcesList: string[] = [
'appbar.html',
'appbar.js',
'util.js',
'edit-app.js',
'datalab.css',
'idle-timeout.js',
'minitoolbar.js',
'notebook-app.js',
'notebook-list.js',
'reporting.html',
'settings.html',
'settings.js',
'websocket.js',
];
// Map of resources where we change the name.
const staticResourcesMap: {[key: string]: string} = {
'about.txt': 'datalab.txt',
'favicon.ico': 'datalab.ico',
'logo.png': 'datalab.png',
};
response.setHeader('Cache-Control', 'public, max-age=3600');
const subpath = pathname.substr(pathname.lastIndexOf('/') + 1);
if (staticResourcesList.indexOf(subpath) >= 0) {
sendDataLabFile(subpath, response);
} else if (subpath in staticResourcesMap) {
sendDataLabFile(staticResourcesMap[subpath], response);
} else if (pathname.indexOf('/codemirror/mode/') > 0) {
const split = pathname.lastIndexOf('/');
const newPath = 'codemirror/mode/' + pathname.substring(split + 1);
if (datalabFileExists(newPath)) {
sendDataLabFile(newPath, response);
} else {
// load codemirror modes from proper path
pathname = pathname.substr(1).replace('static/codemirror', 'static/components/codemirror');
sendJupyterFile(pathname, response);
}
} else if (pathname.lastIndexOf('/custom.js') >= 0) {
// NOTE: Uncomment to use external content mapped into the container.
// This is only useful when actively developing the content itself.
// var text = fs.readFileSync('/sources/datalab/static/datalab.js', { encoding: 'utf8' });
// response.writeHead(200, { 'Content-Type': 'text/javascript' });
// response.end(text);
sendDataLabFile('datalab.js', response);
} else if (pathname.lastIndexOf('/custom.css') > 0) {
const userId = userManager.getUserId(request);
const userSettings = settings.loadUserSettings(userId);
if ('theme' in userSettings) {
const theme = userSettings['theme'];
if (theme === 'custom') {
sendUserCustomTheme(userId, response);
} else if (theme === 'dark') {
sendDataLabFile('dark.css', response, true);
} else {
sendDataLabFile('light.css', response, true);
}
} else {
sendDataLabFile(DEFAULT_THEME_FILE, response, true);
}
} else if ((pathname.indexOf('/static/extensions/') === 0) ||
(pathname.indexOf('/static/require/') === 0) ||
(pathname.indexOf('/static/fonts/') === 0)) {
// Strip off the leading '/static/' to turn pathname into a relative path within the
// static directory.
sendDataLabFile(pathname.substr('/static/'.length), response);
} else {
// Strip off the leading slash to turn pathname into a relative file path
sendJupyterFile(pathname.substr(1), response);
}
}
/**
* Creates the static content request handler.
* @param handlerSettings configuration settings for the application.
* @returns the request handler to handle static requests.
*/
export function createHandler(handlerSettings: common.AppSettings): http.RequestHandler {
appSettings = handlerSettings;
return requestHandler;
} | the_stack |
import { Component, ViewChild, OnInit } from '@angular/core';
import { SampleTestData } from './sample-test-data.spec';
import { IgxColumnComponent } from '../grids/public_api';
import { IgxHierarchicalGridComponent } from '../grids/hierarchical-grid/hierarchical-grid.component';
import { IgxRowIslandComponent } from '../grids/hierarchical-grid/row-island.component';
import { IPinningConfig } from '../grids/grid.common';
import { ColumnPinningPosition, RowPinningPosition } from '../grids/common/enums';
import { IgxActionStripComponent } from '../action-strip/public_api';
import { HIERARCHICAL_SAMPLE_DATA } from 'src/app/shared/sample-data';
import { IgxHierarchicalTransactionServiceFactory } from '../grids/hierarchical-grid/hierarchical-grid-base.directive';
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [allowFiltering]="true" [rowEditable]="true" [pinning]='pinningConfig'
[height]="'600px'" [width]="'700px'" #hierarchicalGrid [primaryKey]="'ID'">
<igx-column field="ID" [groupable]="true" [movable]='true'></igx-column>
<igx-column-group header="Information">
<igx-column field="ChildLevels" [groupable]="true" [sortable]="true" [editable]="true" [movable]='true'></igx-column>
<igx-column field="ProductName" [groupable]="true" [hasSummary]='true' [movable]='true'></igx-column>
</igx-column-group>
<igx-paginator *ngIf="paging"></igx-paginator>
<igx-row-island [key]="'childData'" #rowIsland [allowFiltering]="true" [rowEditable]="true" [primaryKey]="'ID'">
<igx-grid-toolbar [grid]="grid" *igxGridToolbar="let grid"></igx-grid-toolbar>
<igx-column field="ID" [groupable]="true" [hasSummary]='true' [movable]='true'>
<ng-template igxHeader let-columnRef="column">
<div>
<span>ID</span>
<igx-icon (click)="pinColumn(columnRef)">lock</igx-icon>
</div>
</ng-template>
</igx-column>
<igx-column-group header="Information">
<igx-column field="ChildLevels" [groupable]="true" [sortable]="true" [editable]="true"></igx-column>
<igx-column field="ProductName" [groupable]="true"></igx-column>
</igx-column-group>
<igx-row-island [key]="'childData'" #rowIsland2 >
<igx-column field="ID" [groupable]="true" ></igx-column>
<igx-column-group header="Information">
<igx-column field="ChildLevels" [groupable]="true" [sortable]="true" [editable]="true"></igx-column>
<igx-column field="ProductName" [groupable]="true" [hasSummary]='true'></igx-column>
</igx-column-group>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>`
})
export class IgxHierarchicalGridTestBaseComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true })
public hgrid: IgxHierarchicalGridComponent;
@ViewChild('rowIsland', { read: IgxRowIslandComponent, static: true })
public rowIsland: IgxRowIslandComponent;
@ViewChild('rowIsland2', { read: IgxRowIslandComponent, static: true })
public rowIsland2: IgxRowIslandComponent;
public data;
public pinningConfig: IPinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Top };
public paging = false;
constructor() {
// 3 level hierarchy
this.data = SampleTestData.generateHGridData(40, 3);
}
public pinColumn(column: IgxColumnComponent) {
if (column.pinned) {
column.unpin();
} else {
column.pin();
}
}
}
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [allowFiltering]="true" [rowEditable]="true" [pinning]='pinningConfig'
[height]="'600px'" [width]="'700px'" #hierarchicalGrid [primaryKey]="'ID'">
<igx-column field="ID" [groupable]="true" [movable]='true'></igx-column>
<igx-column-group header="Information">
<igx-column field="ChildLevels" [groupable]="true" [sortable]="true" [editable]="true" [movable]='true'></igx-column>
<igx-column field="ProductName" [groupable]="true" [hasSummary]='true' [movable]='true'></igx-column>
</igx-column-group>
<igx-paginator *ngIf="paging"></igx-paginator>
<igx-row-island [key]="'childData'" #rowIsland [allowFiltering]="true" [rowEditable]="true" [primaryKey]="'ID'">
<igx-grid-toolbar [grid]="grid" *igxGridToolbar="let grid"></igx-grid-toolbar>
<igx-column field="ID" [groupable]="true" [hasSummary]='true' [movable]='true'>
<ng-template igxHeader let-columnRef="column">
<div>
<span>ID</span>
<igx-icon (click)="pinColumn(columnRef)">lock</igx-icon>
</div>
</ng-template>
</igx-column>
<igx-column-group header="Information">
<igx-column field="ChildLevels" [groupable]="true" [sortable]="true" [editable]="true"></igx-column>
<igx-column field="ProductName" [groupable]="true"></igx-column>
</igx-column-group>
<igx-row-island [key]="'childData'" #rowIsland2 >
<igx-column field="ID" [groupable]="true" ></igx-column>
<igx-column-group header="Information">
<igx-column field="ChildLevels" [groupable]="true" [sortable]="true" [editable]="true"></igx-column>
<igx-column field="ProductName" [groupable]="true" [hasSummary]='true'></igx-column>
</igx-column-group>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>`,
providers: [IgxHierarchicalTransactionServiceFactory]
})
export class IgxHierarchicalGridWithTransactionProviderComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true })
public hgrid: IgxHierarchicalGridComponent;
@ViewChild('rowIsland', { read: IgxRowIslandComponent, static: true })
public rowIsland: IgxRowIslandComponent;
@ViewChild('rowIsland2', { read: IgxRowIslandComponent, static: true })
public rowIsland2: IgxRowIslandComponent;
public data;
public pinningConfig: IPinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Top };
public paging = false;
constructor() {
// 3 level hierarchy
this.data = SampleTestData.generateHGridData(40, 3);
}
public pinColumn(column: IgxColumnComponent) {
if (column.pinned) {
column.unpin();
} else {
column.pin();
}
}
}
@Component({
template: `
<igx-hierarchical-grid #grid1 [batchEditing]="true"
[data]="data" [height]="'600px'" [width]="'700px'" #hierarchicalGrid [primaryKey]="'ID'"
[rowSelection]="'multiple'" [selectedRows]="selectedRows">
<igx-column field="ID" ></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland [primaryKey]="'ID'" [rowSelection]="'single'">
<igx-column field="ID"> </igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland2 [primaryKey]="'ID'" [rowSelection]="'none'">
<igx-column field="ID"></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>`
})
export class IgxHierarchicalGridRowSelectionComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true }) public hgrid: IgxHierarchicalGridComponent;
@ViewChild('rowIsland', { read: IgxRowIslandComponent, static: true }) public rowIsland: IgxRowIslandComponent;
@ViewChild('rowIsland2', { read: IgxRowIslandComponent, static: true }) public rowIsland2: IgxRowIslandComponent;
public data;
public selectedRows = [];
constructor() {
// 3 level hierarchy
this.data = SampleTestData.generateHGridData(5, 3);
}
}
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [height]="'600px'" [width]="'700px'" #hierarchicalGrid [primaryKey]="'ID'"
[rowSelection]="'multiple'" [selectedRows]="selectedRows" [selectRowOnClick]="false">
<igx-column field="ID" ></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland [primaryKey]="'ID'" [rowSelection]="'single'">
<igx-column field="ID"> </igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland2 [primaryKey]="'ID'" [rowSelection]="'none'">
<igx-column field="ID"></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>`
})
export class IgxHierarchicalGridRowSelectionTestSelectRowOnClickComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true }) public hgrid: IgxHierarchicalGridComponent;
@ViewChild('rowIsland', { read: IgxRowIslandComponent, static: true }) public rowIsland: IgxRowIslandComponent;
@ViewChild('rowIsland2', { read: IgxRowIslandComponent, static: true }) public rowIsland2: IgxRowIslandComponent;
public data;
public selectedRows = [];
constructor() {
// 3 level hierarchy
this.data = SampleTestData.generateHGridData(5, 3);
}
}
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [height]="'600px'" [width]="'700px'" #hierarchicalGrid [primaryKey]="'ID'"
[rowSelection]="'multiple'">
<igx-column field="ID" ></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland [primaryKey]="'ID'" [rowSelection]="'multiple'">
<igx-column field="ID"> </igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland2 [primaryKey]="'ID'" [rowSelection]="'multiple'">
<igx-column field="ID"></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>`,
})
export class IgxHierarchicalGridRowSelectionNoTransactionsComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true }) public hgrid: IgxHierarchicalGridComponent;
@ViewChild('rowIsland', { read: IgxRowIslandComponent, static: true }) public rowIsland: IgxRowIslandComponent;
@ViewChild('rowIsland2', { read: IgxRowIslandComponent, static: true }) public rowIsland2: IgxRowIslandComponent;
public data;
constructor() {
// 3 level hierarchy
this.data = SampleTestData.generateHGridData(5, 3);
}
}
@Component({
template: `
<igx-hierarchical-grid [data]="data" [cellSelection]="false" [height]="'600px'"
[width]="'700px'" #hGridCustomSelectors [primaryKey]="'ID'"
[rowSelection]="'multiple'">
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-paginator></igx-paginator>
<igx-row-island [key]="'childData'" #rowIsland1 [primaryKey]="'ID'" [rowSelection]="'single'">
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-paginator *igxPaginator></igx-paginator>
<ng-template igxHeadSelector let-headContext>
<igx-checkbox [readonly]="true" (click)="handleHeadSelectorClick(headContext)"
[checked]="headContext.selectedCount === headContext.totalCount"
[indeterminate]="headContext.selectedCount !== headContext.totalCount && headContext.selectedCount !== 0">
</igx-checkbox>
</ng-template>
<ng-template igxRowSelector let-rowContext>
<span class="rowNumberChild">{{ rowContext.index }}</span>
<igx-checkbox (click)="handleRowSelectorClick(rowContext)" [checked]="rowContext.selected">
</igx-checkbox>
</ng-template>
</igx-row-island>
<ng-template igxHeadSelector let-headContext>
<igx-checkbox [readonly]="true" (click)="handleHeadSelectorClick(headContext)"
[checked]="headContext.selectedCount === headContext.totalCount"
[indeterminate]="headContext.selectedCount !== headContext.totalCount && headContext.selectedCount !== 0">
</igx-checkbox>
</ng-template>
<ng-template igxRowSelector let-rowContext>
<span class="rowNumber">{{ rowContext.index }}</span>
<igx-checkbox [readonly]="true" (click)="handleRowSelectorClick(rowContext)" [checked]="rowContext.selected">
</igx-checkbox>
</ng-template>
</igx-hierarchical-grid>`
})
export class IgxHierarchicalGridCustomSelectorsComponent implements OnInit {
@ViewChild('hGridCustomSelectors', { read: IgxHierarchicalGridComponent, static: true })
public hGrid: IgxHierarchicalGridComponent;
@ViewChild('rowIsland1', { read: IgxRowIslandComponent, static: true })
public firstLevelChild: IgxRowIslandComponent;
public data = [];
public ngOnInit(): void {
// 2 level hierarchy
this.data = SampleTestData.generateHGridData(40, 2);
}
public handleHeadSelectorClick(headContext) {
if (headContext.totalCount !== headContext.selectedCount) {
headContext.selectAll();
} else {
headContext.deselectAll();
}
}
public handleRowSelectorClick(rowContext) {
if (rowContext.selected) {
rowContext.deselect();
} else {
rowContext.select();
}
}
}
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [height]="'600px'" [width]="'700px'" #hierarchicalGrid
[primaryKey]="'ID'" [autoGenerate]="true">
<igx-grid-toolbar>
<button igxButton="raised">Parent Button</button>
</igx-grid-toolbar>
<igx-row-island [key]="'childData1'" #rowIsland1 [primaryKey]="'ID'" [autoGenerate]="true">
<igx-grid-toolbar *igxGridToolbar="let grid" [grid]="grid">
<button igxButton="raised">Child 1 Button</button>
</igx-grid-toolbar>
</igx-row-island>
<igx-row-island [key]="'childData2'" #rowIsland2 [primaryKey]="'ID'" [autoGenerate]="true">
<igx-grid-toolbar *igxGridToolbar="let grid" [grid]="grid">
<button igxButton="raised">Child2 Button</button>
</igx-grid-toolbar>
</igx-row-island>
</igx-hierarchical-grid>`
})
export class IgxHierarchicalGridTestCustomToolbarComponent extends IgxHierarchicalGridTestBaseComponent { }
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [height]="'600px'" [width]="'700px'" #hierarchicalGrid
[primaryKey]="'ID'" [autoGenerate]="true" [rowEditable]='true'>
<igx-action-strip #actionStrip1>
<igx-grid-pinning-actions></igx-grid-pinning-actions>
<igx-grid-editing-actions></igx-grid-editing-actions>
</igx-action-strip>
<igx-row-island [key]="'childData1'" #rowIsland1 [primaryKey]="'ID'" [autoGenerate]="true">
</igx-row-island>
<igx-row-island [key]="'childData2'" #rowIsland2 [primaryKey]="'ID'" [autoGenerate]="true">
<igx-action-strip #actionStrip2>
<igx-grid-pinning-actions></igx-grid-pinning-actions>
<igx-grid-editing-actions [asMenuItems]='true'></igx-grid-editing-actions>
</igx-action-strip>
</igx-row-island>
</igx-hierarchical-grid>`
})
export class IgxHierarchicalGridActionStripComponent extends IgxHierarchicalGridTestBaseComponent {
@ViewChild('actionStrip1', { read: IgxActionStripComponent, static: true })
public actionStripRoot: IgxActionStripComponent;
@ViewChild('actionStrip2', { read: IgxActionStripComponent, static: true })
public actionStripChild: IgxActionStripComponent;
}
@Component({
template: `
<igx-hierarchical-grid #grid1 [data]="data" [height]="'300px'" [width]="'700px'" #hierarchicalGrid [primaryKey]="'ID'">
<igx-column field="ID" ></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland [primaryKey]="'ID'" [rowSelection]="'single'">
<igx-column field="ID"> </igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
<igx-row-island [key]="'childData'" #rowIsland2 [primaryKey]="'ID'" [rowSelection]="'none'">
<igx-column field="ID"></igx-column>
<igx-column field="ChildLevels"></igx-column>
<igx-column field="ProductName"></igx-column>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>
<igx-advanced-filtering-dialog [grid]="grid1">
</igx-advanced-filtering-dialog>`
})
export class IgxHierGridExternalAdvancedFilteringComponent extends IgxHierarchicalGridTestBaseComponent {
// @ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true })
// public hgrid: IgxHierarchicalGridComponent;
public data = SampleTestData.generateHGridData(5, 3);
}
@Component({
template: `
<igx-hierarchical-grid [data]="data" [height]="'1200px'" [width]="'700px'"
[allowFiltering]="true" [filterMode]="'excelStyleFilter'" #hierarchicalGrid>
<igx-column field="Artist" [filterable]="true" [sortable]="true"></igx-column>
<igx-column field="Debut" [sortable]="true" dataType="number"></igx-column>
<igx-column field="GrammyNominations" header="Grammy Nominations" [sortable]="true"></igx-column>
<igx-column field="GrammyAwards" header="Grammy Awards" [sortable]="true"></igx-column>
<igx-row-island [key]="'Albums'" [allowFiltering]='true' [filterMode]="'excelStyleFilter'" [autoGenerate]="false">
<igx-column field="Album"></igx-column>
<igx-column field="LaunchDate" header="Launch Date" [dataType]="'date'"></igx-column>
<igx-column field="BillboardReview" header="Billboard Review"></igx-column>
<igx-column field="USBillboard200" header="US Billboard 200"></igx-column>
<igx-row-island [key]="'Songs'" [allowFiltering]='true' [filterMode]="'excelStyleFilter'" [autoGenerate]="false">
<igx-column field="Number" header="No."></igx-column>
<igx-column field="Title"></igx-column>
<igx-column field="Released" dataType="date"></igx-column>
<igx-column field="Genre"></igx-column>
</igx-row-island>
</igx-row-island>
<igx-row-island [key]="'Tours'" [autoGenerate]="false">
<igx-column field="Tour"></igx-column>
<igx-column field="StartedOn" header="Started on"></igx-column>
<igx-column field="Location"></igx-column>
<igx-column field="Headliner"></igx-column>
<igx-row-island [key]="'TourData'" [autoGenerate]="false">
<igx-column field="Country"></igx-column>
<igx-column field="TicketsSold" header="Tickets Sold"></igx-column>
<igx-column field="Attendants"></igx-column>
</igx-row-island>
</igx-row-island>
</igx-hierarchical-grid>
`
})
export class IgxHierarchicalGridExportComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true }) public hGrid: IgxHierarchicalGridComponent;
public data = SampleTestData.hierarchicalGridExportData();
}
@Component({
template: `
<igx-hierarchical-grid [data]="data" [height]="'1200px'" [width]="'700px'" #hierarchicalGrid>
<igx-column field="CustomerID" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column-group [movable]="true" [pinned]="false" header="General Information">
<igx-column field="CompanyName" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column-group [movable]="true" header="Personal Details">
<igx-column field="ContactName" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="ContactTitle" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
</igx-column-group>
</igx-column-group>
<igx-column-group header="Address Information">
<igx-column-group header="Location">
<igx-column field="Address" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="City" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="PostalCode" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="Country" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
</igx-column-group>
<igx-column-group header="Contact Information">
<igx-column field="Phone" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="Fax" [sortable]="true" [resizable]="true"></igx-column>
</igx-column-group>
</igx-column-group>
<igx-row-island [key]="'ChildCompanies'" [autoGenerate]="false">
<igx-column-group [movable]="true" [pinned]="false" header="General Information">
<igx-column field="CompanyName" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column-group [movable]="true" header="Personal Details">
<igx-column field="ContactName" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="ContactTitle" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
</igx-column-group>
</igx-column-group>
<igx-column-group header="Address Information">
<igx-column-group header="Location">
<igx-column field="Address" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="City" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="PostalCode" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="Country" [movable]="true" [sortable]="true" [resizable]="true"></igx-column>
</igx-column-group>
<igx-column-group header="Contact Information">
<igx-column field="Phone" [sortable]="true" [resizable]="true"></igx-column>
<igx-column field="Fax" [sortable]="true" [resizable]="true"></igx-column>
</igx-column-group>
</igx-column-group>
</igx-row-island>
</igx-hierarchical-grid>
`
})
export class IgxHierarchicalGridMultiColumnHeadersExportComponent {
@ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true }) public hGrid: IgxHierarchicalGridComponent;
public data = HIERARCHICAL_SAMPLE_DATA;
} | the_stack |
import {
CheckOutlined,
CloseOutlined,
DashboardOutlined,
DeleteOutlined,
PlusOutlined,
ReloadOutlined,
RetweetOutlined
} from '@ant-design/icons';
import { Button, Empty, message, Spin, Tooltip } from 'antd';
import classnames from 'classnames';
import _ from 'lodash';
import React, {
forwardRef,
ReactElement,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useReducer,
useRef,
useState
} from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
import KeyEvent from 'react-keyevent';
import { generateUuid, reducer } from '../utils';
import Widget from '../widget';
import WidgetSelector from '../widget/selector';
import { getWidgetType } from '../widget/utils';
import { Toolbar } from './components';
import './index.less';
import { fetch as fetchApi, update as updateApi } from './service';
import './style/button.css';
import './style/empty.css';
import './style/input.css';
import './style/message.css';
import './style/modal.css';
import './style/spin.css';
import './style/tooltip.css';
import { calcMinAndMax, copy, formatLayout } from './utils';
const ResponsiveReactGridLayout: any = WidthProvider(Responsive);
export type LayoutItem = {
w: number; //宽度份数,总共12份
h: number; //高度份数,1份大概30px
x: number; //横向位置,总共12份
y: number; //纵向位置,1份大概30px
i: string; //唯一标识
minW: number; //最小宽度
maxW: number; //最大宽度
minH: number; //最小高度
maxH: number; //最大高度
};
export type LayoutsIF = LayoutItem[];
export interface widgetIF {
name: string;
description: string;
tags: string[];
component: ReactElement;
configComponent: ReactElement;
maxLength: number;
snapShot: ImageBitmapSource;
icon: ReactElement;
iconBackground: string;
size: {
defaultWidth: number;
defaultHeight: number;
maxWidth: number;
maxHeight: number;
minWidth: number;
minHeight: number;
};
[key: string]: any;
}
interface widgetsIF {
[key: string]: widgetIF;
}
export interface Dashboard {
widgets: widgetsIF; //widgets对象
editMode?: boolean; //是否编辑状态
defaultLayout?: LayoutsIF; //初始布局
widgetWrapClassName?: string; //widget容器类名
widgetWrapStyle?: React.CSSProperties; //widget容器样式
layout?: LayoutsIF; //布局数据
minHeight?: number; //最小高度
maxWidgetLength?: number; //当前仪表板最大可添加的widget数量
toolbar?: boolean; //是否显示默认工具栏
storageKey?: string; //本地存储唯一标识
onLayoutChange?: (layout: LayoutsIF) => void;
onReset?: (dirtyCurrentLayout: LayoutsIF, currentLayout: LayoutItem) => void; //清空
onRemoveWidget?: (
widget: widgetIF,
dirtyCurrentLayout: LayoutsIF,
currentLayout: LayoutsIF,
) => void; //删除
onAddWidget?: (
widget: widgetIF,
dirtyCurrentLayout: LayoutsIF,
currentLayout: LayoutsIF,
) => void; //新增
onReload?: (currentLayout: LayoutsIF) => void; // 刷新
onCancelEdit?: (
dirtyCurrentLayout: LayoutsIF,
currentLayout: LayoutItem,
) => void; //取消编辑
onEdit?: (currentLayout: LayoutsIF) => void; //编辑
onSave?: (currentLayout: LayoutsIF) => void; //编辑
onRevert?: (dirtyCurrentLayout: LayoutsIF, currentLayout: LayoutItem) => void; //重置
[key: string]: any;
}
const Dashboard = forwardRef((props: Dashboard, ref: any) => {
const {
storageKey = 'default',
editMode = false,
widgets,
defaultLayout = [],
widgetWrapClassName,
widgetWrapStyle,
layout: customLayout = null,
minHeight = 300,
maxWidgetLength = 20,
toolbar = true,
onLayoutChange: _onLayoutChange,
onReset, //清空
onReload, //刷新
onRemoveWidget, //删除
onAddWidget, //新增
onCancelEdit, //取消编辑
onEdit, //编辑
onRevert, //重置
onSave, //保存
...restProps
} = props;
const [stateEditMode, setStateEditMode] = useState(editMode);
const [loading, setLoading] = useState(editMode);
const [state, dispatch] = useReducer(reducer, {
currentLayout: [],
dirtyCurrentLayout: [],
});
const { currentLayout = [], dirtyCurrentLayout = [] } = state;
const dom = useRef<any>(null);
//获取操作
const fetch = useCallback(
_.debounce(async () => {
try {
const response = await fetchApi({ id: storageKey });
let layout = _.isArray(defaultLayout) ? defaultLayout : [];
if (response) {
const resArr = JSON.parse(response).currentLayout;
if (!_.isEmpty(resArr)) {
layout = resArr;
}
}
if (layout) {
const data =calcMinAndMax(layout,widgets)
dispatch({
type: 'save',
payload: {
currentLayout: data,
dirtyCurrentLayout: data,
},
});
}
setLoading(false);
} catch (error) {}
}, 200),
[storageKey, widgets],
);
//刷新
const reload = useCallback(async () => {
setLoading(true);
onReload && onReload(formatLayout(currentLayout));
if (customLayout) {
return;
}
fetch();
}, [fetch, customLayout]);
//设置布局信息
const update = useCallback(
async (payload: any, callback: Function = () => {}) => {
const layout = payload['layout'];
try {
const response = await updateApi({
id: storageKey,
data: {
currentLayout: layout,
},
});
if (!response) {
return;
}
callback();
} catch (error) {}
},
[storageKey, widgets],
);
//改变布局触发
const onLayoutChange = useCallback(
_.debounce((layout: any, layouts?: any, callback?: Function) => {
window.dispatchEvent(new Event('resize'));
if (!stateEditMode) {
return;
}
dispatch({
type: 'save',
payload: {
dirtyCurrentLayout: layout,
},
});
_onLayoutChange && _onLayoutChange(formatLayout(layout));
callback && callback();
}, 300),
[stateEditMode],
);
//添加小程序
const addWidget = useCallback(
(widget: widgetIF) => {
if (dirtyCurrentLayout.length >= maxWidgetLength) {
message.warning(
`超过了最大限制数量${maxWidgetLength}` + ',' + '不能再添加了',
);
}
const lastItem = dirtyCurrentLayout[dirtyCurrentLayout.length - 1];
const newLayout = [
...dirtyCurrentLayout,
{
w: widget.size.defaultWidth,
h: widget.size.defaultHeight,
x: 0,
y: lastItem ? lastItem['y'] + lastItem['h'] : 0,
i: widget.name + '-' + generateUuid(),
minW: widget.size.minWidth,
maxW: widget.size.maxWidth,
minH: widget.size.minHeight,
maxH: widget.size.maxHeight,
},
];
onAddWidget &&
onAddWidget(
widget,
formatLayout(dirtyCurrentLayout),
formatLayout(newLayout),
);
onLayoutChange(newLayout);
message.success('添加成功');
},
[dirtyCurrentLayout, onLayoutChange, maxWidgetLength],
);
//删除小程序
const removeWidget = useCallback(
(widgetKey: string) => {
let removedWidget: any;
let newLayout = _.cloneDeep(dirtyCurrentLayout);
newLayout.map((item: widgetIF, index: number) => {
if (item['i'] === widgetKey) {
removedWidget = item;
newLayout.splice(index, 1);
}
});
onRemoveWidget &&
onRemoveWidget(
removedWidget,
formatLayout(dirtyCurrentLayout),
formatLayout(newLayout),
);
dispatch({
type: 'save',
payload: {
dirtyCurrentLayout: newLayout,
},
});
},
[dirtyCurrentLayout, onLayoutChange],
);
//重置
const reset = useCallback(async () => {
onReset && onReset([], formatLayout(currentLayout));
onLayoutChange([]);
}, [onLayoutChange]);
//最终的布局数据
const finLayout = useMemo(() => {
return stateEditMode ? dirtyCurrentLayout : currentLayout;
}, [stateEditMode, dirtyCurrentLayout, currentLayout]);
//取消编辑
const cancelEdit = useCallback(() => {
setStateEditMode(false);
onCancelEdit &&
onCancelEdit(
formatLayout(dirtyCurrentLayout),
formatLayout(currentLayout),
);
dispatch({
type: 'save',
payload: {
dirtyCurrentLayout: currentLayout,
},
});
}, [dirtyCurrentLayout, currentLayout]);
const revert = useCallback(() => {
onRevert &&
onRevert(formatLayout(dirtyCurrentLayout), formatLayout(currentLayout));
dispatch({
type: 'save',
payload: {
dirtyCurrentLayout: currentLayout,
},
});
}, [dirtyCurrentLayout, currentLayout]);
const edit = () => setStateEditMode(true);
const save = useCallback(() => {
dispatch({
type: 'save',
payload: {
currentLayout: dirtyCurrentLayout,
widgets,
},
});
onSave && onSave(formatLayout(dirtyCurrentLayout));
setStateEditMode(false);
if (customLayout) {
return;
}
update({
layout: dirtyCurrentLayout,
});
}, [dirtyCurrentLayout, update, customLayout]);
useImperativeHandle(ref, () => ({
dom: dom.current,
reset, //清空
removeWidget, //删除
addWidget, //新增
reload, // 刷新
cancelEdit, //取消编辑
edit, //编辑
revert, //重置
save, //保存
}));
//打印布局数据
const onCtrlShiftC = useCallback(() => {
const res = formatLayout(currentLayout);
copy(JSON.stringify(res));
message.success('已复制布局数据到剪切板');
console.log('currentLayout', res);
}, [currentLayout]);
//默认存储
useEffect(() => {
if (customLayout) {
return;
}
fetch();
}, [customLayout]);
//编辑状态改变副作用
useEffect(() => {
setStateEditMode(editMode);
}, [editMode]);
//响应外部数据
useEffect(() => {
if (!_.isArray(customLayout)) {
return;
}
const data = calcMinAndMax(customLayout,widgets);
dispatch({
type: 'save',
payload: {
customLayout: data,
dirtyCurrentLayout: data,
},
});
}, [customLayout, widgets]);
return (
<Spin
spinning={loading}
style={{
width: '100%',
}}
>
<KeyEvent
style={{
width: '100%',
}}
events={{
onCtrlShiftC,
}}
needFocusing
>
<div
style={{
width: '100%',
}}
ref={dom}
>
<ResponsiveReactGridLayout
className="react-dashboard-layout"
layouts={{ lg: finLayout }}
rowHeight={30}
isDraggable={stateEditMode}
breakpoints={{ lg: 1200, md: 800, sm: 600, xs: 400, xxs: 300 }}
cols={{ lg: 12, md: 12, sm: 2, xs: 2, xxs: 2 }}
// onBreakpointChange={onBreakpointChange} //断点回调
onLayoutChange={onLayoutChange} //布局改变回调
isResizable={stateEditMode} //准许改变大小
// onWidthChange={()=>onWidthChange()} //宽度改变回调
measureBeforeMount //动画相关
>
{finLayout.map((item: any) => (
<div
key={item.i}
className={classnames(
'react-dashboard-item',
stateEditMode ? 'react-dashboard-item-edit' : '',
)}
>
{widgets[getWidgetType(item.i, widgets)] ? (
<Widget
{...restProps}
widgetKey={item.i}
widgetType={getWidgetType(item.i, widgets)}
height={item.h * 40 - 10}
editMode={stateEditMode}
onDeleteWidget={() => removeWidget(item.i)}
widgets={widgets}
widgetWrapClassName={widgetWrapClassName}
widgetWrapStyle={widgetWrapStyle}
/>
) : (
<div className="react-dashboard-aligncenter react-dashboard-full">
<div style={{ textAlign: 'center' }}>
<div>
{'数据有误'} {item.i}
</div>
{stateEditMode && (
<Button
icon={<DeleteOutlined />}
size="small"
style={{ margin: '10px 0' }}
onClick={() => removeWidget(item.i)}
>
{'删除'}
</Button>
)}
</div>
</div>
)}
</div>
))}
</ResponsiveReactGridLayout>
{toolbar && finLayout.length > 0 ? (
!stateEditMode && (
<div
style={{
display: 'flex',
margin: '0 10px',
marginBottom: '10px',
}}
>
<Button
size="small"
icon={<ReloadOutlined />}
loading={loading}
style={{ marginRight: '10px' }}
onClick={() => reload()}
/>
<Button
size="small"
type="default"
style={{ flex: 1 }}
onClick={edit}
>
<DashboardOutlined />
{'编辑仪表板'}
</Button>
</div>
)
) : (
<>
{!stateEditMode ? (
<Spin spinning={loading}>
<div
className="react-dashboard-emptyContent"
style={{ minHeight }}
>
{!loading && (
<Empty
description={<span>{'当前仪表板没有小程序'}</span>}
>
<Button size="small" type="primary" onClick={edit}>
<DashboardOutlined />
{'编辑仪表板'}
</Button>
</Empty>
)}
</div>
</Spin>
) : (
<div
className={classnames(
'react-dashboard-full',
'react-dashboard-aligncenter',
)}
style={{ minHeight }}
>
<WidgetSelector
widgets={widgets}
currentLayout={finLayout}
addWidget={addWidget}
>
<>
<Tooltip title={'添加'}>
<Button
type="dashed"
shape="circle"
icon={<PlusOutlined />}
size="large"
/>
</Tooltip>
</>
</WidgetSelector>
</div>
)}
</>
)}
{toolbar && stateEditMode && (
<Toolbar
fixed={false}
extraRight={
<>
<Button
size="small"
onClick={cancelEdit}
icon={<CloseOutlined />}
>
{'取消'}
</Button>
<Button
size="small"
onClick={revert}
icon={<RetweetOutlined />}
>
{'恢复'}
</Button>
{!_.isEmpty(finLayout) && (
<Button
size="small"
danger
onClick={reset}
icon={<DeleteOutlined />}
>
{'清空'}
</Button>
)}
<WidgetSelector
widgets={widgets}
currentLayout={finLayout}
addWidget={addWidget}
/>
<Button
size="small"
onClick={save}
type="primary"
icon={<CheckOutlined />}
>
{'保存'}
</Button>
</>
}
/>
)}
</div>
</KeyEvent>
</Spin>
);
});
export default Dashboard; | the_stack |
import {
RenderingContext2D
} from '../types';
import {
vectorsRatio,
vectorsAngle
} from '../util';
import Point from '../Point';
import BoundingBox from '../BoundingBox';
import PathParser from '../PathParser';
import Document from './Document';
import RenderedElement from './RenderedElement';
import MarkerElement from './MarkerElement';
export type Marker = [Point, number];
export default class PathElement extends RenderedElement {
type = 'path';
readonly pathParser: PathParser = null;
constructor(
document: Document,
node: HTMLElement,
captureTextNodes?: boolean
) {
super(document, node, captureTextNodes);
this.pathParser = new PathParser(this.getAttribute('d').getString());
}
path(ctx?: RenderingContext2D) {
const {
pathParser
} = this;
const boundingBox = new BoundingBox();
pathParser.reset();
if (ctx) {
ctx.beginPath();
}
while (!pathParser.isEnd()) {
switch (pathParser.next().type) {
case PathParser.MOVE_TO:
this.pathM(ctx, boundingBox);
break;
case PathParser.LINE_TO:
this.pathL(ctx, boundingBox);
break;
case PathParser.HORIZ_LINE_TO:
this.pathH(ctx, boundingBox);
break;
case PathParser.VERT_LINE_TO:
this.pathV(ctx, boundingBox);
break;
case PathParser.CURVE_TO:
this.pathC(ctx, boundingBox);
break;
case PathParser.SMOOTH_CURVE_TO:
this.pathS(ctx, boundingBox);
break;
case PathParser.QUAD_TO:
this.pathQ(ctx, boundingBox);
break;
case PathParser.SMOOTH_QUAD_TO:
this.pathT(ctx, boundingBox);
break;
case PathParser.ARC:
this.pathA(ctx, boundingBox);
break;
case PathParser.CLOSE_PATH:
this.pathZ(ctx, boundingBox);
break;
default:
}
}
return boundingBox;
}
getBoundingBox(_?: RenderingContext2D) {
return this.path();
}
getMarkers(): Marker[] {
const {
pathParser
} = this;
const points = pathParser.getMarkerPoints();
const angles = pathParser.getMarkerAngles();
const markers = points.map((point, i): Marker => [
point,
angles[i]
]);
return markers;
}
renderChildren(ctx: RenderingContext2D) {
this.path(ctx);
this.document.screen.mouse.checkPath(this, ctx);
const fillRuleStyleProp = this.getStyle('fill-rule');
if (ctx.fillStyle !== '') {
if (fillRuleStyleProp.getString('inherit') !== 'inherit') {
ctx.fill(fillRuleStyleProp.getString() as CanvasFillRule);
} else {
ctx.fill();
}
}
if (ctx.strokeStyle !== '') {
if (this.getAttribute('vector-effect').getString() === 'non-scaling-stroke') {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.stroke();
ctx.restore();
} else {
ctx.stroke();
}
}
const markers = this.getMarkers();
if (markers) {
const markersLastIndex = markers.length - 1;
const markerStartStyleProp = this.getStyle('marker-start');
const markerMidStyleProp = this.getStyle('marker-mid');
const markerEndStyleProp = this.getStyle('marker-end');
if (markerStartStyleProp.isUrlDefinition()) {
const marker = markerStartStyleProp.getDefinition<MarkerElement>();
const [
point,
angle
] = markers[0];
marker.render(ctx, point, angle);
}
if (markerMidStyleProp.isUrlDefinition()) {
const marker = markerMidStyleProp.getDefinition<MarkerElement>();
for (let i = 1; i < markersLastIndex; i++) {
const [
point,
angle
] = markers[i];
marker.render(ctx, point, angle);
}
}
if (markerEndStyleProp.isUrlDefinition()) {
const marker = markerEndStyleProp.getDefinition<MarkerElement>();
const [
point,
angle
] = markers[markersLastIndex];
marker.render(ctx, point, angle);
}
}
}
static pathM(pathParser: PathParser) {
const point = pathParser.getAsCurrentPoint();
pathParser.start = pathParser.current;
return {
point
};
}
protected pathM(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
point
} = PathElement.pathM(pathParser);
const {
x,
y
} = point;
pathParser.addMarker(point);
boundingBox.addPoint(x, y);
if (ctx) {
ctx.moveTo(x, y);
}
}
static pathL(pathParser: PathParser) {
const {
current
} = pathParser;
const point = pathParser.getAsCurrentPoint();
return {
current,
point
};
}
protected pathL(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
point
} = PathElement.pathL(pathParser);
const {
x,
y
} = point;
pathParser.addMarker(point, current);
boundingBox.addPoint(x, y);
if (ctx) {
ctx.lineTo(x, y);
}
}
static pathH(pathParser: PathParser) {
const {
current,
command
} = pathParser;
const point = new Point(
(command.relative ? current.x : 0) + command.x,
current.y
);
pathParser.current = point;
return {
current,
point
};
}
protected pathH(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
point
} = PathElement.pathH(pathParser);
const {
x,
y
} = point;
pathParser.addMarker(point, current);
boundingBox.addPoint(x, y);
if (ctx) {
ctx.lineTo(x, y);
}
}
static pathV(pathParser: PathParser) {
const {
current,
command
} = pathParser;
const point = new Point(
current.x,
(command.relative ? current.y : 0) + command.y
);
pathParser.current = point;
return {
current,
point
};
}
protected pathV(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
point
} = PathElement.pathV(pathParser);
const {
x,
y
} = point;
pathParser.addMarker(point, current);
boundingBox.addPoint(x, y);
if (ctx) {
ctx.lineTo(x, y);
}
}
static pathC(pathParser: PathParser) {
const {
current
} = pathParser;
const point = pathParser.getPoint('x1', 'y1');
const controlPoint = pathParser.getAsControlPoint('x2', 'y2');
const currentPoint = pathParser.getAsCurrentPoint();
return {
current,
point,
controlPoint,
currentPoint
};
}
protected pathC(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
point,
controlPoint,
currentPoint
} = PathElement.pathC(pathParser);
pathParser.addMarker(currentPoint, controlPoint, point);
boundingBox.addBezierCurve(
current.x,
current.y,
point.x,
point.y,
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
if (ctx) {
ctx.bezierCurveTo(
point.x,
point.y,
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
}
}
static pathS(pathParser: PathParser) {
const {
current
} = pathParser;
const point = pathParser.getReflectedControlPoint();
const controlPoint = pathParser.getAsControlPoint('x2', 'y2');
const currentPoint = pathParser.getAsCurrentPoint();
return {
current,
point,
controlPoint,
currentPoint
};
}
protected pathS(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
point,
controlPoint,
currentPoint
} = PathElement.pathS(pathParser);
pathParser.addMarker(currentPoint, controlPoint, point);
boundingBox.addBezierCurve(
current.x,
current.y,
point.x,
point.y,
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
if (ctx) {
ctx.bezierCurveTo(
point.x,
point.y,
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
}
}
static pathQ(pathParser: PathParser) {
const {
current
} = pathParser;
const controlPoint = pathParser.getAsControlPoint('x1', 'y1');
const currentPoint = pathParser.getAsCurrentPoint();
return {
current,
controlPoint,
currentPoint
};
}
protected pathQ(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
controlPoint,
currentPoint
} = PathElement.pathQ(pathParser);
pathParser.addMarker(currentPoint, controlPoint, controlPoint);
boundingBox.addQuadraticCurve(
current.x,
current.y,
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
if (ctx) {
ctx.quadraticCurveTo(
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
}
}
static pathT(pathParser: PathParser) {
const {
current
} = pathParser;
const controlPoint = pathParser.getReflectedControlPoint();
pathParser.control = controlPoint;
const currentPoint = pathParser.getAsCurrentPoint();
return {
current,
controlPoint,
currentPoint
};
}
protected pathT(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
current,
controlPoint,
currentPoint
} = PathElement.pathT(pathParser);
pathParser.addMarker(currentPoint, controlPoint, controlPoint);
boundingBox.addQuadraticCurve(
current.x,
current.y,
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
if (ctx) {
ctx.quadraticCurveTo(
controlPoint.x,
controlPoint.y,
currentPoint.x,
currentPoint.y
);
}
}
static pathA(pathParser: PathParser) {
const {
current,
command
} = pathParser;
let {
rX,
rY,
xRot,
lArcFlag,
sweepFlag
} = command;
const xAxisRotation = xRot * (Math.PI / 180.0);
const currentPoint = pathParser.getAsCurrentPoint();
// Conversion from endpoint to center parameterization
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// x1', y1'
const currp = new Point(
Math.cos(xAxisRotation) * (current.x - currentPoint.x) / 2.0
+ Math.sin(xAxisRotation) * (current.y - currentPoint.y) / 2.0,
-Math.sin(xAxisRotation) * (current.x - currentPoint.x) / 2.0
+ Math.cos(xAxisRotation) * (current.y - currentPoint.y) / 2.0
);
// adjust radii
const l =
Math.pow(currp.x, 2) / Math.pow(rX, 2)
+ Math.pow(currp.y, 2) / Math.pow(rY, 2);
if (l > 1) {
rX *= Math.sqrt(l);
rY *= Math.sqrt(l);
}
// cx', cy'
let s = (lArcFlag === sweepFlag ? -1 : 1) * Math.sqrt(
(
(Math.pow(rX, 2) * Math.pow(rY, 2))
- (Math.pow(rX, 2) * Math.pow(currp.y, 2))
- (Math.pow(rY, 2) * Math.pow(currp.x, 2))
) / (
Math.pow(rX, 2) * Math.pow(currp.y, 2)
+ Math.pow(rY, 2) * Math.pow(currp.x, 2)
)
);
if (isNaN(s)) {
s = 0;
}
const cpp = new Point(
s * rX * currp.y / rY,
s * -rY * currp.x / rX
);
// cx, cy
const centp = new Point(
(current.x + currentPoint.x) / 2.0
+ Math.cos(xAxisRotation) * cpp.x
- Math.sin(xAxisRotation) * cpp.y,
(current.y + currentPoint.y) / 2.0
+ Math.sin(xAxisRotation) * cpp.x
+ Math.cos(xAxisRotation) * cpp.y
);
// initial angle
const a1 = vectorsAngle([1, 0], [(currp.x - cpp.x) / rX, (currp.y - cpp.y) / rY]); // θ1
// angle delta
const u = [(currp.x - cpp.x) / rX, (currp.y - cpp.y) / rY];
const v = [(-currp.x - cpp.x) / rX, (-currp.y - cpp.y) / rY];
let ad = vectorsAngle(u, v); // Δθ
if (vectorsRatio(u, v) <= -1) {
ad = Math.PI;
}
if (vectorsRatio(u, v) >= 1) {
ad = 0;
}
return {
currentPoint,
rX,
rY,
sweepFlag,
xAxisRotation,
centp,
a1,
ad
};
}
protected pathA(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
const {
pathParser
} = this;
const {
currentPoint,
rX,
rY,
sweepFlag,
xAxisRotation,
centp,
a1,
ad
} = PathElement.pathA(pathParser);
// for markers
const dir = 1 - sweepFlag ? 1.0 : -1.0;
const ah = a1 + dir * (ad / 2.0);
const halfWay = new Point(
centp.x + rX * Math.cos(ah),
centp.y + rY * Math.sin(ah)
);
pathParser.addMarkerAngle(halfWay, ah - dir * Math.PI / 2);
pathParser.addMarkerAngle(currentPoint, ah - dir * Math.PI);
boundingBox.addPoint(currentPoint.x, currentPoint.y); // TODO: this is too naive, make it better
if (ctx && !isNaN(a1) && !isNaN(ad)) {
const r = rX > rY ? rX : rY;
const sx = rX > rY ? 1 : rX / rY;
const sy = rX > rY ? rY / rX : 1;
ctx.translate(centp.x, centp.y);
ctx.rotate(xAxisRotation);
ctx.scale(sx, sy);
ctx.arc(0, 0, r, a1, a1 + ad, Boolean(1 - sweepFlag));
ctx.scale(1 / sx, 1 / sy);
ctx.rotate(-xAxisRotation);
ctx.translate(-centp.x, -centp.y);
}
}
static pathZ(pathParser: PathParser) {
pathParser.current = pathParser.start;
}
protected pathZ(
ctx: RenderingContext2D,
boundingBox: BoundingBox
) {
PathElement.pathZ(this.pathParser);
if (ctx) {
// only close path if it is not a straight line
if (boundingBox.x1 !== boundingBox.x2
&& boundingBox.y1 !== boundingBox.y2
) {
ctx.closePath();
}
}
}
} | the_stack |
import * as Clutter from 'clutter';
import * as GLib from 'glib';
import * as Meta from 'meta';
import { MsWindow } from 'src/layout/msWorkspace/msWindow';
import { MsWorkspace } from 'src/layout/msWorkspace/msWorkspace';
import { MsManager } from 'src/manager/msManager';
import { KeyBindingAction } from 'src/module/hotKeysModule';
import { assert, assertNotNull } from 'src/utils/assert';
import { Async } from 'src/utils/async';
import { registerGObjectClass } from 'src/utils/gjs';
import { reparentActor, throttle } from 'src/utils/index';
import { main as Main } from 'ui';
import { MsWindowManager } from './msWindowManager';
/** Extension imports */
const Me = imports.misc.extensionUtils.getCurrentExtension();
interface CurrentDrag {
msWindow: MsWindow;
originPointerAnchor: [number, number];
originalParent: any;
}
export class MsDndManager extends MsManager {
msWindowManager: MsWindowManager;
signalMap: Map<any, any>;
dragInProgress: CurrentDrag | null;
inputGrabber: InputGrabber;
throttledCheckUnderPointer: (this: any) => any;
constructor(msWindowManager: MsWindowManager) {
super();
this.msWindowManager = msWindowManager;
this.signalMap = new Map();
this.dragInProgress = null;
this.inputGrabber = new InputGrabber();
this.observe(this.msWindowManager, 'ms-window-created', () => {
this.listenForMsWindowsSignal();
});
this.listenForMsWindowsSignal();
this.observe(
global.workspace_manager,
'active-workspace-changed',
() => {
if (this.dragInProgress !== null) {
const newMsWorkspace =
Me.msWorkspaceManager.getActivePrimaryMsWorkspace();
if (this.dragInProgress.msWindow.metaWindow) {
this.dragInProgress.msWindow.metaWindow.change_workspace_by_index(
global.workspace_manager.get_active_workspace_index(),
true
);
} else {
Me.msWorkspaceManager.setWindowToMsWorkspace(
this.dragInProgress.msWindow,
newMsWorkspace
);
}
this.dragInProgress.originalParent =
newMsWorkspace.msWorkspaceActor.tileableContainer;
}
}
);
this.observe(
global.display,
'grab-op-begin',
(display, metaWindow, op) => {
if (op === Meta.GrabOp.MOVING) {
const msWindow = metaWindow.msWindow;
if (
msWindow &&
msWindow.metaWindow === metaWindow &&
!msWindow.followMetaWindow
) {
global.display.end_grab_op(global.get_current_time());
this.startDrag(msWindow);
}
}
}
);
this.observe(this.inputGrabber, 'captured-event', (_, event) => {
if (this.dragInProgress !== null) {
const [stageX, stageY] = event.get_coords();
const msWindowDragged = this.dragInProgress.msWindow;
switch (event.type()) {
case Clutter.EventType.MOTION:
msWindowDragged.set_position(
Math.round(
stageX -
msWindowDragged.width *
this.dragInProgress
.originPointerAnchor[0]
),
Math.round(
stageY -
msWindowDragged.height *
this.dragInProgress
.originPointerAnchor[1]
)
);
this.throttledCheckUnderPointer();
break;
case Clutter.EventType.BUTTON_RELEASE:
this.endDrag();
break;
}
}
});
this.throttledCheckUnderPointer = throttle(
this.checkUnderThePointer,
50,
{ trailing: false }
);
}
/**
* Handle drag and drop for placeholders
*/
listenForMsWindowsSignal() {
this.msWindowManager.msWindowList.forEach((msWindow) => {
if (!this.signalMap.has(msWindow)) {
const id = msWindow.connect('event', (_, event) => {
if (this.dragInProgress) return;
switch (event.type()) {
case Clutter.EventType.MOTION:
if ((event.get_state() as number) === 320) {
this.startDrag(msWindow);
}
break;
}
});
this.signalMap.set(msWindow, id);
}
});
}
startDrag(msWindow: MsWindow) {
global.stage.add_child(this.inputGrabber);
const originalParent = msWindow.get_parent();
msWindow.freezeAllocation();
this.msWindowManager.msWindowList.forEach((aMsWindow) => {
aMsWindow.updateMetaWindowVisibility();
});
const [globalX, globalY] = global.get_pointer();
const [_, relativeX, relativeY] = msWindow.transform_stage_point(
globalX,
globalY
);
this.dragInProgress = {
msWindow,
originPointerAnchor: [
relativeX / msWindow.width,
relativeY / msWindow.height,
],
originalParent,
};
Me.layout.setActorAbove(msWindow);
this.checkUnderThePointerRoutine();
msWindow.set_position(
Math.round(
globalX -
msWindow.width * this.dragInProgress.originPointerAnchor[0]
),
Math.round(
globalY -
msWindow.height * this.dragInProgress.originPointerAnchor[1]
)
);
this.msWindowManager.msFocusManager.pushModal(this.inputGrabber);
global.display.set_cursor(Meta.Cursor.DND_IN_DRAG);
}
endDrag() {
assert(this.dragInProgress !== null, 'No drag in progress');
const { msWindow, originalParent } = this.dragInProgress;
this.dragInProgress = null;
this.msWindowManager.msFocusManager.popModal(this.inputGrabber);
global.stage.remove_child(this.inputGrabber);
msWindow.unFreezeAllocation();
reparentActor(msWindow, originalParent);
this.msWindowManager.msWindowList.forEach((aMsWindow) => {
aMsWindow.updateMetaWindowVisibility();
});
global.display.set_cursor(Meta.Cursor.DEFAULT);
}
checkUnderThePointerRoutine() {
if (this.dragInProgress === null) return;
this.throttledCheckUnderPointer();
Async.addTimeout(GLib.PRIORITY_DEFAULT, 100, () => {
this.checkUnderThePointerRoutine();
});
}
/** */
checkUnderThePointer() {
assert(this.dragInProgress !== null, 'No drag in progress');
const [x, y] = global.get_pointer();
const monitor = Main.layoutManager.currentMonitor;
//Check for all tileable of the msWindow's msWorkspace if the pointer is above another msWindow
const msWindowDragged = this.dragInProgress.msWindow;
const msWorkspace = msWindowDragged.msWorkspace;
if (monitor.index !== msWorkspace.monitor.index) {
let newMsWorkspace: MsWorkspace;
if (monitor === Main.layoutManager.primaryMonitor) {
newMsWorkspace =
Me.msWorkspaceManager.getActivePrimaryMsWorkspace();
} else {
newMsWorkspace =
Me.msWorkspaceManager.getMsWorkspacesOfMonitorIndex(
monitor.index
)[0];
}
Me.msWorkspaceManager.setWindowToMsWorkspace(
msWindowDragged,
newMsWorkspace
);
this.dragInProgress.originalParent =
newMsWorkspace.msWorkspaceActor.tileableContainer;
}
const workArea = Main.layoutManager.getWorkAreaForMonitor(
msWorkspace.monitor.index
);
const relativeX = x - workArea.x;
const relativeY = y - workArea.y;
msWorkspace.tileableList
.filter(
(tileable) =>
tileable instanceof MsWindow &&
tileable.visible &&
tileable.get_parent() ===
msWorkspace.msWorkspaceActor.tileableContainer
)
.forEach((tileable) => {
if (
relativeX >= tileable.x &&
relativeX <= tileable.x + tileable.width &&
relativeY >= tileable.y &&
relativeY <= tileable.y + tileable.height
) {
msWorkspace.swapTileable(msWindowDragged, tileable);
}
});
}
}
@registerGObjectClass
export class InputGrabber extends Clutter.Actor {
constructor() {
super({
name: 'InputGrabber',
reactive: true,
//backgroundColor: Clutter.Color.new(255, 0, 0, 100),
});
this.add_constraint(
new Clutter.BindConstraint({
source: global.stage,
coordinate: Clutter.BindCoordinate.ALL,
})
);
}
override vfunc_key_press_event(keyEvent: Clutter.KeyEvent) {
const actionId = global.display.get_keybinding_action(
keyEvent.hardware_keycode,
keyEvent.modifier_state
);
if (Me.hotKeysModule.actionIdToNameMap.has(actionId)) {
const actionName = Me.hotKeysModule.actionIdToNameMap.get(actionId);
switch (actionName) {
case KeyBindingAction.PREVIOUS_WINDOW:
assertNotNull(
Me.hotKeysModule.actionNameToActionMap.get(
KeyBindingAction.MOVE_WINDOW_LEFT
)
)();
break;
case KeyBindingAction.NEXT_WINDOW:
assertNotNull(
Me.hotKeysModule.actionNameToActionMap.get(
KeyBindingAction.MOVE_WINDOW_RIGHT
)
)();
break;
case KeyBindingAction.PREVIOUS_WORKSPACE:
assertNotNull(
Me.hotKeysModule.actionNameToActionMap.get(
KeyBindingAction.MOVE_WINDOW_TOP
)
)();
break;
case KeyBindingAction.NEXT_WORKSPACE:
assertNotNull(
Me.hotKeysModule.actionNameToActionMap.get(
KeyBindingAction.MOVE_WINDOW_BOTTOM
)
)();
break;
}
}
return false;
}
} | the_stack |
import { Rule, RuleResult, RuleFail, RuleContext, RulePotential, RuleManual, RulePass } from "../../../api/IEngine";
import { DOMUtil } from "../../../dom/DOMUtil";
import { FragmentUtil } from "../util/fragment";
import { RPTUtil } from "../util/legacy";
let a11yRulesLabel: Rule[] = [
{
/**
* Description: Raise if more than one <label> found with the same for value.
* Origin: RPT 5.6
*/
id: "RPT_Label_UniqueFor",
context: "dom:label[for]",
run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => {
const ruleContext = context["dom"].node as Element;
// JCH - NO OUT OF SCOPE hidden in context
let labelIds = RPTUtil.getCache(FragmentUtil.getOwnerFragment(ruleContext), "RPT_Label_Single", {})
let id = ruleContext.getAttribute("for");
let passed = !(id in labelIds);
labelIds[id] = true;
if (!passed) {
return RuleFail("Fail_1");
} else {
return RulePass("Pass_0");
}
}
},
{
/**
* Description: Trigger label has no content
* Origin: RPT 5.6
*/
id: "Valerie_Label_HasContent",
context: "dom:label",
run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => {
const ruleContext = context["dom"].node as Element;
if (RPTUtil.hasInnerContentHidden(ruleContext)) {
return RulePass("Pass_Regular");
} else if ((ruleContext.getAttribute("aria-label") || "").trim().length > 0) {
return RulePass("Pass_AriaLabel");
} else if (ruleContext.hasAttribute("aria-labelledby")) {
let labelElem = FragmentUtil.getById(ruleContext, ruleContext.getAttribute('aria-labelledby'));
if (labelElem && RPTUtil.hasInnerContent(labelElem)) {
return RulePass("Pass_LabelledBy");
}
}
return RuleFail("Fail_1");
}
},
{
/**
* Description: Trigger if label for points to an invalid id
* Origin: WCAG 2.0 Technique F17
*/
id: "WCAG20_Label_RefValid",
context: "dom:label[for]",
run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => {
const ruleContext = context["dom"].node as Element;
let id = ruleContext.getAttribute("for");
let passed = false;
let target = FragmentUtil.getById(ruleContext, id);
if (target) {
passed = true;
// handles null and undefined
if (!target.hasAttribute("role")) {
// Fail if we're pointing at something that is labelled by another mechanism
let nodeName = target.nodeName.toLowerCase();
passed = nodeName == "input" || nodeName == "select" || nodeName == "textarea"
|| nodeName == "button" || nodeName == "datalist"
|| nodeName == "optgroup" || nodeName == "option"
|| nodeName == "keygen" || nodeName == "output"
|| nodeName == "progress" || nodeName == "meter"
|| nodeName == "fieldset" || nodeName == "legend";
if (target.nodeName.toLowerCase() == "input" && target.hasAttribute("type")) {
let type = target.getAttribute("type").toLowerCase();
passed = type == "text" || type == "password" || type == "file" ||
type == "checkbox" || type == "radio" ||
type == "hidden" || type == "search" || type == "tel" || type == "url" || type == "email" || //HTML 5
type == "date" || type == "number" || type == "range" || type == "image" || //HTML 5
type == "time" || type == "color" || // HTML 5
type == "datetime" || type == "month" || type == "week"; //HTML5.1
}
}
// Add one more check to make sure the target element is NOT hidden, in the case the target is hidden
// flag a violation regardless of what the Check Hidden Content setting is.
if (passed && !RPTUtil.isNodeVisible(target)) {
passed = false;
}
}
let retToken : string[] = [];
if (!passed) {
retToken.push(id);
}
//return new ValidationResult(passed, [ruleContext], '', '', passed == true ? [] : [retToken]);
if (!passed) {
return RuleFail("Fail_1", retToken);
} else {
return RulePass("Pass_0");
}
}
},
{
/**
* Description: Trigger if label "for" points to an hidden element.
* Note: RPT doesn't support querying style information,
* so this rule only addresses type="hidden" elements.
* Origin: WCAG 2.0 Technique F68
*/
id: "WCAG20_Label_TargetInvisible",
context: "dom:label[for]",
run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => {
const ruleContext = context["dom"].node as Element;
let passed = true;
let id = ruleContext.getAttribute("for");
let target = FragmentUtil.getById(ruleContext, id);
if (target) {
passed = RPTUtil.getElementAttribute(target, "type") != "hidden";
}
if (passed) return RulePass("Pass_0");
if (!passed) return RulePotential("Potential_1");
}
},
{
/**
* Description: Flag a violation if Accessible name does not match or contain the visible label text.
* Origin: WCAG 2.1 Success Criterion 2.5.3: Label in Name
*/
id: "WCAG21_Label_Accessible",
context: "aria:button,aria:checkbox,aria:gridcell,aria:link,aria:menuitem,aria:menuitemcheckbox"
+",aria:menuitemradio,aria:option,aria:radio,aria:switch,aria:tab,aria:treeitem"
+",dom:input,dom:textarea,dom:select,dom:output,dom:meter",
run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => {
const ruleContext = context["dom"].node as Element;
if (!RPTUtil.isNodeVisible(ruleContext) ||
RPTUtil.isNodeDisabled(ruleContext)) {
return null;
}
let passed = true;
let nodeName = ruleContext.nodeName.toLowerCase();
let isInputButton = false;
let buttonTypes = ["button", "reset", "submit"/*, "image"*/];
let inputType = null;
if (nodeName === "input" && ruleContext.hasAttribute("type")) {
inputType = ruleContext.getAttribute("type").toLowerCase();
if (buttonTypes.indexOf(inputType) !== -1) {
isInputButton = true;
}
}
let theLabelBy = RPTUtil.getAriaAttribute(ruleContext, "aria-labelledby");
if (theLabelBy && !isInputButton) {
// skip the checks if it has an aria-labelledby since it takes precedence.
} else {
let theLabel = null;
if (theLabelBy) {
let labelValues = theLabelBy.split(/\s+/);
for (let j = 0; j < labelValues.length; ++j) {
let elementById = FragmentUtil.getById(ruleContext, labelValues[j]);
if (elementById) {
theLabel = RPTUtil.getInnerText(elementById);
break;
}
}
} else {
theLabel = RPTUtil.getAriaAttribute(ruleContext, "aria-label");
}
if (!theLabel) {
return null;
}
let text = null;
if (isInputButton) {
/* Note: Disable the alt check in images until we get confirmation
if (inputType==="image" && ruleContext.hasAttribute("alt")){
// use 'alt' attribute as visible text
text = ruleContext.getAttribute("alt");
}else
*/
if (ruleContext.hasAttribute("value")) {
// use 'value' attribute as visible text
text = ruleContext.getAttribute("value");
} else {
// use default value
if (inputType === "submit"/*||inputType==="image"*/) {
text = "submit";
} else if (inputType === "reset") {
text = "reset";
}
}
}
if (!text) {
// look for a <label> element
let labelElem = RPTUtil.getLabelForElementHidden(ruleContext, true);
if (!labelElem) {
let parentNode = DOMUtil.parentNode(ruleContext);
if (parentNode.nodeName.toLowerCase() === "label" /*&& RPTUtil.isFirstFormElement(parentNode, ruleContext)*/) {
let parentClone = parentNode.cloneNode(true);
// exclude all form elements from the label since they might also have inner content
labelElem = RPTUtil.removeAllFormElementsFromLabel(parentClone);
}
}
let element = labelElem ? labelElem : ruleContext;
let elementsToSkipContentCheck = ["meter", "output", "progress", "select", "textarea"];
if (!labelElem && elementsToSkipContentCheck.indexOf(nodeName) !== -1) {
text = ""; // skip content check for some elements
} else {
// get the visible text
text = RPTUtil.getInnerText(element);
}
/* Note: Disable this alt check in images for now until we get confirmation
// Look for the alt attribute of an image which is considered visible text.
let hasImgAlt = false;
if (element.firstChild != null) {
let nw = RPTUtil.new NodeWalker(element);
while (!hasImgAlt && nw.nextNode() && nw.node != element && nw.node != element.nextSibling) {
hasImgAlt = (nw.node.nodeName.toLowerCase() == "img" && RPTUtil.attributeNonEmpty(nw.node, "alt"));
if (hasImgAlt) {
text = text ? text + nw.node.getAttribute("alt") : nw.node.getAttribute("alt");
}
}
}
*/
}
let nonalphanumeric = /[^a-zA-Z0-9]/g;
text = text.replace(nonalphanumeric, " "); // only consider alphanumeric characters
let normalizedText = RPTUtil.normalizeSpacing(text).toLowerCase(); // Leading and trailing whitespace and difference in case sensitivity should be ignored.
theLabel = theLabel.replace(nonalphanumeric, " "); // only consider alphanumeric characters
let normalizedLabel = RPTUtil.normalizeSpacing(theLabel).toLowerCase();
if (normalizedText.length > 1) { // skip non-text content. e.g. <button aria-label="close">X</button>
let location = normalizedLabel.indexOf(normalizedText);
// Avoid matching partial words.e.g. text "name" should not match 'surname' or 'names'
if (location >= 0 && normalizedLabel.length > normalizedText.length) {
let letters = /^[0-9a-zA-Z]+$/;
if ((location + normalizedText.length) < normalizedLabel.length) {
// check ending
let theChar = normalizedLabel.charAt(location + normalizedText.length);
if (theChar.match(letters)) {
passed = false;
}
}
if (passed && location > 0) {
// check beginning
let theChar = normalizedLabel.charAt(location - 1);
if (theChar.match(letters)) {
passed = false;
}
}
}
if (location === -1) { // check that visible text content of the target is contained within its accessible name.
passed = false;
}
}
}
if (!passed) {
return RuleFail("Fail_1");
} else {
return RulePass("Pass_0");
}
}
}
]
export { a11yRulesLabel } | the_stack |
import {
SearchedArtifact,
SearchedVersion,
ArtifactMetaData,
Rule,
VersionMetaData,
ContentTypes
} from "../../models";
import {BaseService} from "../baseService";
import YAML from "yaml";
export interface CreateArtifactData {
groupId: string;
id: string|null;
type: string;
content: string;
}
export interface CreateVersionData {
type: string;
content: string;
}
export interface GetArtifactsCriteria {
type: string;
value: string;
sortAscending: boolean;
}
export interface Paging {
page: number;
pageSize: number;
}
export interface ArtifactsSearchResults {
artifacts: SearchedArtifact[];
count: number;
page: number;
pageSize: number;
}
export interface EditableMetaData {
name: string;
description: string;
labels: string[];
}
/**
* The artifacts service. Used to query the backend search API to fetch lists of
* artifacts and also details about individual artifacts.
*/
export class GroupsService extends BaseService {
public createArtifact(data: CreateArtifactData): Promise<ArtifactMetaData> {
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts", { groupId: data.groupId });
const headers: any = {};
if (data.id) {
headers["X-Registry-ArtifactId"] = data.id;
}
if (data.type) {
headers["X-Registry-ArtifactType"] = data.type;
}
headers["Content-Type"] = this.contentType(data.type, data.content);
return this.httpPostWithReturn<any, ArtifactMetaData>(endpoint, data.content, this.options(headers));
}
public createArtifactVersion(groupId: string|null, artifactId: string, data: CreateVersionData): Promise<VersionMetaData> {
groupId = this.normalizeGroupId(groupId);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/versions", { groupId, artifactId });
const headers: any = {};
if (data.type) {
headers["X-Registry-ArtifactType"] = data.type;
}
headers["Content-Type"] = this.contentType(data.type, data.content);
return this.httpPostWithReturn<any, VersionMetaData>(endpoint, data.content, this.options(headers));
}
public getArtifacts(criteria: GetArtifactsCriteria, paging: Paging): Promise<ArtifactsSearchResults> {
this.logger.debug("[GroupsService] Getting artifacts: ", criteria, paging);
const start: number = (paging.page - 1) * paging.pageSize;
const end: number = start + paging.pageSize;
const queryParams: any = {
limit: end,
offset: start,
order: criteria.sortAscending ? "asc" : "desc",
orderby: "name"
};
if (criteria.value) {
if (criteria.type == "everything") {
queryParams["name"] = criteria.value;
queryParams["description"] = criteria.value;
queryParams["labels"] = criteria.value;
} else {
queryParams[criteria.type] = criteria.value;
}
}
const endpoint: string = this.endpoint("/v2/search/artifacts", {}, queryParams);
return this.httpGet<ArtifactsSearchResults>(endpoint, undefined, (data) => {
const results: ArtifactsSearchResults = {
artifacts: data.artifacts,
count: data.count,
page: paging.page,
pageSize: paging.pageSize
};
return results;
});
}
public getArtifactMetaData(groupId: string|null, artifactId: string, version: string): Promise<ArtifactMetaData> {
groupId = this.normalizeGroupId(groupId);
let endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/versions/:version/meta", { groupId, artifactId, version });
if (version === "latest") {
endpoint = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/meta", { groupId, artifactId });
}
return this.httpGet<ArtifactMetaData>(endpoint);
}
public updateArtifactMetaData(groupId: string|null, artifactId: string, version: string, metaData: EditableMetaData): Promise<void> {
groupId = this.normalizeGroupId(groupId);
let endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/versions/:version/meta", { groupId, artifactId, version });
if (version === "latest") {
endpoint = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/meta", { groupId, artifactId });
}
return this.httpPut<EditableMetaData>(endpoint, metaData);
}
public getArtifactContent(groupId: string|null, artifactId: string, version: string): Promise<string> {
groupId = this.normalizeGroupId(groupId);
let endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/versions/:version", { groupId, artifactId, version });
if (version === "latest") {
endpoint = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId", { groupId, artifactId });
}
const options: any = this.options({
"Accept": "*"
});
options.maxContentLength = "5242880"; // TODO 5MB hard-coded, make this configurable?
options.responseType = "text";
options.transformResponse = (data: any) => data;
return this.httpGet<string>(endpoint, options);
}
public getArtifactVersions(groupId: string|null, artifactId: string): Promise<SearchedVersion[]> {
groupId = this.normalizeGroupId(groupId);
this.logger.info("[GroupsService] Getting the list of versions for artifact: ", groupId, artifactId);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/versions", { groupId, artifactId }, {
limit: 500,
offset: 0
});
return this.httpGet<SearchedVersion[]>(endpoint, undefined, (data) => {
return data.versions;
});
}
public getArtifactRules(groupId: string|null, artifactId: string): Promise<Rule[]> {
groupId = this.normalizeGroupId(groupId);
this.logger.info("[GroupsService] Getting the list of rules for artifact: ", groupId, artifactId);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/rules", { groupId, artifactId });
return this.httpGet<string[]>(endpoint).then( ruleTypes => {
return Promise.all(ruleTypes.map(rt => this.getArtifactRule(groupId, artifactId, rt)));
});
}
public getArtifactRule(groupId: string|null, artifactId: string, type: string): Promise<Rule> {
groupId = this.normalizeGroupId(groupId);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/rules/:rule", {
groupId,
artifactId,
rule: type
});
return this.httpGet<Rule>(endpoint);
}
public createArtifactRule(groupId: string|null, artifactId: string, type: string, config: string): Promise<Rule> {
groupId = this.normalizeGroupId(groupId);
this.logger.info("[GroupsService] Creating rule:", type);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/rules", { groupId, artifactId });
const body: Rule = {
config,
type
};
return this.httpPostWithReturn(endpoint, body);
}
public updateArtifactRule(groupId: string|null, artifactId: string, type: string, config: string): Promise<Rule> {
groupId = this.normalizeGroupId(groupId);
this.logger.info("[GroupsService] Updating rule:", type);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/rules/:rule", {
groupId,
artifactId,
"rule": type
});
const body: Rule = { config, type };
return this.httpPutWithReturn<Rule, Rule>(endpoint, body);
}
public deleteArtifactRule(groupId: string|null, artifactId: string, type: string): Promise<void> {
groupId = this.normalizeGroupId(groupId);
this.logger.info("[GroupsService] Deleting rule:", type);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId/rules/:rule", {
groupId,
artifactId,
"rule": type
});
return this.httpDelete(endpoint);
}
public deleteArtifact(groupId: string|null, artifactId: string): Promise<void> {
groupId = this.normalizeGroupId(groupId);
this.logger.info("[GroupsService] Deleting artifact:", groupId, artifactId);
const endpoint: string = this.endpoint("/v2/groups/:groupId/artifacts/:artifactId", { groupId, artifactId });
return this.httpDelete(endpoint);
}
private normalizeGroupId(groupId: string|null): string {
return groupId || "default";
}
private contentType(type: string, content: string): string {
switch (type) {
case "PROTOBUF":
return ContentTypes.APPLICATION_PROTOBUF;
case "WSDL":
case "XSD":
case "XML":
return ContentTypes.APPLICATION_XML;
case "GRAPHQL":
return ContentTypes.APPLICATION_GRAPHQL;
}
if (this.isJson(content)) {
return ContentTypes.APPLICATION_JSON;
} else if (this.isXml(content)) {
return ContentTypes.APPLICATION_XML;
} else if (this.isYaml(content)) {
return ContentTypes.APPLICATION_YAML;
} else {
return "application/octet-stream";
}
}
private isJson(content: string): boolean {
try {
JSON.parse(content);
return true;
} catch (e) {
return false;
}
}
private isXml(content: string): boolean {
try {
const xmlParser: DOMParser = new DOMParser();
const dom: Document = xmlParser.parseFromString(content, "application/xml");
const isParseError: boolean = dom.getElementsByTagName("parsererror").length !== 0;
return !isParseError;
} catch (e) {
return false;
}
}
private isYaml(content: string): boolean {
try {
const parsedContent: any = YAML.parse(content);
return typeof parsedContent === "object";
} catch (e) {
return false;
}
}
} | the_stack |
import { useEffect, useMemo } from 'react'
import {
useHistoricalPricesState,
useTB3HistoricalPricesState,
} from '../atoms/historicalPricesState'
import {
Cashflows,
Portfolio,
useCashflowState,
useDateRangeValue,
useInitialAmountState,
usePortfoliosState,
useSetLabLoading,
} from '../atoms/labSettingState'
import { Indicator, PortfolioResult, useSetReport } from '../atoms/reportState'
import { HistoricalPrice } from '../lib/api/assets/types'
import useUnfetchedTickers from './useUnfetchedTickers'
import useFirstHistoricalDate from './useFirstHistoricalDate'
import { periodToMonthsMap } from '../lib/constants'
import {
cagr,
maxDrawdown,
sharpeRatio,
sortinoRatio,
stdev,
} from '../lib/utils/calculateIndicators'
import useDateRangeHook from './useDateRangeHook'
type GenerateReportDataParams = {
initialAmount: number
portfolios: Portfolio[]
pricesByTicker: Record<string, HistoricalPrice[]>
startDate: Date
lastDate: Date
cashflows: Cashflows
tb3HistoricalPrices: HistoricalPrice[]
}
const initialIndicator: Indicator = {
finalBalance: 0,
cagr: 0,
stdev: 0,
mdd: 0,
sharpeRatio: 0,
sortinoRatio: null,
best: { year: 0, month: 0 },
worst: { year: 0, month: 0 },
}
type IndicatorRecord = Record<number, Indicator>
function generateReportData({
initialAmount,
portfolios,
pricesByTicker,
startDate,
lastDate,
cashflows,
tb3HistoricalPrices,
}: GenerateReportDataParams): PortfolioResult[] {
// 1. filter prices that contains date bigger than given start date
const startTime = new Date(startDate).getTime()
const lastTime = lastDate.getTime()
const filterByTime = (hp: HistoricalPrice) => {
const d = new Date(hp.date)
return d.getTime() >= startTime && d.getTime() < lastTime
}
const filteredPricesByTicker = Object.entries(pricesByTicker).reduce(
(acc, [ticker, prices]) => {
acc[ticker] = prices.filter(filterByTime)
return acc
},
{} as typeof pricesByTicker
)
/* day - 1 since each historical price is the rate of the first day of the month
2020-01-01 -> 2019-12-31
filter startDate
*/
const processedTB3HistoricalPrices = tb3HistoricalPrices
.map((hp) => {
const d = new Date(hp.date)
d.setDate(0)
return {
...hp,
date: d.toISOString(),
}
})
.filter(filterByTime)
// 1.5. calculate risk free rate
const riskFreeRates = processedTB3HistoricalPrices.map(
(hp) => hp.close / 3 / 100
)
// 2. generate report data based on portfolios
const monthsCount = Object.values(filteredPricesByTicker)[0].length
const months = Object.values(filteredPricesByTicker)[0].map((hp) => hp.date)
const diff = months.length - 1 - riskFreeRates.length
if (diff > 0) {
for (let i = 0; i < diff; i += 1) {
riskFreeRates.push(riskFreeRates[riskFreeRates.length - 1])
}
}
return portfolios.map((portfolio) => {
const yearlyBalance: { date: Date; balance: number }[] = []
const yearlyBalanceWOC: { date: Date; balance: number }[] = []
const yearlyBalances = [yearlyBalance, yearlyBalanceWOC]
const fixedYearlyBalance: { date: Date; balance: number }[] = []
const indicator: Indicator = { ...initialIndicator }
const dataset: number[] = [initialAmount]
const datasetWOC: number[] = [initialAmount]
const tickerValueMap = new Map<string, number>()
const tickerValueMapWOC = new Map<string, number>() // without cashflow
const tickerValueMaps = [tickerValueMap, tickerValueMapWOC]
const weightSum = portfolio.assets.reduce(
(acc, current) => acc + current.weight,
0
)
// set initial amount for each tickers
portfolio.assets.forEach((asset) => {
tickerValueMaps.forEach((tvm) => {
tvm.set(asset.ticker, (initialAmount * asset.weight) / weightSum)
})
})
yearlyBalances.forEach((yb) => {
yb.push({
date: startDate,
balance: initialAmount,
})
})
fixedYearlyBalance.push({
date: new Date(months[0]),
balance: initialAmount,
})
for (let i = 1; i < monthsCount; i += 1) {
portfolio.assets.forEach((asset) => {
const prices = filteredPricesByTicker[asset.ticker]
const pricePrev = prices[i - 1].close
const priceCurrent = prices[i].close
// const diffRatio = (priceCurrent - pricePrev) / pricePrev
const ratio = priceCurrent / pricePrev
tickerValueMaps.forEach((tvm) => {
const currentAmount = tvm.get(asset.ticker)!
const priceNext = ratio * currentAmount
tvm.set(asset.ticker, priceNext)
})
})
if (cashflows.enabled) {
const monthsPeriod = periodToMonthsMap[cashflows.period] ?? null
if (monthsPeriod && i % monthsPeriod === 0) {
portfolio.assets.forEach((asset) => {
const currentValue = tickerValueMap.get(asset.ticker)!
tickerValueMap.set(
asset.ticker,
currentValue + (cashflows.amount * asset.weight) / weightSum
)
})
}
}
let [totalAmount, totalAmountWOC] = tickerValueMaps.map((tvm) =>
Array.from(tvm.values()).reduce(
(acc: number, current: number) => acc + current,
0
)
)
if (portfolio.rebalancing !== 'No Rebalancing') {
const monthsPeriod = periodToMonthsMap[portfolio.rebalancing] ?? null
if (monthsPeriod && i % monthsPeriod === 0) {
portfolio.assets.forEach((asset) => {
tickerValueMap.set(
asset.ticker,
totalAmount * (asset.weight / weightSum)
)
tickerValueMapWOC.set(
asset.ticker,
totalAmountWOC * (asset.weight / weightSum)
)
})
}
}
const d = new Date(months[i])
if (d.getMonth() === 11 || i === monthsCount - 1) {
fixedYearlyBalance.push({
date: d,
balance: totalAmountWOC,
})
}
if (i % 12 === 0) {
yearlyBalance.push({
date: d,
balance: totalAmount,
})
yearlyBalanceWOC.push({
date: d,
balance: totalAmountWOC,
})
}
dataset.push(totalAmount)
datasetWOC.push(totalAmountWOC)
}
/* this rate includes cashflow
const yearlyProfitRate = yearlyBalance.reduce<number[]>(
(acc, current, i, array) => {
if (i === 0) return acc
const prev = array[i - 1]
const diff = current.balance - prev.balance
const rate = diff / prev.balance
acc.push(rate)
return acc
},
[]
)
*/
const monthlyRateWOC = datasetWOC.reduce<number[]>(
(acc, current, i, arr) => {
if (i === 0) return acc
const prev = arr[i - 1]
const diff = current - prev
const rate = diff / prev
acc.push(rate)
return acc
},
[]
)
const yearlyRateWOC = yearlyBalanceWOC.reduce<number[]>(
(acc, current, i, array) => {
if (i === 0) return acc
const prev = array[i - 1]
const diff = current.balance - prev.balance
const rate = diff / prev.balance
acc.push(rate)
return acc
},
[]
)
const fixedYearlyRate = fixedYearlyBalance.reduce<
{
year: number
rate: number
}[]
>((acc, current, i, array) => {
if (i === 0) return acc
const prev = array[i - 1]
const rate = current.balance / prev.balance - 1
acc.push({
year: new Date(current.date).getFullYear(),
rate,
})
return acc
}, [])
const best = {
year: Math.max(...fixedYearlyRate.map((fyr) => fyr.rate)),
month: Math.max(...monthlyRateWOC),
}
const worst = {
year: Math.min(...fixedYearlyRate.map((fyr) => fyr.rate)),
month: Math.min(...monthlyRateWOC),
}
indicator.finalBalance = dataset[dataset.length - 1]
indicator.cagr = cagr({
beginningValue: initialAmount,
endingValue: datasetWOC[datasetWOC.length - 1],
yearsCount: monthsCount / 12,
})
indicator.mdd = maxDrawdown(datasetWOC)
indicator.stdev = stdev(monthlyRateWOC) * Math.sqrt(12) // Annualized
indicator.sharpeRatio = sharpeRatio(monthlyRateWOC, riskFreeRates)
indicator.sortinoRatio = sortinoRatio(monthlyRateWOC, riskFreeRates)
indicator.best = best
indicator.worst = worst
// indicator.sortinoRatio = sortinoRatio(monthlyRateWOC, riskFreeRates)
return {
id: portfolio.id,
name: portfolio.name,
returns: dataset.map((value, i) => ({
x: new Date(months[i]),
y: value,
})),
monthlyRate: monthlyRateWOC.map((rate, i) => ({
x: new Date(months[i]),
y: rate,
})),
yearlyRate: fixedYearlyRate.map((rate, i) => ({
x: rate.year,
y: rate.rate,
})),
indicator,
}
})
}
export default function useGenerateReportEffect() {
const [initialAmount] = useInitialAmountState()
const [{ pricesByTicker }] = useHistoricalPricesState()
const firstHistoricalDate = useFirstHistoricalDate()
const [cashflows] = useCashflowState()
const dateRange = useDateRangeValue()
const [portfolios] = usePortfoliosState()
const unfetchedTickers = useUnfetchedTickers()
const [{ prices: tb3HistoricalPrices }] = useTB3HistoricalPricesState()
const setReport = useSetReport()
const setLoading = useSetLabLoading()
const { setStartDate } = useDateRangeHook()
const startDate = useMemo(() => {
const { year, month } = dateRange.startDate
if (!firstHistoricalDate) return null
const configuredStartDate = new Date(year, month - 2)
return firstHistoricalDate.date > configuredStartDate
? firstHistoricalDate.date
: configuredStartDate
}, [firstHistoricalDate, dateRange])
useEffect(() => {
if (!startDate) return
const date = new Date(startDate.getFullYear(), startDate.getMonth() + 2)
const startDateInfo = {
year: date.getFullYear(),
month: date.getMonth(),
}
// configured
const { year: cYear, month: cMonth } = dateRange.startDate
// managed
const { year: mYear, month: mMonth } = startDateInfo
if (cYear !== mYear || cMonth !== mMonth) {
setStartDate({
month: mMonth,
year: mYear,
})
}
}, [startDate, dateRange.startDate, setStartDate])
useEffect(() => {
if (unfetchedTickers.length > 0 || !startDate) {
return
}
if (!tb3HistoricalPrices) return
const validPortfolios = portfolios.filter((p) => p.assets.length !== 0)
const report = generateReportData({
initialAmount,
portfolios: validPortfolios,
pricesByTicker,
startDate,
cashflows,
lastDate: new Date(dateRange.endDate.year, dateRange.endDate.month), // + 1month,
tb3HistoricalPrices,
})
setLoading(false)
setReport(report)
}, [
initialAmount,
pricesByTicker,
startDate,
portfolios,
unfetchedTickers,
cashflows,
dateRange,
tb3HistoricalPrices,
setReport,
setLoading,
])
// check unfetchedTickers is empty before fetch
} | the_stack |
import fs from "fs/promises";
import path from "path";
import { URL } from "url";
import {
AdditionalModules,
BeforeSetupResult,
Compatibility,
Context,
Log,
Mutex,
Options,
PluginContext,
PluginEntries,
PluginOptions,
PluginOptionsUnion,
PluginSignatures,
RequestContext,
ScriptBlueprint,
ScriptRunner,
ScriptRunnerResult,
SetupResult,
StorageFactory,
TypedEventTarget,
WranglerConfig,
addAll,
logOptions,
resolveStoragePersist,
} from "@miniflare/shared";
import type { Watcher } from "@miniflare/watcher";
import { dequal } from "dequal/lite";
import { dim } from "kleur/colors";
import { MiniflareCoreError } from "./error";
import { formatSize, pathsToString } from "./helpers";
import {
BindingsPlugin,
CorePlugin,
_CoreMount,
_populateBuildConfig,
} from "./plugins";
import { Router } from "./router";
import {
Request,
RequestInfo,
RequestInit,
Response,
ServiceWorkerGlobalScope,
_kLoopHeader,
kAddModuleFetchListener,
kAddModuleScheduledListener,
kDispatchFetch,
kDispatchScheduled,
kDispose,
withImmutableHeaders,
withStringFormDataFiles,
} from "./standards";
import { PluginStorageFactory } from "./storage";
export * from "./plugins";
export * from "./standards";
export * from "./error";
export * from "./router";
export * from "./storage";
/** @internal */
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function _deepEqual(a: any, b: any): boolean {
if (!dequal(a, b)) return false;
// Check top-level symbol properties are equal (used by BindingsPlugin for
// Wrangler variables)
if (typeof a === "object") {
const aSymbols = Object.getOwnPropertySymbols(a);
for (const aSymbol of aSymbols) {
if (!(aSymbol in b) || !dequal(a[aSymbol], b[aSymbol])) return false;
}
return aSymbols.length === Object.getOwnPropertySymbols(b).length;
}
return true;
}
export type CorePluginSignatures = PluginSignatures & {
CorePlugin: typeof CorePlugin;
};
export type PluginInstances<Plugins extends PluginSignatures> = {
[K in keyof Plugins]: InstanceType<Plugins[K]>;
};
type PluginData<Plugins extends PluginSignatures, Data> = Map<
keyof Plugins,
Data
>;
export type MiniflareCoreOptions<Plugins extends CorePluginSignatures> = Omit<
Options<Plugins>,
"mounts" // Replace Record<string, string | ...> from CoreOptions...
> & {
// ...with Record that allows any options from Plugins to be specified,
// disallowing nesting
mounts?: Record<string, string | Omit<Options<Plugins>, "mounts">>;
};
function getPluginEntries<Plugins extends PluginSignatures>(
plugins: Plugins
): PluginEntries<Plugins> {
// Split plugins into entries so they're easier to iterate later on.
// Also make sure CorePlugin is always first (so other plugins can override
// built-ins, e.g. WebSocketPlugin overriding fetch to handle WebSocket
// upgrades), and BindingsPlugin (if included) is always last (so user can
// override any binding/global).
const entries = Object.entries(plugins) as PluginEntries<Plugins>;
let coreIndex = -1;
let bindingsIndex = -1;
for (let i = 0; i < entries.length; i++) {
const [, plugin] = entries[i];
// @ts-expect-error plugin has type `typeof Plugin`
if (plugin === CorePlugin) coreIndex = i;
// @ts-expect-error plugin has type `typeof Plugin`
else if (plugin === BindingsPlugin) bindingsIndex = i;
}
// If CorePlugin isn't already first, move it to start
if (coreIndex > 0) {
entries.unshift(...entries.splice(coreIndex, 1));
}
// If BindingsPlugin isn't already last (and it was included), move it to end
if (bindingsIndex !== -1 && bindingsIndex !== entries.length - 1) {
entries.push(...entries.splice(bindingsIndex, 1));
}
return entries;
}
function splitPluginOptions<Plugins extends CorePluginSignatures>(
plugins: PluginEntries<Plugins>,
options: MiniflareCoreOptions<Plugins>
): PluginOptions<Plugins> {
const result = {} as PluginOptions<Plugins>;
for (const [name, plugin] of plugins) {
const pluginResult = {} as PluginOptionsUnion<Plugins>;
for (const key of plugin.prototype.opts?.keys() ?? []) {
// Only include defined keys, otherwise all options defined in Wrangler
// config would be unset
if (key in (options as any)) {
(pluginResult as any)[key] = (options as any)[key];
}
}
result[name] = pluginResult;
}
return result;
}
function splitWranglerConfig<Plugins extends PluginSignatures>(
plugins: PluginEntries<Plugins>,
overrides: PluginOptions<Plugins>,
config: WranglerConfig,
configDir: string
): PluginOptions<Plugins> {
// Create a new options object so we don't override overrides with undefined,
// causing future reloads to unset config defined in Wrangler
const result = {} as PluginOptions<Plugins>;
for (const [name, plugin] of plugins) {
const pluginResult = {} as PluginOptionsUnion<Plugins>;
const pluginOverrides = overrides[name];
for (const [key, meta] of plugin.prototype.opts?.entries() ?? []) {
// TODO: merge object options (e.g. bindings)
// `in` check means users can pass `undefined` to unset options defined
// in wrangler.toml
if (key in pluginOverrides) {
(pluginResult as any)[key] = pluginOverrides[key];
} else {
(pluginResult as any)[key] = meta.fromWrangler?.(config, configDir);
}
}
result[name] = pluginResult;
}
return result;
}
const pathResolve = (p: string) => path.resolve(p);
function throwNoScriptError(modules?: boolean) {
const execName = process.env.MINIFLARE_EXEC_NAME ?? "miniflare";
const script = modules ? "worker.mjs" : "worker.js";
const format = modules ? "modules" : "service-worker";
const pkgScriptField = modules ? "module" : "main";
const lines = [
"No script defined, either:",
"- Pass it as a positional argument, if you're using the CLI",
dim(` $ ${execName} dist/${script}`),
"- Set the script or scriptPath option, if you're using the API",
dim(` new Miniflare({ scriptPath: "dist/${script}" })`),
`- Set ${pkgScriptField} in package.json`,
dim(` { "${pkgScriptField}": "dist/${script}" }`),
];
if (modules) {
lines.push(
"- Set build.upload.main in wrangler.toml",
dim(" [build.upload]"),
dim(` format = "${format}"`),
dim(` dir = "dist"`),
dim(` main = "${script}"`)
);
}
lines.push("");
throw new MiniflareCoreError("ERR_NO_SCRIPT", lines.join("\n"));
}
export interface MiniflareCoreContext {
log: Log;
storageFactory: StorageFactory;
scriptRunner?: ScriptRunner;
scriptRequired?: boolean;
scriptRunForModuleExports?: boolean;
isMount?: boolean;
}
export class ReloadEvent<Plugins extends PluginSignatures> extends Event {
readonly plugins: PluginInstances<Plugins>;
readonly initial: boolean;
constructor(
type: "reload",
init: { plugins: PluginInstances<Plugins>; initial: boolean }
) {
super(type);
this.plugins = init.plugins;
this.initial = init.initial;
}
}
export type MiniflareCoreEventMap<Plugins extends PluginSignatures> = {
reload: ReloadEvent<Plugins>;
};
export class MiniflareCore<
Plugins extends CorePluginSignatures
> extends TypedEventTarget<MiniflareCoreEventMap<Plugins>> {
readonly #originalPlugins: Plugins;
readonly #plugins: PluginEntries<Plugins>;
#previousSetOptions: MiniflareCoreOptions<Plugins>;
#overrides: PluginOptions<Plugins>;
#previousOptions?: PluginOptions<Plugins>;
readonly #ctx: MiniflareCoreContext;
readonly #pluginStorages: PluginData<Plugins, PluginStorageFactory>;
#compat?: Compatibility;
#previousRootPath?: string;
#previousGlobalAsyncIO?: boolean;
#instances?: PluginInstances<Plugins>;
#mounts?: Map<string, MiniflareCore<Plugins>>;
#router?: Router;
#wranglerConfigPath?: string;
#watching?: boolean;
#beforeSetupWatch?: PluginData<Plugins, Set<string>>;
#setupWatch?: PluginData<Plugins, Set<string>>;
#setupResults?: PluginData<Plugins, SetupResult>;
readonly #scriptWatchPaths = new Set<string>();
#reloaded = false;
#globalScope?: ServiceWorkerGlobalScope;
#bindings?: Context;
#moduleExports?: Context;
#watcher?: Watcher;
#watcherCallbackMutex?: Mutex;
#previousWatchPaths?: Set<string>;
constructor(
plugins: Plugins,
ctx: MiniflareCoreContext,
options: MiniflareCoreOptions<Plugins> = {} as MiniflareCoreOptions<Plugins>
) {
super();
this.#originalPlugins = plugins;
this.#plugins = getPluginEntries(plugins);
this.#previousSetOptions = options;
this.#overrides = splitPluginOptions(this.#plugins, options);
this.#ctx = ctx;
this.#pluginStorages = new Map<keyof Plugins, PluginStorageFactory>();
this.#initPromise = this.#init().then(() => this.#reload());
}
#updateWatch(
data: PluginData<Plugins, Set<string>>,
name: keyof Plugins,
result: BeforeSetupResult | void
): void {
if (this.#watching && result?.watch) {
const resolved = result.watch.map(pathResolve);
data.set(name, new Set(resolved));
} else {
data.delete(name);
}
}
async #runBeforeSetup(name: keyof Plugins): Promise<boolean> {
const instance = this.#instances![name];
if (!instance.beforeSetup) return false;
this.#ctx.log.verbose(`- beforeSetup(${name})`);
const result = await instance.beforeSetup();
this.#updateWatch(this.#beforeSetupWatch!, name, result);
return true;
}
async #runSetup(name: keyof Plugins): Promise<boolean> {
const instance = this.#instances![name];
if (!instance.setup) return false;
this.#ctx.log.verbose(`- setup(${name})`);
const result = await instance.setup(this.getPluginStorage(name));
this.#updateWatch(this.#setupWatch!, name, result);
this.#setupResults!.set(name, result ?? {});
return true;
}
readonly #initPromise: Promise<void>;
async #init(reloadAll = false): Promise<void> {
// The caller must eventually call #reload() at some point after #init()
this.#ctx.log.debug("Initialising worker...");
// Get required options
const previous = this.#previousOptions;
let options = this.#overrides;
const rootPath = options.CorePlugin.rootPath ?? process.cwd();
// Merge in wrangler config if defined
const originalConfigPath = options.CorePlugin.wranglerConfigPath;
const configEnv = options.CorePlugin.wranglerConfigEnv;
let configPath =
originalConfigPath === true ? "wrangler.toml" : originalConfigPath;
if (configPath) {
configPath = path.resolve(rootPath, configPath);
this.#wranglerConfigPath = configPath;
try {
const configData = await fs.readFile(configPath, "utf8");
const toml: typeof import("@iarna/toml") = require("@iarna/toml");
const config: WranglerConfig = toml.parse(configData);
if (configEnv && config.env && configEnv in config.env) {
// TODO: take into account option inheritance properly
Object.assign(config, config.env[configEnv]);
}
const configDir = path.dirname(configPath);
// Add build configuration for webpack and rust builds
_populateBuildConfig(config, configDir, configEnv);
options = splitWranglerConfig(
this.#plugins,
this.#overrides,
config,
configDir
);
} catch (e: any) {
// Ignore ENOENT (file not found) errors for default path
if (!(e.code === "ENOENT" && originalConfigPath === true)) {
throw e;
}
}
}
// Store the watching option for the first init only. We don't want to stop
// watching if the user changes the watch option in wrangler config mid-way
// through execution. (NOTE: ??= will only assign on undefined, not false)
this.#watching ??= options.CorePlugin.watch ?? false;
// Build compatibility manager, rebuild all plugins if reloadAll is set,
// compatibility data, root path or any limits have changed
const { compatibilityDate, compatibilityFlags, globalAsyncIO } =
options.CorePlugin;
let ctxUpdate =
(this.#previousRootPath && this.#previousRootPath !== rootPath) ||
this.#previousGlobalAsyncIO !== globalAsyncIO ||
reloadAll;
this.#previousRootPath = rootPath;
if (this.#compat) {
if (this.#compat.update(compatibilityDate, compatibilityFlags)) {
ctxUpdate = true;
}
} else {
this.#compat = new Compatibility(compatibilityDate, compatibilityFlags);
}
const ctx: PluginContext = {
log: this.#ctx.log,
compat: this.#compat,
rootPath,
globalAsyncIO,
};
// Log options and compatibility flags every time they might've changed
logOptions(this.#plugins, this.#ctx.log, options);
const enabled = this.#compat.enabled;
this.#ctx.log.debug(
`Enabled Compatibility Flags:${enabled.length === 0 ? " <none>" : ""}`
);
for (const flag of enabled) this.#ctx.log.debug(`- ${flag}`);
// Create plugin instances and run beforeSetup hooks, recreating any plugins
// with changed options
this.#instances ??= {} as PluginInstances<Plugins>;
this.#beforeSetupWatch ??= new Map<keyof Plugins, Set<string>>();
let ranBeforeSetup = false;
for (const [name, plugin] of this.#plugins) {
if (
previous !== undefined &&
!ctxUpdate &&
_deepEqual(previous[name], options[name])
) {
continue;
}
// If we have an existing instance, run its cleanup first
const existingInstance = this.#instances[name];
if (existingInstance?.dispose) {
this.#ctx.log.verbose(`- dispose(${name})`);
await existingInstance.dispose();
}
const instance = new plugin(ctx, options[name]);
this.#instances[name] = instance as any;
if (await this.#runBeforeSetup(name)) ranBeforeSetup = true;
}
// Run setup hooks for (re)created plugins
this.#setupWatch ??= new Map<keyof Plugins, Set<string>>();
this.#setupResults ??= new Map<keyof Plugins, SetupResult>();
for (const [name] of this.#plugins) {
if (
previous !== undefined &&
!ctxUpdate &&
_deepEqual(previous[name], options[name]) &&
// Make sure if we ran any beforeSetups and this plugin previously
// returned scripts, that we rerun its setup
!(ranBeforeSetup && this.#setupResults.get(name)?.script)
) {
continue;
}
await this.#runSetup(name);
}
// Store previous options so we can diff them later when wrangler config
// changes
this.#previousOptions = options;
// Update mounts
this.#mounts ??= new Map();
const mounts = options.CorePlugin
.mounts as MiniflareCoreOptions<Plugins>["mounts"];
if (mounts) {
// Always copy watch option
const defaultMountOptions: {
watch?: boolean;
kvPersist?: boolean | string;
cachePersist?: boolean | string;
durableObjectsPersist?: boolean | string;
} = { watch: this.#watching || undefined };
// Copy defined storage persistence options, we want mounted workers to
// share the same underlying storage for shared namespaces.
// (this tight coupling makes me sad)
const kvPersist = resolveStoragePersist(
rootPath,
options.KVPlugin?.kvPersist
);
const cachePersist = resolveStoragePersist(
rootPath,
options.CachePlugin?.cachePersist
);
const durableObjectsPersist = resolveStoragePersist(
rootPath,
options.DurableObjectsPlugin?.durableObjectsPersist
);
if (kvPersist !== undefined) {
defaultMountOptions.kvPersist = kvPersist;
}
if (cachePersist !== undefined) {
defaultMountOptions.cachePersist = cachePersist;
}
if (durableObjectsPersist !== undefined) {
defaultMountOptions.durableObjectsPersist = durableObjectsPersist;
}
// Create new and update existing mounts
for (const [name, rawOptions] of Object.entries(mounts)) {
if (name === "") {
throw new MiniflareCoreError(
"ERR_MOUNT_NO_NAME",
"Mount name cannot be empty"
);
}
const mountOptions: MiniflareCoreOptions<Plugins> =
typeof rawOptions === "string"
? ({
...defaultMountOptions,
rootPath: rawOptions,
// Autoload configuration from files
packagePath: true,
envPath: true,
wranglerConfigPath: true,
} as any)
: {
...defaultMountOptions,
...rawOptions,
};
if ("mounts" in mountOptions) {
throw new MiniflareCoreError(
"ERR_MOUNT_NESTED",
"Nested mounts are unsupported"
);
}
let mount = this.#mounts.get(name);
if (mount) {
this.#ctx.log.verbose(`Updating mount \"${name}\"...`);
// Don't dispatch a "reload" event once the worker has reloaded,
// this would update this (the parent's) router and reload it, which
// we're already going to do at the end of this function.
await mount.setOptions(mountOptions, /* dispatchReloadEvent */ false);
} else {
this.#ctx.log.debug(`Mounting \"${name}\"...`);
let log = this.#ctx.log;
// Not using `instanceof` here, we don't want subclasses
if (Object.getPrototypeOf(this.#ctx.log) === Log.prototype) {
log = new Log(this.#ctx.log.level, { suffix: name });
}
const ctx: MiniflareCoreContext = {
...this.#ctx,
log,
// Never run mounts just for module exports as there may be plugins
// in the parent depending on the mount's exports, and the mount
// might not have plugins depending on its own exports
scriptRunForModuleExports: false,
// Mark this as a mount, so we defer calling reload() hooks,
// see #reload()
isMount: true,
};
mount = new MiniflareCore(this.#originalPlugins, ctx, mountOptions);
mount.addEventListener("reload", async (event) => {
// Reload parent (us) whenever mounted child reloads, ignoring the
// initial reload. This ensures the page is reloaded when live
// reloading, and also that we're using up-to-date Durable Object
// classes from mounts.
if (!event.initial) {
try {
await this.#updateRouter();
await this.#reload();
} catch (e: any) {
this.#ctx.log.error(e);
}
}
});
try {
await mount.getPlugins();
} catch (e: any) {
// Make sure thrown error includes mount name for easier debugging
throw new MiniflareCoreError(
"ERR_MOUNT",
`Error mounting \"${name}\"`,
e
);
}
this.#mounts.set(name, mount);
}
}
}
// Dispose old mounts (outside `if (mounts)` check in case `mounts` section
// deleted, in which call all mounts should be unmounted)
for (const [name, mount] of [...this.#mounts]) {
if (mounts === undefined || !(name in mounts)) {
this.#ctx.log.debug(`Unmounting \"${name}\"...`);
await mount.dispose();
this.#mounts.delete(name);
}
}
await this.#updateRouter();
// Make sure we've got a script if it's required (if we've got mounts,
// allow no script, as we might always route to those)
if (
this.#ctx.scriptRequired &&
!this.#setupResults.get("CorePlugin")?.script &&
this.#mounts.size === 0
) {
throwNoScriptError(options.CorePlugin.modules);
}
// #reload() is ALWAYS called eventually after this function by the caller
}
async #updateRouter(): Promise<void> {
const allRoutes = new Map<string, string[]>();
// If this (parent) worker has a name, "mount" it so more specific routes
// are handled by it instead of mounts
const { CorePlugin } = this.#instances!;
if (CorePlugin.name) {
const routes = CorePlugin.routes;
if (routes) allRoutes.set(CorePlugin.name, routes);
}
// Add all other mounts
for (const [name, mount] of this.#mounts!) {
const { CorePlugin } = await mount.getPlugins();
if (CorePlugin.name !== undefined && CorePlugin.name !== name) {
throw new MiniflareCoreError(
"ERR_MOUNT_NAME_MISMATCH",
`Mounted name "${name}" must match service name "${CorePlugin.name}"`
);
}
const routes = CorePlugin.routes;
if (routes) allRoutes.set(name, routes);
}
this.#router ??= new Router();
this.#router.update(allRoutes);
if (this.#mounts!.size) {
this.#ctx.log.debug(
`Mount Routes:${this.#router.routes.length === 0 ? " <none>" : ""}`
);
for (let i = 0; i < this.#router.routes.length; i++) {
const route = this.#router.routes[i];
this.#ctx.log.debug(`${i + 1}. ${route.route} => ${route.target}`);
}
}
}
async #runAllBeforeReloads(): Promise<void> {
for (const [name] of this.#plugins) {
const instance = this.#instances![name];
if (instance.beforeReload) {
this.#ctx.log.verbose(`- beforeReload(${name})`);
await instance.beforeReload();
}
}
}
async #runAllReloads(mounts: Map<string, _CoreMount>): Promise<void> {
// #bindings and #moduleExports should be set, as this is always called
// after running scripts in #reload().
//
// #instances should be set as #reload() always follows #init().
const bindings = this.#bindings;
const exports = this.#moduleExports;
for (const [name] of this.#plugins) {
const instance = this.#instances![name];
if (instance.reload) {
this.#ctx.log.verbose(`- reload(${name})`);
await instance.reload(bindings ?? {}, exports ?? {}, mounts);
}
}
}
async #reload(dispatchReloadEvent = true): Promise<void> {
this.#ctx.log.debug("Reloading worker...");
const globals: Context = {};
const bindings: Context = {};
const newWatchPaths = new Set<string>();
if (this.#wranglerConfigPath) newWatchPaths.add(this.#wranglerConfigPath);
// Run all before reload hooks, including mounts if we have any
await this.#runAllBeforeReloads();
if (!this.#ctx.isMount) {
// this.#mounts is set in #init() which is always called before this
for (const mount of this.#mounts!.values()) {
await mount.#runAllBeforeReloads();
}
}
let script: ScriptBlueprint | undefined = undefined;
let requiresModuleExports = false;
const additionalModules: AdditionalModules = {};
for (const [name] of this.#plugins) {
// Build global scope, extracting script blueprints and additional modules
const result = this.#setupResults!.get(name);
Object.assign(globals, result?.globals);
Object.assign(bindings, result?.bindings);
if (result?.script) {
if (script) {
throw new TypeError("Multiple plugins returned a script");
}
script = result.script;
}
if (result?.requiresModuleExports) requiresModuleExports = true;
if (result?.additionalModules) {
Object.assign(additionalModules, result.additionalModules);
}
// Extract watch paths
const beforeSetupWatch = this.#beforeSetupWatch!.get(name);
if (beforeSetupWatch) addAll(newWatchPaths, beforeSetupWatch);
const setupWatch = this.#setupWatch!.get(name);
if (setupWatch) addAll(newWatchPaths, setupWatch);
}
const { modules, processedModuleRules, logUnhandledRejections } =
this.#instances!.CorePlugin;
// Clean up process-wide promise rejection event listeners
this.#globalScope?.[kDispose]();
// Create new global scope on each reload
const globalScope = new ServiceWorkerGlobalScope(
this.#ctx.log,
globals,
bindings,
modules,
logUnhandledRejections
);
this.#globalScope = globalScope;
this.#bindings = bindings;
this.#moduleExports = {};
// Run script blueprints, with modules rules if in modules mode
const rules = modules ? processedModuleRules : undefined;
let res: ScriptRunnerResult | undefined = undefined;
if (
// Run the script if we've got one...
script &&
// ...and either we're always running it, or we're in modules mode
// and require its exports
(!this.#ctx.scriptRunForModuleExports ||
(modules && requiresModuleExports))
) {
if (!this.#ctx.scriptRunner) {
throw new TypeError("Running scripts requires a script runner");
}
this.#ctx.log.verbose("Running script...");
res = await this.#ctx.scriptRunner.run(
globalScope,
script,
rules,
additionalModules
);
this.#scriptWatchPaths.clear();
this.#scriptWatchPaths.add(script.filePath);
if (res.watch) {
addAll(newWatchPaths, res.watch);
addAll(this.#scriptWatchPaths, res.watch);
}
// Record module exports and add module event listeners if any
this.#moduleExports = res.exports;
if (res.exports) {
const defaults = res.exports.default;
const fetchListener = defaults?.fetch?.bind(defaults);
if (fetchListener) {
globalScope[kAddModuleFetchListener](fetchListener);
}
const scheduledListener = defaults?.scheduled?.bind(defaults);
if (scheduledListener) {
globalScope[kAddModuleScheduledListener](scheduledListener);
}
}
}
// If this is a mount, defer calling reload() plugin hooks, these will be
// called by the parent (us) once the root and all mounts have reloaded.
// This ensures that if some mounts depend on other mounts, they'll
// be ready when reload() hooks are called.
if (!this.#ctx.isMount) {
// Run reload hooks, getting module exports for each mount (we await
// getPlugins() for each mount before running #reload() so their scripts
// must've been run)
const mounts = new Map<string, _CoreMount>();
// this.#mounts and this.#instances are set in #init(), which is always
// called before this
// If this (parent) worker has a name, "mount" it so mounts can access it
const name = this.#instances!.CorePlugin.name;
if (name) {
mounts.set(name, {
moduleExports: this.#moduleExports,
// `true` so service bindings requests always proxied to upstream,
// `Mount`'s `dispatchFetch` requires a function with signature
// `(Request) => Awaitable<Response>` too
dispatchFetch: (request) => this[kDispatchFetch](request, true),
} as _CoreMount);
}
// Add all other mounts
for (const [name, mount] of this.#mounts!) {
mounts.set(name, {
moduleExports: await mount.getModuleExports(),
dispatchFetch: (request) => mount[kDispatchFetch](request, true),
} as _CoreMount);
}
await this.#runAllReloads(mounts);
for (const mount of this.#mounts!.values()) {
await mount.#runAllReloads(mounts);
}
}
// Dispatch reload event (expect if we're updating mount options via
// setOptions() in #init(), in which call we'll call #reload() later
// ourselves, so don't want to trigger the "reload" event listener
// which would cause a double reload)
if (dispatchReloadEvent) {
const reloadEvent = new ReloadEvent("reload", {
plugins: this.#instances!,
initial: !this.#reloaded,
});
this.dispatchEvent(reloadEvent);
}
this.#reloaded = true;
// Log bundle size and warning if too big
// noinspection JSObjectNullOrUndefined
this.#ctx.log.info(
`Worker reloaded!${
res?.bundleSize !== undefined ? ` (${formatSize(res.bundleSize)})` : ""
}`
);
// TODO (someday): compress asynchronously
// noinspection JSObjectNullOrUndefined
if (res?.bundleSize !== undefined && res.bundleSize > 1_048_576) {
this.#ctx.log.warn(
"Worker's uncompressed size exceeds the 1MiB limit! " +
"Note that your worker will be compressed during upload " +
"so you may still be able to deploy it."
);
}
// Update watched paths if watching
if (this.#watching) {
let watcher = this.#watcher;
// Make sure we've created the watcher
if (!watcher) {
const {
Watcher,
}: typeof import("@miniflare/watcher") = require("@miniflare/watcher");
this.#watcherCallbackMutex = new Mutex();
watcher = new Watcher(this.#watcherCallback.bind(this));
this.#watcher = watcher;
}
// Store changed paths
const unwatchedPaths = new Set<string>();
const watchedPaths = new Set<string>();
// Unwatch paths that should no longer be watched
for (const watchedPath of this.#previousWatchPaths ?? []) {
if (!newWatchPaths.has(watchedPath)) {
unwatchedPaths.add(watchedPath);
}
}
// Watch paths that should now be watched
for (const newWatchedPath of newWatchPaths) {
if (!this.#previousWatchPaths?.has(newWatchedPath)) {
watchedPaths.add(newWatchedPath);
}
}
// Apply and log changes
if (unwatchedPaths.size > 0) {
this.#ctx.log.debug(`Unwatching ${pathsToString(unwatchedPaths)}...`);
watcher.unwatch(unwatchedPaths);
}
if (watchedPaths.size > 0) {
this.#ctx.log.debug(`Watching ${pathsToString(newWatchPaths)}...`);
watcher.watch(watchedPaths);
}
this.#previousWatchPaths = newWatchPaths;
}
}
#ignoreScriptUpdates = false;
#ignoreScriptUpdatesTimeout!: NodeJS.Timeout;
#watcherCallback(eventPath: string): void {
this.#ctx.log.debug(`${path.relative("", eventPath)} changed...`);
if (this.#ignoreScriptUpdates && this.#scriptWatchPaths.has(eventPath)) {
this.#ctx.log.verbose("Ignoring script change after build...");
return;
}
const promise = this.#watcherCallbackMutex!.runWith(async () => {
// If wrangler config changed, re-init any changed plugins
if (eventPath === this.#wranglerConfigPath) {
await this.#init();
}
// Re-run hooks that returned the paths to watch originally
let ranBeforeSetup = false;
for (const [name] of this.#plugins) {
if (this.#beforeSetupWatch!.get(name)?.has(eventPath)) {
await this.#runBeforeSetup(name);
ranBeforeSetup = true;
// Ignore script updates for 1s
this.#ignoreScriptUpdates = true;
clearTimeout(this.#ignoreScriptUpdatesTimeout);
this.#ignoreScriptUpdatesTimeout = setTimeout(
() => (this.#ignoreScriptUpdates = false),
1000
);
}
if (this.#setupWatch!.get(name)?.has(eventPath)) {
await this.#runSetup(name);
}
}
if (ranBeforeSetup) {
// If we ran any beforeSetup hooks, rerun setup hooks for any plugins
// that returned scripts
for (const [name] of this.#plugins) {
if (this.#setupResults!.get(name)?.script) {
await this.#runSetup(name);
}
}
}
// If the eventPath wasn't the wrangler config or from any plugins, it's
// probably a linked module we picked up when running the script. In that
// case, just reloading will re-read it so we don't need to do anything.
// Wait until we've processed all changes before reloading
if (!this.#watcherCallbackMutex!.hasWaiting) {
await this.#reload();
}
});
promise.catch((e) => this.#ctx.log.error(e));
}
get log(): Log {
return this.#ctx.log;
}
async reload(): Promise<void> {
await this.#initPromise;
// Force re-build of all plugins, regardless of whether options have changed
// or not. This ensures files (scripts, .env files, WASM modules, etc.) are
// re-read from disk.
await this.#init(/* reloadAll */ true);
await this.#reload();
}
async setOptions(
options: MiniflareCoreOptions<Plugins>,
dispatchReloadEvent = true
): Promise<void> {
await this.#initPromise;
options = { ...this.#previousSetOptions, ...options };
this.#previousSetOptions = options;
this.#overrides = splitPluginOptions(this.#plugins, options);
await this.#init();
await this.#reload(dispatchReloadEvent);
}
getPluginStorage(name: keyof Plugins): StorageFactory {
let storage = this.#pluginStorages.get(name);
if (storage) return storage;
this.#pluginStorages.set(
name,
(storage = new PluginStorageFactory(
this.#ctx.storageFactory,
name as string
))
);
return storage;
}
async getPlugins(): Promise<PluginInstances<Plugins>> {
await this.#initPromise;
return this.#instances!;
}
async getGlobalScope(): Promise<Context> {
await this.#initPromise;
return this.#globalScope!;
}
async getBindings(): Promise<Context> {
await this.#initPromise;
return this.#bindings!;
}
async getModuleExports(): Promise<Context> {
await this.#initPromise;
return this.#moduleExports!;
}
async getMount(name: string): Promise<MiniflareCore<Plugins>> {
await this.#initPromise;
return this.#mounts!.get(name)!;
}
async dispatchFetch<WaitUntil extends any[] = unknown[]>(
input: RequestInfo,
init?: RequestInit
): Promise<Response<WaitUntil>> {
await this.#initPromise;
// noinspection SuspiciousTypeOfGuard
let request =
input instanceof Request && !init ? input : new Request(input, init);
const url = new URL(request.url);
// Forward to matching mount if any
if (this.#mounts?.size) {
const mountMatch = this.#router!.match(url);
const name = this.#instances!.CorePlugin.name;
// If there was a match, and it isn't the current (parent) worker,
// forward the request to the matching mount instead
if (mountMatch !== null && mountMatch !== name) {
const mount = this.#mounts.get(mountMatch);
if (mount) return mount.dispatchFetch(request);
}
}
// If upstream set, and the request URL doesn't begin with it, rewrite it
// so fetching the incoming request gets a response from the upstream
const { upstreamURL } = this.#instances!.CorePlugin;
if (upstreamURL && !url.toString().startsWith(upstreamURL.toString())) {
let path = url.pathname + url.search;
// Remove leading slash so we resolve relative to upstream's path
if (path.startsWith("/")) path = path.substring(1);
const newURL = new URL(path, upstreamURL);
request = new Request(newURL, request);
// We don't set the Host header here, fetch will automatically set it
// based on the request url
}
// Each fetch gets its own context (e.g. 50 subrequests).
// Start a new pipeline, incrementing the request depth (defaulting to 1).
const requestDepth =
(parseInt(request.headers.get(_kLoopHeader)!) || 0) + 1;
// Hide the loop header from the user
request.headers.delete(_kLoopHeader);
return new RequestContext({
requestDepth,
pipelineDepth: 1,
}).runWith(() =>
this[kDispatchFetch](
request,
!!upstreamURL // only proxy if upstream URL set
)
);
}
// This is a separate internal function so it can be called by service
// bindings that don't need (or want) any of the mounting stuff.
// Declared as arrow function for correctly bound `this`.
async [kDispatchFetch]<WaitUntil extends any[] = unknown[]>(
request: Request,
proxy: boolean
): Promise<Response<WaitUntil>> {
await this.#initPromise;
// Parse form data files as strings if the compatibility flag isn't set
if (!this.#compat!.isEnabled("formdata_parser_supports_files")) {
request = withStringFormDataFiles(request);
}
// Make headers immutable
request = withImmutableHeaders(request);
return this.#globalScope![kDispatchFetch]<WaitUntil>(request, proxy);
}
async dispatchScheduled<WaitUntil extends any[] = unknown[]>(
scheduledTime?: number,
cron?: string
): Promise<WaitUntil> {
await this.#initPromise;
const globalScope = this.#globalScope;
// Each fetch gets its own context (e.g. 50 subrequests).
// Start a new pipeline too.
return new RequestContext().runWith(() =>
globalScope![kDispatchScheduled]<WaitUntil>(scheduledTime, cron)
);
}
async dispose(): Promise<void> {
// Run dispose hooks
for (const [name] of this.#plugins) {
const instance = this.#instances?.[name];
if (instance?.dispose) {
this.#ctx.log.verbose(`- dispose(${name})`);
await instance.dispose();
}
}
// Dispose of watcher
this.#watcher?.dispose();
// Dispose of mounts
if (this.#mounts) {
for (const [name, mount] of this.#mounts) {
this.#ctx.log.debug(`Unmounting \"${name}\"...`);
await mount.dispose();
}
this.#mounts.clear();
}
}
} | the_stack |
* @fileoverview Implements the CommonMtable wrapper mixin for the MmlMtable object
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
import {AnyWrapper, WrapperConstructor, Constructor} from '../Wrapper.js';
import {CommonMtr} from './mtr.js';
import {CommonMo} from './mo.js';
import {BBox} from '../../../util/BBox.js';
import {DIRECTION} from '../FontData.js';
import {split, isPercent} from '../../../util/string.js';
import {sum, max} from '../../../util/numeric.js';
/*****************************************************************/
/**
* The heights, depths, and widths of the rows and columns
* Plus the natural height and depth (i.e., without the labels)
* Plus the label column width
*/
export type TableData = {
H: number[];
D: number[];
W: number[];
NH: number[];
ND: number[];
L: number;
};
/**
* An array of table dimensions
*/
export type ColumnWidths = (string | number | null)[];
/*****************************************************************/
/**
* The CommonMtable interface
*
* @template C The class for table cells
* @template R The class for table rows
*/
export interface CommonMtable<C extends AnyWrapper, R extends CommonMtr<C>> extends AnyWrapper {
/**
* The number of columns and rows in the table
*/
numCols: number;
numRows: number;
/**
* True if there are labeled rows
*/
hasLabels: boolean;
/**
* True if this mtable is the top element, or in a top-most mrow
*/
isTop: boolean;
/**
* The parent node of this table (skipping non-parents and mrows)
* and the position of the table as a child node
*/
container: AnyWrapper;
containerI: number;
/**
* The spacing and line data
*/
frame: boolean;
fLine: number;
fSpace: number[];
cSpace: number[];
rSpace: number[];
cLines: number[];
rLines: number[];
cWidths: (number | string)[];
/**
* The bounding box information for the table rows and columns
*/
data: TableData;
/**
* The table cells that have percentage-width content
*/
pwidthCells: [C, number][];
/**
* The full width of a percentage-width table
*/
pWidth: number;
/**
* The rows of the table
*/
readonly tableRows: R[];
/**
* @override
*/
childNodes: R[];
/**
* Find the container and the child position of the table
*/
findContainer(): void;
/**
* If the table has a precentage width or has labels, set the pwidth of the bounding box
*/
getPercentageWidth(): void;
/**
* Stretch the rows to the equal height or natural height
*/
stretchRows(): void;
/**
* Stretch the columns to their proper widths
*/
stretchColumns(): void;
/**
* Handle horizontal stretching within the ith column
*
* @param {number} i The column number
* @param {number} W The computed width of the column (or null of not computed)
*/
stretchColumn(i: number, W: number): void;
/**
* Determine the row heights and depths, the column widths,
* and the natural width and height of the table.
*
* @return {TableData} The dimensions of the rows and columns
*/
getTableData(): TableData;
/**
* @param {C} cell The cell whose height, depth, and width are to be added into the H, D, W arrays
* @param {number} i The column number for the cell
* @param {number} j The row number for the cell
* @param {string} align The row alignment
* @param {number[]} H The maximum height for each of the rows
* @param {number[]} D The maximum depth for each of the rows
* @param {number[]} W The maximum width for each column
* @param {number} M The current height for items aligned top and bottom
* @return {number} The updated value for M
*/
updateHDW(cell: C, i: number, j: number, align: string, H: number[], D: number[], W: number[], M: number): number;
/**
* Extend the H and D of a row to cover the maximum height needed by top/bottom aligned items
*
* @param {number} i The row whose hight and depth should be adjusted
* @param {number[]} H The row heights
* @param {number[]} D The row depths
* @param {number} M The maximum height of top/bottom aligned items
*/
extendHD(i: number, H: number[], D: number[], M: number): void;
/**
* Set cell widths for columns with percentage width children
*/
setColumnPWidths(): void;
/**
* @param {number} height The total height of the table
* @return {number[]} The [height, depth] for the aligned table
*/
getBBoxHD(height: number): number[];
/**
* Get bbox left and right amounts to cover labels
*/
getBBoxLR(): number[];
/**
* @param {string} side The side for the labels
* @return {[number, string, number]} The padding, alignment, and shift amounts
*/
getPadAlignShift(side: string): [number, string, number];
/**
* @return {number} The true width of the table (without labels)
*/
getWidth(): number;
/**
* @return {number} The maximum height of a row
*/
getEqualRowHeight(): number;
/**
* @return {number[]} The array of computed widths
*/
getComputedWidths(): number[];
/**
* Determine the column widths that can be computed (and need to be set).
* The resulting arrays will have numbers for fixed-size arrays,
* strings for percentage sizes that can't be determined now,
* and null for stretchy columns tht will expand to fill the extra space.
* Depending on the width specified for the table, different column
* values can be determined.
*
* @return {ColumnWidths} The array of widths
*/
getColumnWidths(): ColumnWidths;
/**
* For tables with equal columns, get the proper amount per row.
*
* @return {ColumnWidths} The array of widths
*/
getEqualColumns(width: string): ColumnWidths;
/**
* For tables with width="auto", auto and fit columns
* will end up being natural width, so don't need to
* set those explicitly.
*
* @return {ColumnWidths} The array of widths
*/
getColumnWidthsAuto(swidths: string[]): ColumnWidths;
/**
* For tables with percentage widths, let 'fit' columns (or 'auto'
* columns if there are not 'fit' ones) will stretch automatically,
* but for 'auto' columns (when there are 'fit' ones), set the size
* to the natural size of the column.
*
* @param {string[]} widths Strings giving the widths
* @return {ColumnWidths} The array of widths
*/
getColumnWidthsPercent(widths: string[]): ColumnWidths;
/**
* For fixed-width tables, compute the column widths of all columns.
*
* @return {ColumnWidths} The array of widths
*/
getColumnWidthsFixed(swidths: string[], width: number): ColumnWidths;
/**
* @param {number} i The row number (starting at 0)
* @param {string} align The alignment on that row
* @return {number} The offest of the alignment position from the top of the table
*/
getVerticalPosition(i: number, align: string): number;
/**
* @param {number} fspace The frame spacing to use
* @param {number[]} space The array of spacing values to convert to strings
* @param {number} scale A scaling factor to use for the sizes
* @return {string[]} The half-spacing as stings with units of "em"
* with frame spacing at the beginning and end
*/
getEmHalfSpacing(fspace: number, space: number[], scale?: number): string[];
/**
* @return {number[]} The half-spacing for rows with frame spacing at the ends
*/
getRowHalfSpacing(): number[];
/**
* @return {number[]} The half-spacing for columns with frame spacing at the ends
*/
getColumnHalfSpacing(): number[];
/**
* @return {[string,number|null]} The alignment and row number (based at 0) or null
*/
getAlignmentRow(): [string, number | null];
/**
* @param {string} name The name of the attribute to get as an array
* @param {number=} i Return this many fewer than numCols entries
* @return {string[]} The array of values in the given attribute, split at spaces,
* padded to the number of table columns (minus 1) by repeating the last entry
*/
getColumnAttributes(name: string, i?: number): string[];
/**
* @param {string} name The name of the attribute to get as an array
* @param {number=} i Return this many fewer than numRows entries
* @return {string[]} The array of values in the given attribute, split at spaces,
* padded to the number of table rows (minus 1) by repeating the last entry
*/
getRowAttributes(name: string, i?: number): string[];
/**
* @param {string} name The name of the attribute to get as an array
* @return {string[]} The array of values in the given attribute, split at spaces
* (after leading and trailing spaces are removed, and multiple
* spaces have been collapsed to one).
*/
getAttributeArray(name: string): string[];
/**
* Adds "em" to a list of dimensions, after dividing by n (defaults to 1).
*
* @param {string[]} list The array of dimensions (in em's)
* @param {nunber=} n The number to divide each dimension by after converted
* @return {string[]} The array of values with "em" added
*/
addEm(list: number[], n?: number): string[];
/**
* Converts an array of dimensions (with arbitrary units) to an array of numbers
* representing the dimensions in units of em's.
*
* @param {string[]} list The array of dimensions to be turned into em's
* @return {number[]} The array of values converted to em's
*/
convertLengths(list: string[]): number[];
}
/**
* Shorthand for the CommonMtable constructor
*/
export type MtableConstructor<C extends AnyWrapper, R extends CommonMtr<C>> = Constructor<CommonMtable<C, R>>;
/*****************************************************************/
/**
* The CommonMtable wrapper mixin for the MmlMtable object
*
* @template C The table cell class
* @temlpate R the table row class
* @template T The Wrapper class constructor type
*/
export function CommonMtableMixin<
C extends AnyWrapper,
R extends CommonMtr<C>,
T extends WrapperConstructor
>(Base: T): MtableConstructor<C, R> & T {
return class extends Base {
/**
* The number of columns in the table
*/
public numCols: number = 0;
/**
* The number of rows in the table
*/
public numRows: number = 0;
/**
* True if there are labeled rows
*/
public hasLabels: boolean;
/**
* True if this mtable is the top element, or in a top-most mrow
*/
public isTop: boolean;
/**
* The parent node of this table (skipping non-parents and mrows)
*/
public container: AnyWrapper;
/**
* The position of the table as a child node of its container
*/
public containerI: number;
/**
* True if there is a frame
*/
public frame: boolean;
/**
* The size of the frame line (or 0 if none)
*/
public fLine: number;
/**
* frame spacing on the left and right
*/
public fSpace: number[];
/**
* The spacing between columns
*/
public cSpace: number[];
/**
* The spacing between rows
*/
public rSpace: number[];
/**
* The width of columns lines (or 0 if no line for the column)
*/
public cLines: number[];
/**
* The width of row lines (or 0 if no lone for that row)
*/
public rLines: number[];
/**
* The column widths (or percentages, etc.)
*/
public cWidths: (number | string)[];
/**
* The bounding box information for the table rows and columns
*/
public data: TableData = null;
/**
* The table cells that have percentage-width content
*/
public pwidthCells: [C, number][] = [];
/**
* The full width of a percentage-width table
*/
public pWidth: number = 0;
/**
* @return {R[]} The rows of the table
*/
get tableRows(): R[] {
return this.childNodes;
}
/******************************************************************/
/**
* @override
* @constructor
*/
constructor(...args: any[]) {
super(...args);
//
// Determine the number of columns and rows, and whether the table is stretchy
//
this.numCols = max(this.tableRows.map(row => row.numCells));
this.numRows = this.childNodes.length;
this.hasLabels = this.childNodes.reduce((value, row) => value || row.node.isKind('mlabeledtr'), false);
this.findContainer();
this.isTop = !this.container || (this.container.node.isKind('math') && !this.container.parent);
if (this.isTop) {
this.jax.table = this;
}
this.getPercentageWidth();
//
// Get the frame, row, and column parameters
//
const attributes = this.node.attributes;
this.frame = attributes.get('frame') !== 'none';
this.fLine = (this.frame && attributes.get('frame') ? .07 : 0);
this.fSpace = (this.frame ? this.convertLengths(this.getAttributeArray('framespacing')) : [0, 0]);
this.cSpace = this.convertLengths(this.getColumnAttributes('columnspacing'));
this.rSpace = this.convertLengths(this.getRowAttributes('rowspacing'));
this.cLines = this.getColumnAttributes('columnlines').map(x => (x === 'none' ? 0 : .07));
this.rLines = this.getRowAttributes('rowlines').map(x => (x === 'none' ? 0 : .07));
this.cWidths = this.getColumnWidths();
//
// Stretch the rows and columns
//
this.stretchRows();
this.stretchColumns();
}
/**
* Find the container and the child position of the table
*/
public findContainer() {
let node = this as AnyWrapper;
let parent = node.parent as AnyWrapper;
while (parent && (parent.node.notParent || parent.node.isKind('mrow'))) {
node = parent;
parent = parent.parent;
}
this.container = parent;
this.containerI = node.node.childPosition();
}
/**
* If the table has a precentage width or has labels, set the pwidth of the bounding box
*/
public getPercentageWidth() {
if (this.hasLabels) {
this.bbox.pwidth = BBox.fullWidth;
} else {
const width = this.node.attributes.get('width') as string;
if (isPercent(width)) {
this.bbox.pwidth = width;
}
}
}
/**
* Stretch the rows to the equal height or natural height
*/
public stretchRows() {
const equal = this.node.attributes.get('equalrows') as boolean;
const HD = (equal ? this.getEqualRowHeight() : 0);
const {H, D} = (equal ? this.getTableData() : {H: [0], D: [0]});
const rows = this.tableRows;
for (let i = 0; i < this.numRows; i++) {
const hd = (equal ? [(HD + H[i] - D[i]) / 2, (HD - H[i] + D[i]) / 2] : null);
rows[i].stretchChildren(hd);
}
}
/**
* Stretch the columns to their proper widths
*/
public stretchColumns() {
for (let i = 0; i < this.numCols; i++) {
const width = (typeof this.cWidths[i] === 'number' ? this.cWidths[i] as number : null);
this.stretchColumn(i, width);
}
}
/**
* Handle horizontal stretching within the ith column
*
* @param {number} i The column number
* @param {number} W The computed width of the column (or null of not computed)
*/
public stretchColumn(i: number, W: number) {
let stretchy: AnyWrapper[] = [];
//
// Locate and count the stretchy children
//
for (const row of this.tableRows) {
const cell = row.getChild(i);
if (cell) {
const child = cell.childNodes[0];
if (child.stretch.dir === DIRECTION.None &&
child.canStretch(DIRECTION.Horizontal)) {
stretchy.push(child);
}
}
}
let count = stretchy.length;
let nodeCount = this.childNodes.length;
if (count && nodeCount > 1) {
if (W === null) {
W = 0;
//
// If all the children are stretchy, find the largest one,
// otherwise, find the width of the non-stretchy children.
//
let all = (count > 1 && count === nodeCount);
for (const row of this.tableRows) {
const cell = row.getChild(i);
if (cell) {
const child = cell.childNodes[0];
const noStretch = (child.stretch.dir === DIRECTION.None);
if (all || noStretch) {
const {w} = child.getBBox(noStretch);
if (w > W) {
W = w;
}
}
}
}
}
//
// Stretch the stretchable children
//
for (const child of stretchy) {
(child.coreMO() as CommonMo).getStretchedVariant([W]);
}
}
}
/******************************************************************/
/**
* Determine the row heights and depths, the column widths,
* and the natural width and height of the table.
*
* @return {TableData} The dimensions of the rows and columns
*/
public getTableData(): TableData {
if (this.data) {
return this.data;
}
const H = new Array(this.numRows).fill(0);
const D = new Array(this.numRows).fill(0);
const W = new Array(this.numCols).fill(0);
const NH = new Array(this.numRows);
const ND = new Array(this.numRows);
const LW = [0];
const rows = this.tableRows;
for (let j = 0; j < rows.length; j++) {
let M = 0;
const row = rows[j];
const align = row.node.attributes.get('rowalign') as string;
for (let i = 0; i < row.numCells; i++) {
const cell = row.getChild(i);
M = this.updateHDW(cell, i, j, align, H, D, W, M);
this.recordPWidthCell(cell, i);
}
NH[j] = H[j];
ND[j] = D[j];
if (row.labeled) {
M = this.updateHDW(row.childNodes[0], 0, j, align, H, D, LW, M);
}
this.extendHD(j, H, D, M);
this.extendHD(j, NH, ND, M);
}
const L = LW[0];
this.data = {H, D, W, NH, ND, L};
return this.data;
}
/**
* @override
*/
public updateHDW(
cell: C, i: number, j: number, align: string, H: number[], D: number[], W: number[], M: number
): number {
let {h, d, w} = cell.getBBox();
const scale = cell.parent.bbox.rscale;
if (cell.parent.bbox.rscale !== 1) {
h *= scale;
d *= scale;
w *= scale;
}
if (this.node.getProperty('useHeight')) {
if (h < .75) h = .75;
if (d < .25) d = .25;
}
let m = 0;
align = cell.node.attributes.get('rowalign') as string || align;
if (align !== 'baseline' && align !== 'axis') {
m = h + d;
h = d = 0;
}
if (h > H[j]) H[j] = h;
if (d > D[j]) D[j] = d;
if (m > M) M = m;
if (W && w > W[i]) W[i] = w;
return M;
}
/**
* @override
*/
public extendHD(i: number, H: number[], D: number[], M: number) {
const d = (M - (H[i] + D[i])) / 2;
if (d < .00001) return;
H[i] += d;
D[i] += d;
}
/**
* @param {C} cell The cell to check for percentage widths
* @param {number} i The column index of the cell
*/
public recordPWidthCell(cell: C, i: number) {
if (cell.childNodes[0] && cell.childNodes[0].getBBox().pwidth) {
this.pwidthCells.push([cell, i]);
}
}
/**
* @override
*/
public computeBBox(bbox: BBox, _recompute: boolean = false) {
const {H, D} = this.getTableData();
let height, width;
//
// For equal rows, use the common height and depth for all rows
// Otherwise, use the height and depths for each row separately.
// Add in the spacing, line widths, and frame size.
//
if (this.node.attributes.get('equalrows') as boolean) {
const HD = this.getEqualRowHeight();
height = sum([].concat(this.rLines, this.rSpace)) + HD * this.numRows;
} else {
height = sum(H.concat(D, this.rLines, this.rSpace));
}
height += 2 * (this.fLine + this.fSpace[1]);
//
// Get the widths of all columns
//
const CW = this.getComputedWidths();
//
// Get the expected width of the table
//
width = sum(CW.concat(this.cLines, this.cSpace)) + 2 * (this.fLine + this.fSpace[0]);
//
// If the table width is not 'auto', determine the specified width
// and pick the larger of the specified and computed widths.
//
const w = this.node.attributes.get('width') as string;
if (w !== 'auto') {
width = Math.max(this.length2em(w, 0) + 2 * this.fLine, width);
}
//
// Return the bounding box information
//
let [h, d] = this.getBBoxHD(height);
bbox.h = h;
bbox.d = d;
bbox.w = width;
let [L, R] = this.getBBoxLR();
bbox.L = L;
bbox.R = R;
//
// Handle cell widths if width is not a percentage
//
if (!isPercent(w)) {
this.setColumnPWidths();
}
}
/**
* @override
*/
public setChildPWidths(_recompute: boolean, cwidth: number, _clear: boolean) {
const width = this.node.attributes.get('width') as string;
if (!isPercent(width)) return false;
if (!this.hasLabels) {
this.bbox.pwidth = '';
this.container.bbox.pwidth = '';
}
const {w, L, R} = this.bbox;
const labelInWidth = this.node.attributes.get('data-width-includes-label') as boolean;
const W = Math.max(w, this.length2em(width, Math.max(cwidth, L + w + R))) - (labelInWidth ? L + R : 0);
const cols = (this.node.attributes.get('equalcolumns') as boolean ?
Array(this.numCols).fill(this.percent(1 / Math.max(1, this.numCols))) :
this.getColumnAttributes('columnwidth', 0));
this.cWidths = this.getColumnWidthsFixed(cols, W);
const CW = this.getComputedWidths();
this.pWidth = sum(CW.concat(this.cLines, this.cSpace)) + 2 * (this.fLine + this.fSpace[0]);
if (this.isTop) {
this.bbox.w = this.pWidth;
}
this.setColumnPWidths();
if (this.pWidth !== w) {
this.parent.invalidateBBox();
}
return this.pWidth !== w;
}
/**
* Finalize any cells that have percentage-width content
*/
public setColumnPWidths() {
const W = this.cWidths as number[];
for (const [cell, i] of this.pwidthCells) {
if (cell.setChildPWidths(false, W[i])) {
cell.invalidateBBox();
cell.getBBox();
}
}
}
/**
* @param {number} height The total height of the table
* @return {[number, number]} The [height, depth] for the aligned table
*/
public getBBoxHD(height: number): [number, number] {
const [align, row] = this.getAlignmentRow();
if (row === null) {
const a = this.font.params.axis_height;
const h2 = height / 2;
const HD: {[key: string]: [number, number]} = {
top: [0, height],
center: [h2, h2],
bottom: [height, 0],
baseline: [h2, h2],
axis: [h2 + a, h2 - a]
};
return HD[align] || [h2, h2];
} else {
const y = this.getVerticalPosition(row, align);
return [y, height - y];
}
}
/**
* Get bbox left and right amounts to cover labels
*/
public getBBoxLR() {
if (this.hasLabels) {
const attributes = this.node.attributes;
const side = attributes.get('side') as string;
let [pad, align] = this.getPadAlignShift(side);
//
// If labels are included in the width,
// remove the frame spacing if there is no frame line (added by multline)
// and use left or right justification rather than centering so that
// there is no extra space reserved for the label on the opposite side,
// (as there usually is to center the equation).
//
const labels = this.hasLabels && !!attributes.get('data-width-includes-label');
if (labels && this.frame && this.fSpace[0]) {
pad -= this.fSpace[0];
}
return (align === 'center' && !labels ? [pad, pad] :
side === 'left' ? [pad, 0] : [0, pad]);
}
return [0, 0];
}
/**
* @param {string} side The side for the labels
* @return {[number, string, number]} The padding, alignment, and shift amounts
*/
public getPadAlignShift(side: string): [number, string, number] {
//
// Make sure labels don't overlap table
//
const {L} = this.getTableData();
const sep = this.length2em(this.node.attributes.get('minlabelspacing'));
let pad = L + sep;
const [lpad, rpad] = (this.styles == null ? ['', ''] :
[this.styles.get('padding-left'), this.styles.get('padding-right')]);
if (lpad || rpad) {
pad = Math.max(pad, this.length2em(lpad || '0'), this.length2em(rpad || '0'));
}
//
// Handle indentation
//
let [align, shift] = this.getAlignShift();
if (align === side) {
shift = (side === 'left' ? Math.max(pad, shift) - pad : Math.min(-pad, shift) + pad);
}
return [pad, align, shift] as [number, string, number];
}
/**
* @override
*/
public getAlignShift() {
return (this.isTop ? super.getAlignShift() :
[this.container.getChildAlign(this.containerI), 0] as [string, number]);
}
/**
* @return {number} The true width of the table (without labels)
*/
public getWidth(): number {
return this.pWidth || this.getBBox().w;
}
/******************************************************************/
/**
* @return {number} The maximum height of a row
*/
public getEqualRowHeight(): number {
const {H, D} = this.getTableData();
const HD = Array.from(H.keys()).map(i => H[i] + D[i]);
return Math.max.apply(Math, HD);
}
/**
* @return {number[]} The array of computed widths
*/
public getComputedWidths(): number[] {
const W = this.getTableData().W;
let CW = Array.from(W.keys()).map(i => {
return (typeof this.cWidths[i] === 'number' ? this.cWidths[i] as number : W[i]);
});
if (this.node.attributes.get('equalcolumns') as boolean) {
CW = Array(CW.length).fill(max(CW));
}
return CW;
}
/**
* Determine the column widths that can be computed (and need to be set).
* The resulting arrays will have numbers for fixed-size arrays,
* strings for percentage sizes that can't be determined now,
* and null for stretchy columns that will expand to fill the extra space.
* Depending on the width specified for the table, different column
* values can be determined.
*
* @return {(string|number|null)[]} The array of widths
*/
public getColumnWidths(): (string | number | null)[] {
const width = this.node.attributes.get('width') as string;
if (this.node.attributes.get('equalcolumns') as boolean) {
return this.getEqualColumns(width);
}
const swidths = this.getColumnAttributes('columnwidth', 0);
if (width === 'auto') {
return this.getColumnWidthsAuto(swidths);
}
if (isPercent(width)) {
return this.getColumnWidthsPercent(swidths);
}
return this.getColumnWidthsFixed(swidths, this.length2em(width));
}
/**
* For tables with equal columns, get the proper amount per column.
*
* @param {string} width The width attribute of the table
* @return {(string|number|null)[]} The array of widths
*/
public getEqualColumns(width: string): (string | number | null)[] {
const n = Math.max(1, this.numCols);
let cwidth;
if (width === 'auto') {
const {W} = this.getTableData();
cwidth = max(W);
} else if (isPercent(width)) {
cwidth = this.percent(1 / n);
} else {
const w = sum([].concat(this.cLines, this.cSpace)) + 2 * this.fSpace[0];
cwidth = Math.max(0, this.length2em(width) - w) / n;
}
return Array(this.numCols).fill(cwidth);
}
/**
* For tables with width="auto", auto and fit columns
* will end up being natural width, so don't need to
* set those explicitly.
*
* @param {string[]} swidths The split and padded columnwidths attribute
* @return {ColumnWidths} The array of widths
*/
public getColumnWidthsAuto(swidths: string[]): ColumnWidths {
return swidths.map(x => {
if (x === 'auto' || x === 'fit') return null;
if (isPercent(x)) return x;
return this.length2em(x);
});
}
/**
* For tables with percentage widths, the 'fit' columns (or 'auto'
* columns if there are not 'fit' ones) will stretch automatically,
* but for 'auto' columns (when there are 'fit' ones), set the size
* to the natural size of the column.
*
* @param {string[]} swidths The split and padded columnwidths attribute
* @return {ColumnWidths} The array of widths
*/
public getColumnWidthsPercent(swidths: string[]): ColumnWidths {
const hasFit = swidths.indexOf('fit') >= 0;
const {W} = (hasFit ? this.getTableData() : {W: null});
return Array.from(swidths.keys()).map(i => {
const x = swidths[i];
if (x === 'fit') return null;
if (x === 'auto') return (hasFit ? W[i] : null);
if (isPercent(x)) return x;
return this.length2em(x);
});
}
/**
* For fixed-width tables, compute the column widths of all columns.
*
* @param {string[]} swidths The split and padded columnwidths attribute
* @param {number} width The width of the table
* @return {ColumnWidths} The array of widths
*/
public getColumnWidthsFixed(swidths: string[], width: number): ColumnWidths {
//
// Get the indices of the fit and auto columns, and the number of fit or auto entries.
// If there are fit or auto columns, get the column widths.
//
const indices = Array.from(swidths.keys());
const fit = indices.filter(i => swidths[i] === 'fit');
const auto = indices.filter(i => swidths[i] === 'auto');
const n = fit.length || auto.length;
const {W} = (n ? this.getTableData() : {W: null});
//
// Determine the space remaining from the fixed width after the
// separation and lines have been removed (cwidth), and
// after the width of the columns have been removed (dw).
//
const cwidth = width - sum([].concat(this.cLines, this.cSpace)) - 2 * this.fSpace[0];
let dw = cwidth;
indices.forEach(i => {
const x = swidths[i];
dw -= (x === 'fit' || x === 'auto' ? W[i] : this.length2em(x, cwidth));
});
//
// Get the amount of extra space per column, or 0 (fw)
//
const fw = (n && dw > 0 ? dw / n : 0);
//
// Return the column widths (plus extra space for those that are stretching
//
return indices.map(i => {
const x = swidths[i];
if (x === 'fit') return W[i] + fw;
if (x === 'auto') return W[i] + (fit.length === 0 ? fw : 0);
return this.length2em(x, cwidth);
});
}
/**
* @param {number} i The row number (starting at 0)
* @param {string} align The alignment on that row
* @return {number} The offest of the alignment position from the top of the table
*/
public getVerticalPosition(i: number, align: string): number {
const equal = this.node.attributes.get('equalrows') as boolean;
const {H, D} = this.getTableData();
const HD = (equal ? this.getEqualRowHeight() : 0);
const space = this.getRowHalfSpacing();
//
// Start with frame size and add in spacing, height and depth,
// and line thickness for each row.
//
let y = this.fLine;
for (let j = 0; j < i; j++) {
y += space[j] + (equal ? HD : H[j] + D[j]) + space[j + 1] + this.rLines[j];
}
//
// For equal rows, get updated height and depth
//
const [h, d] = (equal ? [(HD + H[i] - D[i]) / 2, (HD - H[i] + D[i]) / 2] : [H[i], D[i]]);
//
// Add the offset into the specified row
//
const offset: {[name: string]: number} = {
top: 0,
center: space[i] + (h + d) / 2,
bottom: space[i] + h + d + space[i + 1],
baseline: space[i] + h,
axis: space[i] + h - .25
};
y += offset[align] || 0;
//
// Return the final result
//
return y;
}
/******************************************************************/
/**
* @param {number} fspace The frame spacing to use
* @param {number[]} space The array of spacing values to convert to strings
* @param {number} scale A scaling factor to use for the sizes
* @return {string[]} The half-spacing as stings with units of "em"
* with frame spacing at the beginning and end
*/
public getEmHalfSpacing(fspace: number, space: number[], scale: number = 1): string[] {
//
// Get the column spacing values, and add the frame spacing values at the left and right
//
const fspaceEm = this.em(fspace * scale);
const spaceEm = this.addEm(space, 2 / scale);
spaceEm.unshift(fspaceEm);
spaceEm.push(fspaceEm);
return spaceEm;
}
/**
* @return {number[]} The half-spacing for rows with frame spacing at the ends
*/
public getRowHalfSpacing(): number[] {
const space = this.rSpace.map(x => x / 2);
space.unshift(this.fSpace[1]);
space.push(this.fSpace[1]);
return space;
}
/**
* @return {number[]} The half-spacing for columns with frame spacing at the ends
*/
public getColumnHalfSpacing(): number[] {
const space = this.cSpace.map(x => x / 2);
space.unshift(this.fSpace[0]);
space.push(this.fSpace[0]);
return space;
}
/**
* @return {[string,number|null]} The alignment and row number (based at 0) or null
*/
public getAlignmentRow(): [string, number] {
const [align, row] = split(this.node.attributes.get('align') as string);
if (row == null) return [align, null];
let i = parseInt(row);
if (i < 0) i += this.numRows + 1;
return [align, i < 1 || i > this.numRows ? null : i - 1];
}
/**
* @param {string} name The name of the attribute to get as an array
* @param {number=} i Return this many fewer than numCols entries
* @return {string[]} The array of values in the given attribute, split at spaces,
* padded to the number of table columns (minus 1) by repeating the last entry
*/
public getColumnAttributes(name: string, i: number = 1): string[] | null {
const n = this.numCols - i;
const columns = this.getAttributeArray(name);
if (columns.length === 0) return null;
while (columns.length < n) {
columns.push(columns[columns.length - 1]);
}
if (columns.length > n) {
columns.splice(n);
}
return columns;
}
/**
* @param {string} name The name of the attribute to get as an array
* @param {number=} i Return this many fewer than numRows entries
* @return {string[]} The array of values in the given attribute, split at spaces,
* padded to the number of table rows (minus 1) by repeating the last entry
*/
public getRowAttributes(name: string, i: number = 1): string[] | null {
const n = this.numRows - i;
const rows = this.getAttributeArray(name);
if (rows.length === 0) return null;
while (rows.length < n) {
rows.push(rows[rows.length - 1]);
}
if (rows.length > n) {
rows.splice(n);
}
return rows;
}
/**
* @param {string} name The name of the attribute to get as an array
* @return {string[]} The array of values in the given attribute, split at spaces
* (after leading and trailing spaces are removed, and multiple
* spaces have been collapsed to one).
*/
public getAttributeArray(name: string): string[] {
const value = this.node.attributes.get(name) as string;
if (!value) return [this.node.attributes.getDefault(name) as string];
return split(value);
}
/**
* Adds "em" to a list of dimensions, after dividing by n (defaults to 1).
*
* @param {string[]} list The array of dimensions (in em's)
* @param {nunber=} n The number to divide each dimension by after converted
* @return {string[]} The array of values with "em" added
*/
public addEm(list: number[], n: number = 1): string[] | null {
if (!list) return null;
return list.map(x => this.em(x / n));
}
/**
* Converts an array of dimensions (with arbitrary units) to an array of numbers
* representing the dimensions in units of em's.
*
* @param {string[]} list The array of dimensions to be turned into em's
* @return {number[]} The array of values converted to em's
*/
public convertLengths(list: string[]): number[] | null {
if (!list) return null;
return list.map(x => this.length2em(x));
}
};
} | the_stack |
import {Factor} from '@/services/data/tuples/factor-types';
import {Pipeline} from '@/services/data/tuples/pipeline-types';
import {connectSimulatorDB} from '@/services/local-persist/db';
import {ICON_SEARCH} from '@/widgets/basic/constants';
import {ButtonInk} from '@/widgets/basic/types';
import {useForceUpdate} from '@/widgets/basic/utils';
import {useEventBus} from '@/widgets/events/event-bus';
import {EventTypes} from '@/widgets/events/types';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import dayjs from 'dayjs';
import React, {useEffect, useState} from 'react';
import {DataRow} from '../../../types';
import {getPipelineName} from '../../../utils';
import {TopicsData} from '../../state/types';
import {getValueFromSourceData} from '../compute/parameter-kits';
import {DataDialog} from '../data-dialog';
import {useRunsEventBus} from '../runs-event-bus';
import {RunsEventTypes} from '../runs-event-bus-types';
import {useRuntimeEventBus} from '../runtime/runtime-event-bus';
import {RuntimeEventTypes} from '../runtime/runtime-event-bus-types';
import {ChangedDataRow, PipelineRunStatus, PipelineRuntimeContext} from '../types';
import {generateRuntimeId} from '../utils';
import {CellButton, PipelineElementType, RunTableBodyCell, RunTablePipelineRow} from '../widgets';
import {PipelineRunStatusCell} from './pipeline-run-status-cell';
import {useCompleted} from './use-completed';
import {useConditionCheck} from './use-condition-check';
import {useRunStages} from './use-run-stages';
import {useTriggerTypeCheck} from './use-trigger-type-check';
import {buildContextBody, createLogWriter, findRuntimeData} from './utils';
const startPipeline = async (context: PipelineRuntimeContext, start: () => void) => {
context.pipelineRuntimeId = generateRuntimeId();
await (createLogWriter(context)('Start pipeline'));
// now, here is a thing more tricky:
// normally, for pipelines defined, trigger data is not existed in runtime data
// and for pipelines triggered by others (called dynamic pipelines), trigger data is already existed in runtime data.
// but there is still an exception case, consider the following scenario:
// this pipeline is in pipelines defined, which means it is first bulk.
// it has trigger data which is defined manually,
// but when some pipelines run, data might be already written into runtime data,
// which means trigger data is already existed in runtime data just like dynamic pipeline.
// now have to find a way to identify this, use unique index
const triggerData = context.triggerData;
const topicId = context.topic.topicId;
// find it in runtime data
const topicData = context.runtimeData[topicId];
if (!topicData) {
// not exists, put it into runtime data
// make sure trigger data in runtime data
context.runtimeData[topicId] = [triggerData];
} else if (topicData.some(row => row === triggerData)) {
// exists, do nothing. it is dynamic pipeline triggered
} else {
// not exists, use unique index
// group unique index factors and find sequence factor
const factorsGroups = context.topic.factors.reduce((groups, factor) => {
if (factor.indexGroup && factor.indexGroup.startsWith('u-')) {
let group = groups.find(group => group.key === factor.indexGroup);
if (!group) {
group = {
key: factor.indexGroup,
factors: [factor],
values: [getValueFromSourceData(factor, triggerData)]
};
groups.push(group);
} else {
group.factors.push(factor);
group.values.push(getValueFromSourceData(factor, triggerData));
}
}
return groups;
}, [] as Array<{ key: string, factors: Array<Factor>, values: Array<any> }>);
if (factorsGroups.length === 0) {
// unique index not found, just simply insert trigger data to runtime data
topicData.push(triggerData);
} else {
// use these groups to find the fit one and only one in runtime data
const fits: Array<DataRow> = [];
for (let row of topicData) {
// must fit all groups
// raise exception if some matched and some mismatched
let hasMatched = false;
for (let factorGroup of factorsGroups) {
const matched = factorGroup.factors.every((factor, index) => {
// eslint-disable-next-line
return (getValueFromSourceData(factor, row) ?? '') == (factorGroup.values[index] ?? '');
});
if (matched) {
hasMatched = true;
} else if (hasMatched) {
throw new Error(`Ignored by cannot identify topic data by multiple unique indexes matched, data[trigger=${JSON.stringify(triggerData)}, exists=${JSON.stringify(row)}].`);
}
}
if (hasMatched) {
fits.push(row);
}
}
if (fits.length === 0) {
// not found
topicData.push(triggerData);
} else if (fits.length === 1) {
const index = topicData.findIndex(row => row === fits[0]);
// remove the fit one, replace with trigger data
context.triggerDataOnce = fits[0];
topicData.splice(index, 1, triggerData);
} else {
throw new Error(`More than one rows matched with trigger data[${JSON.stringify(triggerData)}].`);
}
}
}
context.status = PipelineRunStatus.RUNNING;
await connectSimulatorDB().pipelines.add({
pipelineId: context.pipeline.pipelineId,
pipelineRuntimeId: context.pipelineRuntimeId,
status: context.status,
context: buildContextBody(context),
dataBefore: context.runtimeData,
lastModifiedAt: dayjs().toDate()
});
start();
};
export const PipelineRuntime = (props: {
context: PipelineRuntimeContext;
pipelines: Array<Pipeline>
}) => {
const {context, pipelines} = props;
const {fire: fireGlobal} = useEventBus();
const {on: onRuns, off: offRuns} = useRunsEventBus();
const {fire} = useRuntimeEventBus();
const [message, setMessage] = useState('');
const forceUpdate = useForceUpdate();
useCompleted(context, pipelines, setMessage);
useTriggerTypeCheck(context, setMessage);
useConditionCheck(context, setMessage);
useRunStages(context, setMessage);
useEffect(() => {
const onRunPipeline = async (c: PipelineRuntimeContext) => {
if (c !== context) {
return;
}
try {
await startPipeline(context, () => {
forceUpdate();
fire(RuntimeEventTypes.DO_PIPELINE_TRIGGER_TYPE_CHECK, context);
});
} catch (e: any) {
await (createLogWriter(context)(e.message));
fire(RuntimeEventTypes.PIPELINE_FAILED, context);
}
};
onRuns(RunsEventTypes.RUN_PIPELINE, onRunPipeline);
return () => {
offRuns(RunsEventTypes.RUN_PIPELINE, onRunPipeline);
};
}, [onRuns, offRuns, fire, forceUpdate, context]);
const onStartPipeline = async () => {
try {
await startPipeline(context, () => {
forceUpdate();
fire(RuntimeEventTypes.DO_PIPELINE_TRIGGER_TYPE_CHECK, context);
});
} catch (e: any) {
await (createLogWriter(context)(e.message));
fire(RuntimeEventTypes.PIPELINE_FAILED, context);
}
};
const onExportClicked = async () => {
const {pipelineRuntimeId, topic, triggerData, triggerDataOnce, allTopics} = context;
const data = await findRuntimeData(pipelineRuntimeId!);
const beforeData = data!.dataBefore as TopicsData;
const afterData = data!.dataAfter as TopicsData;
const changedData = context.changedData;
const content = {
triggerData: {
topicId: topic.topicId,
topic: topic.name,
new: triggerData,
old: triggerDataOnce
},
dataBeforeRun: Object.keys(beforeData).map(topicId => {
return {
topicId,
topic: allTopics[topicId]!.name,
data: beforeData[topicId]
};
}),
dataChanged: Array.from((changedData || []).reduce((map, changed) => {
let rows = map.get(changed.topicId);
if (!rows) {
rows = [];
map.set(changed.topicId, rows);
}
rows.push(changed);
return map;
}, new Map<string, Array<ChangedDataRow>>()).values()).map((rows) => {
if (rows.length === 0) {
return null;
} else {
return {
topicId: rows[0].topicId,
topic: allTopics[rows[0].topicId]!.name,
data: rows.map(row => {
return {before: row.before, after: row.after};
})
};
}
}).filter(x => x != null),
dataAfterRun: Object.keys(afterData).map(topicId => {
return {
topicId,
topic: allTopics[topicId]!.name,
data: afterData[topicId]
};
})
};
const link = document.createElement('a');
link.href = 'data:application/json;charset=utf-8,' + encodeURI(JSON.stringify(content));
link.target = '_blank';
link.download = `data-of-pipeline -${dayjs().format('YYYYMMDDHHmmss')}.json`;
link.click();
};
const onDataClicked = async () => {
const {pipelineRuntimeId, triggerData, triggerDataOnce} = context;
let beforeData: TopicsData;
let afterData: TopicsData | undefined = void 0;
let data = pipelineRuntimeId ? await findRuntimeData(pipelineRuntimeId) : (void 0);
if (data) {
beforeData = data.dataBefore as TopicsData;
afterData = data.dataAfter as TopicsData;
} else {
beforeData = context.runtimeData;
}
const changedData = context.changedData;
fireGlobal(EventTypes.SHOW_DIALOG,
<DataDialog title="Data of Pipeline Run"
triggerData={{topic: context.topic, newOne: triggerData, oldOne: triggerDataOnce}}
beforeData={beforeData} afterData={afterData}
changedData={changedData}
allTopics={context.allTopics}
buttons={context.status === PipelineRunStatus.DONE ? [{
label: 'Export',
ink: ButtonInk.PRIMARY,
action: onExportClicked
}] : (void 0)}/>,
{
marginTop: '5vh',
marginLeft: '10%',
width: '80%',
height: '90vh'
});
};
return <RunTablePipelineRow>
<RunTableBodyCell><PipelineElementType>p</PipelineElementType>{getPipelineName(context.pipeline)}
</RunTableBodyCell>
<RunTableBodyCell>
<PipelineRunStatusCell status={context.status} onStart={onStartPipeline}/>
</RunTableBodyCell>
<RunTableBodyCell>
<CellButton ink={ButtonInk.SUCCESS} onClick={onDataClicked}>
<FontAwesomeIcon icon={ICON_SEARCH}/>
</CellButton>
</RunTableBodyCell>
<RunTableBodyCell>{message}</RunTableBodyCell>
</RunTablePipelineRow>;
}; | the_stack |
import { FigmaElement } from '../../contracts/FigmaElement';
import { FRAME as Frame } from '../../contracts/Figma';
import { Config } from '../../contracts/Config';
import { UpdatedCssAndImports } from '../../contracts/Imports';
import { TypographyElement } from '../../contracts/TypographyElement';
import { parseCssFromElement } from './logic/parseCssFromElement';
import { parseTypographyStylingFromElement } from './logic/parseTypographyStylingFromElement';
import { processNestedCss } from './logic/processNestedCss';
import { MsgProcessElementsCreatingElement } from '../../frameworks/messages/messages';
/**
* @description Factory function to create Figmagic element
*/
export const makeFigmagicElement = (
element: FigmaElement,
config: Config,
description = '',
isGraphicElement = false
): FigmagicElement => {
return new FigmagicElement(element, config, description, isGraphicElement);
};
class FigmagicElement {
id: string;
name: string;
children?: Frame[];
type: string;
isGraphicElement: boolean;
config: Config;
description: string;
element: string;
css: string;
html: string;
extraProps: string;
text: string | undefined;
imports: string[];
constructor(element: FigmaElement, config: Config, description = '', isGraphicElement: boolean) {
// Element
this.id = element.id;
this.name = element.name;
this.children = element.children;
this.type = element.type;
// Metadata
this.config = config;
this.description = description;
this.isGraphicElement = isGraphicElement;
this.element = ``;
this.css = ``;
this.html = ``;
this.extraProps = ``;
this.text = ``;
this.imports = [];
this.init();
}
init(): void {
this.setElement();
this.setElementType();
this.setPlaceholderText();
this.setText();
this.setDescription();
// Graphic elements only need the scaffolding, not any of the CSS parsing/processing
if (!this.isGraphicElement) {
const { updatedCss, updatedImports } = this.handleElements();
this.setCss(updatedCss);
// @ts-ignore
this.imports = [...new Set(updatedImports)];
}
}
/**
* @description Controller to funnel elements to the correct handler.
*/
private handleElements(): any {
try {
// Filter out hidden elements (using "_")
// @ts-ignore
const FILTERED_ELEMENTS = this.children.filter((child) => child.name[0] !== '_');
// If the remaining elements/layers contain any groups, use the nested elements handler
if (FILTERED_ELEMENTS?.some((element: Frame) => element.type === 'GROUP'))
return this.handleNestedElements(FILTERED_ELEMENTS);
else return this.handleFlatElements(FILTERED_ELEMENTS);
} catch (error: any) {
throw Error(error);
}
}
private setCss(css: string): void {
this.css = css;
}
private replaceHtml(match: string, replacement: string): void {
this.html = this.html.replace(match, replacement);
}
private addExtraProps(extraProps: string): void {
this.extraProps += extraProps;
}
/**
* @description Try setting Figmagic element text to the characters of an element-root-level layer going by the name ":text".
*/
private setText(): void {
const TEXT_CHILD = this.children?.filter((c) => c.name === ':text')[0];
if (TEXT_CHILD && TEXT_CHILD.characters) this.text = TEXT_CHILD.characters;
}
/**
* @description Set the element type (i.e "div", "input"...).
*/
private setElement(): void {
const ELEMENT_TYPE = (() => {
const _ELEMENT = this.description.match(/element=(.*)/);
if (_ELEMENT && _ELEMENT[1]) return _ELEMENT[1];
return 'div';
})();
const HTML = `<${ELEMENT_TYPE}>{{TEXT}}</${ELEMENT_TYPE}>`;
this.html = HTML;
this.element = ELEMENT_TYPE;
}
/**
* @description Set description for the Figmagic element. This is later output to the description file.
*/
private setDescription(): void {
let description = this.description;
const handleMatch = (regexMatch: any, currentDescription: string) => {
const match = regexMatch ? regexMatch[0] : null;
if (match) return currentDescription.replace(match, '');
return currentDescription;
};
if (description.match(/element=(.*)/)) {
const regexMatch = description.match(/element=(.*)/);
description = handleMatch(regexMatch, description);
}
if (description.match(/type=(.*)/)) {
const regexMatch = description.match(/type=(.*)/);
description = handleMatch(regexMatch, description);
}
// Clean up description
if (description.match(/description=(.*)/)) {
const regexMatch = description.match(/description=(.*)/);
description = handleMatch(regexMatch, description);
}
this.description = description;
}
/**
* @description Set element's placeholder text value, if we find an element-root-level layer going by the name ":placeholder".
*/
private setPlaceholderText(): void {
const PLACEHOLDER_TEXT_CHILD = this.children?.filter(
(child: Frame) => child.name.toLowerCase() === ':placeholder'
)[0];
if (PLACEHOLDER_TEXT_CHILD)
this.addExtraProps(`placeholder="${PLACEHOLDER_TEXT_CHILD.characters}"`);
}
/**
* @description Set element type (such as "type=checkbox"). This attribute is specified by the designer in Figma's description box.
*/
private setElementType(): void {
const TYPE = this.description.match(/type=(.*)/)?.[0];
if (TYPE) this.addExtraProps(`type="${TYPE.split('type=')[1]}" `);
}
/**
* @description Handle nested, multi-level elements. To correctly calculate elements we need both a "main" (layout) element and a "text" element.
*/
private handleNestedElements(elements: Frame[]): UpdatedCssAndImports {
try {
let css = ``;
let imports: Record<string, unknown>[] = [];
const CHILD_ELEMENTS = elements.filter(
(el: Frame) => el.type === 'GROUP' && el.name[0] !== '_'
);
CHILD_ELEMENTS?.forEach((variant: Frame) => {
const PARSED_CSS = this.parseNestedCss(variant, this.config);
css += PARSED_CSS.css;
imports = imports.concat(PARSED_CSS.imports);
});
const PROCESSED_CSS = processNestedCss(css);
return { updatedCss: PROCESSED_CSS, updatedImports: imports };
} catch (error: any) {
throw Error(error);
}
}
/**
* @description Handle flat, single-layer elements. To correctly calculate elements we need both a "main" (layout) element and a "text" element.
*/
private handleFlatElements(elements: Frame[]): UpdatedCssAndImports {
try {
let css = `\n`;
let imports: Record<string, unknown>[] = [];
this.replaceHtml('{{TEXT}}', this.text || '');
const MAIN_ELEMENT = elements?.filter(
(element: Frame) => element.name.toLowerCase() === this.name.toLowerCase()
)[0];
const TEXT_ELEMENT = elements?.filter((element: Frame) => element.type === 'TEXT')[0];
// Set text styling
if (TEXT_ELEMENT) {
const { updatedCss, updatedImports } = parseTypographyStylingFromElement({
textElement: TEXT_ELEMENT,
remSize: this.config.remSize,
usePostscriptFontNames: this.config.usePostscriptFontNames,
outputFormatTokens: this.config.outputFormatTokens,
outputFormatColors: this.config.outputFormatColors,
letterSpacingUnit: this.config.letterSpacingUnit,
outputFolderTokens: this.config.outputFolderTokens
} as TypographyElement);
css += updatedCss;
imports = imports.concat(updatedImports);
this.text = TEXT_ELEMENT.characters || '';
}
if (MAIN_ELEMENT) {
const { updatedCss, updatedImports } = this.parseFlatCss(MAIN_ELEMENT, TEXT_ELEMENT);
const COMBINED_CSS = css + updatedCss;
const PROCESSED_CSS = this.processFlatCss(COMBINED_CSS);
css = PROCESSED_CSS;
imports = imports.concat(updatedImports);
}
return { updatedCss: css, updatedImports: imports };
} catch (error: any) {
throw Error(error);
}
}
/**
* @description Process CSS for any nested elements (i.e. grouped in groups, in Figma)
*/
private parseNestedCss(el: Frame, config: Config, id?: number) {
let css = `\n`;
let imports: Record<string, unknown>[] = [];
const ID = id || Math.round(Math.random() * 10000);
const MAIN_ELEMENT = el.children?.filter(
(e: Frame) => e.type === 'RECTANGLE' && e.name[0] !== '_'
)[0];
const TEXT_ELEMENT = el.children?.filter(
(e: Frame) => e.type === 'TEXT' && e.name[0] !== '_'
)[0];
if (!MAIN_ELEMENT && !TEXT_ELEMENT) throw Error('Missing both main and text element!');
const FIXED_NAME = el.name.replace(/\s/gi, '');
const CHILD_ELEMENTS = el.children?.filter((child: Frame) => child.type === 'GROUP');
CHILD_ELEMENTS?.forEach((state: Frame) => {
const PARSED_CSS = this.parseNestedCss(state, config, ID);
css += PARSED_CSS.css;
imports = imports.concat(PARSED_CSS.imports);
});
if (MAIN_ELEMENT) {
console.log(MsgProcessElementsCreatingElement(MAIN_ELEMENT.name, FIXED_NAME));
const { updatedCss, updatedImports } = parseCssFromElement(
MAIN_ELEMENT,
TEXT_ELEMENT as any,
config.remSize,
config.outputFormatTokens,
config.outputFolderTokens
);
css += `\n.${FIXED_NAME}__#${ID} {\n${updatedCss}}`;
imports = imports.concat(updatedImports);
}
if (TEXT_ELEMENT) {
const { updatedCss, updatedImports } = parseTypographyStylingFromElement({
textElement: TEXT_ELEMENT,
remSize: config.remSize,
usePostscriptFontNames: config.usePostscriptFontNames,
outputFormatTokens: config.outputFormatTokens,
outputFormatColors: config.outputFormatColors,
letterSpacingUnit: config.letterSpacingUnit,
outputFolderTokens: config.outputFolderTokens
} as TypographyElement);
css += `\n.${FIXED_NAME}__#${ID} {\n${updatedCss}}`;
imports = imports.concat(updatedImports);
}
return { css, imports };
}
/**
* @description Process CSS for any "flat" elements
*/
private parseFlatCss(
layoutElement: Frame,
textElement: Frame | null = null
): UpdatedCssAndImports {
try {
let css = ``;
let imports: Record<string, unknown>[] = [];
if (layoutElement) {
const FIXED_NAME = this.name.replace(/\s/gi, '');
console.log(MsgProcessElementsCreatingElement(this.name, FIXED_NAME));
const { updatedCss, updatedImports } = parseCssFromElement(
layoutElement,
textElement,
this.config.remSize,
this.config.outputFormatTokens,
this.config.outputFolderTokens
);
css += updatedCss;
imports = imports.concat(updatedImports);
}
return { updatedCss: css, updatedImports: imports };
} catch (error: any) {
throw Error(error);
}
}
/**
* @description Process CSS for flat elements
*/
private processFlatCss(css: string): string {
if (!css) throw Error('Missing CSS string when calling processCss()!'); // TODO: Add real error
let processedCss = Array.from(new Set(css.split(/\n/gi))).toString();
if (processedCss[0] === ',') processedCss = processedCss.slice(1, processedCss.length);
processedCss = `\n ` + processedCss;
processedCss = processedCss.replace(/;,/gi, ';\n ');
processedCss += `\n`;
return processedCss;
}
} | the_stack |
import adaptor from '../adaptor'
import { Collection } from '../collection'
import { unwrapData, wrapData } from '../data'
import { Doc, doc } from '../doc'
import { Field } from '../field'
import { Ref, ref } from '../ref'
import { SetModel } from '../set'
import { UpdateModel } from '../update'
import { UpsetModel } from '../upset'
/**
* The transaction read API object. It contains {@link TransactionRead.get|get}
* the function that allows reading documents from the database.
*/
export interface TransactionRead {
/**
* Retrieves a document from a collection.
*
* ```ts
* import { transaction, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* transaction(
* ({ get }) => get('420'),
* //=> { __type__: 'doc', data: { count: 42 }, ... }
* ({ data: counter, set }) =>
* set(counter.ref, { count: counter.data.count + 1 })
* )
* ```
*
* @returns Promise to the document or null if not found
*
* @param ref - The reference to the document
*/
get<Model>(ref: Ref<Model>): Promise<Doc<Model> | null>
/**
* @param collection - The collection to get document from
* @param id - The document id
*/
get<Model>(
collection: Collection<Model>,
id: string
): Promise<Doc<Model> | null>
}
/**
* The transaction write API object. It unions a set of functions ({@link TransactionWrite.set|set},
* {@link TransactionWrite.update|update} and {@link TransactionWrite.remove|remove})
* that are similar to regular set, update and remove with the only
* difference that the transaction counterparts will retry writes if
* the state of data received with {@link TransactionRead.get|get} would change.
*/
export interface TransactionWrite<ReadResult> {
/**
* The result of the read function.
*/
data: ReadResult
/**
* Sets a document to the given data.
*
* ```ts
* import { transaction, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* transaction(
* ({ get }) => get('420'),
* ({ data: counter, set }) =>
* set(counter.ref, { count: counter.data.count + 1 })
* )
* ```
*
* @param ref - the reference to the document to set
* @param data - the document data
*/
set<Model>(ref: Ref<Model>, data: SetModel<Model>): void
/**
* @param collection - the collection to set document in
* @param id - the id of the document to set
* @param data - the document data
*/
set<Model>(
collection: Collection<Model>,
id: string,
data: SetModel<Model>
): void
/**
* Sets or updates a document with the given data.
*
* ```ts
* import { transaction, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* transaction(
* ({ get }) => get('420'),
* ({ data: counter, upset }) =>
* upset(counter.ref, { count: counter.data.count + 1 })
* )
* ```
*
* @param ref - the reference to the document to set or update
* @param data - the document data
*/
upset<Model>(ref: Ref<Model>, data: UpsetModel<Model>): void
/**
* @param collection - the collection to set document in
* @param id - the id of the document to set
* @param data - the document data
*/
upset<Model>(
collection: Collection<Model>,
id: string,
data: UpsetModel<Model>
): void
/**
* Updates a document.
*
* ```ts
* import { transaction, field, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* transaction(
* ({ get }) => get('420'),
* ({ data: counter, update }) =>
* update(counter.ref, { count: counter.data.count + 1 })
* //=> { __type__: 'doc', data: { count: 43 }, ... }
* )
*
* // ...or using field paths:
* transaction(
* ({ get }) => get('420'),
* ({ data: counter, update }) =>
* update(counter.ref, [field('count', counter.data.count + 1)])
* )
* ```
*
* @returns A promise that resolves when operation is finished
*
* @param collection - the collection to update document in
* @param id - the id of the document to update
* @param data - the document data to update
*/
update<Model>(
collection: Collection<Model>,
id: string,
data: Field<Model>[]
): void
/**
* @param ref - the reference to the document to set
* @param data - the document data to update
*/
update<Model>(ref: Ref<Model>, data: Field<Model>[]): void
/**
* @param collection - the collection to update document in
* @param id - the id of the document to update
* @param data - the document data to update
*/
update<Model>(
collection: Collection<Model>,
id: string,
data: UpdateModel<Model>
): void
/**
* @param ref - the reference to the document to set
* @param data - the document data to update
*/
update<Model>(ref: Ref<Model>, data: UpdateModel<Model>): void
/**
* Removes a document.
*
* ```ts
* import { transaction, field, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* transaction(async ({ get, remove }) => {
* const counter = await get('420')
* if (counter === 420) await remove(counter.ref)
* })
* transaction(
* ({ get }) => get('420'),
* ({ data: counter, remove }) => {
* console.log(counter.data.count)
* return remove(counter.ref)
* }
* )
* ```
*
* @returns Promise that resolves when the operation is complete.
*
* @param collection - The collection to remove document in
* @param id - The id of the documented to remove
*/
remove<Model>(collection: Collection<Model>, id: string): void
/**
* @param ref - The reference to the document to remove
*/
remove<Model>(ref: Ref<Model>): void
}
/**
* The transaction body function type.
*/
export type TransactionReadFunction<ReadResult> = (
api: TransactionRead
) => Promise<ReadResult>
/**
* The transaction body function type.
*/
export type TransactionWriteFunction<ReadResult, WriteResult> = (
api: TransactionWrite<ReadResult>
) => Promise<WriteResult>
/**
* The function allows performing transactions. It accepts two functions.
* The first receives {@link TransactionRead|transaction read API} that allows
* getting data from the database and pass it to the second function.
* The second function gets {@link TransactionWrite|transaction write API}
* with the data returned from the first function as `data` property of the argument.
*
* ```ts
* import { transaction, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* transaction(
* ({ get }) => get('420'),
* ({ data: counter, update }) =>
* update(counter.ref, { count: counter.data.count + 1 })
* )
* ```
*
* @param readFunction - the transaction read function that accepts transaction
* read API and returns data for write function
* @param writeFunction - the transaction write function that accepts
* transaction write API with the data returned by the read function
* @returns Promise that is resolved when transaction is closed
*/
export async function transaction<ReadResult, WriteResult>(
readFunction: TransactionReadFunction<ReadResult>,
writeFunction: TransactionWriteFunction<ReadResult, WriteResult>
): Promise<WriteResult> {
const a = await adaptor()
return a.firestore.runTransaction((t) => {
async function get<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
maybeId?: string
): Promise<Doc<Model> | null> {
let collection: Collection<Model>
let id: string
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = maybeId as string
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
}
const firestoreDoc = a.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above and below because is all the same as in the regular get function
const firestoreSnap = await t.get(firestoreDoc)
// v below
const firestoreData = firestoreSnap.data()
const data = firestoreData && (wrapData(a, firestoreData) as Model)
return data
? doc(ref(collection, id), data, a.getDocMeta(firestoreSnap))
: null
}
function set<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
idOrData: string | SetModel<Model>,
maybeData?: SetModel<Model>
): void {
let collection: Collection<Model>
let id: string
let data: SetModel<Model>
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = idOrData as string
data = maybeData as SetModel<Model>
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
data = idOrData as SetModel<Model>
}
const firestoreDoc = a.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above and below because is all the same as in the regular set function
t.set(firestoreDoc, unwrapData(a, data))
}
function upset<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
idOrData: string | SetModel<Model>,
maybeData?: UpsetModel<Model>
): void {
let collection: Collection<Model>
let id: string
let data: UpsetModel<Model>
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = idOrData as string
data = maybeData as UpsetModel<Model>
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
data = idOrData as UpsetModel<Model>
}
const firestoreDoc = a.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above and below because is all the same as in the regular set function
t.set(firestoreDoc, unwrapData(a, data), { merge: true })
}
function update<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
idOrData: string | Field<Model>[] | UpdateModel<Model>,
maybeData?: Field<Model>[] | UpdateModel<Model>
): void {
let collection: Collection<Model>
let id: string
let data: Model
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = idOrData as string
data = maybeData as Model
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
data = idOrData as Model
}
const firebaseDoc = a.firestore.collection(collection.path).doc(id)
const updateData = Array.isArray(data)
? data.reduce((acc, { key, value }) => {
acc[Array.isArray(key) ? key.join('.') : key] = value
return acc
}, {} as { [key: string]: any })
: data
// ^ above
// TODO: Refactor code above because is all the same as in the regular update function
t.update(firebaseDoc, unwrapData(a, updateData))
}
function remove<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
maybeId?: string
): void {
let collection: Collection<Model>
let id: string
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = maybeId as string
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
}
const firebaseDoc = a.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above because is all the same as in the regular update function
t.delete(firebaseDoc)
}
return readFunction({ get }).then((data) =>
writeFunction({ data, set, upset, update, remove })
)
})
} | the_stack |
import {
ArrayUtils, ClassParameter, Configuration, Logger, ObjectValidatorUtils, TypeChecker
} from '@plugcore/core';
import { FastifyInstance, FastifySchema, HTTPMethods } from 'fastify';
import fastifySwagger, { SwaggerOptions } from 'fastify-swagger';
import { FastifyValidationResult } from 'fastify/types/schema';
import { encode } from 'jwt-simple';
import { SecuritySchemeObject } from 'openapi3-ts';
import { JwtAvailableAlgorithms, WebOasConfiguration } from '../configuration/configuration.insterfaces';
import { MimeTypes } from './routes.constants';
import { ErrorResponseModel, FileField, IRegisteredController, IRouteSchemas, ModelRefTypes, Request, Response, TMethodOptions } from './routes.shared';
import { RoutesUtils } from './routes.utils';
export class RoutesInitializerHelper {
private modelPrefix = '';
private readonly eventNames = ['onRequest', 'preParsing', 'preValidation', 'preHandler', 'preSerialization', 'setValidatorCompiler'];
private readonly isFileType = 'isFileType';
private modelRefs: { clazz: ClassParameter<any>, ref: { name: string, path: string }, schema: any, isArray?: boolean }[] = [];
constructor(
private log: Logger,
private configuration: Configuration,
private securityEnabled = false,
private jwtConfiguration: {
// Default private key, should be changed
privateKey: string,
algorithm: JwtAvailableAlgorithms,
expiration: number | undefined
},
private oasDocumentationPath: string,
private disableModelRefs: boolean
) { }
//
// Public methods
//
public applyMappingToRoutes(restControllers: { controllerService: any; controller: IRegisteredController; }[], plugin: FastifyInstance) {
let securityOnAllRoutes = this.configuration && this.configuration.web &&
this.configuration.web.auth && this.securityEnabled && this.configuration.web.auth.securityInAllRoutes;
if (securityOnAllRoutes) {
securityOnAllRoutes = Array.isArray(securityOnAllRoutes) ? securityOnAllRoutes : [securityOnAllRoutes];
} else {
securityOnAllRoutes = [];
}
let routesToAdd: any[] = [];
for (const restController of restControllers) {
const methods = RoutesUtils.getRegisteredMethods(restController.controller.controller);
// 2: Attach all controller methods to fastify methods
for (const method of methods) {
const controllerMethodHandler = restController.controllerService[method.methodName].bind(restController.controllerService);
const controllerOptions: TMethodOptions = method.options || <TMethodOptions>{};
const url = restController.controller.options.urlBase + (method.path || '');
// Check all events, since they can be names of custom functions of the service
// and not stand alone functions.
if (ArrayUtils.someContentsAreTheSame(Object.keys(controllerOptions), this.eventNames)) {
for (const eventName of this.eventNames) {
const possibleEventFunction = (<Record<string, any>>controllerOptions)[eventName];
if (possibleEventFunction && typeof possibleEventFunction === 'function') {
const functName = possibleEventFunction.name;
if (restController.controller.controller.prototype[functName] === possibleEventFunction) {
(<Record<string, any>>controllerOptions)[eventName] =
restController.controllerService[functName].bind(restController.controllerService);
}
}
}
}
// Check if this is a multipart method to ignore the body validation
this.isMultipartMethod(controllerOptions);
// Schema definition
const routeSchemas = controllerOptions.routeSchemas;
let schema: FastifySchema = this.cloneSchema(controllerOptions.schema || {});
// Route validations
if (routeSchemas) {
schema = this.createFromRouteSchemas(method.httpMethod, routeSchemas, schema);
}
controllerOptions.routeSchemas = undefined;
if (this.securityEnabled) {
// Checck if this controller has security, either becouse of global security
// and or specific security of this route
let allAffectedSecurityTypes = (
this.configuration.web && this.configuration.web.auth && this.configuration.web.auth.securityInAllRoutes ?
Array.isArray(this.configuration.web.auth.securityInAllRoutes) ? this.configuration.web.auth.securityInAllRoutes : [
this.configuration.web.auth.securityInAllRoutes
] : []
) || [];
if (controllerOptions.security) {
allAffectedSecurityTypes = allAffectedSecurityTypes.concat(
Array.isArray(controllerOptions.security) ? controllerOptions.security : [controllerOptions.security]
);
}
const allSecurityTypes = ArrayUtils.removeDuplicates(allAffectedSecurityTypes);
const routeSecurity: any[] = [];
const regexAuth: string[] = [];
for (const securityType of allSecurityTypes) {
if (securityType === 'jwt') {
routeSecurity.push({ JWTBearerAuth: [] });
regexAuth.push('Bearer');
} else if (securityType === 'basic') {
routeSecurity.push({ BasicAuth: [] });
regexAuth.push('Basic');
}
}
if (routeSecurity.length > 0) {
schema.security = routeSecurity;
}
// TODO: Check tests, and add heather only when necesssary
/* if (regexAuth.length > 0) {
const headerSchema: Record<string, any> = schema.headers || {
type: 'object',
properties: {}
};
const properties = headerSchema.properties || <any>{};
if (!properties.Authorization) {
properties.Authorization = {
type: 'string',
pattern: `^(${regexAuth.join('|')}) .*$`
};
}
const prevRequired = headerSchema.required || [];
if (!prevRequired.includes('Authorization')) {
prevRequired.push('Authorization');
}
headerSchema.required = prevRequired;
schema.headers = headerSchema;
} */
}
// Check if we have to put some securty
if (securityOnAllRoutes.length > 0 || controllerOptions.security) {
const currentPreHandlers = controllerOptions.preHandler ?
Array.isArray(controllerOptions.preHandler) ? controllerOptions.preHandler : [controllerOptions.preHandler] : [];
const securityTypes = Array.isArray(controllerOptions.security) ? controllerOptions.security : [controllerOptions.security];
const securityHandlers: any[] = [];
if (securityOnAllRoutes.includes('jwt') || securityTypes.includes('jwt')) {
securityHandlers.push(plugin.verifyJwt);
}
if (securityOnAllRoutes.includes('basic') || securityTypes.includes('basic')) {
securityHandlers.push(plugin.verifyUserAndPassword);
}
if (securityOnAllRoutes.includes('custom') || securityTypes.includes('custom')) {
securityHandlers.push(plugin.customAuth);
}
if (!(securityTypes.length === 1 && securityTypes[0] === 'none') &&
securityHandlers.length > 0 && this.securityEnabled) {
// TODO, remove <any>
controllerOptions.preHandler = <any>currentPreHandlers.concat(plugin.auth(
securityHandlers
));
if (schema.response) {
(schema.response as any)[401] = ObjectValidatorUtils.generateJsonSchema(ErrorResponseModel);
} else {
schema.response = { 401: ObjectValidatorUtils.generateJsonSchema(ErrorResponseModel) };
}
}
}
// Multipart
const routeConfiguration = Object.assign(controllerOptions, {
method: method.httpMethod,
url,
handler: controllerMethodHandler,
schema
});
routesToAdd.push(routeConfiguration as any);
this.log.debug(`Registered http method < ${restController.controller.controller.name} > ${method.httpMethod} ${url}`);
}
}
// We have to add model refs before loading the routes
this.addSchemasToFastify(plugin);
for (const route of routesToAdd) {
plugin.route(route);
}
}
public applyAuthToRoutes(plugin: FastifyInstance) {
if (this.configuration.web && this.configuration.web.auth && this.securityEnabled) {
// Set jwt configuration
this.jwtConfiguration.algorithm = this.configuration.web.auth.jwtAlgorithm || this.jwtConfiguration.algorithm;
this.jwtConfiguration.privateKey = this.configuration.web.auth.jwtPrivateKey || this.jwtConfiguration.privateKey;
this.jwtConfiguration.expiration = this.configuration.web.auth.jwtExpiration || this.jwtConfiguration.expiration;
// Other vars
const loginUrl = this.configuration.web.auth.jwtLoginPath || '/auth/login';
// Register JWT login route
plugin.route({
method: 'POST',
url: loginUrl,
handler: <any>this.handleJwtLogin.bind(this),
schema: RoutesUtils.jwtLoginMeta ?
this.createFromRouteSchemas('POST', RoutesUtils.jwtLoginMeta.routeSchemas, undefined) : undefined
});
}
}
public applyOasToRoutes(oasConfiguration: WebOasConfiguration, plugin: FastifyInstance, restControllers: { controllerService: any; controller: IRegisteredController; }[]) {
if (oasConfiguration.enableDocumentation) {
// OAS configuration
const oasSecurity = this.configuration.web && this.configuration.web.auth && this.configuration.web.auth.securityInOas;
const securityHandlers: any[] = [];
if (this.securityEnabled && oasSecurity) {
// Create security handlers
if (oasSecurity.includes('jwt')) {
securityHandlers.push(plugin.verifyJwt);
}
if (oasSecurity.includes('basic')) {
securityHandlers.push(plugin.verifyUserAndPassword);
}
}
if (this.securityEnabled) {
// Check all controllers and global configuration
// to know all the security types
const allControllerSecurity = restControllers.map(r => RoutesUtils.getRegisteredMethods(r.controller.controller).map(c => c.options ?
c.options.security ? Array.isArray(c.options.security) ? c.options.security : [c.options.security] : [] : []
)
);
const controllerSecurityTypes = ArrayUtils.flat(allControllerSecurity);
if (this.configuration.web && this.configuration.web.auth && this.securityEnabled) {
controllerSecurityTypes.concat(
this.configuration.web.auth.securityInAllRoutes ?
Array.isArray(this.configuration.web.auth.securityInAllRoutes) ?
this.configuration.web.auth.securityInAllRoutes : [this.configuration.web.auth.securityInAllRoutes] :
[]
);
}
const possibleSecurityTypes = ArrayUtils.flatAndRemoveDuplicates(controllerSecurityTypes);
const securitySchemes: Record<string, SecuritySchemeObject> = {};
for (const securityType of possibleSecurityTypes) {
if (securityType === 'basic') {
securitySchemes['BasicAuth'] = { type: 'http', scheme: 'basic' };
}
if (securityType === 'jwt') {
securitySchemes['JWTBearerAuth'] = { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' };
}
}
if (Object.keys(securitySchemes).length > 0) {
const components = oasConfiguration.components || {};
// TODO Remove any
components.securitySchemes = <any>securitySchemes;
oasConfiguration.components = components;
}
}
this.log.info('Registering API documentation at: ' + this.oasDocumentationPath);
// Documentation route
plugin.route({
url: this.oasDocumentationPath,
method: 'GET',
schema: { hide: true } as any,
preHandler: securityHandlers.length > 0 ? plugin.auth(securityHandlers) : undefined,
handler: (_, reply) => {
reply.redirect(this.oasDocumentationPath + '/index.html');
}
});
plugin.route({
url: this.oasDocumentationPath + '/json',
method: 'GET',
schema: { hide: true } as any,
preHandler: securityHandlers.length > 0 ? plugin.auth(securityHandlers) : undefined,
handler: (_, reply) => {
reply.send(plugin.swagger());
},
});
plugin.route({
url: this.oasDocumentationPath + '/yaml',
method: 'GET',
schema: { hide: true } as any,
preHandler: securityHandlers.length > 0 ? plugin.auth(securityHandlers) : undefined,
handler: (_, reply) => {
reply.type('application/x-yaml').send((<any>plugin).oas({ yaml: true }));
},
});
// Before registering we have to check if we have som model refs to add
// Generates model refs
for (const restController of restControllers) {
const methods = RoutesUtils.getRegisteredMethods(restController.controller.controller);
for (const method of methods) {
const controllerOptions: TMethodOptions = method.options || <TMethodOptions>{};
const routeSchemas = controllerOptions.routeSchemas;
let schema: FastifySchema = this.cloneSchema(controllerOptions.schema || {});
if (routeSchemas) {
schema = this.createFromRouteSchemas(method.httpMethod, routeSchemas, schema);
}
}
}
if (this.modelRefs.length > 0) {
// With the model refs now we can create the component schemas
oasConfiguration.components = oasConfiguration.components || {};
oasConfiguration.components.schemas = oasConfiguration.components.schemas || {};
for (const modelRef of this.modelRefs) {
oasConfiguration.components.schemas[modelRef.ref.name] = modelRef.schema;
}
}
plugin.register(fastifySwagger, <SwaggerOptions>{
routePrefix: this.oasDocumentationPath,
exposeRoute: false,
openapi: oasConfiguration,
transform: (schema: any) => {
return this.findAndCahngeFileFields(schema);
}
});
}
}
//
// Private methods
//
private async handleJwtLogin(request: Request, reply: Response) {
const payload = await RoutesUtils.jwtLoginFn(request, reply);
if (payload === null || payload === undefined) {
throw new Error('Invalid credentials');
}
if (this.jwtConfiguration.expiration !== undefined) {
payload['exp'] = ((new Date()).getTime() / 1000) + this.jwtConfiguration.expiration;
}
const token = encode(payload, this.jwtConfiguration.privateKey, this.jwtConfiguration.algorithm);
reply.send({ token });
}
private createFromRouteSchemas(httpMethod: HTTPMethods, routeSchemas: IRouteSchemas, schema: FastifySchema | undefined) {
const result = this.cloneSchema(schema || {});
if (httpMethod !== 'GET' && routeSchemas.request) {
result.body = this.getModel(routeSchemas.request, { type: 'request', createModelRefs: routeSchemas.createModelRefs });
}
if (routeSchemas.response) {
result.response = {
200: this.getModel(routeSchemas.response, { type: 'response', createModelRefs: routeSchemas.createModelRefs }),
400: this.getModel(ErrorResponseModel, { type: 'response', forceRef: this.disableModelRefs ? false : true }),
500: this.getModel(ErrorResponseModel, { type: 'response', forceRef: this.disableModelRefs ? false : true }),
};
}
if (routeSchemas.query) {
result.querystring = this.getModel(routeSchemas.query, { type: 'query', createModelRefs: routeSchemas.createModelRefs });
}
if (routeSchemas.urlParameters) {
result.params = this.getModel(routeSchemas.urlParameters, { type: 'urlParameters', createModelRefs: routeSchemas.createModelRefs });
}
if (routeSchemas.headers) {
result.headers = this.getModel(routeSchemas.headers, { type: 'headers', createModelRefs: routeSchemas.createModelRefs });
}
if (routeSchemas.tags) {
result.tags = routeSchemas.tags;
}
if (routeSchemas.hide) {
result.hide = routeSchemas.hide;
}
if (routeSchemas.description) {
result.description = routeSchemas.description;
}
if (routeSchemas.summary) {
result.summary = routeSchemas.summary;
}
if (routeSchemas.consumes) {
result.consumes = routeSchemas.consumes;
}
if (routeSchemas.produces) {
result.produces = routeSchemas.produces;
}
if (routeSchemas.security) {
result.security = routeSchemas.security;
}
if (routeSchemas.operationId) {
result.operationId = routeSchemas.operationId;
}
return result;
}
private isModelArray(model: any): model is { isArray: true; model: ClassParameter<any> } {
return model.isArray !== undefined && model.isArray === true;
}
private cloneSchema(schema: FastifySchema) {
return JSON.parse(JSON.stringify(schema));
}
private getModel(
schemaRq: ClassParameter<any> | { isArray: true; model: ClassParameter<any> },
opts: { type: ModelRefTypes, createModelRefs?: ModelRefTypes[], forceRef?: boolean }
) {
const model = this.isModelArray(schemaRq) ? schemaRq.model : schemaRq;
const isArray = this.isModelArray(schemaRq);
// If we don't want to generate a model ref we simply return the schema
if (!opts.forceRef && (!opts.createModelRefs || !opts.createModelRefs.includes(opts.type))) {
return this.getRouteModelSchema(model, isArray, opts.type);
}
// We can check if the model ref has been already created
const targetModel = this.modelRefs.find(mr => mr.clazz == model && mr.isArray == isArray);
if (targetModel) {
return { $ref: targetModel.ref.path };
}
const modelSchema = this.getRouteModelSchema(model, isArray, opts.type);
// We have to generate a unique id
const currentRefs = this.modelRefs.map(mr => mr.ref.path);
let newRef = { name: '', path: '' };
let refCounter = 0;
while (newRef.path.length === 0) {
const refPathName = model.name.replace(/([A-Z])/g, '-$1').replace(/^-/, '').toLocaleLowerCase();
const testRef = `${this.modelPrefix}#/components/schemas/${refPathName}${refCounter === 0 ? '' : `-${refCounter}`}`;
if (currentRefs.includes(testRef)) {
refCounter++;
} else {
newRef = {
name: refPathName,
path: testRef
};
}
}
// Create a new ref
const newModelRef = {
clazz: model,
ref: newRef,
isArray: isArray,
schema: modelSchema
}
this.modelRefs.push(newModelRef);
return { $ref: newModelRef.ref.path };
}
private addSchemasToFastify(plugin: FastifyInstance) {
if (this.modelRefs.length > 0) {
for (const modelRef of this.modelRefs) {
plugin.addSchema({
...modelRef.schema,
$id: modelRef.ref.path
});
}
}
}
private getRouteModelSchema(model: ClassParameter<any>, asArray: boolean, type: ModelRefTypes) {
const schema = ObjectValidatorUtils.generateJsonSchema(model, { asArray });
// If we have a FileField object, we have to make some modifications in order the have
// the input field in the swagger UI
if (type === 'request' && schema.type === 'object' && schema.properties) {
for (const property of Object.keys(schema.properties)) {
const objProperty = schema.properties[property];
if (TypeChecker.isObject(objProperty) && objProperty.title === FileField.name) {
schema.properties[property] = <any>{ type: 'object', [this.isFileType]: true };
} else if (
TypeChecker.isObject(objProperty) && objProperty.type === 'array' &&
objProperty.items && TypeChecker.isObject(objProperty.items) &&
!TypeChecker.isArray(objProperty.items) && objProperty.items.title === FileField.name
) {
objProperty.items = <any>{ type: 'object', [this.isFileType]: true };
}
}
}
return schema;
}
private findAndCahngeFileFields(schema: any) {
for (const key of Object.keys(schema)) {
const value = schema[key];
if (key === this.isFileType) {
schema.type = 'file';
} else if (!TypeChecker.isPrimitive(value) && TypeChecker.isObject(schema[key])) {
this.findAndCahngeFileFields(value);
}
}
return schema;
}
private isMultipartMethod(controllerOptions: TMethodOptions) {
if (
(controllerOptions.routeSchemas?.consumes?.length || 0) > 0 &&
controllerOptions.routeSchemas!.consumes!.includes('multipart/form-data')
) {
(controllerOptions as any).validatorCompiler = () => {};
}
return false;
}
} | the_stack |
import {
JupyterFrontEnd,
JupyterFrontEndPlugin,
ILabShell,
} from '@jupyterlab/application';
import { ICellModel, isCodeCellModel } from '@jupyterlab/cells';
import {
Converter,
createConverter,
DataTypeNoArgs,
DataTypeStringArg,
externalURLDataType,
internalURLDataType,
nestedDataType,
Registry,
resolveDataType,
URLTemplate,
} from '@jupyterlab/dataregistry';
import { IOutputModel } from '@jupyterlab/rendermime';
import { IRegistry } from '@jupyterlab/dataregistry-registry-extension';
import { NotebookPanel } from '@jupyterlab/notebook';
import { ReadonlyPartialJSONObject } from '@lumino/coreutils';
import { combineLatest, defer, Observable, of, from } from 'rxjs';
import { map, switchMap, filter } from 'rxjs/operators';
import { notebookContextDataType } from './documents';
import {
observableListToObservable,
outputAreaModelToObservable,
} from './observables';
import { IActiveDataset } from './active';
import { signalToObservable } from './utils';
/**
* URLS
*/
const notebookURL = new URLTemplate('file://{+path}', {
path: URLTemplate.extension('.ipynb'),
});
const notebookCellURL = notebookURL.extend('#/cell-model/{cellID}', {
cellID: URLTemplate.uuid,
});
const notebookCellExternalURL = notebookURL.extend('#/cells/{cellIndex}', {
cellIndex: URLTemplate.number,
});
const notebookOutputURL = notebookCellURL.extend('/outputs/{outputID}', {
outputID: URLTemplate.number,
});
const notebookOutputExternalURL = notebookCellExternalURL.extend(
'/outputs/{outputID}',
{
outputID: URLTemplate.number,
}
);
const notebookMimeDataURL = notebookOutputURL.extend('/data/{mimeType}', {
mimeType: URLTemplate.string,
});
const notebookMimeDataExternalURL = notebookOutputExternalURL.extend(
'/data/{mimeType}',
{
mimeType: URLTemplate.string,
}
);
/**
* Mimetypes
*/
const notebookCellsDataType = new DataTypeNoArgs<Observable<Array<ICellModel>>>(
'application/x.jupyterlab.notebook-cells'
);
const cellModelDataType = new DataTypeNoArgs<Observable<ICellModel>>(
'application/x.jupyterlab.cell-model'
);
const cellIndexDataType = new DataTypeNoArgs<Observable<number>>(
'application/x.jupyterlab.cell-index'
);
const cellIDDataType = new DataTypeNoArgs<Observable<string>>(
'application/x.jupyterlab.cell-id'
);
const outputsDataType = new DataTypeNoArgs<Observable<Array<IOutputModel>>>(
'application/x.jupyterlab.outputs'
);
// The data in the mimebundle of an output cell
const mimeBundleDataType = new DataTypeNoArgs<
Observable<ReadonlyPartialJSONObject>
>('application/x.jupyterlab.mime-bundle');
// The data for a certain mimetype in an output.
const mimeDataDataType = new DataTypeStringArg<
Observable<ReadonlyPartialJSONObject>
>('application/x.jupyterlab.mimedata', 'mimeType');
/**
* Converters
*/
export function createConverters(
registry: Registry
): Array<Converter<any, any>> {
return [
/**
* Notebook
*/
createConverter(
{ from: notebookContextDataType, to: notebookCellsDataType },
({ data }) =>
data.pipe(
switchMap((context) =>
observableListToObservable(context.model.cells)
)
)
),
createConverter(
{ from: notebookCellsDataType, to: nestedDataType, url: notebookURL },
({ url: { path }, data }) =>
data.pipe(
map(
(cells) =>
new Set(
cells.map((arg) =>
notebookCellURL.create({ path, cellID: arg.id })
)
)
)
)
),
/**
* Cell
*/
createConverter(
{
from: resolveDataType,
to: cellIndexDataType,
url: notebookCellURL,
},
({ url: { cellID, ...rest } }) =>
defer(() =>
notebookCellsDataType
.getDataset(registry.getURL(notebookURL.create(rest)))!
.pipe(map((cells) => cells.findIndex((cell) => cell.id === cellID)))
)
),
createConverter(
{
from: cellIndexDataType,
to: cellModelDataType,
url: notebookCellURL,
},
({ data, url: { cellID, ...rest } }) =>
defer(() =>
combineLatest(
data,
notebookCellsDataType.getDataset(
registry.getURL(notebookURL.create(rest))
)!
).pipe(map(([index, cells]) => cells[index]))
)
),
createConverter(
{ from: cellModelDataType, to: outputsDataType },
({ data }) =>
data.pipe(
switchMap((cellModel) => {
if (isCodeCellModel(cellModel)) {
return outputAreaModelToObservable(cellModel.outputs);
}
return of([]);
})
)
),
createConverter(
{ from: outputsDataType, to: nestedDataType, url: notebookCellURL },
({ url, data }) =>
data.pipe(
map(
(outputs) =>
new Set(
outputs.map((_, outputID) =>
notebookOutputURL.create({ outputID, ...url })
)
)
)
)
),
createConverter(
{
from: cellIndexDataType,
to: externalURLDataType,
url: notebookCellURL,
},
({ data, url: { cellID, ...rest } }) =>
data.pipe(
map((cellIndex) =>
notebookCellExternalURL.create({
...rest,
cellIndex,
})
)
)
),
createConverter(
{
from: resolveDataType,
to: cellIDDataType,
url: notebookCellExternalURL,
},
({ url: { cellIndex, ...rest } }) =>
defer(() =>
notebookCellsDataType
.getDataset(registry.getURL(notebookURL.create(rest)))!
.pipe(map((cells) => cells[cellIndex].id))
)
),
createConverter(
{
from: cellIDDataType,
to: internalURLDataType,
url: notebookCellExternalURL,
},
({ url: { path }, data }) =>
data.pipe(
map((cellID) =>
notebookCellURL.create({
path,
cellID,
})
)
)
),
/**
* Output
*/
createConverter(
{ from: resolveDataType, to: mimeBundleDataType, url: notebookOutputURL },
({ url: { outputID, ...rest } }) =>
defer(() =>
outputsDataType
.getDataset(registry.getURL(notebookCellURL.create(rest)))!
.pipe(map((outputs) => outputs[outputID].data))
)
),
createConverter(
{ from: mimeBundleDataType, to: nestedDataType, url: notebookOutputURL },
({ url, data }) =>
data.pipe(
map(
(mimeData) =>
new Set(
Object.keys(mimeData).map((mimeType) =>
notebookMimeDataURL.create({ ...url, mimeType })
)
)
)
)
),
createConverter(
{
from: resolveDataType,
to: externalURLDataType,
url: notebookOutputURL,
},
({ url: { outputID, cellID, path } }) =>
defer(() =>
cellIndexDataType
.getDataset(
registry.getURL(notebookCellURL.create({ path, cellID }))
)!
.pipe(
map((cellIndex) =>
notebookOutputExternalURL.create({
path,
cellIndex,
outputID,
})
)
)
)
),
createConverter(
{
from: resolveDataType,
to: internalURLDataType,
url: notebookOutputExternalURL,
},
({ url: { outputID, cellIndex, path } }) =>
defer(() =>
cellIDDataType
.getDataset(
registry.getURL(
notebookCellExternalURL.create({ path, cellIndex })
)
)!
.pipe(
map((cellID) =>
notebookOutputURL.create({
path,
cellID,
outputID,
})
)
)
)
),
/**
* MimeData
*/
createConverter(
{ from: resolveDataType, to: mimeDataDataType, url: notebookMimeDataURL },
({ url: { mimeType, ...rest } }) => ({
type: mimeType,
data: defer(() =>
mimeBundleDataType
.getDataset(registry.getURL(notebookOutputURL.create(rest)))!
.pipe(map((mimeBundle) => mimeBundle[mimeType]))
),
})
),
createConverter(
{
from: resolveDataType,
to: externalURLDataType,
url: notebookMimeDataURL,
},
({ url: { path, cellID, outputID, mimeType } }) =>
defer(() =>
cellIndexDataType
.getDataset(
registry.getURL(notebookCellURL.create({ path, cellID }))
)!
.pipe(
map((cellIndex) =>
notebookMimeDataExternalURL.create({
path,
cellIndex,
outputID,
mimeType,
})
)
)
)
),
createConverter(
{
from: resolveDataType,
to: internalURLDataType,
url: notebookMimeDataExternalURL,
},
({ url: { outputID, cellIndex, path, mimeType } }) =>
defer(() =>
cellIDDataType
.getDataset(
registry.getURL(
notebookCellExternalURL.create({ path, cellIndex })
)
)!
.pipe(
map((cellID) =>
notebookMimeDataURL.create({
path,
cellID,
mimeType,
outputID,
})
)
)
)
),
createConverter<
Observable<ReadonlyPartialJSONObject>,
Observable<ReadonlyPartialJSONObject>,
string,
string
>({ from: mimeDataDataType }, ({ type, data }) => ({ type, data })),
];
}
function activate(
app: JupyterFrontEnd,
labShell: ILabShell,
registry: Registry,
active: IActiveDataset
) {
// get the url of all active cells, and set the active url to them
signalToObservable(labShell.currentChanged)
.pipe(
switchMap(([_, { newValue }]) => {
if (newValue instanceof NotebookPanel) {
return signalToObservable(newValue.content.activeCellChanged).pipe(
// filter for unselected cells
filter(([notebook, cell]) => !!cell),
map(([notebook, cell]) =>
notebookCellURL.create({
path: `/${newValue.context.path}`,
cellID: cell.model.id,
})
)
);
}
return from([]);
})
)
.subscribe({
next: (url) => {
active.next(url);
},
});
registry.addConverter(...createConverters(registry));
}
export default {
id: '@jupyterlab/dataregistry-extension:notebooks',
requires: [ILabShell, IRegistry, IActiveDataset],
activate,
autoStart: true,
} as JupyterFrontEndPlugin<void>; | the_stack |
import { EventEmitter } from 'events';
import * as stream from 'stream';
import * as util from 'util'
import * as fs from 'fs';
import { nanoid } from 'nanoid'
const finished = util.promisify(stream.finished);
// Emit event to class instance when piping/unpiping and connecting/disconnecting?
class Logger extends EventEmitter {
// Required constructor argument
name: string;
// Arrays used in class methods
connected: any[] = [];
_logged: string[] = [];
_sent: string[] = []; // Any message sent to another instance through .connect()
_forwarded: string[] = []; // Any message sent anywhere that isn't this using .pipe()
_piped: any[] = [];
// Vars
file: string;
_out?: stream.Writable;
// Optional constructor arguments
//logToConsole;
maxConnected: number;
includeCurrentDate: boolean;
dateAsEpoch: boolean;
includeUniqueIdentifier: boolean;
uniqueIdentifierLength: number;
constructor(name: string, file: string, {
//logToConsole = true,
maxConnected = 5,
includeCurrentDate = false,
dateAsEpoch = true,
includeUniqueIdentifier = false,
uniqueIdentifierLength = 10
} = {}) {
super()
this.name = name;
this.file = file;
//this.logToConsole = logToConsole;
this.maxConnected = maxConnected;
this.includeCurrentDate = includeCurrentDate;
this.dateAsEpoch = dateAsEpoch;
this.includeUniqueIdentifier = includeUniqueIdentifier;
this.uniqueIdentifierLength = uniqueIdentifierLength;
}
/**
* Log a message.
*/
async log(msg: string) {
const date = (this.includeCurrentDate && this.dateAsEpoch) ? Date.now() : new Date();
const id = nanoid(this.uniqueIdentifierLength);
const writeStream = fs.createWriteStream(this.file, { encoding: "utf8" });
let message: string = `\n${this.name}`;
if (this.includeCurrentDate) {
message += ` AT ${date}`;
}
message += `: ${msg}`;
if (this.includeUniqueIdentifier) {
message += ` | ID: ${id}`;
}
this._logged.push((message as unknown) as string);
if (this._out) {
this._out.write(message);
this.emit('message', msg, "log");
this.emit('logMessage', msg, message, date, id);
return this;
}
for await (const char of message) {
if (!writeStream.write(char)) {
await EventEmitter.once(writeStream, 'drain');
}
}
writeStream.end();
await finished(writeStream);
this.emit('message', msg, "log");
this.emit('logMessage', msg, message, date, id)
return this;
}
async warn(msg: string) {
const date = (this.includeCurrentDate && this.dateAsEpoch) ? Date.now() : new Date();
const id = nanoid(this.uniqueIdentifierLength);
const writeStream = fs.createWriteStream(this.file, { encoding: "utf8" });
let message = `\n${this.name} (WARNING)`;
if (this.includeCurrentDate) {
message += ` AT ${date}`;
}
message += `: ${msg}`;
if (this.includeUniqueIdentifier) {
message += ` | ID: ${id}`;
}
this._logged.push(message);
for await (const char of message) {
if (!writeStream.write(char)) {
await EventEmitter.once(writeStream, 'drain');
}
}
writeStream.end();
await finished(writeStream);
this.emit('message', msg, "warning");
this.emit('warningMessage', msg, message, date, id);
return this;
}
async error(msg: string) {
const date = (this.includeCurrentDate && this.dateAsEpoch) ? Date.now() : new Date();
const id = nanoid(this.uniqueIdentifierLength);
const writeStream = fs.createWriteStream(this.file, { encoding: "utf8" });
let message = `\nERR! ${this.name}`;
if (this.includeCurrentDate) {
message += ` AT ${date}`;
}
message += `: ${msg}`;
if (this.includeUniqueIdentifier) {
message += ` | ID: ${id}`;
}
this._logged.push(message);
for await (const char of message) {
if (!writeStream.write(char)) {
await EventEmitter.once(writeStream, 'drain');
}
}
writeStream.end();
await finished(writeStream);
this.emit('message', msg, "error");
this.emit('errorMessage', msg, message, date, id);
return this;
}
/**
* Connect an instance to this one. If a message is sent that the given instance accepts, that instance will also log the message in the appropriate file.
*/
connect(logger: this, callback: Function) {
if (!(logger instanceof Logger)) {
throw Error("Cannot connect instance to this.")
}
if (this.connected.length >= this.maxConnected) {
throw Error("Cannot exceed max number of connectd instances.")
}
if (this.connected.filter(e => e.logger === logger).length > 0) {
throw Error("Instance is already connectd.")
}
this.connected.push({ logger, callback });
// Prevents unneeded listeners being added
if (this.connected.length > 1) {
return this;
}
return this.on('message', (msg: any) => {
this.connected.forEach((i: any) => {
const instance = i.logger;
const cb = i.callback;
if ((!cb) || (cb && cb(msg))) {
instance.log(msg)
if (!this._sent.includes(msg)) {
this._sent.push(msg);
}
}
})
})
}
/**
* Disconnect specific connected instances from this instance
*/
disconnect(given: any) {
if (typeof given === "number") {
this.connected.splice(given, 1);
return this;
}
const instance = this.connected.filter((e: any) => e.logger === given)[0];
if (!instance) {
throw Error("Instance is not connected.");
}
const index = this.connected.indexOf(instance);
this.connected.splice(index, 1);
return this;
}
/**
* Disconnect all instances from this instance
*/
disconnectAll() {
this.connected = [];
this.removeAllListeners();
return this;
}
disconnectIf(callback: Function) {
if (!callback) {
throw Error("Callback expected as first argument.");
}
this.connected.forEach((instance, iter, arr) => {
if (callback(instance, iter, arr)) {
this.disconnect(iter);
}
})
}
getLoggedMessages(callback: Function) {
if (!callback) {
return this._logged;
}
return this._logged.filter(msg => {
if (callback(msg)) {
return msg;
}
})
}
getForwardedMessages(callback: Function) {
if (!callback) {
return this._sent;
}
return this._sent.filter(msg => {
if (callback(msg)) {
return msg;
}
})
}
enableAutomaticLogging(readableStream: stream.Readable, mode = 'log') {
if (!readableStream.readable) {
throw Error("Provide a readable stream as an argument");
}
if (!['log', 'warn', 'error'].some(e => mode === e)) {
throw Error("Mode must be either 'log', 'warn', or 'error'");
}
readableStream.on('readable', () => {
let data;
while (null !== (data = readableStream.read())) {
this.log(data);
}
})
this.emit("autolog");
return this;
}
streamTo(val: stream.Writable) {
if (val === this._out) {
return;
}
if (!val.write) {
throw Error("Argument must be a WritableStream");
}
this._out = val;
}
}
export default Logger;
/*import fs from 'fs'
import util from 'util';
import EventEmitter from 'events';
import * as stream from 'stream';
import { nanoid } from 'nanoid';
const finished = util.promisify(stream.finished);
export default class Logger extends EventEmitter {
private file: string;
private dateAsEpoch: boolean;
private includeUniqueIdentifier: boolean;
private uniqueIdentifierLength: number;
constructor(file: string, {
dateAsEpoch = true,
includeUniqueIdentifier = true,
uniqueIdentifierLength = 15
}: { dateAsEpoch?: boolean; includeUniqueIdentifier?: boolean; uniqueIdentifierLength?: number; } = {}) {
super()
this.file = file;
this.dateAsEpoch = dateAsEpoch;
this.includeUniqueIdentifier = includeUniqueIdentifier;
this.uniqueIdentifierLength = uniqueIdentifierLength;
}
/**
* Send a message to a preset log file.
* @param {string} message - Message to send.
*
public async log(message: string): Promise<void> {
const writeStream: fs.WriteStream = fs.createWriteStream(this.file, { encoding: 'utf8' });
let fullMessage: string = `LOGGED AT ${this.dateAsEpoch ? Date.now() : new Date()}: ${message}`
if (this.includeUniqueIdentifier) {
fullMessage += ` | ID: ${nanoid(this.uniqueIdentifierLength)}`;
}
this.emit('message', fullMessage);
for await (const char of fullMessage) {
if (!writeStream.write(char)) {
await EventEmitter.once(writeStream, 'drain');
}
}
writeStream.end();
await finished(writeStream);
}
/**
* Link two Logger instances together. When a message is sent to the original class instance .pipe() was called on, that message is sent to the second Logger as well.
* @param {Logger} logger Instance of Logger class to send messages to.
*
public async pipe(logger: Logger, callback?: Function): Promise<this> {
return this.on('message', (msg) => {
if ((!callback) || (callback && callback(msg))) {
logger.log(msg)
}
})
}
/**
* Detaches all Loggers from this instance
* @returns this
*
public unpipe(): this {
return this.removeAllListeners('message');
}
}*/ | the_stack |
import {CloudPrintInterfaceEventType, Destination, DestinationConnectionStatus, DestinationErrorType, DestinationOrigin, DestinationStore, DestinationStoreEventType, DestinationType, GooglePromotedDestinationId, LocalDestinationInfo, makeRecentDestination, NativeInitialSettings, NativeLayerImpl, PrinterType} from 'chrome://print/print_preview.js';
// <if expr="not chromeos and not lacros">
import {RecentDestination} from 'chrome://print/print_preview.js';
// </if>
import {assert} from 'chrome://resources/js/assert.m.js';
// <if expr="not chromeos and not lacros">
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
// </if>
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise} from 'chrome://webui-test/test_util.js';
import {CloudPrintInterfaceStub} from './cloud_print_interface_stub.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {setNativeLayerCrosInstance} from './native_layer_cros_stub.js';
// </if>
import {NativeLayerStub} from './native_layer_stub.js';
import {createDestinationStore, createDestinationWithCertificateStatus, getCddTemplate, getDefaultInitialSettings, getDestinations, getSaveAsPdfDestination, setupTestListenerElement} from './print_preview_test_utils.js';
// <if expr="not chromeos and not lacros">
import {getGoogleDriveDestination} from './print_preview_test_utils.js';
// </if>
const destination_store_test = {
suiteName: 'DestinationStoreTest',
TestNames: {
SingleRecentDestination: 'single recent destination',
MultipleRecentDestinations: 'multiple recent destinations',
RecentCloudPrintFallback:
'failure to load cloud print destination results in save as pdf',
MultipleRecentDestinationsOneRequest:
'multiple recent destinations one request',
MultipleRecentDestinationsAndCloudPrint:
'multiple recents and a Cloud Print destination',
DefaultDestinationSelectionRules: 'default destination selection rules',
// <if expr="not chromeos and not lacros">
SystemDefaultPrinterPolicy: 'system default printer policy',
// </if>
KioskModeSelectsFirstPrinter: 'kiosk mode selects first printer',
NoPrintersShowsError: 'no printers shows error',
UnreachableRecentCloudPrinter: 'unreachable recent cloud printer',
RecentSaveAsPdf: 'recent save as pdf',
// <if expr="not chromeos and not lacros">
MultipleRecentDestinationsAccounts: 'multiple recent destinations accounts',
// </if>
LoadAndSelectDestination: 'select loaded destination',
// <if expr="chromeos_ash or chromeos_lacros">
MultipleRecentDestinationsAccountsCros:
'multiple recent destinations accounts for Chrome OS',
LoadSaveToDriveCros: 'load Save to Drive Cros',
DriveNotMounted: 'drive not mounted',
// </if>
}
};
Object.assign(window, {destination_store_test: destination_store_test});
suite(destination_store_test.suiteName, function() {
let destinationStore: DestinationStore;
let nativeLayer: NativeLayerStub;
let cloudPrintInterface: CloudPrintInterfaceStub;
let initialSettings: NativeInitialSettings;
let userAccounts: string[] = [];
let localDestinations: LocalDestinationInfo[] = [];
let cloudDestinations: Destination[] = [];
let destinations: Destination[] = [];
let numPrintersSelected: number = 0;
setup(function() {
// Clear the UI.
document.body.innerHTML = '';
setupTestListenerElement();
nativeLayer = new NativeLayerStub();
NativeLayerImpl.setInstance(nativeLayer);
// <if expr="chromeos_ash or chromeos_lacros">
setNativeLayerCrosInstance();
// </if>
initialSettings = getDefaultInitialSettings();
localDestinations = [];
destinations = getDestinations(localDestinations);
});
/*
* Sets the initial settings to the stored value and creates the page.
* @param opt_expectPrinterFailure Whether printer fetch is
* expected to fail
* @param opt_cloudPrintEnabled Whether the cloud print interface
* should be present
* @return Promise that resolves when initial settings and,
* if printer failure is not expected, printer capabilities have
* been returned.
*/
function setInitialSettings(
opt_expectPrinterFailure?: boolean,
opt_cloudPrintEnabled: boolean =
true): Promise<{destinationId: string, printerType: PrinterType}> {
// Set local print list.
nativeLayer.setLocalDestinations(localDestinations);
// Create destination store.
destinationStore = createDestinationStore();
// Create cloud print interface if it's enabled. Otherwise, skip setting it
// to replicate the behavior in DestinationSettings.
if (opt_cloudPrintEnabled) {
cloudPrintInterface = new CloudPrintInterfaceStub();
cloudDestinations.forEach(cloudDestination => {
cloudPrintInterface.setPrinter(cloudDestination);
});
destinationStore.setCloudPrintInterface(cloudPrintInterface);
}
destinationStore.addEventListener(
DestinationStoreEventType.DESTINATION_SELECT, function() {
numPrintersSelected++;
});
// Initialize.
const recentDestinations = initialSettings.serializedAppStateStr ?
JSON.parse(initialSettings.serializedAppStateStr).recentDestinations :
[];
const whenCapabilitiesReady = eventToPromise(
DestinationStoreEventType.SELECTED_DESTINATION_CAPABILITIES_READY,
destinationStore);
destinationStore.init(
initialSettings.pdfPrinterDisabled, !!initialSettings.isDriveMounted,
initialSettings.printerName,
initialSettings.serializedDefaultDestinationSelectionRulesStr,
recentDestinations);
if (userAccounts) {
destinationStore.setActiveUser(userAccounts[0]!);
destinationStore.reloadUserCookieBasedDestinations(userAccounts[0]!);
}
return opt_expectPrinterFailure ? Promise.resolve() : Promise.race([
nativeLayer.whenCalled('getPrinterCapabilities'), whenCapabilitiesReady
]);
}
/**
* Tests that if the user has a single valid recent destination the
* destination is automatically reselected.
*/
test(
assert(destination_store_test.TestNames.SingleRecentDestination),
function() {
const recentDestination = makeRecentDestination(destinations[0]!);
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: [recentDestination],
});
return setInitialSettings(false).then(args => {
assertEquals('ID1', args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals('ID1', destinationStore.selectedDestination!.id);
});
});
/**
* Tests that if the user has multiple valid recent destinations the most
* recent destination is automatically reselected and its capabilities are
* fetched.
*/
test(
assert(destination_store_test.TestNames.MultipleRecentDestinations),
function() {
const recentDestinations = destinations.slice(0, 3).map(
destination => makeRecentDestination(destination));
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: recentDestinations,
});
return setInitialSettings(false).then(function(args) {
// Should have loaded ID1 as the selected printer, since it was most
// recent.
assertEquals('ID1', args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals('ID1', destinationStore.selectedDestination!.id);
// Verify that all local printers have been added to the store.
const reportedPrinters = destinationStore.destinations();
destinations.forEach(destination => {
const match = reportedPrinters.find((reportedPrinter) => {
return reportedPrinter.id === destination.id;
});
assertFalse(typeof match === 'undefined');
});
});
});
/**
* Tests that if the user has multiple recent destinations and a Cloud Print
* destination, the most recent destination is automatically reselected and
* its capabilities are fetched except for the Cloud Print destination.
*/
test(
assert(destination_store_test.TestNames
.MultipleRecentDestinationsAndCloudPrint),
function() {
// Convert the first 3 entries into recents.
const recentDestinations = destinations.slice(0, 3).map(
destination => makeRecentDestination(destination));
const cloudPrintDestination = new Destination(
'cp_id', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'Cloud Printer', DestinationConnectionStatus.ONLINE);
// Insert a Cloud Print printer into recent destinations.
recentDestinations.unshift(
makeRecentDestination(cloudPrintDestination));
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: recentDestinations,
});
// For accounts that are not allowed to use Cloud Print, they get a null
// interface object.
return setInitialSettings(false, false).then(function(args) {
// Should have loaded ID1 as the selected printer, since it was most
// recent.
assertEquals('ID1', args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals('ID1', destinationStore.selectedDestination!.id);
// Verify that all local printers have been added to the store.
const reportedPrinters = destinationStore.destinations();
destinations.forEach(destination => {
// <if expr="chromeos_ash or chromeos_lacros">
assertEquals(DestinationOrigin.CROS, destination.origin);
// </if>
// <if expr="not chromeos and not lacros">
assertEquals(DestinationOrigin.LOCAL, destination.origin);
// </if>
const match = reportedPrinters.find((reportedPrinter) => {
return reportedPrinter.id === destination.id;
});
assertFalse(typeof match === 'undefined');
});
// The Cloud Print printer should be missing.
const match = reportedPrinters.find(
reportedPrinter =>
cloudPrintDestination.id === reportedPrinter.id);
assertTrue(typeof match === 'undefined');
});
});
/**
* Tests that if the user has a recent Cloud Print destination selected, we
* fail to initialize the Cloud Print interface, and no other destinations are
* available, we fall back to Save As PDF.
*/
test(
assert(destination_store_test.TestNames.RecentCloudPrintFallback),
function() {
const cloudPrintDestination = new Destination(
'cp_id', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'Cloud Printer', DestinationConnectionStatus.ONLINE);
const recentDestination = makeRecentDestination(cloudPrintDestination);
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: [recentDestination],
});
localDestinations = [];
// For accounts that are not allowed to use Cloud Print, they get a null
// interface object.
return setInitialSettings(false, false).then(() => {
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
destinationStore.selectedDestination!.id);
});
});
/**
* Tests that if the user has multiple valid recent destinations, the
* correct destination is selected for the preview request.
* For crbug.com/666595.
*/
test(
assert(destination_store_test.TestNames
.MultipleRecentDestinationsOneRequest),
function() {
const recentDestinations = destinations.slice(0, 3).map(
destination => makeRecentDestination(destination));
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: recentDestinations,
});
return setInitialSettings(false).then(function(args) {
// Should have loaded ID1 as the selected printer, since it was most
// recent.
assertEquals('ID1', args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals('ID1', destinationStore.selectedDestination!.id);
// The other local destinations should be in the store, but only one
// should have been selected so there was only one preview request.
const reportedPrinters = destinationStore.destinations();
const expectedPrinters =
// <if expr="chromeos_ash or chromeos_lacros">
7;
// </if>
// <if expr="not chromeos and not lacros">
6;
// </if>
assertEquals(expectedPrinters, reportedPrinters.length);
destinations.forEach(destination => {
assertTrue(reportedPrinters.some(p => p.id === destination.id));
});
assertEquals(1, numPrintersSelected);
});
});
/**
* Tests that if there are default destination selection rules they are
* respected and a matching destination is automatically selected.
*/
test(
assert(destination_store_test.TestNames.DefaultDestinationSelectionRules),
function() {
initialSettings.serializedDefaultDestinationSelectionRulesStr =
JSON.stringify({namePattern: '.*Four.*'});
initialSettings.serializedAppStateStr = '';
return setInitialSettings(false).then(function(args) {
// Should have loaded ID4 as the selected printer, since it matches
// the rules.
assertEquals('ID4', args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals('ID4', destinationStore.selectedDestination!.id);
});
});
// <if expr="not chromeos and not lacros">
/**
* Tests that if the system default printer policy is enabled the system
* default printer is automatically selected even if the user has recent
* destinations.
*/
test(
assert(destination_store_test.TestNames.SystemDefaultPrinterPolicy),
function() {
// Set the policy in loadTimeData.
loadTimeData.overrideValues({useSystemDefaultPrinter: true});
// Setup some recent destinations to ensure they are not selected.
const recentDestinations: RecentDestination[] = [];
destinations.slice(0, 3).forEach(destination => {
recentDestinations.push(makeRecentDestination(destination));
});
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: recentDestinations,
});
return Promise
.all([
setInitialSettings(false),
eventToPromise(
DestinationStoreEventType
.SELECTED_DESTINATION_CAPABILITIES_READY,
destinationStore),
])
.then(() => {
// Need to load FooDevice as the printer, since it is the system
// default.
assertEquals(
'FooDevice', destinationStore.selectedDestination!.id);
});
});
// </if>
/**
* Tests that if there is no system default destination, the default
* selection rules and recent destinations are empty, and the preview
* is in app kiosk mode (so no PDF printer), the first destination returned
* from printer fetch is selected.
*/
test(
assert(destination_store_test.TestNames.KioskModeSelectsFirstPrinter),
function() {
initialSettings.serializedDefaultDestinationSelectionRulesStr = '';
initialSettings.serializedAppStateStr = '';
initialSettings.pdfPrinterDisabled = true;
initialSettings.isDriveMounted = false;
initialSettings.printerName = '';
return setInitialSettings(false).then(function(args) {
// Should have loaded the first destination as the selected printer.
assertEquals(destinations[0]!.id, args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals(
destinations[0]!.id, destinationStore.selectedDestination!.id);
});
});
/**
* Tests that if there is no system default destination, the default
* selection rules and recent destinations are empty, the preview
* is in app kiosk mode (so no PDF printer), and there are no
* destinations found, the NO_DESTINATIONS error is fired and the selected
* destination is null.
*/
test(
assert(destination_store_test.TestNames.NoPrintersShowsError),
function() {
initialSettings.serializedDefaultDestinationSelectionRulesStr = '';
initialSettings.serializedAppStateStr = '';
initialSettings.pdfPrinterDisabled = true;
initialSettings.isDriveMounted = false;
initialSettings.printerName = '';
localDestinations = [];
return Promise
.all([
setInitialSettings(true),
eventToPromise(DestinationStoreEventType.ERROR, destinationStore),
])
.then(function(argsArray) {
const errorEvent = argsArray[1];
assertEquals(
DestinationErrorType.NO_DESTINATIONS, errorEvent.detail);
assertEquals(null, destinationStore.selectedDestination);
});
});
/**
* Tests that if the user has a recent destination that triggers a cloud
* print error this does not disable the dialog.
*/
test(
assert(destination_store_test.TestNames.UnreachableRecentCloudPrinter),
function() {
const cloudPrinter = createDestinationWithCertificateStatus(
'BarDevice', 'BarName', false);
const recentDestination = makeRecentDestination(cloudPrinter);
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: [recentDestination],
});
userAccounts = ['foo@chromium.org'];
return setInitialSettings(false).then(function(args) {
assertEquals('FooDevice', args.destinationId);
assertEquals(PrinterType.LOCAL_PRINTER, args.printerType);
assertEquals('FooDevice', destinationStore.selectedDestination!.id);
});
});
/**
* Tests that if the user has a recent destination that is already in the
* store (PDF printer), the DestinationStore does not try to select a
* printer again later. Regression test for https://crbug.com/927162.
*/
test(assert(destination_store_test.TestNames.RecentSaveAsPdf), function() {
const pdfPrinter = getSaveAsPdfDestination();
const recentDestination = makeRecentDestination(pdfPrinter);
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: [recentDestination],
});
return setInitialSettings(false)
.then(function() {
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
destinationStore.selectedDestination!.id);
return new Promise(resolve => setTimeout(resolve));
})
.then(function() {
// Should still have Save as PDF.
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
destinationStore.selectedDestination!.id);
});
});
// <if expr="not chromeos and not lacros">
/**
* Tests that if there are recent destinations from different accounts, only
* destinations associated with the most recent account are fetched.
*/
test(
assert(
destination_store_test.TestNames.MultipleRecentDestinationsAccounts),
function() {
const account1 = 'foo@chromium.org';
const account2 = 'bar@chromium.org';
const driveUser1 = getGoogleDriveDestination(account1);
const driveUser2 = getGoogleDriveDestination(account2);
const cloudPrintFoo = new Destination(
'FooCloud', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'FooCloudName', DestinationConnectionStatus.ONLINE,
{account: account1});
const recentDestinations = [
makeRecentDestination(driveUser1),
makeRecentDestination(driveUser2),
makeRecentDestination(cloudPrintFoo),
];
cloudDestinations = [driveUser1, driveUser2, cloudPrintFoo];
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: recentDestinations,
});
userAccounts = [account1, account2];
const waitForPrinterDone = () => {
return eventToPromise(
CloudPrintInterfaceEventType.PRINTER_DONE,
cloudPrintInterface.getEventTarget());
};
// Wait for the first cloud printer to be fetched for selection.
return Promise
.all([
setInitialSettings(false),
waitForPrinterDone(),
])
.then(() => {
// Should have loaded Google Drive as the selected printer, since
// it was most recent.
assertEquals(
GooglePromotedDestinationId.DOCS,
destinationStore.selectedDestination!.id);
// Since the system default is local, local destinations will also
// have been loaded. Should have 5 local printers + 2 cloud
// printers for account 1 + Save as PDF.
const loadedPrintersAccount1 =
destinationStore.destinations(account1);
assertEquals(8, loadedPrintersAccount1.length);
cloudDestinations.forEach((destination) => {
assertEquals(
destination.account === account1,
loadedPrintersAccount1.some(
p => p.key === destination.key));
});
assertEquals(1, numPrintersSelected);
// 5 local + Save as PDF for account 2. Cloud printers for this
// account won't be retrieved until
// reloadUserCookieBasedDestinations() is called when the active
// user changes.
const loadedPrintersAccount2 =
destinationStore.destinations(account2);
assertEquals(6, loadedPrintersAccount2.length);
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
loadedPrintersAccount2[0]!.id);
loadedPrintersAccount2.forEach(printer => {
assertFalse(printer.origin === DestinationOrigin.COOKIES);
});
});
});
// </if>
/**
* Tests that if the user has a single valid recent destination the
* destination is automatically reselected.
*/
test(
assert(destination_store_test.TestNames.LoadAndSelectDestination),
function() {
destinations = getDestinations(localDestinations);
initialSettings.printerName = '';
const id1 = 'ID1';
const name1 = 'One';
let destination: Destination;
return setInitialSettings(false)
.then(function(args) {
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF, args.destinationId);
assertEquals(PrinterType.PDF_PRINTER, args.printerType);
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
destinationStore.selectedDestination!.id);
const localDestinationInfo = {
deviceName: id1,
printerName: name1
};
// Typecast localDestinationInfo to work around the fact that
// policy types are only defined on Chrome OS.
nativeLayer.setLocalDestinationCapabilities({
printer: localDestinationInfo,
capabilities: getCddTemplate(id1, name1).capabilities,
});
destinationStore.startLoadAllDestinations();
return nativeLayer.whenCalled('getPrinters');
})
.then(() => {
destination =
destinationStore.destinations().find(d => d.id === id1)!;
// No capabilities or policies yet.
assertFalse(!!destination.capabilities);
destinationStore.selectDestination(destination);
return nativeLayer.whenCalled('getPrinterCapabilities');
})
.then(() => {
assertEquals(destination, destinationStore.selectedDestination);
// Capabilities are updated.
assertTrue(!!destination.capabilities);
});
});
// <if expr="chromeos_ash or chromeos_lacros">
/**
* Tests that if there are recent destinations from different accounts, only
* destinations associated with the most recent account are fetched.
*/
test(
assert(destination_store_test.TestNames
.MultipleRecentDestinationsAccountsCros),
function() {
const account1 = 'foo@chromium.org';
const account2 = 'bar@chromium.org';
const cloudPrintFoo = new Destination(
'FooCloud', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'FooCloudName', DestinationConnectionStatus.ONLINE,
{account: account1});
const cloudPrintBar = new Destination(
'BarCloud', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'BarCloudName', DestinationConnectionStatus.ONLINE,
{account: account1});
const cloudPrintBaz = new Destination(
'BazCloud', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'BazCloudName', DestinationConnectionStatus.ONLINE,
{account: account2});
const recentDestinations = [
makeRecentDestination(cloudPrintFoo),
makeRecentDestination(cloudPrintBar),
makeRecentDestination(cloudPrintBaz),
];
cloudDestinations = [cloudPrintFoo, cloudPrintBar, cloudPrintBaz];
initialSettings.serializedAppStateStr = JSON.stringify({
version: 2,
recentDestinations: recentDestinations,
});
userAccounts = [account1, account2];
const waitForPrinterDone = () => {
return eventToPromise(
CloudPrintInterfaceEventType.PRINTER_DONE,
cloudPrintInterface.getEventTarget());
};
// Wait for all three cloud printers to load.
return Promise
.all([
setInitialSettings(false),
waitForPrinterDone(),
])
.then(() => {
// Should have loaded FooCloud as the selected printer, since
// it was most recent.
assertEquals(
'FooCloud', destinationStore.selectedDestination!.id);
// Since the system default is local, local destinations will also
// have been loaded. Should have 5 local printers + 2 cloud
// printers for account 1 + Save as PDF + Drive.
const loadedPrintersAccount1 =
destinationStore.destinations(account1);
assertEquals(9, loadedPrintersAccount1.length);
cloudDestinations.forEach((destination) => {
assertEquals(
destination.account === account1,
loadedPrintersAccount1.some(
p => p.key === destination.key));
});
assertEquals(1, numPrintersSelected);
// 5 local, Save as PDF, and Save to Drive exist
// when filtering for account 2 because its cloud printers are not
// requested at startup.
const loadedPrintersAccount2 =
destinationStore.destinations(account2);
assertEquals(7, loadedPrintersAccount2.length);
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
loadedPrintersAccount2[0]!.id);
});
});
/** Tests that the SAVE_TO_DRIVE_CROS destination is loaded on Chrome OS. */
test(
assert(destination_store_test.TestNames.LoadSaveToDriveCros), function() {
return setInitialSettings(false).then(() => {
assertTrue(!!destinationStore.destinations().find(
destination => destination.id ===
GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS));
});
});
// Tests that the SAVE_TO_DRIVE_CROS destination is not loaded on Chrome OS
// when Google Drive is not mounted.
test(assert(destination_store_test.TestNames.DriveNotMounted), function() {
initialSettings.isDriveMounted = false;
return setInitialSettings(false).then(() => {
assertFalse(!!destinationStore.destinations().find(
destination => destination.id ===
GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS));
});
});
// </if>
}); | the_stack |
import React, { PureComponent } from "react";
import Modal from "react-modal";
import TextareaAutosize from "react-textarea-autosize";
import { RouteComponentProps, withRouter } from "react-router-dom";
import styles from "./Send.module.css";
import cstyles from "./Common.module.css";
import { ToAddr, AddressBalance, SendPageState, Info, AddressBookEntry, TotalBalance, SendProgress } from "./AppState";
import Utils from "../utils/utils";
import ScrollPane from "./ScrollPane";
import ArrowUpLight from "../assets/img/arrow_up_dark.png";
import { BalanceBlockHighlight } from "./BalanceBlocks";
import RPC from "../rpc";
import routes from "../constants/routes.json";
import { parseZcashURI, ZcashURITarget } from "../utils/uris";
type OptionType = {
value: string;
label: string;
};
const Spacer = () => {
return <div style={{ marginTop: "24px" }} />;
};
type ToAddrBoxProps = {
toaddr: ToAddr;
zecPrice: number;
updateToField: (
id: number,
address: React.ChangeEvent<HTMLInputElement> | null,
amount: React.ChangeEvent<HTMLInputElement> | null,
memo: React.ChangeEvent<HTMLTextAreaElement> | string | null
) => void;
fromAddress: string;
fromAmount: number;
setSendButtonEnable: (sendButtonEnabled: boolean) => void;
setMaxAmount: (id: number, total: number) => void;
totalAmountAvailable: number;
};
const ToAddrBox = ({
toaddr,
zecPrice,
updateToField,
fromAddress,
fromAmount,
setMaxAmount,
setSendButtonEnable,
totalAmountAvailable,
}: ToAddrBoxProps) => {
const isMemoDisabled = !Utils.isZaddr(toaddr.to);
const addressIsValid = toaddr.to === "" || Utils.isZaddr(toaddr.to) || Utils.isTransparent(toaddr.to);
let amountError = null;
if (toaddr.amount) {
if (toaddr.amount < 0) {
amountError = "Amount cannot be negative";
}
if (toaddr.amount > fromAmount) {
amountError = "Amount Exceeds Balance";
}
if (toaddr.amount < 10 ** -8) {
amountError = "Amount is too small";
}
const s = toaddr.amount.toString().split(".");
if (s && s.length > 1 && s[1].length > 8) {
amountError = "Too Many Decimals";
}
}
if (isNaN(toaddr.amount)) {
// Amount is empty
amountError = "Amount cannot be empty";
}
let buttonstate = true;
if (!addressIsValid || amountError || toaddr.to === "" || toaddr.amount === 0 || fromAmount === 0) {
buttonstate = false;
}
setTimeout(() => {
setSendButtonEnable(buttonstate);
}, 10);
const usdValue = Utils.getZecToUsdString(zecPrice, toaddr.amount);
const addReplyTo = () => {
if (toaddr.memo.endsWith(fromAddress)) {
return;
}
if (fromAddress && toaddr.id) {
updateToField(toaddr.id, null, null, `${toaddr.memo}\nReply-To:\n${fromAddress}`);
}
};
return (
<div>
<div className={[cstyles.well, cstyles.verticalflex].join(" ")}>
<div className={[cstyles.flexspacebetween].join(" ")}>
<div className={cstyles.sublight}>To</div>
<div className={cstyles.validationerror}>
{addressIsValid ? (
<i className={[cstyles.green, "fas", "fa-check"].join(" ")} />
) : (
<span className={cstyles.red}>Invalid Address</span>
)}
</div>
</div>
<input
type="text"
placeholder="Z or T address"
className={cstyles.inputbox}
value={toaddr.to}
onChange={(e) => updateToField(toaddr.id as number, e, null, null)}
/>
<Spacer />
<div className={[cstyles.flexspacebetween].join(" ")}>
<div className={cstyles.sublight}>Amount</div>
<div className={cstyles.validationerror}>
{amountError ? <span className={cstyles.red}>{amountError}</span> : <span>{usdValue}</span>}
</div>
</div>
<div className={[cstyles.flexspacebetween].join(" ")}>
<input
type="number"
step="any"
className={cstyles.inputbox}
value={isNaN(toaddr.amount) ? "" : toaddr.amount}
onChange={(e) => updateToField(toaddr.id as number, null, e, null)}
/>
<img
className={styles.toaddrbutton}
src={ArrowUpLight}
alt="Max"
onClick={() => setMaxAmount(toaddr.id as number, totalAmountAvailable)}
/>
</div>
<Spacer />
{isMemoDisabled && <div className={cstyles.sublight}>Memos only for z-addresses</div>}
{!isMemoDisabled && (
<div>
<div className={[cstyles.flexspacebetween].join(" ")}>
<div className={cstyles.sublight}>Memo</div>
<div className={cstyles.validationerror}>{toaddr.memo.length}</div>
</div>
<TextareaAutosize
className={cstyles.inputbox}
value={toaddr.memo}
disabled={isMemoDisabled}
onChange={(e) => updateToField(toaddr.id as number, null, null, e)}
/>
<input type="checkbox" onChange={(e) => e.target.checked && addReplyTo()} />
Include Reply-To address
</div>
)}
<Spacer />
</div>
<Spacer />
</div>
);
};
export type SendManyJson = {
address: string;
amount: number;
memo?: string;
};
function getSendManyJSON(sendPageState: SendPageState): SendManyJson[] {
const json = sendPageState.toaddrs.flatMap((to) => {
const memo = to.memo || "";
const amount = parseInt((to.amount * 10 ** 8).toFixed(0));
if (memo === "") {
return { address: to.to, amount, memo: undefined };
} else if (memo.length <= 512) {
return { address: to.to, amount, memo };
} else {
// If the memo is more than 512 bytes, then we split it into multiple transactions.
// Each memo will be `(xx/yy)memo_part`. The prefix "(xx/yy)" is 7 bytes long, so
// we'll split the memo into 512-7 = 505 bytes length
const splits = Utils.utf16Split(memo, 505);
const tos = [];
// The first one contains all the tx value
tos.push({ address: to.to, amount, memo: `(1/${splits.length})${splits[0]}` });
for (let i = 1; i < splits.length; i++) {
tos.push({ address: to.to, amount: 0, memo: `(${i + 1}/${splits.length})${splits[i]}` });
}
return tos;
}
});
console.log("Sending:");
console.log(json);
return json;
}
type ConfirmModalToAddrProps = {
toaddr: ToAddr;
info: Info;
};
const ConfirmModalToAddr = ({ toaddr, info }: ConfirmModalToAddrProps) => {
const { bigPart, smallPart } = Utils.splitZecAmountIntoBigSmall(toaddr.amount);
const memo: string = toaddr.memo ? toaddr.memo : "";
return (
<div className={cstyles.well}>
<div className={[cstyles.flexspacebetween, cstyles.margintoplarge].join(" ")}>
<div className={[styles.confirmModalAddress].join(" ")}>
{Utils.splitStringIntoChunks(toaddr.to, 6).join(" ")}
</div>
<div className={[cstyles.verticalflex, cstyles.right].join(" ")}>
<div className={cstyles.large}>
<div>
<span>
{info.currencyName} {bigPart}
</span>
<span className={[cstyles.small, styles.zecsmallpart].join(" ")}>{smallPart}</span>
</div>
</div>
<div>{Utils.getZecToUsdString(info.zecPrice, toaddr.amount)}</div>
</div>
</div>
<div className={[cstyles.sublight, cstyles.breakword, cstyles.memodiv].join(" ")}>{memo}</div>
</div>
);
};
// Internal because we're using withRouter just below
type ConfirmModalProps = {
sendPageState: SendPageState;
info: Info;
sendTransaction: (sendJson: SendManyJson[], setSendProgress: (p?: SendProgress) => void) => Promise<string>;
clearToAddrs: () => void;
closeModal: () => void;
modalIsOpen: boolean;
openErrorModal: (title: string, body: string) => void;
openPasswordAndUnlockIfNeeded: (successCallback: () => void | Promise<void>) => void;
};
const ConfirmModalInternal: React.FC<RouteComponentProps & ConfirmModalProps> = ({
sendPageState,
info,
sendTransaction,
clearToAddrs,
closeModal,
modalIsOpen,
openErrorModal,
openPasswordAndUnlockIfNeeded,
history,
}) => {
const defaultFee = RPC.getDefaultFee();
const sendingTotal = sendPageState.toaddrs.reduce((s, t) => s + t.amount, 0.0) + defaultFee;
const { bigPart, smallPart } = Utils.splitZecAmountIntoBigSmall(sendingTotal);
const sendButton = () => {
// First, close the confirm modal.
closeModal();
// This will be replaced by either a success TXID or error message that the user
// has to close manually.
openErrorModal("Computing Transaction", "Please wait...This could take a while");
const setSendProgress = (progress?: SendProgress) => {
if (progress && progress.sendInProgress) {
openErrorModal(
`Computing Transaction`,
`Step ${progress.progress} of ${progress.total}. ETA ${progress.etaSeconds}s`
);
}
};
// Now, send the Tx in a timeout, so that the error modal above has a chance to display
setTimeout(() => {
openPasswordAndUnlockIfNeeded(() => {
// Then send the Tx async
(async () => {
const sendJson = getSendManyJSON(sendPageState);
let txid = "";
try {
txid = await sendTransaction(sendJson, setSendProgress);
console.log(txid);
openErrorModal(
"Successfully Broadcast Transaction",
`Transaction was successfully broadcast.\nTXID: ${txid}`
);
clearToAddrs();
// Redirect to dashboard after
history.push(routes.DASHBOARD);
} catch (err) {
// If there was an error, show the error modal
openErrorModal("Error Sending Transaction", `${err}`);
}
})();
});
}, 10);
};
return (
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
className={styles.confirmModal}
overlayClassName={styles.confirmOverlay}
>
<div className={[cstyles.verticalflex].join(" ")}>
<div className={[cstyles.marginbottomlarge, cstyles.center].join(" ")}>Confirm Transaction</div>
<div className={cstyles.flex}>
<div
className={[
cstyles.highlight,
cstyles.xlarge,
cstyles.flexspacebetween,
cstyles.well,
cstyles.maxwidth,
].join(" ")}
>
<div>Total</div>
<div className={[cstyles.right, cstyles.verticalflex].join(" ")}>
<div>
<span>
{info.currencyName} {bigPart}
</span>
<span className={[cstyles.small, styles.zecsmallpart].join(" ")}>{smallPart}</span>
</div>
<div className={cstyles.normal}>{Utils.getZecToUsdString(info.zecPrice, sendingTotal)}</div>
</div>
</div>
</div>
<ScrollPane offsetHeight={400}>
<div className={[cstyles.verticalflex, cstyles.margintoplarge].join(" ")}>
{sendPageState.toaddrs.map((t) => (
<ConfirmModalToAddr key={t.to} toaddr={t} info={info} />
))}
</div>
<ConfirmModalToAddr toaddr={{ to: "Fee", amount: defaultFee, memo: "" }} info={info} />
</ScrollPane>
<div className={cstyles.buttoncontainer}>
<button type="button" className={cstyles.primarybutton} onClick={() => sendButton()}>
Send
</button>
<button type="button" className={cstyles.primarybutton} onClick={closeModal}>
Cancel
</button>
</div>
</div>
</Modal>
);
};
const ConfirmModal = withRouter(ConfirmModalInternal);
type Props = {
addresses: string[];
totalBalance: TotalBalance;
addressBook: AddressBookEntry[];
sendPageState: SendPageState;
setSendTo: (targets: ZcashURITarget[] | ZcashURITarget) => void;
sendTransaction: (sendJson: SendManyJson[], setSendProgress: (p?: SendProgress) => void) => Promise<string>;
setSendPageState: (sendPageState: SendPageState) => void;
openErrorModal: (title: string, body: string) => void;
info: Info;
openPasswordAndUnlockIfNeeded: (successCallback: () => void) => void;
};
class SendState {
modalIsOpen: boolean;
sendButtonEnabled: boolean;
constructor() {
this.modalIsOpen = false;
this.sendButtonEnabled = false;
}
}
export default class Send extends PureComponent<Props, SendState> {
constructor(props: Props) {
super(props);
this.state = new SendState();
}
addToAddr = () => {
const { sendPageState, setSendPageState } = this.props;
const newToAddrs = sendPageState.toaddrs.concat(new ToAddr(Utils.getNextToAddrID()));
// Create the new state object
const newState = new SendPageState();
newState.fromaddr = sendPageState.fromaddr;
newState.toaddrs = newToAddrs;
setSendPageState(newState);
};
clearToAddrs = () => {
const { sendPageState, setSendPageState } = this.props;
const newToAddrs = [new ToAddr(Utils.getNextToAddrID())];
// Create the new state object
const newState = new SendPageState();
newState.fromaddr = sendPageState.fromaddr;
newState.toaddrs = newToAddrs;
setSendPageState(newState);
};
changeFrom = (selectedOption: OptionType) => {
const { sendPageState, setSendPageState } = this.props;
// Create the new state object
const newState = new SendPageState();
newState.fromaddr = selectedOption.value;
newState.toaddrs = sendPageState.toaddrs;
setSendPageState(newState);
};
updateToField = (
id: number,
address: React.ChangeEvent<HTMLInputElement> | null,
amount: React.ChangeEvent<HTMLInputElement> | null,
memo: React.ChangeEvent<HTMLTextAreaElement> | string | null
) => {
const { sendPageState, setSendPageState, setSendTo } = this.props;
const newToAddrs = sendPageState.toaddrs.slice(0);
// Find the correct toAddr
const toAddr = newToAddrs.find((a) => a.id === id) as ToAddr;
if (address) {
// First, check if this is a URI
// $FlowFixMe
const parsedUri = parseZcashURI(address.target.value);
if (Array.isArray(parsedUri)) {
setSendTo(parsedUri);
return;
}
toAddr.to = address.target.value.replace(/ /g, ""); // Remove spaces
}
if (amount) {
// Check to see the new amount if valid
// $FlowFixMe
const newAmount = parseFloat(amount.target.value);
if (newAmount < 0 || newAmount > 21 * 10 ** 6) {
return;
}
// $FlowFixMe
toAddr.amount = newAmount;
}
if (memo) {
if (typeof memo === "string") {
toAddr.memo = memo;
} else {
// $FlowFixMe
toAddr.memo = memo.target.value;
}
}
// Create the new state object
const newState = new SendPageState();
newState.fromaddr = sendPageState.fromaddr;
newState.toaddrs = newToAddrs;
setSendPageState(newState);
};
setMaxAmount = (id: number, total: number) => {
const { sendPageState, setSendPageState } = this.props;
const newToAddrs = sendPageState.toaddrs.slice(0);
let totalOtherAmount: number = newToAddrs.filter((a) => a.id !== id).reduce((s, a) => s + a.amount, 0);
// Add Fee
totalOtherAmount += RPC.getDefaultFee();
// Find the correct toAddr
const toAddr = newToAddrs.find((a) => a.id === id) as ToAddr;
toAddr.amount = total - totalOtherAmount;
if (toAddr.amount < 0) toAddr.amount = 0;
//toAddr.amount = Utils.maxPrecisionTrimmed(toAddr.amount);
// Create the new state object
const newState = new SendPageState();
newState.fromaddr = sendPageState.fromaddr;
newState.toaddrs = newToAddrs;
setSendPageState(newState);
};
setSendButtonEnable = (sendButtonEnabled: boolean) => {
this.setState({ sendButtonEnabled });
};
openModal = () => {
this.setState({ modalIsOpen: true });
};
closeModal = () => {
this.setState({ modalIsOpen: false });
};
getBalanceForAddress = (addr: string, addressesWithBalance: AddressBalance[]): number => {
// Find the addr in addressesWithBalance
const addressBalance = addressesWithBalance.find((ab) => ab.address === addr) as AddressBalance;
if (!addressBalance) {
return 0;
}
return addressBalance.balance;
};
getLabelForFromAddress = (addr: string, addressesWithBalance: AddressBalance[], currencyName: string) => {
// Find the addr in addressesWithBalance
const { addressBook } = this.props;
const label = addressBook.find((ab) => ab.address === addr);
const labelStr = label ? ` [ ${label.label} ]` : "";
const balance = this.getBalanceForAddress(addr, addressesWithBalance);
return `[ ${currencyName} ${balance.toString()} ]${labelStr} ${addr}`;
};
render() {
const { modalIsOpen, sendButtonEnabled } = this.state;
const {
addresses,
sendTransaction,
sendPageState,
info,
totalBalance,
openErrorModal,
openPasswordAndUnlockIfNeeded,
} = this.props;
const totalAmountAvailable = totalBalance.transparent + totalBalance.spendablePrivate;
const fromaddr = addresses.find((a) => Utils.isSapling(a)) as string;
// If there are unverified funds, then show a tooltip
let tooltip: string = "";
if (totalBalance.unverifiedPrivate) {
tooltip = `Waiting for confirmation of ZEC ${totalBalance.unverifiedPrivate} with 5 blocks (approx 6 minutes)`;
}
return (
<div>
<div className={[cstyles.xlarge, cstyles.padall, cstyles.center].join(" ")}>Send</div>
<div className={styles.sendcontainer}>
<div className={[cstyles.well, cstyles.balancebox, cstyles.containermargin].join(" ")}>
<BalanceBlockHighlight
topLabel="Spendable Funds"
zecValue={totalAmountAvailable}
usdValue={Utils.getZecToUsdString(info.zecPrice, totalAmountAvailable)}
currencyName={info.currencyName}
tooltip={tooltip}
/>
<BalanceBlockHighlight
topLabel="All Funds"
zecValue={totalBalance.total}
usdValue={Utils.getZecToUsdString(info.zecPrice, totalBalance.total)}
currencyName={info.currencyName}
/>
</div>
<ScrollPane className={cstyles.containermargin} offsetHeight={320}>
{sendPageState.toaddrs.map((toaddr) => {
return (
<ToAddrBox
key={toaddr.id}
toaddr={toaddr}
zecPrice={info.zecPrice}
updateToField={this.updateToField}
fromAddress={fromaddr}
fromAmount={totalAmountAvailable}
setMaxAmount={this.setMaxAmount}
setSendButtonEnable={this.setSendButtonEnable}
totalAmountAvailable={totalAmountAvailable}
/>
);
})}
<div style={{ textAlign: "right" }}>
<button type="button" onClick={this.addToAddr}>
<i className={["fas", "fa-plus"].join(" ")} />
</button>
</div>
</ScrollPane>
<div className={cstyles.center}>
<button
type="button"
disabled={!sendButtonEnabled}
className={cstyles.primarybutton}
onClick={this.openModal}
>
Send
</button>
<button type="button" className={cstyles.primarybutton} onClick={this.clearToAddrs}>
Cancel
</button>
</div>
<ConfirmModal
sendPageState={sendPageState}
info={info}
sendTransaction={sendTransaction}
openErrorModal={openErrorModal}
closeModal={this.closeModal}
modalIsOpen={modalIsOpen}
clearToAddrs={this.clearToAddrs}
openPasswordAndUnlockIfNeeded={openPasswordAndUnlockIfNeeded}
/>
</div>
</div>
);
}
} | the_stack |
import { existsSync } from 'fs';
import { basename, dirname, extname, join, relative } from 'path';
import * as recursive from 'recursive-readdir';
import {
CompletionItem,
InputBoxOptions,
Position,
QuickPickItem,
QuickPickOptions,
window,
workspace,
ExtensionContext
} from 'vscode';
import { Command } from '../Command';
import {
hasValidWorkSpaceRootPath,
ignoreFiles,
insertContentToEditor,
isMarkdownFileCheck,
isValidEditor,
noActiveEditorMessage,
postWarning,
setCursorPosition
} from '../helper/common';
import { sendTelemetryData } from '../helper/telemetry';
const telemetryCommandMedia: string = 'insertMedia';
const telemetryCommandLink: string = 'insertLink';
const imageExtensions = ['.jpeg', '.jpg', '.png', '.gif', '.bmp', '.svg'];
const telemetryCommand: string = 'insertImage';
let commandOption: string;
export const insertImageCommand: Command[] = [
{ command: pickImageType.name, callback: pickImageType },
{ command: applyImage.name, callback: applyImage },
{ command: applyIcon.name, callback: applyIcon },
{ command: applyComplex.name, callback: applyComplex },
{ command: applyLocScope.name, callback: applyLocScope },
{ command: applyLightbox.name, callback: applyLightbox },
{ command: applyLink.name, callback: applyLink }
];
export async function pickImageType(context: ExtensionContext) {
const opts: QuickPickOptions = { placeHolder: 'Select an Image type' };
const items: QuickPickItem[] = [];
const config = workspace.getConfiguration('markdown');
const alwaysIncludeLocScope = config.get<boolean>('alwaysIncludeLocScope');
items.push({
description: '',
label: 'Image'
});
items.push({
description: '',
label: 'Icon image'
});
items.push({
description: '',
label: 'Complex image'
});
if (!alwaysIncludeLocScope) {
items.push({
description: '',
label: 'Add localization scope to image'
});
}
items.push({
description: '',
label: 'Add lightbox to image'
});
items.push({
description: '',
label: 'Add link to image'
});
const selection = await window.showQuickPick(items, opts);
if (!selection) {
return;
}
switch (selection.label.toLowerCase()) {
case 'image':
await applyImage(context);
commandOption = 'image';
break;
case 'icon image':
await applyIcon();
commandOption = 'icon';
break;
case 'complex image':
await applyComplex(context);
commandOption = 'complex';
break;
case 'add localization scope to image':
await applyLocScope(context);
commandOption = 'loc-scope';
break;
case 'add lightbox to image':
await applyLightbox();
commandOption = 'lightbox';
break;
case 'add link to image':
await applyLink();
commandOption = 'link';
break;
}
sendTelemetryData(telemetryCommand, commandOption);
}
export async function applyImage(context: ExtensionContext) {
// get editor, its needed to apply the output to editor window.
const editor = window.activeTextEditor;
let folderPath: string = '';
if (!editor) {
noActiveEditorMessage();
return;
}
let image = '';
if (checkEditor(editor)) {
// Get images from repo as quickpick items
// User should be given a list of quickpick items which list images from repo
if (workspace.workspaceFolders) {
folderPath = workspace.workspaceFolders[0].uri.fsPath;
}
// recursively get all the files from the root folder
recursive(folderPath, ignoreFiles, async (err: any, files: any) => {
if (err) {
window.showErrorMessage(err);
}
const items: QuickPickItem[] = [];
files.sort();
files
.filter((file: any) => imageExtensions.indexOf(extname(file.toLowerCase())) !== -1)
.forEach((file: any) => {
items.push({ label: basename(file), description: dirname(file) });
});
// allow user to select source items from quickpick
const source = await window.showQuickPick(items, { placeHolder: 'Select Image from repo' });
if (source && source.description) {
const activeFileDir = dirname(editor.document.fileName);
const sourcePath = relative(
activeFileDir,
join(source.description, source.label).split('//').join('//')
).replace(/\\/g, '/');
// Ask user input for alt text
const selection = editor.selection;
const selectedText = editor.document.getText(selection);
let altText: string | undefined = '';
if (selectedText === '') {
// Ask user input for alt text
altText = await window.showInputBox({
placeHolder: 'Add alt text (up to 250 characters)',
validateInput: (text: string) =>
text !== ''
? text.length <= 250
? ''
: 'alt text should be less than 250 characters'
: 'alt-text input must not be empty'
});
if (!altText) {
// if user did not enter any alt text, then exit.
altText = '';
}
} else {
altText = selectedText;
}
const config = workspace.getConfiguration('markdown');
const alwaysIncludeLocScope = config.get<boolean>('alwaysIncludeLocScope');
if (alwaysIncludeLocScope) {
const allowlist: QuickPickItem[] = context.globalState.get('product');
// show quickpick to user for products list.
const locScope = await window.showQuickPick(allowlist, {
placeHolder: 'Select from product list'
});
if (locScope) {
image = `:::image type="content" source="${sourcePath}" alt-text="${altText}" loc-scope="${locScope.label}":::`;
}
} else {
image = `:::image type="content" source="${sourcePath}" alt-text="${altText}":::`;
}
// output image content type
insertContentToEditor(editor, image, true);
}
});
}
}
function checkEditor(editor: any) {
let actionType: string = 'Get File for Image';
// determines the name to set in the ValidEditor check
actionType = 'Art';
commandOption = 'art';
sendTelemetryData(telemetryCommandMedia, commandOption);
// checks for valid environment
if (!isValidEditor(editor, false, actionType)) {
return;
}
if (!isMarkdownFileCheck(editor, false)) {
return;
}
if (!hasValidWorkSpaceRootPath(telemetryCommandLink)) {
return;
}
// The active file should be used as the origin for relative links.
// The path is split so the file type is not included when resolving the path.
const activeFileName = editor.document.fileName;
const pathDelimited = editor.document.fileName.split('.');
const activeFilePath = pathDelimited[0];
// Check to see if the active file has been saved. If it has not been saved, warn the user.
// The user will still be allowed to add a link but it the relative path will not be resolved.
if (!existsSync(activeFileName)) {
window.showWarningMessage(
activeFilePath + ' is not saved. Cannot accurately resolve path to create link.'
);
return;
}
return true;
}
export async function applyIcon() {
// get editor to see if user has selected text
const editor = window.activeTextEditor;
let folderPath: string = '';
if (!editor) {
noActiveEditorMessage();
return;
}
let image = '';
if (checkEditor(editor)) {
const selection = editor.selection;
const selectedText = editor.document.getText(selection);
if (selectedText === '') {
// Get images from repo as quickpick items
// User should be given a list of quickpick items which list images from repo
if (workspace.workspaceFolders) {
folderPath = workspace.workspaceFolders[0].uri.fsPath;
}
// recursively get all the files from the root folder
recursive(folderPath, ignoreFiles, async (err: any, files: any) => {
if (err) {
window.showErrorMessage(err);
}
const items: QuickPickItem[] = [];
files.sort();
files
.filter((file: any) => imageExtensions.indexOf(extname(file.toLowerCase())) !== -1)
.forEach((file: any) => {
items.push({ label: basename(file), description: dirname(file) });
});
// allow user to select source items from quickpick
const source = await window.showQuickPick(items, { placeHolder: 'Select Image from repo' });
if (source && source.description) {
const activeFileDir = dirname(editor.document.fileName);
const sourcePath = relative(
activeFileDir,
join(source.description, source.label).split('//').join('//')
).replace(/\\/g, '/');
// output image content type
image = `:::image type="icon" source="${sourcePath}" border="false":::`;
insertContentToEditor(editor, image, true);
}
});
}
} else {
// if user has selected text then exit?
return;
}
return;
}
export async function applyComplex(context: ExtensionContext) {
// get editor, its needed to apply the output to editor window.
const editor = window.activeTextEditor;
let folderPath: string = '';
if (!editor) {
noActiveEditorMessage();
return;
}
let image = '';
if (checkEditor(editor)) {
// Get images from repo as quickpick items
// User should be given a list of quickpick items which list images from repo
if (workspace.workspaceFolders) {
folderPath = workspace.workspaceFolders[0].uri.fsPath;
}
// recursively get all the files from the root folder
recursive(folderPath, ignoreFiles, async (err: any, files: any) => {
if (err) {
window.showErrorMessage(err);
}
const items: QuickPickItem[] = [];
files.sort();
files
.filter((file: any) => imageExtensions.indexOf(extname(file.toLowerCase())) !== -1)
.forEach((file: any) => {
items.push({ label: basename(file), description: dirname(file) });
});
// allow user to select source items from quickpick
const source = await window.showQuickPick(items, { placeHolder: 'Select Image from repo' });
if (source && source.description) {
const activeFileDir = dirname(editor.document.fileName);
const sourcePath = relative(
activeFileDir,
join(source.description, source.label).split('//').join('//')
).replace(/\\/g, '/');
const selection = editor.selection;
const selectedText = editor.document.getText(selection);
let altText: string | undefined = '';
if (selectedText === '') {
// Ask user input for alt text
altText = await window.showInputBox({
placeHolder: 'Add alt text (up to 250 characters)',
validateInput: (text: string) =>
text !== ''
? text.length <= 250
? ''
: 'alt text should be less than 250 characters'
: 'alt-text input must not be empty'
});
if (!altText) {
// if user did not enter any alt text, then exit.
altText = '';
}
} else {
altText = selectedText;
}
const config = workspace.getConfiguration('markdown');
const alwaysIncludeLocScope = config.get<boolean>('alwaysIncludeLocScope');
if (alwaysIncludeLocScope) {
const allowlist: QuickPickItem[] = context.globalState.get('product');
// show quickpick to user for products list.
const locScope = await window.showQuickPick(allowlist, {
placeHolder: 'Select from product list'
});
if (locScope) {
image = `:::image type="complex" source="${sourcePath}" alt-text="${altText}" loc-scope="${locScope.label}":::
:::image-end:::`;
}
} else {
// output image complex type
image = `:::image type="complex" source="${sourcePath}" alt-text="${altText}":::
:::image-end:::`;
}
insertContentToEditor(editor, image, true);
// Set editor position to the middle of long description body
setCursorPosition(
editor,
editor.selection.active.line + 1,
editor.selection.active.character
);
}
});
}
}
export async function applyLocScope(context: ExtensionContext) {
// get editor, its needed to apply the output to editor window.
const editor = window.activeTextEditor;
if (!editor) {
noActiveEditorMessage();
return;
}
// if user has not selected any text, then continue
const RE_LOC_SCOPE = /:::image\s+((source|type|alt-text|lightbox|border|link)="(.*?)"\s*)+:::/gm;
const position = new Position(editor.selection.active.line, editor.selection.active.character);
// get the current editor position and check if user is inside :::image::: tags
const wordRange = editor.document.getWordRangeAtPosition(position, RE_LOC_SCOPE);
if (wordRange) {
const start = RE_LOC_SCOPE.exec(editor.document.getText(wordRange));
if (start) {
const type = start[start.indexOf('type') + 1];
if (type.toLowerCase() === 'icon') {
window.showErrorMessage(
'The loc-scope attribute should not be added to icons, which are not localized.'
);
return;
}
}
// if user is inside :::image::: tag, then ask them for quickpick of products based on allow list
const allowlist: QuickPickItem[] = context.globalState.get('product');
// show quickpick to user for products list.
const product = await window.showQuickPick(allowlist, {
placeHolder: 'Select from product list'
});
if (!product) {
// if user did not select source image then exit.
return;
} else {
// insert loc-sope into editor
await editor.edit(selected => {
selected.insert(
new Position(wordRange.end.line, wordRange.end.character - 3),
` loc-scope="${product.label}"`
);
});
}
} else {
const RE_LOC_SCOPE_EXISTS = /:::image\s+((source|type|alt-text|lightbox|border|loc-scope|link)="(.*?)"\s*)+:::/gm;
const locScopeAlreadyExists = editor.document.getWordRangeAtPosition(
position,
RE_LOC_SCOPE_EXISTS
);
if (locScopeAlreadyExists) {
window.showErrorMessage('loc-scope attribute already exists on :::image::: tag.');
return;
}
window.showErrorMessage('invalid cursor position. You must be inside :::image::: tags.');
}
return;
}
export async function applyLightbox() {
// get editor, its needed to apply the output to editor window.
const editor = window.activeTextEditor;
if (!editor) {
noActiveEditorMessage();
return;
}
// if user has not selected any text, then continue
const RE_LIGHTBOX = /:::image\s+((source|type|alt-text|loc-scope|border|link)="(.*?)"\s*)+:::/gm;
const position = new Position(editor.selection.active.line, editor.selection.active.character);
// get the current editor position and check if user is inside :::image::: tags
const wordRange = editor.document.getWordRangeAtPosition(position, RE_LIGHTBOX);
if (wordRange) {
let folderPath = '';
if (workspace.workspaceFolders) {
folderPath = workspace.workspaceFolders[0].uri.fsPath;
}
// get available files
recursive(folderPath, ignoreFiles, async (err: any, files: any) => {
if (err) {
window.showErrorMessage(err);
}
const items: QuickPickItem[] = [];
files.sort();
files
.filter((file: any) => imageExtensions.indexOf(extname(file.toLowerCase())) !== -1)
.forEach((file: any) => {
items.push({ label: basename(file), description: dirname(file) });
});
// show quickpick to user available images.
const image = await window.showQuickPick(items, { placeHolder: 'Select Image from repo' });
if (image && image.description) {
// insert lightbox into editor
const activeFileDir = dirname(editor.document.fileName);
const imagePath = relative(
activeFileDir,
join(image.description, image.label).split('//').join('//')
).replace(/\\/g, '/');
await editor.edit(selected => {
selected.insert(
new Position(wordRange.end.line, wordRange.end.character - 3),
` lightbox="${imagePath}"`
);
});
}
});
} else {
const RE_LIGHTBOX_EXISTS = /:::image\s+((source|type|alt-text|lightbox|border|loc-scope|link)="(.*?)"\s*)+:::/gm;
const lightboxAlreadyExists = editor.document.getWordRangeAtPosition(
position,
RE_LIGHTBOX_EXISTS
);
if (lightboxAlreadyExists) {
window.showErrorMessage('lightbox attribute already exists on :::image::: tag.');
return;
}
window.showErrorMessage('invalid cursor position. You must be inside :::image::: tags.');
}
return;
}
export function imageKeyWordHasBeenTyped(editor: any) {
const RE_IMAGE = /image/g;
if (editor) {
const position = new Position(editor.selection.active.line, editor.selection.active.character);
const wordRange = editor.document.getWordRangeAtPosition(position, RE_IMAGE);
if (wordRange) {
return true;
}
}
}
export function imageCompletionProvider() {
const completionItems: CompletionItem[] = [];
completionItems.push(
new CompletionItem(`:::image type="content" source="" alt-text="" loc-scope="":::`)
);
completionItems.push(
new CompletionItem(`:::image type="icon" source="" alt-text="" loc-scope="":::`)
);
completionItems.push(
new CompletionItem(`:::image type="complex" source="" alt-text="" loc-scope="":::`)
);
return completionItems;
}
export async function applyLink() {
// get editor, its needed to apply the output to editor window.
const editor = window.activeTextEditor;
if (!editor) {
noActiveEditorMessage();
return;
}
// if user has not selected any text, then continue
const RE_LINK = /:::image\s+((source|type|alt-text|lightbox|border|loc-scope)="(.*?)"\s*)+:::/gm;
const position = new Position(editor.selection.active.line, editor.selection.active.character);
// get the current editor position and check if user is inside :::image::: tags
const wordRange = editor.document.getWordRangeAtPosition(position, RE_LINK);
if (wordRange) {
const options: InputBoxOptions = {
placeHolder: 'Enter link (URL or relative path)'
};
const imageLink = await window.showInputBox(options);
if (imageLink === undefined) {
postWarning('No link provided, abandoning command.');
} else {
await editor.edit(selected => {
selected.insert(
new Position(wordRange.end.line, wordRange.end.character - 3),
` link="${imageLink}"`
);
});
}
} else {
const RE_LINK_EXISTS = /:::image\s+((source|type|alt-text|lightbox|border|loc-scope|link)="(.*?)"\s*)+:::/gm;
const linkAlreadyExists = editor.document.getWordRangeAtPosition(position, RE_LINK_EXISTS);
if (linkAlreadyExists) {
window.showErrorMessage('link attribute already exists on :::image::: tag.');
return;
}
window.showErrorMessage('invalid cursor position. You must be inside :::image::: tags.');
}
return;
} | the_stack |
import {normalizeURL, parseQuery, stringifyQuery, URLOptions} from '@layr/navigator';
import {possiblyAsync} from 'possibly-async';
import isEmpty from 'lodash/isEmpty';
import {parsePattern, Pattern, PathMatcher, PathGenerator} from './pattern';
import {
serializeParam,
deserializeParam,
parseParamTypeSpecifier,
Params,
ParamTypeDescriptor
} from './param';
export type AddressableOptions = {
params?: Params;
aliases?: Pattern[];
filter?: Filter;
transformers?: Transformers;
};
export type Filter = (request: any) => boolean;
export type Transformers = {
input?: (params?: any, request?: any) => any;
output?: (result?: any, request?: any) => any;
error?: (error?: any, request?: any) => any;
};
/**
* Represents a route or a wrapper in a [routable component](https://layrjs.com/docs/v2/reference/routable#routable-component-class).
*
* An addressable is composed of:
*
* - A name matching a method of the [routable component](https://layrjs.com/docs/v2/reference/routable#routable-component-class) that contains the addressable.
* - The canonical [URL pattern](https://layrjs.com/docs/v2/reference/addressable#url-pattern-type) of the addressable.
* - Some [URL pattern](https://layrjs.com/docs/v2/reference/addressable#url-pattern-type) aliases.
*
* #### Usage
*
* Typically, you create a `Route` (or a `Wrapper`) and associate it to a routable component by using the [`@route()`](https://layrjs.com/docs/v2/reference/routable#route-decorator) (or [`@wrapper()`](https://layrjs.com/docs/v2/reference/routable#wrapper-decorator)) decorator.
*
* See an example of use in the [`Routable()`](https://layrjs.com/docs/v2/reference/routable#usage) mixin.
*/
export abstract class Addressable {
_name: string;
_patterns: {
pattern: Pattern;
matcher: PathMatcher;
generator: PathGenerator;
wrapperGenerator: PathGenerator;
}[];
_isCatchAll: boolean;
_params: Record<string, ParamTypeDescriptor>;
_filter: Filter | undefined;
_transformers: Transformers;
/**
* Creates an instance of [`Addressable`](https://layrjs.com/docs/v2/reference/addressable). Typically, instead of using this constructor, you would rather use the [`@route()`](https://layrjs.com/docs/v2/reference/routable#route-decorator) (or [`@wrapper()`](https://layrjs.com/docs/v2/reference/routable#wrapper-decorator)) decorator.
*
* @param name The name of the addressable.
* @param pattern The canonical [URL pattern](https://layrjs.com/docs/v2/reference/addressable#url-pattern-type) of the addressable.
* @param [options.aliases] An array of alternate [URL patterns](https://layrjs.com/docs/v2/reference/addressable#url-pattern-type).
*
* @returns The [`Addressable`](https://layrjs.com/docs/v2/reference/addressable) instance that was created.
*
* @example
* ```
* const addressable = new Addressable('Home', '/', {aliases: ['/home']});
* ```
*
* @category Creation
*/
constructor(name: string, pattern: Pattern, options: AddressableOptions = {}) {
const {params = {}, aliases = [], filter, transformers = {}} = options;
this._name = name;
this._params = Object.create(null);
for (const [name, typeSpecifier] of Object.entries(params)) {
this._params[name] = {
...parseParamTypeSpecifier(typeSpecifier),
specifier: typeSpecifier
};
}
this._patterns = [];
this._isCatchAll = false;
for (const patternOrAlias of [pattern, ...aliases]) {
const {matcher, generator, wrapperGenerator, isCatchAll} = parsePattern(patternOrAlias);
this._patterns.push({pattern: patternOrAlias, matcher, generator, wrapperGenerator});
if (isCatchAll) {
this._isCatchAll = true;
}
}
if (this._isCatchAll && this._patterns.length > 1) {
throw new Error(
`Couldn't create the addressable '${name}' (a catch-all addressable cannot have aliases)`
);
}
this._filter = filter;
this._transformers = transformers;
}
/**
* Returns the name of the addressable.
*
* @returns A string.
*
* @example
* ```
* const addressable = new Addressable('Home', '/');
*
* addressable.getName(); // => 'Home'
* ```
*
* @category Basic Methods
*/
getName() {
return this._name;
}
/**
* Returns the canonical URL pattern of the addressable.
*
* @returns An [URL pattern](https://layrjs.com/docs/v2/reference/addressable#url-pattern-type) string.
*
* @example
* ```
* const addressable = new Addressable('Viewer', '/movies/:slug\\?:showDetails');
*
* addressable.getPattern(); // => '/movies/:slug\\?:showDetails'
* ```
*
* @category Basic Methods
*/
getPattern() {
return this._patterns[0].pattern;
}
isCatchAll() {
return this._isCatchAll;
}
getParams() {
const params: Params = {};
for (const [name, descriptor] of Object.entries(this._params)) {
params[name] = descriptor.specifier;
}
return params;
}
/**
* Returns the alternate URL patterns of the addressable.
*
* @returns An array of [URL pattern](https://layrjs.com/docs/v2/reference/addressable#url-pattern-type) strings.
*
* @example
* ```
* const addressable = new Addressable('Home', '/', {aliases: ['/home']});
*
* addressable.getAliases(); // => ['/home']
* ```
*
* @category Basic Methods
*/
getAliases() {
return this._patterns.slice(1).map(({pattern}) => pattern);
}
getFilter() {
return this._filter;
}
getTransformers() {
return this._transformers;
}
transformMethod(method: Function, request: any) {
const transformers = this._transformers;
if (isEmpty(transformers)) {
// OPTIMIZATION
return method;
}
return function (this: any, params: any) {
if (transformers.input !== undefined) {
params = transformers.input.call(this, params, request);
}
return possiblyAsync.invoke(
() => method.call(this, params),
(result) => {
if (transformers.output !== undefined) {
result = transformers.output.call(this, result, request);
}
return result;
},
(error) => {
if (transformers.error !== undefined) {
return transformers.error.call(this, error, request);
}
throw error;
}
);
};
}
/**
* Checks if the addressable matches the specified URL.
*
* @param url A string or a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object.
*
* @returns If the addressable matches the specified URL, a plain object representing the parameters that are included in the URL (or an empty object if there is no parameters) is returned. Otherwise, `undefined` is returned.
*
* @example
* ```
* const addressable = new Addressable('Viewer', '/movies/:slug\\?:showDetails');
*
* addressable.matchURL('/movies/abc123'); // => {slug: 'abc123'}
*
* addressable.matchURL('/movies/abc123?showDetails=1'); // => {slug: 'abc123', showDetails: '1'}
*
* addressable.matchURL('/films'); // => undefined
* ```
*
* @category URL Matching and Generation
*/
matchURL(url: URL | string, request?: any) {
const {pathname: path, search: queryString} = normalizeURL(url);
const result = this.matchPath(path, request);
if (result !== undefined) {
const query: Record<string, string> = parseQuery(queryString);
const params: Record<string, any> = {};
for (const [name, descriptor] of Object.entries(this._params)) {
const queryValue = query[name];
const paramValue = deserializeParam(name, queryValue, descriptor);
params[name] = paramValue;
}
return {params, ...result};
}
return undefined;
}
matchPath(path: string, request?: any) {
for (const {matcher, wrapperGenerator} of this._patterns) {
const identifiers = matcher(path);
if (identifiers === undefined) {
continue;
}
if (this._filter !== undefined && !this._filter(request)) {
continue;
}
const wrapperPath = wrapperGenerator(identifiers);
return {identifiers, wrapperPath};
}
return undefined;
}
/**
* Generates an URL for the addressable.
*
* @param [params] An optional object representing the parameters to include in the generated URL.
* @param [options.hash] A string representing an hash (i.e., a [fragment identifier](https://en.wikipedia.org/wiki/URI_fragment)) to include in the generated URL.
*
* @returns A string.
*
* @example
* ```
* const addressable = new Addressable('Viewer', '/movies/:slug\\?:showDetails');
*
* addressable.generateURL({slug: 'abc123'}); // => '/movies/abc123'
*
* addressable.generateURL({slug: 'abc123', showDetails: '1'}); // => '/movies/abc123?showDetails=1'
*
* addressable.generateURL({}); // => Error (the slug parameter is mandatory)
* ```
*
* @category URL Matching and Generation
*/
generateURL(
identifiers?: Record<string, any>,
params?: Record<string, any>,
options?: URLOptions
) {
let url = this.generatePath(identifiers);
const queryString = this.generateQueryString(params);
if (queryString !== '') {
url += `?${queryString}`;
}
if (options?.hash) {
url += `#${options.hash}`;
}
return url;
}
generatePath(identifiers?: Record<string, any>) {
return this._patterns[0].generator(identifiers);
}
generateQueryString(params: Record<string, any> = {}) {
const query: Record<string, string | undefined> = {};
for (const [name, descriptor] of Object.entries(this._params)) {
const paramValue = params[name];
const queryValue = serializeParam(name, paramValue, descriptor);
query[name] = queryValue;
}
return stringifyQuery(query);
}
/**
* @typedef URLPattern
*
* A string representing the canonical URL pattern (or an alternate URL pattern) of an addressable.
*
* An URL pattern is composed of a *path pattern* and an optional *query pattern* that are separated by an escaped question mark (`\\?`).
*
* A *path pattern* represents the path part of an URL and it can include some parameters by prefixing the name of each parameter with a colon sign (`:`). The [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) package is used under the hood to handle the path patterns, so any path pattern that is supported by `path-to-regexp` is supported by Layr as well.
*
* A *query pattern* represents the query part of an URL and it is composed of a list of parameters separated by an ampersand sign (`&`). Just like a path parameter, a query parameter is represented by a name prefixed with a colon sign (`:`). When an URL is matched against an URL pattern with the [`matchURL()`](https://layrjs.com/docs/v2/reference/addressable#match-url-instance-method) method, the [`qs`](https://github.com/ljharb/qs) package is used under the hood to parse the query part of the URL.
*
* **Examples:**
*
* - `'/'`: Root URL pattern.
* - `'/movies'`: URL pattern without parameters.
* - `'/movies/:id'`: URL pattern with one path parameter (`id`).
* - `'/movies/:movieId/actors/:actorId'`: URL pattern with two path parameter (`movieId` and `actorId`).
* - `'/movies\\?:sortBy'`: URL pattern with one query parameter (`sortBy`).
* - `'/movies\\?:sortBy&:offset'`: URL pattern with two query parameters (`sortBy` and `offset`).
* - `'/movies/:id\\?:showDetails'`: URL pattern with one path parameter (`id`) and one query parameter (`showDetails`).
* - `'/movies/:genre?'`: URL pattern with an [optional](https://github.com/pillarjs/path-to-regexp#optional) path parameter (`genre`).
* - `'/:slugs*'`: URL pattern with [zero or more](https://github.com/pillarjs/path-to-regexp#zero-or-more) path parameters (`slugs`).
* - `'/:slugs+'`: URL pattern with [one or more](https://github.com/pillarjs/path-to-regexp#one-or-more) path parameters (`slugs`).
* - `'/movies/:id(\\d+)'`: URL pattern with one path parameter (`id`) restricted to digits.
*
* @category Types
*/
static isAddressable(value: any): value is Addressable {
return isAddressableInstance(value);
}
}
/**
* Returns whether the specified value is an [`Addressable`](https://layrjs.com/docs/v2/reference/addressable) class.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isAddressableClass(value: any): value is typeof Addressable {
return typeof value?.isAddressable === 'function';
}
/**
* Returns whether the specified value is an [`Addressable`](https://layrjs.com/docs/v2/reference/addressable) instance.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isAddressableInstance(value: any): value is Addressable {
return typeof value?.constructor?.isAddressable === 'function';
} | the_stack |
import { RpcCoder } from '@polkadot/rpc-provider/coder';
import defaults from '@polkadot/rpc-provider/defaults';
import { LRUCache } from '@polkadot/rpc-provider/lru';
import type {
JsonRpcResponse,
ProviderInterface,
ProviderInterfaceCallback,
ProviderInterfaceEmitCb,
ProviderInterfaceEmitted
} from '@polkadot/rpc-provider/types';
import { getWSErrorString } from '@polkadot/rpc-provider/ws/errors';
import {
assert,
isChildClass,
isNull,
isNumber,
isString,
isUndefined,
objectSpread
} from '@polkadot/util';
import { xglobal } from '@polkadot/x-global';
import { WebSocket } from '@polkadot/x-ws';
import chalk from 'chalk';
import EventEmitter from 'eventemitter3';
import log from '../logger';
interface SubscriptionHandler {
callback: ProviderInterfaceCallback;
type: string;
}
interface WsStateAwaiting {
callback: ProviderInterfaceCallback;
method: string;
params: unknown[];
subscription?: SubscriptionHandler;
}
interface WsStateSubscription extends SubscriptionHandler {
method: string;
params: unknown[];
}
const ALIASES: { [index: string]: string } = {
chain_finalisedHead: 'chain_finalizedHead',
chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
};
const RETRY_DELAY = 2500;
const MEGABYTE = 1024 * 1024;
function eraseRecord<T>(
record: Record<string, T>,
cb?: (item: T) => void
): void {
Object.keys(record).forEach((key): void => {
if (cb) {
cb(record[key]);
}
delete record[key];
});
}
function shortParams(result: any, len: number) {
try {
const str =
isString(result) || isNumber(result)
? result.toString()
: JSON.stringify(result);
if (str.length > len + 3) {
return `${str.substr(0, len)}...`;
}
return str;
} catch {
return '...';
}
}
/**
* _ @polkadot/rpc-provider/ws
*
* @name WsProvider
*
* @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes.
*
* @example
* <BR>
*
* ```javascript
* import Api from '@polkadot/api/promise';
* import { WsProvider } from '@polkadot/rpc-provider/ws';
*
* const provider = new WsProvider('ws://127.0.0.1:9944');
* const api = new Api(provider);
* ```
*
* @see [[HttpProvider]]
*/
export class WsProvider implements ProviderInterface {
readonly _callCache = new LRUCache();
readonly _coder: RpcCoder;
readonly _endpoints: string[];
readonly _headers: Record<string, string>;
readonly _eventemitter: EventEmitter;
readonly _handlers: Record<string, WsStateAwaiting> = {};
readonly _isReadyPromise: Promise<WsProvider>;
readonly _waitingForId: Record<string, JsonRpcResponse> = {};
_autoConnectMs: number;
_endpointIndex: number;
_isConnected = false;
_subscriptions: Record<string, WsStateSubscription> = {};
_websocket: WebSocket | null;
/**
* @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
* @param {boolean} autoConnect Whether to connect automatically or not.
*/
constructor(
endpoint: string | string[] = defaults.WS_URL,
// autoConnectMs: number | false = RETRY_DELAY,
headers: Record<string, string> = {}
) {
const endpoints = Array.isArray(endpoint) ? endpoint : [endpoint];
assert(endpoints.length !== 0, 'WsProvider requires at least one Endpoint');
endpoints.forEach((endpoint) => {
assert(
/^(wss|ws):\/\//.test(endpoint),
() => `Endpoint should start with 'ws://', received '${endpoint}'`
);
});
this._eventemitter = new EventEmitter();
// this._autoConnectMs = autoConnectMs || 0;
this._coder = new RpcCoder();
this._endpointIndex = -1;
this._endpoints = endpoints;
this._headers = headers;
this._websocket = null;
// if (autoConnectMs > 0) {
// this.connectWithRetry().catch((): void => {
// // does not throw
// });
// }
this._isReadyPromise = new Promise((resolve): void => {
this._eventemitter.once('connected', (): void => {
resolve(this);
});
});
}
/**
* @summary `true` when this provider supports subscriptions
*/
public get hasSubscriptions(): boolean {
return true;
}
/**
* @summary Whether the node is connected or not.
* @return {boolean} true if connected
*/
public get isConnected(): boolean {
return this._isConnected;
}
/**
* @description Promise that resolves the first time we are connected and loaded
*/
public get isReady(): Promise<WsProvider> {
return this._isReadyPromise;
}
/**
* @description Returns a clone of the object
*/
public clone(): WsProvider {
return new WsProvider(this._endpoints);
}
/**
* @summary Manually connect
* @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may
* connect manually using this method.
*/
// eslint-disable-next-line @typescript-eslint/require-await
public async connect(): Promise<void> {
try {
this._endpointIndex = (this._endpointIndex + 1) % this._endpoints.length;
this._websocket =
typeof xglobal.WebSocket !== 'undefined' &&
isChildClass(xglobal.WebSocket, WebSocket)
? new WebSocket(this._endpoints[this._endpointIndex])
: // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - WS may be an instance of w3cwebsocket, which supports headers
new WebSocket(
this._endpoints[this._endpointIndex],
undefined,
// @ts-ignore - WS may be an instance of w3cwebsocket, which supports headers
undefined,
this._headers,
undefined,
{
// default: true
fragmentOutgoingMessages: true,
// default: 16K (bump, the Node has issues with too many fragments, e.g. on setCode)
fragmentationThreshold: 1 * MEGABYTE,
// default: 1MiB (also align with maxReceivedMessageSize)
maxReceivedFrameSize: 24 * MEGABYTE,
// default: 8MB (however Polkadot api.query.staking.erasStakers.entries(356) is over that, 16M is ok there)
maxReceivedMessageSize: 24 * MEGABYTE
}
);
this._websocket.onclose = this._onSocketClose;
this._websocket.onerror = this._onSocketError;
this._websocket.onmessage = this._onSocketMessage;
this._websocket.onopen = this._onSocketOpen;
return new Promise((resolve, reject) => {
let isConnected = false;
const eventemitter = this._eventemitter;
function removeAll(event?) {
eventemitter.removeListener('connected', onConnect);
eventemitter.removeListener('disconnected', onClose);
eventemitter.removeListener('error', onClose);
if (isConnected) {
resolve();
} else {
reject(event);
}
}
function onConnect() {
isConnected = true;
removeAll();
}
function onClose(event) {
isConnected = false;
removeAll(event);
}
this._eventemitter.once('connected', onConnect);
this._eventemitter.once('disconnected', onClose);
this._eventemitter.once('error', onClose);
});
} catch (error) {
log.error(chalk.red(error));
this._emit('error', error);
throw error;
}
}
/**
* @description Connect, never throwing an error, but rather forcing a retry
*/
public async connectWithRetry(): Promise<void> {
// if (this._autoConnectMs > 0) {
try {
await this.connect();
} catch (error) {
setTimeout((): void => {
this.connectWithRetry().catch((): void => {
// does not throw
});
}, this._autoConnectMs || RETRY_DELAY);
}
// }
}
/**
* @description Manually disconnect from the connection, clearing auto-connect logic
*/
// eslint-disable-next-line @typescript-eslint/require-await
public async disconnect(): Promise<void> {
// switch off autoConnect, we are in manual mode now
this._autoConnectMs = 0;
try {
if (this._websocket) {
// 1000 - Normal closure; the connection successfully completed
this._websocket.close(1000);
}
} catch (error) {
log.error(chalk.red(error));
this._emit('error', error);
throw error;
}
}
/**
* @summary Listens on events after having subscribed using the [[subscribe]] function.
* @param {ProviderInterfaceEmitted} type Event
* @param {ProviderInterfaceEmitCb} sub Callback
* @return unsubscribe function
*/
public on(
type: ProviderInterfaceEmitted,
sub: ProviderInterfaceEmitCb
): () => void {
this._eventemitter.on(type, sub);
return (): void => {
this._eventemitter.removeListener(type, sub);
};
}
/**
* @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue.
* @param method The RPC methods to execute
* @param params Encoded parameters as applicable for the method
* @param subscription Subscription details (internally used)
*/
public send<T = any>(
method: string,
params: unknown[],
isCacheable?: boolean,
subscription?: SubscriptionHandler
): Promise<T> {
const body = this._coder.encodeJson(method, params);
let resultPromise: Promise<T> | null = isCacheable
? (this._callCache.get(body) as Promise<T>)
: null;
if (!resultPromise) {
resultPromise = this._send(body, method, params, subscription);
if (isCacheable) {
this._callCache.set(body, resultPromise);
}
}
return resultPromise;
}
async _send<T>(
json: string,
method: string,
params: unknown[],
subscription?: SubscriptionHandler
): Promise<T> {
return new Promise<T>((resolve, reject): void => {
try {
assert(
this.isConnected && !isNull(this._websocket),
'WebSocket is not connected'
);
const id = this._coder.getId();
const callback = (error?: Error | null, result?: T): void => {
error ? reject(error) : resolve(result as T);
};
log.debug(
`${chalk.green(`⬆`)} Id: ${chalk.bold(
`%d`
)}, method: ${method}, params: ${shortParams(params, 1000)}`,
id
);
this._handlers[id] = {
callback,
method,
params,
subscription
};
this._websocket.send(json);
} catch (error) {
reject(error);
}
});
}
/**
* @name subscribe
* @summary Allows subscribing to a specific event.
*
* @example
* <BR>
*
* ```javascript
* const provider = new WsProvider('ws://127.0.0.1:9944');
* const rpc = new Rpc(provider);
*
* rpc.state.subscribeStorage([[storage.system.account, <Address>]], (_, values) => {
* console.log(values)
* }).then((subscriptionId) => {
* console.log('balance changes subscription id: ', subscriptionId)
* })
* ```
*/
public subscribe(
type: string,
method: string,
params: unknown[],
callback: ProviderInterfaceCallback
): Promise<number | string> {
return this.send<number | string>(method, params, false, {
callback,
type
});
}
/**
* @summary Allows unsubscribing to subscriptions made with [[subscribe]].
*/
public async unsubscribe(
type: string,
method: string,
id: number | string
): Promise<boolean> {
const subscription = `${type}::${id}`;
// FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
// the assigned id now does not match what the API user originally received. It has
// a slight complication in solving - since we cannot rely on the send id, but rather
// need to find the actual subscription id to map it
if (isUndefined(this._subscriptions[subscription])) {
log.warn(`Unable to find active subscription=${subscription}`);
return false;
}
delete this._subscriptions[subscription];
try {
return this.isConnected && !isNull(this._websocket)
? this.send<boolean>(method, [id])
: true;
} catch (error) {
return false;
}
}
_emit = (type: ProviderInterfaceEmitted, ...args: unknown[]): void => {
this._eventemitter.emit(type, ...args);
};
_onSocketClose = (event: CloseEvent): void => {
const error = new Error(
`disconnected from ${this._endpoints[this._endpointIndex]}: ${
event.code
}:: ${event.reason || getWSErrorString(event.code)}`
);
if (this._autoConnectMs > 0) {
log.error(chalk.red(error.message));
}
this._isConnected = false;
if (this._websocket) {
this._websocket.onclose = null;
this._websocket.onerror = null;
this._websocket.onmessage = null;
this._websocket.onopen = null;
this._websocket = null;
}
this._emit('disconnected');
// reject all hanging requests
eraseRecord(this._handlers, (h) => h.callback(error, undefined));
eraseRecord(this._waitingForId);
if (this._autoConnectMs > 0) {
setTimeout((): void => {
this.connectWithRetry().catch(() => {
// does not throw
});
}, this._autoConnectMs);
}
};
_onSocketError = (error: Event): void => {
log.warn(`Socket event: ${error.type}`);
this._emit('error', error);
};
_onSocketMessage = (message: MessageEvent<string>): void => {
const response = JSON.parse(message.data as string) as JsonRpcResponse;
const isMsg = isUndefined(response.method);
if (isMsg) {
log.debug(
`${chalk.red('⬇')} Id: ${chalk.bold(`%d`)}, result: ${shortParams(
response.result,
60
)}`,
response.id
);
return this._onSocketMessageResult(response);
} else {
log.debug(
`${chalk.red('⬇')} SubId: ${chalk.bold(
response.params.subscription.toString()
)}, result: ${shortParams(response.params.result, 60)}`
);
this._onSocketMessageSubscribe(response);
}
};
_onSocketMessageResult = (response: JsonRpcResponse): void => {
const handler = this._handlers[response.id];
if (!handler) {
return;
}
try {
const { method, params, subscription } = handler;
const result = this._coder.decodeResponse(response) as string;
// first send the result - in case of subs, we may have an update
// immediately if we have some queued results already
handler.callback(null, result);
if (subscription) {
const subId = `${subscription.type}::${result}`;
this._subscriptions[subId] = objectSpread({}, subscription, {
method,
params
});
// if we have a result waiting for this subscription already
if (this._waitingForId[subId]) {
this._onSocketMessageSubscribe(this._waitingForId[subId]);
}
}
} catch (error) {
handler.callback(error as Error, undefined);
}
delete this._handlers[response.id];
};
_onSocketMessageSubscribe = (response: JsonRpcResponse): void => {
const method =
ALIASES[response.method as string] || response.method || 'invalid';
const subId = `${method}::${response.params.subscription}`;
const handler = this._subscriptions[subId];
if (!handler) {
// store the JSON, we could have out-of-order subid coming in
this._waitingForId[subId] = response;
log.warn(`Unable to find handler for subscription=${subId}`);
return;
}
// housekeeping
delete this._waitingForId[subId];
try {
const result = this._coder.decodeResponse(response);
handler.callback(null, result);
} catch (error) {
handler.callback(error as Error, undefined);
}
};
_onSocketOpen = (): boolean => {
assert(!isNull(this._websocket), 'WebSocket cannot be null in onOpen');
log.info('Connected to', this._endpoints[this._endpointIndex]);
this._isConnected = true;
this._emit('connected');
this._resubscribe();
return true;
};
_resubscribe = (): void => {
const subscriptions = this._subscriptions;
this._subscriptions = {};
Promise.all(
Object.keys(subscriptions).map(
async (id): Promise<void> => {
const { callback, method, params, type } = subscriptions[id];
// only re-create subscriptions which are not in author (only area where
// transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic'
// are not included (and will not be re-broadcast)
if (type.startsWith('author_')) {
return;
}
try {
await this.subscribe(type, method, params, callback);
} catch (error) {
log.error(error);
}
}
)
).catch(log.error);
};
} | the_stack |
import React from 'react';
import ReactDOM from 'react-dom';
import { Autowired, Injectable, Injector, INJECTOR_TOKEN } from '@opensumi/di';
import {
AppConfig,
compareAnything,
ConfigProvider,
IContextKey,
IContextKeyService,
KeybindingRegistry,
QuickOpenActionProvider,
QuickOpenTabOptions,
} from '@opensumi/ide-core-browser';
import { VALIDATE_TYPE } from '@opensumi/ide-core-browser/lib/components';
import {
HideReason,
Highlight,
QuickOpenItem,
QuickOpenModel as IKaitianQuickOpenModel,
QuickOpenOptions,
QuickOpenService,
} from '@opensumi/ide-core-browser/lib/quick-open';
import { MonacoContextKeyService } from '@opensumi/ide-monaco/lib/browser/monaco.context-key.service';
import { matchesFuzzy } from '@opensumi/monaco-editor-core/esm/vs/base/common/filters';
import { IAutoFocus, IQuickOpenModel, QuickOpenContext } from './quick-open.type';
import { QuickOpenView } from './quick-open.view';
import { QuickOpenWidget } from './quick-open.widget';
export interface IKaitianQuickOpenControllerOpts extends QuickOpenTabOptions {
inputAriaLabel: string;
getAutoFocus(searchValue: string): IAutoFocus;
valueSelection?: [number, number];
enabled?: boolean;
readonly prefix?: string;
readonly password?: boolean;
ignoreFocusOut?: boolean;
canSelectMany?: boolean;
onType?(lookFor: string, acceptor: (model: IQuickOpenModel) => void): void;
onClose?(canceled: boolean): void;
onSelect?(item: QuickOpenItem, index: number): void;
onConfirm?(items: QuickOpenItem[]): void;
onChangeValue?(lookFor: string): void;
keepScrollPosition?: boolean | undefined;
}
@Injectable()
export class MonacoQuickOpenService implements QuickOpenService {
protected _widget: QuickOpenWidget | undefined;
protected opts: IKaitianQuickOpenControllerOpts;
protected container: HTMLElement;
protected previousActiveElement: Element | undefined;
@Autowired(KeybindingRegistry)
protected keybindingRegistry: KeybindingRegistry;
@Autowired(MonacoContextKeyService)
protected readonly monacoContextKeyService: MonacoContextKeyService;
@Autowired(IContextKeyService)
protected readonly contextKeyService: IContextKeyService;
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(AppConfig)
private readonly appConfig: AppConfig;
private preLookFor = '';
get inQuickOpenContextKey(): IContextKey<boolean> {
return this.contextKeyService.createKey<boolean>('inQuickOpen', false);
}
private appendQuickOpenContainer() {
const overlayContainer = document.querySelector('#ide-overlay');
if (!overlayContainer) {
throw new Error('ide-overlay is requried');
}
const overlayWidgets = document.createElement('div');
overlayWidgets.classList.add('quick-open-overlay');
overlayContainer.appendChild(overlayWidgets);
const container = (this.container = document.createElement('quick-open-container'));
container.style.position = 'fixed';
container.style.top = '0px';
container.style.right = '50%';
container.style.zIndex = '1000000';
overlayWidgets.appendChild(container);
}
open(model: IKaitianQuickOpenModel, options?: Partial<QuickOpenOptions.Resolved> | undefined): void {
const opts = new KaitianQuickOpenControllerOpts(model, this.keybindingRegistry, options);
this.hideDecoration();
this.internalOpen(opts);
}
hide(reason?: HideReason): void {
this.widget.hide(reason);
}
protected internalOpen(opts: IKaitianQuickOpenControllerOpts): void {
this.opts = opts;
const widget = this.widget;
widget.show(this.opts.prefix || '', {
placeholder: opts.inputAriaLabel,
password: opts.password,
inputEnable: opts.enabled ?? true,
valueSelection: opts.valueSelection,
canSelectMany: opts.canSelectMany,
keepScrollPosition: opts.keepScrollPosition,
renderTab: opts.renderTab,
toggleTab: opts.toggleTab,
});
this.inQuickOpenContextKey.set(true);
}
refresh(): void {
this.onType(this.widget.inputValue);
}
public get widget(): QuickOpenWidget {
if (this._widget) {
return this._widget;
}
this.appendQuickOpenContainer();
this._widget = this.injector.get(QuickOpenWidget, [
{
onOk: () => {
this.previousActiveElement = undefined;
this.onClose(false);
},
onCancel: () => {
if (this.previousActiveElement instanceof HTMLElement) {
this.previousActiveElement.focus();
}
this.previousActiveElement = undefined;
this.onClose(true);
},
onType: (lookFor) => this.onType(lookFor || ''),
onFocusLost: () => {
if (this.opts && this.opts.ignoreFocusOut !== undefined) {
if (this.opts.ignoreFocusOut === false) {
this.onClose(true);
}
return this.opts.ignoreFocusOut;
} else {
return false;
}
},
onHide: () => {
this.inQuickOpenContextKey.set(false);
},
onSelect: (item: QuickOpenItem, index: number) => {
if (this.opts.onSelect) {
this.opts.onSelect(item, index);
}
},
onConfirm: (items: QuickOpenItem[]) => {
if (this.opts.onConfirm) {
this.opts.onConfirm(items);
}
},
},
]);
this.initWidgetView(this._widget);
return this._widget;
}
private initWidgetView(widget: QuickOpenWidget) {
// 因为 quickopen widget 需要通过构造函数初始化,无法通过 useInjectable 获取实例
// 但其实是一个单例对象,使用 React Context 让其子组件获取到 widget 实例
ReactDOM.render(
<ConfigProvider value={this.appConfig}>
<QuickOpenContext.Provider value={{ widget }}>
<QuickOpenView />
</QuickOpenContext.Provider>
</ConfigProvider>,
this.container,
);
}
protected onClose(cancelled: boolean): void {
this.opts.onClose?.(cancelled);
}
protected async onType(lookFor: string): Promise<void> {
const options = this.opts;
if (this.widget && options.onType) {
options.onType(lookFor, (model) => {
// 触发 onchange 事件
if (this.preLookFor !== lookFor && this.opts.onChangeValue) {
this.opts.onChangeValue(lookFor);
}
this.preLookFor = lookFor;
return this.widget.setInput(model, options.getAutoFocus(lookFor), options.inputAriaLabel);
});
}
}
protected onFocusLost(): boolean {
return !!this.opts.ignoreFocusOut;
}
showDecoration(type: VALIDATE_TYPE): void {
this.widget.validateType = type;
}
hideDecoration(): void {
this.widget.validateType = undefined;
}
}
export class KaitianQuickOpenControllerOpts implements IKaitianQuickOpenControllerOpts {
protected readonly options: QuickOpenOptions.Resolved;
constructor(
protected readonly model: IKaitianQuickOpenModel,
protected keybindingRegistry: KeybindingRegistry,
options?: QuickOpenOptions,
) {
this.model = model;
this.options = QuickOpenOptions.resolve(options);
}
get prefix(): string {
return this.options.prefix;
}
get inputAriaLabel(): string {
return this.options.placeholder || '';
}
get ignoreFocusOut(): boolean {
return this.options.ignoreFocusOut;
}
get password(): boolean {
return this.options.password;
}
get enabled(): boolean {
return this.options.enabled;
}
get valueSelection(): [number, number] | undefined {
return this.options.valueSelection;
}
get keepScrollPosition(): boolean | undefined {
return this.options.keepScrollPosition;
}
get renderTab() {
return this.options.renderTab;
}
get toggleTab() {
return this.options.toggleTab;
}
get canSelectMany() {
return this.options.canPickMany;
}
onClose(cancelled: boolean): void {
this.options.onClose(cancelled);
}
onSelect(item: QuickOpenItem, index: number) {
this.options.onSelect(item, index);
}
onConfirm(items: QuickOpenItem[]) {
this.options.onConfirm(items);
}
onType(lookFor: string, acceptor: (model: IQuickOpenModel) => void): void {
this.model.onType(lookFor, (items, actionProvider) => {
const result = this.toOpenModel(lookFor, items, actionProvider);
acceptor(result);
});
}
/**
* A good default sort implementation for quick open entries respecting highlight information
* as well as associated resources.
*/
private compareEntries(elementA: QuickOpenItem, elementB: QuickOpenItem, lookFor: string): number {
// Give matches with label highlights higher priority over
// those with only description highlights
const labelHighlightsA = elementA.getHighlights()[0] || [];
const labelHighlightsB = elementB.getHighlights()[0] || [];
if (labelHighlightsA.length && !labelHighlightsB.length) {
return -1;
}
if (!labelHighlightsA.length && labelHighlightsB.length) {
return 1;
}
const nameA = elementA.getLabel()!;
const nameB = elementB.getLabel()!;
return compareAnything(nameA, nameB, lookFor);
}
private toOpenModel(
lookFor: string,
items: QuickOpenItem[],
actionProvider?: QuickOpenActionProvider,
): IQuickOpenModel {
const originLookFor = lookFor;
if (this.options.skipPrefix) {
lookFor = lookFor.substr(this.options.skipPrefix);
}
if (actionProvider && actionProvider.getValidateInput) {
lookFor = actionProvider.getValidateInput(lookFor);
}
// 在此过滤 item
const entries: QuickOpenItem[] = items.filter((item) => !!this.fuzzyQuickOpenItem(item, lookFor));
if (this.options.fuzzySort) {
entries.sort((a, b) => this.compareEntries(a, b, lookFor));
}
const { getPlaceholderItem } = this.options;
if (!entries.length && getPlaceholderItem) {
entries.push(getPlaceholderItem(lookFor, originLookFor));
}
return {
items: entries,
actionProvider,
};
}
protected fuzzyQuickOpenItem(item: QuickOpenItem, lookFor: string): QuickOpenItem | undefined {
const { fuzzyMatchLabel, fuzzyMatchDescription, fuzzyMatchDetail } = this.options;
// 自动匹配若为空,取自定义的匹配
const labelHighlights = fuzzyMatchLabel
? this.matchesFuzzy(lookFor, item.getLabel(), fuzzyMatchLabel, item.getLabelHighlights.bind(item))
: item.getLabelHighlights();
const descriptionHighlights = this.options.fuzzyMatchDescription
? this.matchesFuzzy(lookFor, item.getDescription(), fuzzyMatchDescription)
: item.getDescriptionHighlights();
const detailHighlights = this.options.fuzzyMatchDetail
? this.matchesFuzzy(lookFor, item.getDetail(), fuzzyMatchDetail)
: item.getDetailHighlights();
if (
lookFor &&
!labelHighlights &&
!descriptionHighlights &&
(!detailHighlights || detailHighlights.length === 0) &&
!this.options.showItemsWithoutHighlight
) {
return undefined;
}
item.setHighlights(labelHighlights || [], descriptionHighlights, detailHighlights);
return item;
}
protected matchesFuzzy(
lookFor: string,
value: string | undefined,
options?: QuickOpenOptions.FuzzyMatchOptions | boolean,
fallback?: () => Highlight[] | undefined,
): Highlight[] | undefined {
if (!lookFor || !value) {
return [];
}
const enableSeparateSubstringMatching = typeof options === 'object' && options.enableSeparateSubstringMatching;
const res = matchesFuzzy(lookFor, value, enableSeparateSubstringMatching) || undefined;
if (res && res.length) {
return res;
}
const fallbackRes = fallback && fallback();
if (fallbackRes && fallbackRes.length) {
return fallbackRes;
}
return undefined;
}
getAutoFocus(lookFor: string): IAutoFocus {
if (this.options.selectIndex) {
const idx = this.options.selectIndex(lookFor);
if (idx >= 0) {
return {
autoFocusIndex: idx,
};
}
}
return {
autoFocusFirstEntry: true,
autoFocusPrefixMatch: lookFor,
};
}
} | the_stack |
import { ENV } from "../environment";
import * as util from "../util";
import { ArrayData } from "../util";
import { NDArrayMath } from "./math";
import { RandNormalDataTypes } from "./rand";
import { MPRandGauss } from "./rand";
export enum DType {
float32 = "float32",
int32 = "int32",
bool = "bool",
uint8 = "uint8",
}
export type IntDType = "int32" | "uint8";
/** @hidden */
export interface DataTypeMap {
float32: Float32Array;
int32: Int32Array;
bool: Uint8Array;
uint8: Uint8Array;
}
export type DataType = keyof DataTypeMap;
/** @hidden */
export interface RankMap<D extends DataType> {
0: Scalar<D>;
1: Array1D<D>;
2: Array2D<D>;
3: Array3D<D>;
4: Array4D<D>;
higher: NDArray<D, "higher">;
}
export type Rank = keyof RankMap<DataType>;
/** @hidden */
export interface NDArrayData<D extends DataType> {
dataId?: DataId;
values?: DataTypeMap[D];
}
export interface ShapeMap {
0: number[];
1: [number];
2: [number, number];
3: [number, number, number];
4: [number, number, number, number];
higher: number[];
}
export class DataId {}
export class NDArray<D extends DataType = DataType, R extends Rank = Rank> {
private static nextId = 0;
/** Unique id of this ndarray. */
id: number;
/**
* Id of the bucket holding the data for this ndarray. Multiple arrays can
* point to the same bucket (e.g. when calling array.reshape()).
*/
dataId: DataId;
/** The shape of the ndarray. */
shape: ShapeMap[R];
/** Number of elements in the ndarray. */
size: number;
/** The data type for the array. */
dtype: D;
/** The rank type for the array ('0','1','2','3','4','higher'). */
rankType: R;
/**
* Number of elements to skip in each dimension when indexing. See
* https://docs.scipy.org/doc/numpy/reference/generated
* /numpy.ndarray.strides.html
*/
strides: number[];
readonly math: NDArrayMath;
protected constructor(
shape: number[], dtype: D, values?: DataTypeMap[D], dataId?: DataId,
math?: NDArrayMath) {
this.math = math || ENV.math;
this.size = util.sizeFromShape(shape);
if (values != null) {
util.assert(
this.size === values.length,
`Constructing ndarray of shape (${this.size}) should match the ` +
`length of values (${values.length})`);
}
this.shape = shape;
this.dtype = dtype || ("float32" as D);
const dim = this.shape.length;
if (dim < 2) {
this.strides = [];
} else {
// Last dimension has implicit stride of 1, thus having D-1 (instead of D)
// strides.
this.strides = new Array(dim - 1);
this.strides[dim - 2] = this.shape[dim - 1];
for (let i = dim - 3; i >= 0; --i) {
this.strides[i] = this.strides[i + 1] * this.shape[i + 1];
}
}
this.dataId = dataId != null ? dataId : new DataId();
this.id = NDArray.nextId++;
this.rankType = (this.rank < 5 ? this.rank.toString() : "higher") as R;
this.math.register(this);
if (values != null) {
this.math.write(this.dataId, values);
}
}
/** Creates a ndarray of ones with the specified shape. */
static ones<D extends DataType = DataType, R extends Rank = Rank>(
shape: number[], dtype?: D): RankMap<D>[R] {
const values = makeOnesTypedArray(util.sizeFromShape(shape), dtype);
return NDArray.make(shape, {values}, dtype);
}
/** Creates a ndarray of zeros with the specified shape. */
static zeros<D extends DataType = DataType, R extends Rank = Rank>(
shape: number[], dtype?: D): RankMap<D>[R] {
const values = makeZerosTypedArray(util.sizeFromShape(shape), dtype);
return NDArray.make(shape, {values}, dtype);
}
/**
* Creates a ndarray of ones with the same shape as the specified ndarray.
*/
static onesLike<T extends NDArray>(another: T): T {
return NDArray.ones(another.shape, another.dtype) as T;
}
/**
* Creates a ndarray of zeros with the same shape as the specified ndarray.
*/
static zerosLike<T extends NDArray>(another: T): T {
return NDArray.zeros(another.shape, another.dtype) as T;
}
/** Creates a ndarray with the same values/shape as the specified ndarray. */
static like<T extends NDArray>(another: T): T {
const newValues = copyTypedArray(another.dataSync(), another.dtype);
return NDArray.make(
another.shape, {values: newValues}, another.dtype,
another.math) as T;
}
/**
* Makes a new ndarray with the provided shape and values. Values should be in
* a flat array.
*/
static make<D extends DataType = "float32", R extends Rank = Rank>(
shape: number[], data: NDArrayData<D>, dtype?: D,
math?: NDArrayMath): RankMap<D>[R] {
switch (shape.length) {
case 0:
return new Scalar(shape, dtype, data.values, data.dataId, math);
case 1:
return new Array1D(shape, dtype, data.values, data.dataId, math);
case 2:
return new Array2D(
shape as [number, number], dtype, data.values, data.dataId, math);
case 3:
return new Array3D(
shape as [number, number, number], dtype, data.values, data.dataId,
math);
case 4:
return new Array4D(
shape as [number, number, number, number], dtype, data.values,
data.dataId, math);
default:
return new NDArray(shape, dtype, data.values, data.dataId, math) as
RankMap<D>[R];
}
}
static fromPixels(
pixels: ImageData | HTMLImageElement | HTMLCanvasElement |
HTMLVideoElement,
numChannels = 3, math?: NDArrayMath): Array3D<"int32"> {
if (numChannels > 4) {
throw new Error(
"Cannot construct NDArray with more than 4 channels from pixels.");
}
const ndarrayData: NDArrayData<"int32"> = {};
const shape: [number, number, number] =
[pixels.height, pixels.width, numChannels];
math = math || ENV.math;
const res =
NDArray.make(shape, ndarrayData, "int32", math) as Array3D<"int32">;
math.writePixels(res.dataId, pixels, numChannels);
return res;
}
/** Reshapes the current ndarray into the provided shape. */
reshape<R2 extends Rank>(newShape: number[]): RankMap<D>[R2] {
this.throwIfDisposed();
return this.math.reshape(this, newShape);
}
asScalar(): Scalar<D> {
this.throwIfDisposed();
util.assert(this.size === 1, "The array must have only 1 element.");
return this.reshape<"0">([]);
}
as1D(): Array1D<D> {
this.throwIfDisposed();
return this.reshape<"1">([this.size]);
}
as2D(rows: number, columns: number): Array2D<D> {
this.throwIfDisposed();
return this.reshape<"2">([rows, columns]);
}
as3D(rows: number, columns: number, depth: number): Array3D<D> {
this.throwIfDisposed();
return this.reshape<"3">([rows, columns, depth]);
}
as4D(rows: number, columns: number, depth: number, depth2: number):
Array4D<D> {
this.throwIfDisposed();
return this.reshape<"4">([rows, columns, depth, depth2]);
}
asType<D2 extends DataType>(dtype: D2): NDArray<D2, R> {
this.throwIfDisposed();
return this.math.cast(this, dtype) as NDArray<D2, R>;
}
get rank(): number {
return this.shape.length;
}
get(...locs: number[]) {
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return this.dataSync()[index];
}
set(value: number, ...locs: number[]) {
this.throwIfDisposed();
util.assert(
locs.length === this.rank,
`The number of provided coordinates (${locs.length}) must ` +
`match the rank (${this.rank})`);
let index = locs.length > 0 ? locs[locs.length - 1] : 0;
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
const vals = this.dataSync();
vals[index] = value;
this.math.write(this.dataId, vals);
}
async val(...locs: number[]): Promise<number> {
this.throwIfDisposed();
await this.data();
return this.get(...locs);
}
locToIndex(locs: ShapeMap[R]): number {
this.throwIfDisposed();
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return index;
}
indexToLoc(index: number): ShapeMap[R] {
this.throwIfDisposed();
const locs: number[] = new Array(this.shape.length);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / this.strides[i]);
index -= locs[i] * this.strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
fill(value: number) {
this.throwIfDisposed();
const vals = this.dataSync();
vals.fill(value);
this.math.write(this.dataId, vals);
}
/**
* Asynchronously downloads the values from the NDArray. Returns a promise
* that resolves when the data is ready.
*/
async data(): Promise<DataTypeMap[D]> {
this.throwIfDisposed();
return this.math.read(this.dataId);
}
/**
* Synchronously downloads the values from the NDArray. This blocks the UI
* thread until the values are ready, which can cause performance issues.
*/
dataSync(): DataTypeMap[D] {
this.throwIfDisposed();
return this.math.readSync(this.dataId);
}
dispose(): void {
if (this.isDisposed) {
return;
}
this.isDisposed = true;
this.math.disposeData(this.dataId);
}
static rand<D extends DataType, R extends Rank>(
shape: number[], randFunction: () => number, dtype?: D): RankMap<D>[R] {
const size = util.sizeFromShape(shape);
let values = null;
if (dtype == null || dtype === "float32") {
values = new Float32Array(size);
} else if (dtype === "int32") {
values = new Int32Array(size);
} else if (dtype === "bool") {
values = new Uint8Array(size);
} else {
throw new Error(`Unknown data type ${dtype}`);
}
for (let i = 0; i < size; i++) {
values[i] = randFunction();
}
return NDArray.make(shape, {values}, dtype);
}
static randNormal<D extends keyof RandNormalDataTypes, R extends Rank>(
shape: number[], mean = 0, stdDev = 1, dtype?: D,
seed?: number): RankMap<D>[R] {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype);
}
static randTruncatedNormal<D extends keyof RandNormalDataTypes,
R extends Rank>(
shape: number[], mean = 0, stdDev = 1, dtype?: D,
seed?: number): RankMap<D>[R] {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype);
}
static randUniform<D extends DataType, R extends Rank>(
shape: number[], a: number, b: number, dtype?: D): RankMap<D>[R] {
return NDArray.rand(shape, () => util.randUniform(a, b), dtype);
}
private isDisposed = false;
private throwIfDisposed() {
if (this.isDisposed) {
throw new Error(`NDArray is disposed.`);
}
}
}
export class Scalar<D extends DataType = DataType> extends NDArray<D, "0"> {
static new<D extends DataType = "float32">(
value: number | boolean, dtype?: D): Scalar<D> {
const values = [value] as number[] | boolean[];
return new Scalar([], dtype, toTypedArray(values, dtype));
}
get(): number {
return this.dataSync()[0];
}
async val(): Promise<number> {
await this.data();
return this.get();
}
asType<D2 extends DataType>(dtype: D2): Scalar<D2> {
return super.asType(dtype);
}
locToIndex(loc: number[]): number {
return 0;
}
indexToLoc(index: number): number[] {
return [];
}
}
export class Array1D<D extends DataType = DataType> extends NDArray<D, "1"> {
static new<D extends DataType = "float32">(
values: DataTypeMap[D] | number[] | boolean[], dtype?: D): Array1D<D> {
if (!instanceofTypedArray(values)) {
const inferredShape = util.inferShape(values as number[] | boolean[]);
util.assert(
inferredShape.length === 1,
`Error constructing Array1D. Shape of values ${inferredShape} is ` +
`not 1 dimensional.`);
}
return new Array1D([values.length], dtype, toTypedArray(values, dtype));
}
get(i: number): number {
return this.dataSync()[i];
}
async val(i: number): Promise<number> {
await this.data();
return this.get(i);
}
locToIndex(loc: [number]): number {
return loc[0];
}
indexToLoc(index: number): [number] {
return [index];
}
asType<D2 extends DataType>(dtype: D2): Array1D<D2> {
return super.asType(dtype) as Array1D<D2>;
}
static ones<D extends DataType = DataType>(shape: [number], dtype?: D):
Array1D<D> {
return NDArray.ones<D, "1">(shape, dtype);
}
static zeros<D extends DataType = DataType>(shape: [number], dtype?: D):
Array1D<D> {
return NDArray.zeros<D, "1">(shape, dtype);
}
static randNormal<D extends keyof RandNormalDataTypes>(
shape: [number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array1D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array1D<D>;
}
static randTruncatedNormal<D extends keyof RandNormalDataTypes>(
shape: [number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array1D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array1D<D>;
}
static randUniform<D extends DataType>(
shape: [number], a: number, b: number, dtype?: D): Array1D<D> {
return NDArray.rand(shape, () => util.randUniform(a, b), dtype) as
Array1D<D>;
}
}
export class Array2D<D extends DataType = DataType> extends NDArray<D, "2"> {
constructor(
shape: [number, number], dtype: D, values?: DataTypeMap[D],
dataId?: DataId, math?: NDArrayMath) {
util.assert(shape.length === 2, "Shape should be of length 2");
super(shape, dtype, values, dataId, math);
}
static new<D extends DataType = "float32">(
shape: [number, number],
values: DataTypeMap[D] | number[] | number[][] | boolean[] | boolean[][],
dtype?: D): Array2D<D> {
if (!instanceofTypedArray(values)) {
const inferredShape = util.inferShape(values as number[] | boolean[]);
if (inferredShape.length > 1) {
util.assertShapesMatch(
shape, inferredShape,
`Error when constructing Array2D. Shape of values ` +
`${inferredShape} does not match the provided shape ` +
`${shape}. `);
}
}
return new Array2D(shape, dtype, toTypedArray(values, dtype));
}
get(i: number, j: number) {
return this.dataSync()[this.strides[0] * i + j];
}
async val(i: number, j: number): Promise<number> {
await this.data();
return this.get(i, j);
}
locToIndex(locs: [number, number]): number {
return this.strides[0] * locs[0] + locs[1];
}
indexToLoc(index: number): [number, number] {
return [Math.floor(index / this.strides[0]), index % this.strides[0]];
}
asType<D2 extends DataType>(dtype: D2): Array2D<D2> {
return super.asType(dtype) as Array2D<D2>;
}
static ones<D extends DataType = DataType>(
shape: [number, number], dtype?: D): Array2D<D> {
return NDArray.ones<D, "2">(shape, dtype);
}
static zeros<D extends DataType = DataType>(
shape: [number, number], dtype?: D): Array2D<D> {
return NDArray.zeros<D, "2">(shape, dtype);
}
static randNormal<D extends keyof RandNormalDataTypes>(
shape: [number, number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array2D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array2D<D>;
}
static randTruncatedNormal<D extends keyof RandNormalDataTypes>(
shape: [number, number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array2D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array2D<D>;
}
static randUniform<D extends DataType>(
shape: [number, number], a: number, b: number, dtype?: D): Array2D<D> {
return NDArray.rand(shape, () => util.randUniform(a, b), dtype) as
Array2D<D>;
}
}
export class Array3D<D extends DataType = DataType> extends NDArray<D, "3"> {
constructor(
shape: [number, number, number], dtype: D, values?: DataTypeMap[D],
dataId?: DataId, math?: NDArrayMath) {
util.assert(shape.length === 3, "Shape should be of length 3");
super(shape, dtype, values, dataId, math);
}
static new<D extends DataType = "float32">(
shape: [number, number, number],
values: DataTypeMap[D] | number[] | number[][][] | boolean[] |
boolean[][][],
dtype?: D): Array3D<D> {
if (!instanceofTypedArray(values)) {
const inferredShape = util.inferShape(values as number[] | boolean[]);
if (inferredShape.length > 1) {
util.assertShapesMatch(
shape, inferredShape,
`Error when constructing Array3D. Shape of values ` +
`${inferredShape} does not match the provided shape ` +
`${shape}. `);
}
}
return new Array3D(shape, dtype, toTypedArray(values, dtype));
}
get(i: number, j: number, k: number) {
return this.dataSync()[this.strides[0] * i + this.strides[1] * j + k];
}
async val(i: number, j: number, k: number): Promise<number> {
await this.data();
return this.get(i, j, k);
}
locToIndex(locs: [number, number, number]): number {
return this.strides[0] * locs[0] + this.strides[1] * locs[1] + locs[2];
}
indexToLoc(index: number): [number, number, number] {
const i = Math.floor(index / this.strides[0]);
index -= i * this.strides[0];
return [i, Math.floor(index / this.strides[1]), index % this.strides[1]];
}
static ones<D extends DataType = DataType>(
shape: [number, number, number], dtype?: D): Array3D<D> {
return NDArray.ones<D, "3">(shape, dtype);
}
asType<D2 extends DataType>(dtype: D2): Array3D<D2> {
return super.asType(dtype) as Array3D<D2>;
}
static zeros<D extends DataType = DataType>(
shape: [number, number, number], dtype?: D): Array3D<D> {
return NDArray.zeros<D, "3">(shape, dtype);
}
static randNormal<D extends keyof RandNormalDataTypes>(
shape: [number, number, number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array3D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array3D<D>;
}
static randTruncatedNormal<D extends keyof RandNormalDataTypes>(
shape: [number, number, number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array3D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array3D<D>;
}
static randUniform<D extends DataType>(
shape: [number, number, number], a: number, b: number,
dtype?: D): Array3D<D> {
return NDArray.rand(shape, () => util.randUniform(a, b), dtype) as
Array3D<D>;
}
}
export class Array4D<D extends DataType = DataType> extends NDArray<D, "4"> {
constructor(
shape: [number, number, number, number], dtype: D,
values?: DataTypeMap[D], dataId?: DataId, math?: NDArrayMath) {
util.assert(shape.length === 4, "Shape should be of length 4");
super(shape, dtype, values, dataId, math);
}
static new<D extends DataType = "float32">(
shape: [number, number, number, number],
values: DataTypeMap[D] | number[] | number[][][][] | boolean[] |
boolean[][][][],
dtype?: D): Array4D<D> {
if (!instanceofTypedArray(values)) {
const inferredShape = util.inferShape(values as number[] | boolean[]);
if (inferredShape.length > 1) {
util.assertShapesMatch(
shape, inferredShape,
`Error when constructing Array4D. Shape of values ` +
`${inferredShape} does not match the provided shape ` +
`${shape}. `);
}
}
return new Array4D(shape, dtype, toTypedArray(values, dtype));
}
get(i: number, j: number, k: number, l: number) {
return this.dataSync()
[this.strides[0] * i + this.strides[1] * j + this.strides[2] * k + l];
}
async val(i: number, j: number, k: number, l: number): Promise<number> {
await this.data();
return this.get(i, j, k, l);
}
locToIndex(locs: [number, number, number, number]): number {
return this.strides[0] * locs[0] + this.strides[1] * locs[1] +
this.strides[2] * locs[2] + locs[3];
}
indexToLoc(index: number): [number, number, number, number] {
const i = Math.floor(index / this.strides[0]);
index -= i * this.strides[0];
const j = Math.floor(index / this.strides[1]);
index -= j * this.strides[1];
return [i, j, Math.floor(index / this.strides[2]), index % this.strides[2]];
}
asType<D2 extends DataType>(dtype: D2): Array4D<D2> {
return super.asType(dtype) as Array4D<D2>;
}
static ones<D extends DataType = DataType>(
shape: [number, number, number, number], dtype?: D): Array4D<D> {
return NDArray.ones<D, "4">(shape, dtype);
}
static zeros<D extends DataType = DataType>(
shape: [number, number, number, number], dtype?: D): Array4D<D> {
return NDArray.zeros<D, "4">(shape, dtype);
}
static randNormal<D extends keyof RandNormalDataTypes>(
shape: [number, number, number, number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array4D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array4D<D>;
}
static randTruncatedNormal<D extends keyof RandNormalDataTypes>(
shape: [number, number, number, number], mean = 0, stdDev = 1, dtype?: D,
seed?: number): Array4D<D> {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss =
new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
return NDArray.rand(shape, () => randGauss.nextValue(), dtype) as
Array4D<D>;
}
static randUniform<D extends DataType>(
shape: [number, number, number, number], a: number, b: number,
dtype?: D): Array4D<D> {
return NDArray.rand(shape, () => util.randUniform(a, b), dtype) as
Array4D<D>;
}
}
function copyTypedArray<D extends DataType>(
array: DataTypeMap[D] | number[] | boolean[], dtype: D): DataTypeMap[D] {
if (dtype == null || dtype === "float32") {
return new Float32Array(array as number[]);
} else if (dtype === "int32") {
const vals = new Int32Array(array.length);
for (let i = 0; i < vals.length; ++i) {
const val = array[i] as number;
if (util.isValNaN(val, "int32")) {
vals[i] = util.getNaN("int32");
} else {
vals[i] = val;
}
}
return vals;
} else if (dtype === "uint8") {
const vals = new Uint8Array(array.length);
vals.set(array as DataTypeMap[D] | number[]);
return vals;
} else if (dtype === "bool") {
const bool = new Uint8Array(array.length);
for (let i = 0; i < bool.length; ++i) {
const val = array[i] as number;
if (util.isValNaN(val as number, "bool")) {
bool[i] = util.getNaN("bool");
} else if (Math.round(val) !== 0) {
bool[i] = 1;
}
}
return bool;
} else {
throw new Error(`Unknown data type ${dtype}`);
}
}
function instanceofTypedArray(a: ArrayData): boolean {
return a instanceof Float32Array || a instanceof Int32Array ||
a instanceof Uint8Array;
}
function noConversionNeeded(a: ArrayData, dtype: DataType): boolean {
return (a instanceof Float32Array && dtype === "float32") ||
(a instanceof Int32Array && dtype === "int32") ||
(a instanceof Uint8Array && dtype === "bool");
}
function toTypedArray<D extends DataType>(
a: ArrayData, dtype: D): DataTypeMap[D] {
if (noConversionNeeded(a, dtype)) {
return a as DataTypeMap[D];
}
if (Array.isArray(a)) {
a = util.flatten(a) as number[];
}
return copyTypedArray(a, dtype);
}
function makeZerosTypedArray<D extends DataType>(
size: number, dtype: D): DataTypeMap[D] {
if (dtype == null || dtype === "float32") {
return new Float32Array(size);
} else if (dtype === "int32") {
return new Int32Array(size);
} else if (dtype === "bool") {
return new Uint8Array(size);
} else if (dtype === "uint8") {
return new Uint8Array(size);
} else {
throw new Error(`Unknown data type ${dtype}`);
}
}
function makeOnesTypedArray<D extends DataType>(
size: number, dtype: D): DataTypeMap[D] {
const array = makeZerosTypedArray(size, dtype);
for (let i = 0; i < array.length; i++) {
array[i] = 1;
}
return array;
} | the_stack |
import { NgZone, Injectable } from "@angular/core";
import { PanelScopeEnchantmentService } from "./panel-scope-enchantment/panel-scope-enchantment.service";
import { ScopeEnchantmentModel, PanelInfoModel } from "./model";
import { PanelExtendService } from "./panel-extend.service";
import { BehaviorSubject, fromEvent, Subscription, Observable } from "rxjs";
import { PanelWidgetModel } from "./panel-widget/model";
import { PanelExtendMoveBackService } from "./panel-extend-move-back.service";
import { PanelAssistArborService } from "./panel-assist-arbor/panel-assist-arbor.service";
import { DraggablePort } from "@ng-public/directive/draggable/draggable.interface";
import { PanelScaleplateService } from "./panel-scaleplate/panel-scaleplate.service";
import { DraggableTensileCursorService } from "./panel-scope-enchantment/draggable-tensile-cursor.service";
import { cloneDeep, get } from "lodash";
import { NzMessageService } from "ng-zorro-antd";
import { map } from "rxjs/operators";
import { ImageModel } from "@ng-public/image-gallery/model";
import { PanelSoulService } from "./panel-soul/panel-soul.service";
import { PanelSeniorVesselEditService } from "./panel-senior-vessel-edit/panel-senior-vessel-edit.service";
import { AppDataService } from "app/appdata/appdata.service";
import { panelWidgetComponentObj } from "./panel-widget/all-widget-container";
@Injectable({
providedIn: "root",
})
export class PanelExtendQuickShortcutsService {
// 键盘按下的操作监听
private listenKeyboardDown$: Subscription;
// 键盘弹起的操作监听
private listenKeyboardUp$: Subscription;
public get widgetList$(): BehaviorSubject<Array<PanelWidgetModel>> {
return this.panelExtendService.widgetList$;
}
public get panelInfo(): PanelInfoModel {
return this.panelExtendService.panelInfoModel;
}
public get scopeEnchantmentModel(): ScopeEnchantmentModel {
return this.panelScopeEnchantmentService.scopeEnchantmentModel;
}
constructor(
private readonly zone: NgZone,
private readonly panelExtendService: PanelExtendService,
private readonly nzMessageService: NzMessageService,
private readonly draggableTensileCursorService: DraggableTensileCursorService,
private readonly panelSeniorVesselEditService: PanelSeniorVesselEditService,
private readonly appDataService: AppDataService,
private readonly panelScaleplateService: PanelScaleplateService,
private readonly panelSoulService: PanelSoulService,
private readonly panelAssistArborService: PanelAssistArborService,
private readonly panelExtendMoveBackService: PanelExtendMoveBackService,
private readonly panelScopeEnchantmentService: PanelScopeEnchantmentService
) {}
/**
* 获取浏览器的粘贴面板数据
*/
public subClipboardPaste(): Observable<File> {
return fromEvent(document, "paste").pipe(
map((res: ClipboardEvent) => {
if (res.clipboardData && res.clipboardData.items) {
for (let i = 0, len = res.clipboardData.items.length; i < len; i++) {
let item = res.clipboardData.items[i];
if (item.kind === "file") {
return item.getAsFile();
}
}
} else {
return null;
}
})
);
}
/**
* 清空浏览器粘贴板数据
*/
public clearClipboardPaste(): Observable<boolean> {
return fromEvent(document, "copy").pipe(
map((res: ClipboardEvent) => {
if (res.clipboardData && res.clipboardData.items) {
res.clipboardData.setData("file", null);
res.preventDefault();
return true;
} else {
return false;
}
})
);
}
/**
* 开启键盘事件监听
*/
public openKeyboardEvent(): void {
this.closeKeyboardEvent();
this.listenKeyboardDown$ = fromEvent(document, "keydown").subscribe((keyboard: KeyboardEvent) => {
this.zone.run(() => {
// 如果当前获得的焦点标签是输入框且按下了enter键则自动blur;
if (document.activeElement.tagName == "INPUT" && keyboard.keyCode == 13) {
document.activeElement["blur"]();
}
// 如果当前获得的焦点标签不是BODY就关闭键盘事件
if (document.activeElement.tagName == "BODY") {
// 按下了ctr+s 或 command+s 执行保存操作
if (
(keyboard.metaKey == true && keyboard.keyCode == 83) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 83)
) {
keyboard.preventDefault();
}
// 按下了ctr+c 或 command+c 执行复制操作
if (
(keyboard.metaKey == true && keyboard.keyCode == 67) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 67)
) {
this.performCopy();
}
// 按下了ctr+v 或command+v 执行粘贴操作
if (
(keyboard.metaKey == true && keyboard.keyCode == 86) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 86)
) {
this.performPaste();
}
// 按下了ctr+a 或command+a 执行全选
if (
(keyboard.metaKey == true && keyboard.keyCode == 65) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 65)
) {
this.performCheckAll();
}
// 按下了ctr+z 或command+z 执行撤销
if (
(keyboard.metaKey == true && keyboard.shiftKey == false && keyboard.keyCode == 90) ||
(keyboard.ctrlKey == true && keyboard.shiftKey == false && keyboard.keyCode == 90)
) {
this.panelExtendMoveBackService.acquireBackDBData();
}
// 按下了ctr+shift+z 或command+shift+z 执行前进
if (
(keyboard.metaKey == true && keyboard.shiftKey == true && keyboard.keyCode == 90) ||
(keyboard.ctrlKey == true && keyboard.shiftKey == true && keyboard.keyCode == 90)
) {
this.panelExtendMoveBackService.acquireMoveDBData();
}
// 按下了ctr+d 或command+d 执行快捷复制粘贴操作
if (
(keyboard.metaKey == true && keyboard.keyCode == 68) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 68)
) {
keyboard.preventDefault();
this.performCopy();
this.performPaste(false);
}
// 按下了ctr+x 或command+x 执行剪切操作
if (
(keyboard.metaKey == true && keyboard.keyCode == 88) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 88)
) {
this.performCutWidget();
}
// 按下了ctr+g 或command+g 执行组合
if (
(keyboard.metaKey == true && keyboard.shiftKey == false && keyboard.keyCode == 71) ||
(keyboard.ctrlKey == true && keyboard.shiftKey == false && keyboard.keyCode == 71)
) {
keyboard.preventDefault();
this.panelAssistArborService.launchCreateCombination$.next();
}
// 按下了ctr+shift+g 或command+shift+g 执行打散组合
if (
(keyboard.metaKey == true && keyboard.shiftKey == true && keyboard.keyCode == 71) ||
(keyboard.ctrlKey == true && keyboard.shiftKey == true && keyboard.keyCode == 71)
) {
keyboard.preventDefault();
this.panelAssistArborService.launchDisperseCombination$.next();
}
// 按下了ctr+h 或command+h 执行隐藏或显示标尺辅助线操作
if (
(keyboard.metaKey == true && keyboard.keyCode == 72) ||
(keyboard.ctrlKey == true && keyboard.keyCode == 72)
) {
keyboard.preventDefault();
this.panelScaleplateService.controlLineShowOrHide();
}
// 按下上下左右执行移动
if ([39, 38, 37, 40].includes(keyboard.keyCode)) {
this.performFourOrientation(keyboard);
}
// 按下了删除键盘
if (keyboard.keyCode == 8 || keyboard.keyCode == 46) {
this.performDelWidget();
}
// 按下了alt键盘
if (keyboard.keyCode == 18) {
this.panelScopeEnchantmentService.isOpenAltCalc$.next(false);
}
// 按下了shift键盘
if (keyboard.keyCode == 16 && keyboard.shiftKey == true) {
this.draggableTensileCursorService.isOpenConstrainShift$.next(true);
}
// 按下了commadn键
if (keyboard.keyCode == 91 && keyboard.metaKey == true) {
this.panelScaleplateService.isOpenMoveLine$.next(true);
}
// 按下了ctrl键
if (keyboard.keyCode == 17 && keyboard.ctrlKey == true) {
this.panelScaleplateService.isOpenMoveLine$.next(true);
}
// 按下了空格键
if (keyboard.keyCode == 32) {
this.panelExtendService.isOpenSpacebarMove$.next(true);
}
// 按下了esc键
if (keyboard.keyCode == 27) {
// this.panelSeniorVesselEditService.exitRoomVessel()
}
}
});
});
this.listenKeyboardUp$ = fromEvent(document, "keyup").subscribe(() => {
this.zone.run(() => {
this.panelScopeEnchantmentService.isOpenAltCalc$.next(true);
this.panelExtendService.isOpenSpacebarMove$.next(false);
this.panelScaleplateService.isOpenMoveLine$.next(false);
this.draggableTensileCursorService.isOpenConstrainShift$.next(false);
// 如果当前获得的焦点标签不是BODY就关闭键盘事件
if (document.activeElement.tagName == "BODY") {
}
});
});
}
/**
* 取消所有键盘事件监听
*/
public closeKeyboardEvent(): void {
if (this.listenKeyboardDown$) this.listenKeyboardDown$.unsubscribe();
if (this.listenKeyboardUp$) this.listenKeyboardUp$.unsubscribe();
}
/**
* 执行复制操作
*/
public performCopy(): void {
const insetWidget = this.scopeEnchantmentModel.outerSphereInsetWidgetList$.value;
if (Array.isArray(insetWidget) && insetWidget.length > 0) {
const clipCopy = this.clearClipboardPaste().subscribe(() => {
clipCopy.unsubscribe();
});
this.panelScopeEnchantmentService.clipboardList$.next(cloneDeep(insetWidget));
}
}
/**
* 执行粘贴操作
* isNoneFile参数表示是否不需要粘贴文件,如果为false则直接粘贴组件
*/
public performPaste(isNoneFile: boolean = true): void {
const done = () => {
let posi = { left: 0, top: 0 };
const outer = this.scopeEnchantmentModel.valueProfileOuterSphere;
if (outer) {
posi.left = outer.left + Math.floor(outer.width / 2);
posi.top = outer.top + outer.height + Math.floor(outer.height / 2);
} else {
posi.left = Math.floor(this.panelInfo.width / 2);
posi.top = Math.floor(this.panelInfo.height / 2);
}
this.performPasteWidgetInPanel(posi);
};
if (isNoneFile) {
const clipPaste = this.subClipboardPaste().subscribe(file => {
if (file && file instanceof File) {
// 说明浏览器的粘贴板有图片文件,执行(上传 -> 生成widget组件 -> 选中图片组件)
this.handleForClipboardPasteFile();
} else {
done();
}
clipPaste.unsubscribe();
});
} else {
done();
}
}
/**
* 粘贴组件到面板
* 如果是组合组件则把组合组件的子集也一并复制一份
* 同时筛选出不是部件或动态容器的数据,因为动态容器只允许粘贴普通组件
*/
public performPasteWidgetInPanel(position: { left: number; top: number }): void {
let clipList = this.panelScopeEnchantmentService.clipboardList$.value;
if (this.panelSeniorVesselEditService.isEnterEditVesselCondition$.value) {
const allContainerWidgetType = Object.keys(panelWidgetComponentObj);
clipList = clipList.filter(c => {
return allContainerWidgetType.includes(c.type) || c.type == "combination";
});
}
if (clipList.length == 0) {
this.nzMessageService.warning("无粘贴内容");
} else {
const copyC = clipList.map(e => new PanelWidgetModel(cloneDeep(e)));
this.panelExtendService.addPanelWidget(copyC);
this.panelScopeEnchantmentService.pushOuterSphereInsetWidget(copyC);
const outerSphere = this.scopeEnchantmentModel.valueProfileOuterSphere;
const dragIncrement = {
left: position.left - outerSphere.left - Math.floor(outerSphere.width / 2),
top: position.top - outerSphere.top - Math.floor(outerSphere.height / 2),
};
this.scopeEnchantmentModel.handleProfileOuterSphereLocationInsetWidget(dragIncrement);
this.scopeEnchantmentModel.handleLocationInsetWidget(dragIncrement);
}
}
/**
* 执行全选操作
*/
public performCheckAll(): void {
this.panelScopeEnchantmentService.pushOuterSphereInsetWidget(this.panelExtendService.valueWidgetList());
}
/**
* 执行上下左右四个键盘事件的回调
* 对应keyCode如下
* 右: 39
* 上: 38
* 左: 37
* 下: 40
*/
public performFourOrientation(key: KeyboardEvent): void {
const scopeEnchant = this.scopeEnchantmentModel;
if (scopeEnchant.valueProfileOuterSphere) {
const keyCode = key.keyCode;
const isShift: boolean = key.shiftKey;
const move = (drag: DraggablePort) => {
const pro = scopeEnchant.valueProfileOuterSphere;
scopeEnchant.valueProfileOuterSphere.setMouseCoord([pro.left, pro.top]);
scopeEnchant.outerSphereInsetWidgetList$.value.map(e => {
e.profileModel.setMouseCoord([e.profileModel.left, e.profileModel.top]);
});
scopeEnchant.handleProfileOuterSphereLocationInsetWidget(drag);
scopeEnchant.handleLocationInsetWidget(drag);
};
const keyObj = {
"39": { left: isShift ? 10 : 1, top: 0 },
"38": { left: 0, top: isShift ? -10 : -1 },
"37": { left: isShift ? -10 : -1, top: 0 },
"40": { left: 0, top: isShift ? 10 : 1 },
};
if (keyObj[keyCode]) move(keyObj[keyCode]);
}
}
/**
* 删除选中的widget组件
*/
public performDelWidget(): void {
const scopeEnchant = this.scopeEnchantmentModel;
if (scopeEnchant && scopeEnchant.outerSphereInsetWidgetList$.value) {
const insetWidget = scopeEnchant.outerSphereInsetWidgetList$.value;
const insetWidgetNrId = insetWidget.map(e => e.uniqueId);
this.panelExtendService.deletePanelWidget(insetWidgetNrId);
this.scopeEnchantmentModel.emptyAllProfile();
}
}
/**
* 执行剪切操作
*/
public performCutWidget(): void {
this.performCopy();
this.performDelWidget();
}
/**
* 执行图片手动上传操作,然后生成对应的图片组件widget,然后再选中
*/
public handleForClipboardPasteFile(): void {
// empty
}
/**
* 动态创建图片组件,并自动贴上粘贴上传好的图片路径,并选中
*/
public handleCreatePictureWidget(data: { id: [number]; original: string; url: string }): void {
if (data) {
// 创建图片类
const picture = new ImageModel(<ImageModel>{
id: get(data, "id[0]"),
name: get(data, "original"),
url: get(data, "url"),
});
// 找出图片的原始itemwidget类
const itemWidget = this.panelSoulService.fixedWidget$.value.find(e => e.type == "picture");
if (itemWidget) {
// 创建图片widget组件
const widget = new PanelWidgetModel(cloneDeep(itemWidget));
widget.profileModel.setData({
left: 30,
top: 30,
});
widget.autoWidget.content = picture.url;
// 添加到主视图中
this.panelExtendService.addPanelWidget([widget]);
// 选中
this.panelScopeEnchantmentService.onlyOuterSphereInsetWidget(widget);
}
}
}
} | the_stack |
import { Timeline } from '@/lib/audio/timeline';
import { ContextTime, Ticks, Seconds, Beat } from '@/lib/audio/types';
import { Context } from '@/lib/audio/context';
import { watch } from '@vue/composition-api';
import { Clock } from '@/lib/audio/clock';
import { StrictEventEmitter } from '@/lib/events';
import { Disposer } from '@/lib/std';
interface EventContext {
seconds: ContextTime;
ticks: Ticks;
}
// FIXME Ok so this type definition is not 100% correct as the duration does not NEED to be defined iff onEnd AND onTick
// are undefined.
export interface TransportEvent {
time: Ticks;
// Must be defined if `onMidStart` OR `onEnd` OR `onTick` are defined
duration: Ticks;
offset: Ticks;
// This is kinda irrelevant and should maybe be removed
// But it was definitely the easiest solution to implementing row muting
// The reason this isn't the best is that the transport shouldn't really care about rows but if you can find a
// better solution then we can remove this
row: number;
// Called ONLY at the start of the event
onStart?: (context: EventContext) => void;
// Called when the event is started at ANY point during its duration, EXCLUDING the start
onMidStart?: (context: { seconds: ContextTime, ticks: Ticks, secondsOffset: Seconds, ticksOffset: Ticks }) => void;
// Called when the event is finished. This includes at the end its end time, when the clock is paused, when the
// the clock is stopped, if the event is suddenly rescheduled such that the end time is less than the current time
// or if the event is suddenly rescheduled such that the start time is after the current time.
onEnd?: (context: EventContext) => void;
// Called on each tick while the event is active (when the current time >= start time AND the current time <= start
// time + duration).
onTick?: (context: EventContext) => void;
}
export interface TransportEventController {
setStartTime(startTime: Beat): void;
setOffset(offset: Beat): void;
setRow(row: number): void;
setDuration(duration: Beat): void;
remove(): Disposer;
}
export class Transport extends StrictEventEmitter<{ beforeStart: [EventContext], beforeEnd: [EventContext] }> {
private startPosition: Ticks = 0;
private timeline = new Timeline<TransportEvent>();
private active: TransportEvent[] = [];
private isFirstTick = false;
private filters: Array<(event: TransportEvent) => boolean> = [];
// tslint:disable-next-line:variable-name
private _loopStart: Ticks = 0;
// tslint:disable-next-line:variable-name
private _loopEnd: Ticks = 0;
private clock = new Clock({
callback: this.processTick.bind(this),
frequency: 0,
});
private disposer: () => void;
constructor() {
super();
const setBpm = () => this.clock.frequency.value = 1 / (60 / Context.BPM / Context.PPQ);
// FIXME Maybe all of the clocks could share one "ticker"?? IDK? Then we wouldn't have to "watch" the BBM
// Note, this will run automatically
const d = Context.onDidSetBPM(setBpm);
const pause = this.clock.on('stopped', (o) => {
this.checkOnEndEventsAndResetActive(o);
});
this.disposer = () => {
// d.dispose();
// pause.dispose();
};
}
/**
* Schedule an event.
*/
public schedule(event: TransportEvent): TransportEventController {
// make a copy so setting values does nothing
event = {
...event,
// FIXME we probably shouldn't be converting to beats here??
duration: Context.beatsToTicks(event.duration),
time: Context.beatsToTicks(event.time),
offset: Context.beatsToTicks(event.offset),
};
this.timeline.add(event);
const checkNowActive = () => {
if (this.state !== 'started') {
return;
}
if (this.filter(event)) {
return;
}
// If the event hasn't started yet or if it has already ended, we don't care
const current = this.clock.ticks;
const startTime = event.time + event.offset;
const endTime = startTime + event.duration;
if (
startTime > current ||
endTime < current
) {
return;
}
// If it's already in there, we don't need to add it
const index = this.active.indexOf(event);
if (index !== -1) {
return;
}
// Ok now we now that the event needs to be retroactively added to the active list
if (event.onTick || event.onEnd) {
this.active.push(event);
}
// Ok so we the event is now active, but we have to make sure to call the correct function
if (startTime === current) {
if (event.onStart) {
event.onStart({
seconds: Context.now(),
ticks: this.clock.ticks,
});
}
} else {
this.checkMidStart(event, {
seconds: Context.now(),
ticks: this.clock.ticks,
});
}
};
let added = true;
return {
setStartTime: (startTime: Beat) => {
event.time = Context.beatsToTicks(startTime);
// So we need to reposition the element in the sorted array after setting the time
// This is a very simple way to do it but it could be done more efficiently
const didRemove = this.timeline.remove(event);
// It may be the case that the element is not scheduled so we need to take that into consideration
if (didRemove) {
this.timeline.add(event);
}
checkNowActive();
},
setDuration: (duration: Beat) => {
event.duration = Context.beatsToTicks(duration);
checkNowActive();
},
setRow: (row: number) => {
event.row = row;
},
setOffset: (offset: Beat) => {
event.offset = Context.beatsToTicks(offset);
// We also need to make sure it's sorted here
this.timeline.remove(event);
this.timeline.add(event);
checkNowActive();
},
remove: () => {
if (!added) {
return {
dispose: () => {
//
},
};
}
this.timeline.remove(event);
added = false;
const dispose = () => {
this.timeline.add(event);
added = true;
checkNowActive();
};
if (!this.active) {
return {
dispose,
};
}
const i = this.active.indexOf(event);
if (i >= 0) {
if (event.onEnd) {
event.onEnd({
ticks: this.clock.ticks,
seconds: Context.now(),
});
}
this.active.splice(i, 1);
}
return {
dispose,
};
},
};
}
public embed(child: Transport, o: { time: Beat, duration: Beat, row: number }) {
return this.schedule({
onStart: () => {
child.isFirstTick = true;
},
onMidStart: () => {
child.isFirstTick = true;
},
onTick({ seconds, ticks: currentTick }) {
// We subtract the `tick` value because the given transport is positioned relative to this transport.
// For example, if we embed transport A in transport B at tick 1 and the callback is called at tick 2, we want
// transport A to think it is time tick 1
child.processTick(seconds, currentTick - this.time, true);
},
time: o.time,
offset: 0,
duration: o.duration,
row: o.row,
});
}
/**
* Filter out events during playback.
*
* @param filter The filter function. It should return false if the event should be ignored.
*/
public addFilter(filter: (event: TransportEvent) => boolean) {
this.filters.push(filter);
return {
dispose: () => {
const i = this.filters.indexOf(filter);
if (i >= 0) {
this.filters.splice(i, 1);
}
},
};
}
/**
* Start playback from current position.
*/
public start() {
this.isFirstTick = true;
this.clock.start();
}
/**
* Pause playback.
*/
public pause() {
this.clock.pause();
}
/**
* Stop playback and return to the beginning.
*/
public stop() {
this.clock.stop();
this.ticks = this.startPosition;
}
public dispose() {
this.disposer();
}
get loopStart() {
return this._loopStart / Context.PPQ;
}
set loopStart(loopStart: Beat) {
this._loopStart = loopStart * Context.PPQ;
}
get seconds() {
return this.clock.seconds;
}
get loopEnd() {
return this._loopEnd / Context.PPQ;
}
set loopEnd(loopEnd: Beat) {
this._loopEnd = loopEnd * Context.PPQ;
}
get ticks() {
return this.clock.ticks;
}
set ticks(t: number) {
if (this.clock.ticks !== t) {
const now = Context.now();
// stop everything synced to the transport
if (this.state === 'started') {
// restart it with the new time
this.clock.setTicksAtTime(t, now);
} else {
this.clock.setTicksAtTime(t, now);
}
this.startPosition = t;
}
}
get beat() {
return this.ticks / Context.PPQ;
}
set beat(beat: number) {
this.ticks = beat * Context.PPQ;
}
get state() {
return this.clock.state;
}
public getProgress() {
return (this.ticks - this._loopStart) / (this._loopEnd - this._loopStart);
}
private checkMidStart(event: TransportEvent, c: EventContext) {
if (event.onMidStart) {
const ticksOffset = c.ticks - event.time;
const secondsOffset = Context.ticksToSeconds(ticksOffset);
event.onMidStart({
...c,
secondsOffset,
ticksOffset,
});
}
}
private checkOnEndEventsAndResetActive(c: EventContext) {
this.active.forEach((event) => {
if (event.onEnd) {
event.onEnd(c);
}
});
this.active = [];
}
private filter(event: TransportEvent) {
return this.filters.some((filter) => !filter(event));
}
private processTick(seconds: ContextTime, ticks: Ticks, isChild = false) {
if (!isChild && ticks >= this._loopEnd) {
this.emit('beforeEnd', { seconds, ticks });
this.checkOnEndEventsAndResetActive({ seconds, ticks });
this.clock.setTicksAtTime(this._loopStart, seconds);
ticks = this._loopStart;
this.isFirstTick = true;
}
if (this.isFirstTick) {
this.emit('beforeStart', { seconds, ticks });
// The upper bound is exclusive but we don't care about checking about events that haven't started yet.
this.timeline.forEachBetween(0, ticks, (event) => {
if (this.filter(event)) {
return;
}
// Check if it's already finished
if (event.time + event.duration < ticks) {
return;
}
this.checkMidStart(event, {
seconds,
ticks,
});
// Again, we DON't CARE about event that don't need to ba called again
if (event.onTick || event.onEnd) {
this.active.push(event);
}
});
this.isFirstTick = false;
}
// Invoke onTick callbacks for events scheduled on this tick.
// Also, add them to the active list of events if required.
this.timeline.forEachAtTime(ticks, (event) => {
if (this.filter(event)) {
return;
}
if (event.onStart) {
event.onStart({
seconds,
ticks,
});
}
// If neither of these is defined then we don't really care about it anymore
if (event.onTick || event.onEnd) {
this.active.push(event);
}
});
this.active = this.active.filter((event) => {
if (this.filter(event)) {
if (event.onEnd) { event.onEnd({ seconds, ticks }); }
return false;
}
const endTime = event.time + event.duration;
const startTime = event.time + event.offset;
if (endTime < ticks) {
// This occurs if the start time was reduced or the duration was reduced such that the end time became less
// than the current time.
if (event.onEnd) { event.onEnd({ seconds, ticks }); }
} else if (endTime === ticks) {
// If we've reached the end of the event than still call onTick and then onEnd as well.
if (event.onTick) { event.onTick({ seconds, ticks }); }
if (event.onEnd) { event.onEnd({ seconds, ticks }); }
} else if (startTime > ticks) {
// This can happen if the event is rescheduled such that it starts after the current time
if (event.onEnd) { event.onEnd({ seconds, ticks }); }
} else {
if (event.onTick) { event.onTick({ seconds, ticks }); }
}
// Keep iff the end time has not passed and the start time has passed
return ticks < endTime && startTime <= ticks;
});
}
} | the_stack |
import {
EntityTarget,
INTERNAL_ENTITY_ATTRIBUTE,
InvalidParallelScanLimitOptionError,
MANAGER_NAME,
PARALLEL_SCAN_CONCURRENCY_LIMIT,
STATS_TYPE,
} from '@typedorm/common';
import {DynamoDB} from 'aws-sdk';
import pLimit from 'p-limit';
import {getUniqueRequestId} from '../../helpers/get-unique-request-id';
import {Connection} from '../connection/connection';
import {FilterOptions} from '../expression/filter-options-type';
import {ProjectionKeys} from '../expression/projection-keys-options-type';
import {MetadataOptions} from '../transformer/base-transformer';
import {DocumentClientScanTransformer} from '../transformer/document-client-scan-transformer';
interface ScanManageBaseOptions<Entity, PartitionKey> {
/**
* Index to scan for items
* @default - main table
*/
scanIndex?: string;
/**
* Max number of records to query
* @default - implicit dynamo db query limit is applied
*/
limit?: number;
/**
* Cursor to traverse from
* @default none
*/
cursor?: DynamoDB.DocumentClient.Key;
/**
* Specify filter to apply
* Avoid using this where possible, since filters in dynamodb applies after items
* are read
* @default none
*/
where?: FilterOptions<Entity, PartitionKey>;
/**
* Specifies which attributes to fetch
* @default all attributes are fetched
*/
select?: ProjectionKeys<Entity>;
}
export interface ScanManagerFindOptions<Entity>
extends ScanManageBaseOptions<
Entity,
{} // empty object since all attributes including ones used in primary key can be used with filter
> {
/**
* Total number of segments to divide this scan in.
*
* @default none - all items are scanned sequentially
*/
totalSegments?: number;
/**
* Limit to apply per segment.
*
* when no `totalSegments` is provided, this option is ignored
* @default none - limit to apply per segment
*/
limitPerSegment?: number;
/**
* Item cursor, used for paginating a scan.
*
* When the `totalSegments` option is provided, this option should be of type {[segmentNo]: [Key]}
* @default none
*/
cursor?:
| Record<number, ScanManageBaseOptions<Entity, {}>['cursor']>
| ScanManageBaseOptions<Entity, {}>['cursor'];
/**
* Max number of requests to run in parallel
*
* When requesting parallel scan on x segments, request are executed in parallel using Promise.all
* While it is okay to run small number of requests in parallel, it is often a good idea to enforce a concurrency controller to stop node from eating up the all the memory
*
* This parameter does exactly that. i.e if requested to run scan with `20,000` segments, and `requestsConcurrencyLimit` is set to `100`
* TypeDORM will make sure that there are always only `100` requests are running in parallel at any time until all `20,000` segments have finished processing.
*
* @default PARALLEL_SCAN_CONCURRENCY_LIMIT
*/
requestsConcurrencyLimit?: number;
}
export type ScanManagerCountOptions<Entity> = Pick<
ScanManageBaseOptions<
Entity,
{} // empty object since all attributes including ones used in primary key can be used with filter
>,
'scanIndex' | 'where'
>;
export interface ScanManagerParallelScanOptions
extends ScanManageBaseOptions<any, any> {
/**
* Total number of segments to divide this scan in
*/
totalSegments: number;
/**
* Limit to apply per segment
*
* @default none - limit to apply per segment
*/
limitPerSegment?: number;
/**
* Entity to run scan for.
*
* When one is provided, filter expression in auto updated to include a default filer condition for matching entity
*
* @default none
*/
entity?: EntityTarget<any>;
/**
* Per segment cursor, where key is the segment number, and value is the cursor options for that segment
*
* @default none
*/
cursor?: Record<number, ScanManagerScanOptions['cursor']>;
/**
* Max number of requests to run in parallel
*
* When requesting parallel scan on x segments, request are executed in parallel using Promise.all
* While it is okay to run small number of requests in parallel, it is often a good idea to enforce a concurrency controller to stop node from eating up the all the memory
*
* This parameter does exactly that. i.e if requested to run scan with `20,000` segments, and `requestsConcurrencyLimit` is set to `100`
* TypeDORM will make sure that there are always only `100` requests are running in parallel at any time until all `20,000` segments have finished processing.
*
* @default PARALLEL_SCAN_CONCURRENCY_LIMIT
*/
requestsConcurrencyLimit?: number;
}
export interface ScanManagerScanOptions
extends ScanManageBaseOptions<any, any> {
/**
* Entity to scan
*
* When one is provided, filter expression in auto updated to include filer condition for this entity
*
* @default none
*/
entity?: EntityTarget<any>;
/**
* Number of current segment
*
* @default none - scan is not segmented
*/
segment?: number;
/**
* Total number of segments to divide this scan in
*
* @default none - all items are scanned sequentially
*/
totalSegments?: number;
/**
* Limit to apply per segment
*
* @default none - limit to apply per segment
*/
limitPerSegment?: number;
}
export class ScanManager {
private itemsFetchedSoFarTotalParallelCount: number;
private limit = pLimit(PARALLEL_SCAN_CONCURRENCY_LIMIT);
private _dcScanTransformer: DocumentClientScanTransformer;
constructor(private connection: Connection) {
this._dcScanTransformer = new DocumentClientScanTransformer(connection);
this.itemsFetchedSoFarTotalParallelCount = 0;
}
/**
* Finds all the matching entity over document client scan operation
* @param entityClass Entity to find
* @param findOptions find query options
* @param metadataOptions Other metadata options
*/
async find<Entity>(
entityClass: EntityTarget<Entity>,
findOptions?: ScanManagerFindOptions<Entity>,
metadataOptions?: MetadataOptions
) {
const requestId = getUniqueRequestId(metadataOptions?.requestId);
let response: {
items?: Entity[];
unknownItems?: DynamoDB.DocumentClient.AttributeMap[];
cursor?:
| DynamoDB.DocumentClient.Key
| Record<number, DynamoDB.DocumentClient.Key>;
};
if (findOptions?.totalSegments) {
(response = await this.parallelScan<Entity>({
...findOptions,
entity: entityClass,
} as ScanManagerParallelScanOptions)),
{
requestId,
returnConsumedCapacity: metadataOptions?.returnConsumedCapacity,
};
} else {
response = await this.scan<Entity>(
{...findOptions, entity: entityClass} as ScanManagerScanOptions,
{
requestId,
returnConsumedCapacity: metadataOptions?.returnConsumedCapacity,
}
);
}
if (response.unknownItems?.length) {
// log warning for items that were skipped form the response
// These are items that had __en attribute on them but TypeDORM does no longer know about them
this.connection.logger.logWarn({
requestId,
scope: MANAGER_NAME.SCAN_MANAGER,
log: `"${response.unknownItems.length}" items were skipped from the response because TypDORM failed to resolve them.`,
});
}
return {
items: response.items,
cursor: response.cursor,
};
}
/**
* Returns total count of all matching items for current entity
* @param entityClass Entity to count
* @param scanOptions Extra scan options
* @param metadataOptions Other metadata options
*/
async count<Entity>(
entityClass: EntityTarget<Entity>,
scanOptions?: ScanManagerCountOptions<Entity>,
metadataOptions?: MetadataOptions
): Promise<number> {
const requestId = getUniqueRequestId(metadataOptions?.requestId);
const dynamoScanInput = this._dcScanTransformer.toDynamoScanItem(
{...scanOptions, entity: entityClass, onlyCount: true, select: undefined}, // select projection and count can not be used together
{
requestId,
returnConsumedCapacity: metadataOptions?.returnConsumedCapacity,
}
);
const count = await this._internalRecursiveCount({
scanInput: dynamoScanInput,
metadataOptions: {
requestId,
returnConsumedCapacity: metadataOptions?.returnConsumedCapacity,
},
});
return count;
}
/**
* Scans all items from dynamo table in parallel while also respecting the max provisioned concurrency
* @param scanOptions Options for parallel scan
* @param metadataOptions Additional metadata options
*/
async parallelScan<Entity>(
scanOptions: ScanManagerParallelScanOptions,
metadataOptions?: MetadataOptions
): Promise<{
items: Entity[] | undefined;
unknownItems: DynamoDB.DocumentClient.AttributeMap[] | undefined;
cursor: Record<number, DynamoDB.DocumentClient.Key | undefined>;
}> {
// start with 0
this.itemsFetchedSoFarTotalParallelCount = 0;
const concurrencyLimit =
PARALLEL_SCAN_CONCURRENCY_LIMIT || scanOptions.requestsConcurrencyLimit;
const requestId = getUniqueRequestId(metadataOptions?.requestId);
if (scanOptions.requestsConcurrencyLimit) {
this.limit = pLimit(scanOptions.requestsConcurrencyLimit);
}
const parallelScanOptions: ScanManagerScanOptions[] = [];
if (
scanOptions?.limit &&
scanOptions?.limitPerSegment &&
scanOptions?.limit < scanOptions?.limitPerSegment
) {
throw new InvalidParallelScanLimitOptionError(
scanOptions?.limit,
scanOptions?.limitPerSegment
);
}
for (let index = 0; index < scanOptions.totalSegments; index++) {
// only the cursor for same segment can be applied
const cursorForSegment = scanOptions.cursor
? scanOptions.cursor[index]
: undefined;
parallelScanOptions.push({
...scanOptions,
cursor: cursorForSegment,
segment: index,
});
}
this.connection.logger.logInfo({
requestId,
scope: MANAGER_NAME.SCAN_MANAGER,
log: `Running scan in parallel with ${scanOptions.totalSegments} segments.`,
});
if (concurrencyLimit < scanOptions.totalSegments) {
this.connection.logger.logInfo({
requestId,
scope: MANAGER_NAME.SCAN_MANAGER,
log: `Current request concurrency limit ${concurrencyLimit} is lower than requested segments count ${scanOptions.totalSegments}
So requests will be run in a batch of ${concurrencyLimit} at a time until all segments ${scanOptions.totalSegments} have processed.`,
});
}
const allPromisesResponse = await Promise.all(
parallelScanOptions.map(options =>
this.toLimited(this.scan<Entity>(options, metadataOptions))
)
);
// merge all responses
const response = allPromisesResponse.reduce(
(
acc: {
items: Entity[];
unknownItems: DynamoDB.DocumentClient.AttributeMap[];
cursor: Record<number, DynamoDB.DocumentClient.Key>;
},
current,
index
) => {
if (current.items?.length) {
if (!acc.items) {
acc.items = [];
}
acc.items = [...acc.items, ...current.items];
}
if (current.unknownItems?.length) {
if (!acc.unknownItems) {
acc.unknownItems = [];
}
acc.unknownItems = [...acc.unknownItems, ...current.unknownItems];
}
if (current.cursor) {
if (!acc.cursor) {
acc.cursor = {};
}
acc.cursor = {
...acc.cursor,
[index]: current.cursor,
};
}
return acc;
},
{} as {
items: Entity[];
unknownItems: DynamoDB.DocumentClient.AttributeMap[];
cursor: Record<number, DynamoDB.DocumentClient.Key>;
}
);
return response;
}
/**
* Low level scan operation.
*
* Perhaps you are looking for higher level ScanManager.find or ScanManager.parallelScan operation
* @param scanOptions scan options to run scan with
* @param metadataOptions any other metadata options
*/
async scan<Entity>(
scanOptions?: ScanManagerScanOptions,
metadataOptions?: MetadataOptions
): Promise<{
items: Entity[] | undefined;
unknownItems: DynamoDB.DocumentClient.AttributeMap[] | undefined;
cursor: DynamoDB.DocumentClient.Key | undefined;
}> {
const requestId = getUniqueRequestId(metadataOptions?.requestId);
const dynamoScanInput = this._dcScanTransformer.toDynamoScanItem(
{
...scanOptions,
// if requested segmented scan, then apply segment limit or default to limit operator
limit: scanOptions?.totalSegments
? scanOptions?.limitPerSegment
: scanOptions?.limit,
},
{
requestId,
returnConsumedCapacity: metadataOptions?.returnConsumedCapacity,
}
);
const response = await this._internalRecursiveScan({
scanInput: dynamoScanInput,
limit: scanOptions?.limit,
cursor: scanOptions?.cursor,
metadataOptions: {
requestId,
returnConsumedCapacity: metadataOptions?.returnConsumedCapacity,
},
});
const entities = this._dcScanTransformer.fromDynamoScanResponseItemList<
Entity
>(response.items);
if (scanOptions?.entity && entities.unknownItems) {
this.connection.logger.logWarn({
requestId,
scope: MANAGER_NAME.SCAN_MANAGER,
log: `
There were some items that looked like ${scanOptions?.entity.name} but TypeDORM was unable to convert it back to entity type,
This can happen when there are items in the table with "${INTERNAL_ENTITY_ATTRIBUTE.ENTITY_NAME} but was not created by TypeDORM.
You should remove them or update it to something different."`,
});
}
return {
items: entities.items?.length ? entities.items : undefined,
unknownItems: entities.unknownItems?.length
? entities.unknownItems
: undefined,
cursor: response.cursor,
};
}
/**
* Recursively scans table with given options
*/
private async _internalRecursiveScan({
scanInput,
limit,
cursor,
itemsFetched = [],
metadataOptions,
}: {
scanInput: DynamoDB.DocumentClient.ScanInput;
limit?: number;
cursor?: DynamoDB.DocumentClient.Key;
itemsFetched?: DynamoDB.DocumentClient.ItemList;
metadataOptions?: MetadataOptions;
}): Promise<{
items: DynamoDB.DocumentClient.ItemList;
cursor?: DynamoDB.DocumentClient.Key;
}> {
// return if the count is already met
if (limit && this.itemsFetchedSoFarTotalParallelCount >= limit) {
return {
items: itemsFetched,
cursor,
};
}
const {
LastEvaluatedKey,
Items = [],
ConsumedCapacity,
} = await this.connection.documentClient
.scan({...scanInput, ExclusiveStartKey: cursor})
.promise();
// stats
if (ConsumedCapacity) {
this.connection.logger.logStats({
requestId: metadataOptions?.requestId,
scope: MANAGER_NAME.SCAN_MANAGER,
statsType: STATS_TYPE.CONSUMED_CAPACITY,
consumedCapacityData: ConsumedCapacity,
});
}
// recheck if requested items limit is already met, may be other worker
// if so drop the result of current request and return
if (limit && this.itemsFetchedSoFarTotalParallelCount >= limit) {
return {
items: itemsFetched,
cursor,
};
}
itemsFetched = [...itemsFetched, ...Items];
this.itemsFetchedSoFarTotalParallelCount += Items.length;
if (LastEvaluatedKey) {
return this._internalRecursiveScan({
scanInput,
limit,
cursor: LastEvaluatedKey,
itemsFetched,
metadataOptions,
});
}
return {
items: itemsFetched,
cursor: LastEvaluatedKey,
};
}
/**
* Recursively counts items form table with given options
*/
private async _internalRecursiveCount({
scanInput,
cursor,
currentCount = 0,
metadataOptions,
}: {
scanInput: DynamoDB.DocumentClient.ScanInput;
cursor?: DynamoDB.DocumentClient.Key;
currentCount?: number;
metadataOptions?: MetadataOptions;
}): Promise<number> {
const {
Count,
LastEvaluatedKey,
ConsumedCapacity,
} = await this.connection.documentClient
.scan({...scanInput, ExclusiveStartKey: cursor})
.promise();
// stats
if (ConsumedCapacity) {
this.connection.logger.logStats({
requestId: metadataOptions?.requestId,
scope: MANAGER_NAME.SCAN_MANAGER,
statsType: STATS_TYPE.CONSUMED_CAPACITY,
consumedCapacityData: ConsumedCapacity,
});
}
currentCount += Count || 0;
if (LastEvaluatedKey) {
return this._internalRecursiveCount({
scanInput,
cursor: LastEvaluatedKey,
currentCount,
metadataOptions,
});
}
return currentCount;
}
/**
* Simple wrapper to limit number of concurrent calls
* @param promise wraps promise in a limited factory
* @returns
*/
private toLimited<T>(promise: Promise<T>) {
return this.limit(() => promise);
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Budgets } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ConsumptionManagementClient } from "../consumptionManagementClient";
import {
Budget,
BudgetsListNextOptionalParams,
BudgetsListOptionalParams,
BudgetsListResponse,
BudgetsGetOptionalParams,
BudgetsGetResponse,
BudgetsCreateOrUpdateOptionalParams,
BudgetsCreateOrUpdateResponse,
BudgetsDeleteOptionalParams,
BudgetsListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Budgets operations. */
export class BudgetsImpl implements Budgets {
private readonly client: ConsumptionManagementClient;
/**
* Initialize a new instance of the class Budgets class.
* @param client Reference to the service client
*/
constructor(client: ConsumptionManagementClient) {
this.client = client;
}
/**
* Lists all budgets for the defined scope.
* @param scope The scope associated with budget operations. This includes
* '/subscriptions/{subscriptionId}/' for subscription scope,
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
* Department scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
* for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
* for Management Group scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
* for billingProfile scope,
* 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
* for invoiceSection scope.
* @param options The options parameters.
*/
public list(
scope: string,
options?: BudgetsListOptionalParams
): PagedAsyncIterableIterator<Budget> {
const iter = this.listPagingAll(scope, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(scope, options);
}
};
}
private async *listPagingPage(
scope: string,
options?: BudgetsListOptionalParams
): AsyncIterableIterator<Budget[]> {
let result = await this._list(scope, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(scope, continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
scope: string,
options?: BudgetsListOptionalParams
): AsyncIterableIterator<Budget> {
for await (const page of this.listPagingPage(scope, options)) {
yield* page;
}
}
/**
* Lists all budgets for the defined scope.
* @param scope The scope associated with budget operations. This includes
* '/subscriptions/{subscriptionId}/' for subscription scope,
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
* Department scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
* for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
* for Management Group scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
* for billingProfile scope,
* 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
* for invoiceSection scope.
* @param options The options parameters.
*/
private _list(
scope: string,
options?: BudgetsListOptionalParams
): Promise<BudgetsListResponse> {
return this.client.sendOperationRequest(
{ scope, options },
listOperationSpec
);
}
/**
* Gets the budget for the scope by budget name.
* @param scope The scope associated with budget operations. This includes
* '/subscriptions/{subscriptionId}/' for subscription scope,
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
* Department scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
* for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
* for Management Group scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
* for billingProfile scope,
* 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
* for invoiceSection scope.
* @param budgetName Budget Name.
* @param options The options parameters.
*/
get(
scope: string,
budgetName: string,
options?: BudgetsGetOptionalParams
): Promise<BudgetsGetResponse> {
return this.client.sendOperationRequest(
{ scope, budgetName, options },
getOperationSpec
);
}
/**
* The operation to create or update a budget. You can optionally provide an eTag if desired as a form
* of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior
* to your put operation.
* @param scope The scope associated with budget operations. This includes
* '/subscriptions/{subscriptionId}/' for subscription scope,
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
* Department scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
* for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
* for Management Group scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
* for billingProfile scope,
* 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
* for invoiceSection scope.
* @param budgetName Budget Name.
* @param parameters Parameters supplied to the Create Budget operation.
* @param options The options parameters.
*/
createOrUpdate(
scope: string,
budgetName: string,
parameters: Budget,
options?: BudgetsCreateOrUpdateOptionalParams
): Promise<BudgetsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ scope, budgetName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* The operation to delete a budget.
* @param scope The scope associated with budget operations. This includes
* '/subscriptions/{subscriptionId}/' for subscription scope,
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
* Department scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
* for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
* for Management Group scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
* for billingProfile scope,
* 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
* for invoiceSection scope.
* @param budgetName Budget Name.
* @param options The options parameters.
*/
delete(
scope: string,
budgetName: string,
options?: BudgetsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scope, budgetName, options },
deleteOperationSpec
);
}
/**
* ListNext
* @param scope The scope associated with budget operations. This includes
* '/subscriptions/{subscriptionId}/' for subscription scope,
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
* Department scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
* for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
* for Management Group scope,
* '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
* for billingProfile scope,
* 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
* for invoiceSection scope.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
scope: string,
nextLink: string,
options?: BudgetsListNextOptionalParams
): Promise<BudgetsListNextResponse> {
return this.client.sendOperationRequest(
{ scope, nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Consumption/budgets",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BudgetsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.scope],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Budget
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.scope, Parameters.budgetName],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Budget
},
201: {
bodyMapper: Mappers.Budget
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.scope, Parameters.budgetName],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}",
httpMethod: "DELETE",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.scope, Parameters.budgetName],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BudgetsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.scope, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import React, {Component, Fragment, MouseEventHandler} from 'react';
import styled from 'styled-components';
import {FormattedMessage} from 'localization';
import {Button, Input, PanelLabel, SidePanelSection} from 'components/common/styled-components';
import ItemSelector from 'components/common/item-selector/item-selector';
import VisConfigByFieldSelectorFactory from './vis-config-by-field-selector';
import LayerColumnConfigFactory from './layer-column-config';
import LayerTypeSelectorFactory from './layer-type-selector';
import DimensionScaleSelector from './dimension-scale-selector';
import ColorSelector from './color-selector';
import SourceDataSelectorFactory from 'components/side-panel/common/source-data-selector';
import VisConfigSwitchFactory from './vis-config-switch';
import VisConfigSliderFactory from './vis-config-slider';
import LayerConfigGroupFactory, {ConfigGroupCollapsibleContent} from './layer-config-group';
import TextLabelPanelFactory from './text-label-panel';
import {capitalizeFirstLetter} from 'utils/utils';
import {CHANNEL_SCALE_SUPPORTED_FIELDS} from 'constants/default-settings';
import {LAYER_TYPES} from 'layers/types';
import {Layer, LayerBaseConfig, LayerVisConfig} from 'layers';
import {Datasets, NestedPartial, RGBColor} from 'reducers';
import {ColorUI} from 'layers/layer-factory';
import {VisualChannel} from 'layers/base-layer';
import AggregationLayer from 'layers/aggregation-layer';
import {Field} from 'utils/table-utils/kepler-table';
import {toggleModal} from 'actions/ui-state-actions';
import {ColorRange} from 'constants/color-ranges';
import {ActionHandler} from 'actions';
type LayerConfiguratorProps = {
layer: Layer;
datasets: Datasets;
layerTypeOptions: {
id: string;
label: string;
icon: any; //
requireData: any; //
}[];
openModal: ActionHandler<typeof toggleModal>;
updateLayerConfig: (newConfig: Partial<LayerBaseConfig>) => void;
updateLayerType: (newType: string) => void;
updateLayerVisConfig: (newVisConfig: Partial<LayerVisConfig>) => void;
updateLayerVisualChannelConfig: (newConfig: Partial<LayerBaseConfig>, channel: string) => void;
updateLayerColorUI: (prop: string, newConfig: NestedPartial<ColorUI>) => void;
updateLayerTextLabel: (idx: number | 'all', prop: string, value: any) => void;
};
type LayerColorSelectorProps = {
layer: Layer;
onChange: (v: Record<string, RGBColor>) => void;
selectedColor?: RGBColor;
property?: string;
setColorUI: (prop: string, newConfig: NestedPartial<ColorUI>) => void;
};
type ArcLayerColorSelectorProps = {
layer: Layer;
onChangeConfig: (v: {color: RGBColor}) => void;
onChangeVisConfig: (v: {targetColor: RGBColor}) => void;
property?: string;
setColorUI: (prop: string, newConfig: NestedPartial<ColorUI>) => void;
};
type LayerColorRangeSelectorProps = {
layer: Layer;
onChange: (v: Record<string, ColorRange>) => void;
property?: string;
setColorUI: (prop: string, newConfig: NestedPartial<ColorUI>) => void;
};
type ChannelByValueSelectorProps = {
layer: Layer;
channel: VisualChannel;
onChange: (
val: Record<
string,
string | number | boolean | object | readonly (string | number | boolean | object)[] | null
>,
key: string
) => void;
fields: Field[];
description: string;
};
type AggregationSelectorProps = {
channel: VisualChannel;
layer: AggregationLayer;
onChange: (
val: Record<
string,
string | number | boolean | object | readonly (string | number | boolean | object)[] | null
>,
key: string
) => void;
};
const StyledLayerConfigurator = styled.div.attrs({
className: 'layer-panel__config'
})`
position: relative;
margin-top: ${props => props.theme.layerConfiguratorMargin};
padding: ${props => props.theme.layerConfiguratorPadding};
border-left: ${props => props.theme.layerConfiguratorBorder} dashed
${props => props.theme.layerConfiguratorBorderColor};
`;
const StyledLayerVisualConfigurator = styled.div.attrs({
className: 'layer-panel__config__visualC-config'
})`
margin-top: 12px;
`;
export const getLayerFields = (datasets: Datasets, layer: Layer) =>
layer.config?.dataId && datasets[layer.config.dataId] ? datasets[layer.config.dataId].fields : [];
export const getLayerDataset = (datasets: Datasets, layer: Layer) =>
layer.config?.dataId && datasets[layer.config.dataId] ? datasets[layer.config.dataId] : null;
export const getLayerConfiguratorProps = (props: LayerConfiguratorProps) => ({
layer: props.layer,
fields: getLayerFields(props.datasets, props.layer),
onChange: props.updateLayerConfig,
setColorUI: props.updateLayerColorUI
});
export const getVisConfiguratorProps = (props: LayerConfiguratorProps) => ({
layer: props.layer,
fields: getLayerFields(props.datasets, props.layer),
onChange: props.updateLayerVisConfig,
setColorUI: props.updateLayerColorUI
});
export const getLayerChannelConfigProps = (props: LayerConfiguratorProps) => ({
layer: props.layer,
fields: getLayerFields(props.datasets, props.layer),
onChange: props.updateLayerVisualChannelConfig
});
LayerConfiguratorFactory.deps = [
SourceDataSelectorFactory,
VisConfigSliderFactory,
TextLabelPanelFactory,
LayerConfigGroupFactory,
ChannelByValueSelectorFactory,
LayerColumnConfigFactory,
LayerTypeSelectorFactory,
VisConfigSwitchFactory
];
export default function LayerConfiguratorFactory(
SourceDataSelector: ReturnType<typeof SourceDataSelectorFactory>,
VisConfigSlider: ReturnType<typeof VisConfigSliderFactory>,
TextLabelPanel: ReturnType<typeof TextLabelPanelFactory>,
LayerConfigGroup: ReturnType<typeof LayerConfigGroupFactory>,
ChannelByValueSelector: ReturnType<typeof ChannelByValueSelectorFactory>,
LayerColumnConfig: ReturnType<typeof LayerColumnConfigFactory>,
LayerTypeSelector: ReturnType<typeof LayerTypeSelectorFactory>,
VisConfigSwitch: ReturnType<typeof VisConfigSwitchFactory>
): React.ComponentType<LayerConfiguratorProps> {
class LayerConfigurator extends Component<LayerConfiguratorProps> {
_renderPointLayerConfig(props) {
return this._renderScatterplotLayerConfig(props);
}
_renderIconLayerConfig(props) {
return this._renderScatterplotLayerConfig(props);
}
_renderScatterplotLayerConfig({
layer,
visConfiguratorProps,
layerChannelConfigProps,
layerConfiguratorProps
}) {
return (
<StyledLayerVisualConfigurator>
{/* Fill Color */}
<LayerConfigGroup
{...(layer.visConfigSettings.filled || {label: 'layer.color'})}
{...visConfiguratorProps}
collapsible
>
{layer.config.colorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* outline color */}
{layer.type === LAYER_TYPES.point ? (
<LayerConfigGroup
{...layer.visConfigSettings.outline}
{...visConfiguratorProps}
collapsible
>
{layer.config.strokeColorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} property="strokeColorRange" />
) : (
<LayerColorSelector
{...visConfiguratorProps}
selectedColor={layer.config.visConfig.strokeColor}
property="strokeColor"
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.strokeColor}
{...layerChannelConfigProps}
/>
<VisConfigSlider
{...layer.visConfigSettings.thickness}
{...visConfiguratorProps}
disabled={!layer.config.visConfig.outline}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
) : null}
{/* Radius */}
<LayerConfigGroup label={'layer.radius'} collapsible>
{!layer.config.sizeField ? (
<VisConfigSlider
{...layer.visConfigSettings.radius}
{...visConfiguratorProps}
label={false}
disabled={Boolean(layer.config.sizeField)}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.radiusRange}
{...visConfiguratorProps}
label={false}
disabled={!layer.config.sizeField || layer.config.visConfig.fixedRadius}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.size}
{...layerChannelConfigProps}
/>
{layer.config.sizeField ? (
<VisConfigSwitch
{...layer.visConfigSettings.fixedRadius}
{...visConfiguratorProps}
/>
) : null}
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* text label */}
<TextLabelPanel
fields={visConfiguratorProps.fields}
updateLayerTextLabel={this.props.updateLayerTextLabel}
textLabel={layer.config.textLabel}
/>
</StyledLayerVisualConfigurator>
);
}
_renderClusterLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
<LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<AggregationScaleSelector
{...layerConfiguratorProps}
channel={layer.visualChannels.color}
/>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
{layer.visConfigSettings.colorAggregation.condition(layer.config) ? (
<AggregationTypeSelector
{...layer.visConfigSettings.colorAggregation}
{...layerChannelConfigProps}
channel={layer.visualChannels.color}
/>
) : null}
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Cluster Radius */}
<LayerConfigGroup label={'layer.radius'} collapsible>
<VisConfigSlider {...layer.visConfigSettings.clusterRadius} {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<VisConfigSlider {...layer.visConfigSettings.radiusRange} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
</StyledLayerVisualConfigurator>
);
}
_renderHeatmapLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
<LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Radius */}
<LayerConfigGroup label={'layer.radius'}>
<VisConfigSlider
{...layer.visConfigSettings.radius}
{...visConfiguratorProps}
label={false}
/>
</LayerConfigGroup>
{/* Weight */}
<LayerConfigGroup label={'layer.weight'}>
<ChannelByValueSelector
channel={layer.visualChannels.weight}
{...layerChannelConfigProps}
/>
</LayerConfigGroup>
</StyledLayerVisualConfigurator>
);
}
_renderGridLayerConfig(props) {
return this._renderAggregationLayerConfig(props);
}
_renderHexagonLayerConfig(props) {
return this._renderAggregationLayerConfig(props);
}
_renderAggregationLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
const {config} = layer;
const {
visConfig: {enable3d}
} = config;
const elevationByDescription = 'layer.elevationByDescription';
const colorByDescription = 'layer.colorByDescription';
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
<LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<AggregationScaleSelector
{...layerConfiguratorProps}
channel={layer.visualChannels.color}
/>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
{layer.visConfigSettings.colorAggregation.condition(layer.config) ? (
<AggregationTypeSelector
{...layer.visConfigSettings.colorAggregation}
{...layerChannelConfigProps}
description={colorByDescription}
channel={layer.visualChannels.color}
/>
) : null}
{layer.visConfigSettings.percentile &&
layer.visConfigSettings.percentile.condition(layer.config) ? (
<VisConfigSlider
{...layer.visConfigSettings.percentile}
{...visConfiguratorProps}
/>
) : null}
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Cell size */}
<LayerConfigGroup label={'layer.radius'} collapsible>
<VisConfigSlider {...layer.visConfigSettings.worldUnitSize} {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<VisConfigSlider {...layer.visConfigSettings.coverage} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Elevation */}
{layer.visConfigSettings.enable3d ? (
<LayerConfigGroup
{...layer.visConfigSettings.enable3d}
{...visConfiguratorProps}
collapsible
>
<VisConfigSlider
{...layer.visConfigSettings.elevationScale}
{...visConfiguratorProps}
label="layerVisConfigs.heightMultiplier"
/>
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
{...layerChannelConfigProps}
channel={layer.visualChannels.size}
description={elevationByDescription}
disabled={!enable3d}
/>
<AggregationScaleSelector
{...layerConfiguratorProps}
channel={layer.visualChannels.size}
/>
<VisConfigSlider
{...layer.visConfigSettings.sizeRange}
{...visConfiguratorProps}
label="layerVisConfigs.heightRange"
/>
<VisConfigSwitch
{...layer.visConfigSettings.enableElevationZoomFactor}
{...visConfiguratorProps}
label="layerVisConfigs.enableHeightZoomFactor"
/>
{layer.visConfigSettings.sizeAggregation.condition(layer.config) ? (
<AggregationTypeSelector
{...layer.visConfigSettings.sizeAggregation}
{...layerChannelConfigProps}
channel={layer.visualChannels.size}
/>
) : null}
{layer.visConfigSettings.elevationPercentile.condition(layer.config) ? (
<VisConfigSlider
{...layer.visConfigSettings.elevationPercentile}
{...visConfiguratorProps}
/>
) : null}
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
) : null}
</StyledLayerVisualConfigurator>
);
}
// TODO: Shan move these into layer class
_renderHexagonIdLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
{layer.config.colorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Coverage */}
<LayerConfigGroup label={'layer.coverage'} collapsible>
{!layer.config.coverageField ? (
<VisConfigSlider
{...layer.visConfigSettings.coverage}
{...visConfiguratorProps}
label={false}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.coverageRange}
{...visConfiguratorProps}
label={false}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.coverage}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* height */}
<LayerConfigGroup
{...layer.visConfigSettings.enable3d}
{...visConfiguratorProps}
collapsible
>
<ChannelByValueSelector
channel={layer.visualChannels.size}
{...layerChannelConfigProps}
/>
<ConfigGroupCollapsibleContent>
<VisConfigSlider
{...layer.visConfigSettings.elevationScale}
{...visConfiguratorProps}
/>
<VisConfigSlider
{...layer.visConfigSettings.sizeRange}
{...visConfiguratorProps}
label="layerVisConfigs.heightRange"
/>
<VisConfigSwitch
{...layer.visConfigSettings.enableElevationZoomFactor}
{...visConfiguratorProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
</StyledLayerVisualConfigurator>
);
}
_renderArcLayerConfig(args) {
return this._renderLineLayerConfig(args);
}
_renderLineLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
{layer.config.colorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<ArcLayerColorSelector
layer={layer}
setColorUI={layerConfiguratorProps.setColorUI}
onChangeConfig={layerConfiguratorProps.onChange}
onChangeVisConfig={visConfiguratorProps.onChange}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.sourceColor}
{...layerChannelConfigProps}
/>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* thickness */}
<LayerConfigGroup label={'layer.stroke'} collapsible>
{layer.config.sizeField ? (
<VisConfigSlider
{...layer.visConfigSettings.sizeRange}
{...visConfiguratorProps}
disabled={!layer.config.sizeField}
label={false}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.thickness}
{...visConfiguratorProps}
label={false}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.size}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* elevation scale */}
{layer.visConfigSettings.elevationScale ? (
<LayerConfigGroup label="layerVisConfigs.elevationScale" collapsible>
<VisConfigSlider
{...layer.visConfigSettings.elevationScale}
{...visConfiguratorProps}
/>
</LayerConfigGroup>
) : null}
</StyledLayerVisualConfigurator>
);
}
_renderTripLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
const {
meta: {featureTypes = {}}
} = layer;
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
{layer.config.colorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Stroke Width */}
<LayerConfigGroup {...visConfiguratorProps} label="layer.strokeWidth" collapsible>
{layer.config.sizeField ? (
<VisConfigSlider
{...layer.visConfigSettings.sizeRange}
{...visConfiguratorProps}
label={false}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.thickness}
{...visConfiguratorProps}
label={false}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.size}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Trail Length*/}
<LayerConfigGroup
{...visConfiguratorProps}
{...(featureTypes.polygon ? layer.visConfigSettings.stroked : {})}
label="layer.trailLength"
description="layer.trailLengthDescription"
>
<VisConfigSlider
{...layer.visConfigSettings.trailLength}
{...visConfiguratorProps}
label={false}
/>
</LayerConfigGroup>
</StyledLayerVisualConfigurator>
);
}
_renderGeojsonLayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
const {
meta: {featureTypes = {}},
config: {visConfig}
} = layer;
return (
<StyledLayerVisualConfigurator>
{/* Fill Color */}
{featureTypes.polygon || featureTypes.point ? (
<LayerConfigGroup
{...layer.visConfigSettings.filled}
{...visConfiguratorProps}
label="layer.fillColor"
collapsible
>
{layer.config.colorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
) : null}
{/* stroke color */}
<LayerConfigGroup
{...layer.visConfigSettings.stroked}
{...visConfiguratorProps}
label="layer.strokeColor"
collapsible
>
{layer.config.strokeColorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} property="strokeColorRange" />
) : (
<LayerColorSelector
{...visConfiguratorProps}
selectedColor={layer.config.visConfig.strokeColor}
property="strokeColor"
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.strokeColor}
{...layerChannelConfigProps}
/>
<VisConfigSlider
{...layer.visConfigSettings.strokeOpacity}
{...visConfiguratorProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Stroke Width */}
<LayerConfigGroup
{...visConfiguratorProps}
{...(featureTypes.polygon ? layer.visConfigSettings.stroked : {})}
label="layer.strokeWidth"
collapsible
>
{layer.config.sizeField ? (
<VisConfigSlider
{...layer.visConfigSettings.sizeRange}
{...visConfiguratorProps}
label={false}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.thickness}
{...visConfiguratorProps}
label={false}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.size}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Elevation */}
{featureTypes.polygon ? (
<LayerConfigGroup
{...visConfiguratorProps}
{...layer.visConfigSettings.enable3d}
disabled={!visConfig.filled}
collapsible
>
<VisConfigSlider
{...layer.visConfigSettings.elevationScale}
{...visConfiguratorProps}
label={false}
/>
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.height}
{...layerChannelConfigProps}
/>
<VisConfigSwitch
{...layer.visConfigSettings.enableElevationZoomFactor}
{...visConfiguratorProps}
/>
<VisConfigSwitch {...visConfiguratorProps} {...layer.visConfigSettings.wireframe} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
) : null}
{/* Radius */}
{featureTypes.point ? (
<LayerConfigGroup label={'layer.radius'} collapsible>
{!layer.config.radiusField ? (
<VisConfigSlider
{...layer.visConfigSettings.radius}
{...visConfiguratorProps}
label={false}
disabled={Boolean(layer.config.radiusField)}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.radiusRange}
{...visConfiguratorProps}
label={false}
disabled={!layer.config.radiusField}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.radius}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
) : null}
</StyledLayerVisualConfigurator>
);
}
_render3DLayerConfig({layer, visConfiguratorProps}) {
return (
<Fragment>
<LayerConfigGroup label={'layer.3DModel'} collapsible>
<Input
type="file"
accept=".glb,.gltf"
onChange={e => {
if (e.target.files && e.target.files[0]) {
const url = URL.createObjectURL(e.target.files[0]);
visConfiguratorProps.onChange({scenegraph: url});
}
}}
/>
</LayerConfigGroup>
<LayerConfigGroup label={'layer.3DModelOptions'} collapsible>
<VisConfigSlider
{...layer.visConfigSettings.sizeScale}
{...visConfiguratorProps}
disabled={false}
/>
<VisConfigSlider
{...layer.visConfigSettings.angleX}
{...visConfiguratorProps}
disabled={false}
/>
<VisConfigSlider
{...layer.visConfigSettings.angleY}
{...visConfiguratorProps}
disabled={false}
/>
<VisConfigSlider
{...layer.visConfigSettings.angleZ}
{...visConfiguratorProps}
disabled={false}
/>
</LayerConfigGroup>
</Fragment>
);
}
_renderS2LayerConfig({
layer,
visConfiguratorProps,
layerConfiguratorProps,
layerChannelConfigProps
}) {
const {
config: {visConfig}
} = layer;
return (
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup
{...layer.visConfigSettings.filled}
{...visConfiguratorProps}
label="layer.fillColor"
collapsible
>
{layer.config.colorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Stroke */}
<LayerConfigGroup
{...layer.visConfigSettings.stroked}
{...visConfiguratorProps}
label="layer.strokeColor"
collapsible
>
{layer.config.strokeColorField ? (
<LayerColorRangeSelector {...visConfiguratorProps} property="strokeColorRange" />
) : (
<LayerColorSelector
{...visConfiguratorProps}
selectedColor={layer.config.visConfig.strokeColor}
property="strokeColor"
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.strokeColor}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Stroke Width */}
<LayerConfigGroup {...visConfiguratorProps} label="layer.strokeWidth" collapsible>
{layer.config.sizeField ? (
<VisConfigSlider
{...layer.visConfigSettings.sizeRange}
{...visConfiguratorProps}
label={false}
/>
) : (
<VisConfigSlider
{...layer.visConfigSettings.thickness}
{...visConfiguratorProps}
label={false}
/>
)}
<ConfigGroupCollapsibleContent>
<ChannelByValueSelector
channel={layer.visualChannels.size}
{...layerChannelConfigProps}
/>
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
{/* Elevation */}
<LayerConfigGroup
{...visConfiguratorProps}
{...layer.visConfigSettings.enable3d}
disabled={!visConfig.filled}
collapsible
>
<ChannelByValueSelector
channel={layer.visualChannels.height}
{...layerChannelConfigProps}
/>
<VisConfigSlider
{...layer.visConfigSettings.elevationScale}
{...visConfiguratorProps}
label="layerVisConfigs.elevationScale"
/>
<ConfigGroupCollapsibleContent>
<VisConfigSlider
{...layer.visConfigSettings.heightRange}
{...visConfiguratorProps}
label="layerVisConfigs.heightRange"
/>
<VisConfigSwitch
{...layer.visConfigSettings.enableElevationZoomFactor}
{...visConfiguratorProps}
/>
<VisConfigSwitch {...visConfiguratorProps} {...layer.visConfigSettings.wireframe} />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
</StyledLayerVisualConfigurator>
);
}
render() {
const {layer, datasets, updateLayerConfig, layerTypeOptions, updateLayerType} = this.props;
const {fields = [], fieldPairs = undefined} = layer.config.dataId
? datasets[layer.config.dataId]
: {};
const {config} = layer;
const visConfiguratorProps = getVisConfiguratorProps(this.props);
const layerConfiguratorProps = getLayerConfiguratorProps(this.props);
const layerChannelConfigProps = getLayerChannelConfigProps(this.props);
const dataset = getLayerDataset(datasets, layer);
const renderTemplate = layer.type && `_render${capitalizeFirstLetter(layer.type)}LayerConfig`;
return (
<StyledLayerConfigurator>
{layer.layerInfoModal ? (
<HowToButton onClick={() => this.props.openModal(layer.layerInfoModal)} />
) : null}
<LayerConfigGroup label={'layer.basic'} collapsible expanded={!layer.hasAllColumns()}>
<LayerTypeSelector
datasets={datasets}
layer={layer}
layerTypeOptions={layerTypeOptions}
// @ts-ignore
onSelect={updateLayerType}
/>
{Object.keys(datasets).length > 1 && (
<SourceDataSelector
datasets={datasets}
id={layer.id}
dataId={config.dataId}
// @ts-ignore
onSelect={(value: string) => updateLayerConfig({dataId: value})}
/>
)}
<LayerColumnConfig
columnPairs={layer.columnPairs}
columns={layer.config.columns}
assignColumnPairs={layer.assignColumnPairs.bind(layer)}
assignColumn={layer.assignColumn.bind(layer)}
// @ts-ignore
columnLabels={layer.columnLabels}
fields={fields}
fieldPairs={fieldPairs}
updateLayerConfig={updateLayerConfig}
/>
</LayerConfigGroup>
{renderTemplate &&
this[renderTemplate] &&
this[renderTemplate]({
layer,
dataset,
visConfiguratorProps,
layerChannelConfigProps,
layerConfiguratorProps
})}
</StyledLayerConfigurator>
);
}
}
return LayerConfigurator;
}
/*
* Componentize config component into pure functional components
*/
const StyledHowToButton = styled.div`
position: absolute;
right: 12px;
top: -4px;
`;
export const HowToButton = ({onClick}: {onClick: MouseEventHandler}) => (
<StyledHowToButton>
<Button link small onClick={onClick}>
<FormattedMessage id={'layerConfiguration.howTo'} />
</Button>
</StyledHowToButton>
);
export const LayerColorSelector = ({
layer,
onChange,
selectedColor,
property = 'color',
setColorUI
}: LayerColorSelectorProps) => (
<SidePanelSection>
<ColorSelector
colorSets={[
{
selectedColor: selectedColor || layer.config.color,
setColor: (rgbValue: RGBColor) => onChange({[property]: rgbValue})
}
]}
colorUI={layer.config.colorUI[property]}
setColorUI={newConfig => setColorUI(property, newConfig)}
/>
</SidePanelSection>
);
export const ArcLayerColorSelector = ({
layer,
onChangeConfig,
onChangeVisConfig,
property = 'color',
setColorUI
}: ArcLayerColorSelectorProps) => (
<SidePanelSection>
<ColorSelector
colorSets={[
{
selectedColor: layer.config.color,
setColor: (rgbValue: RGBColor) => onChangeConfig({color: rgbValue}),
label: 'Source'
},
{
selectedColor: layer.config.visConfig.targetColor || layer.config.color,
setColor: (rgbValue: RGBColor) => onChangeVisConfig({targetColor: rgbValue}),
label: 'Target'
}
]}
colorUI={layer.config.colorUI[property]}
setColorUI={newConfig => setColorUI(property, newConfig)}
/>
</SidePanelSection>
);
export const LayerColorRangeSelector = ({
layer,
onChange,
property = 'colorRange',
setColorUI
}: LayerColorRangeSelectorProps) => (
<SidePanelSection>
<ColorSelector
colorSets={[
{
selectedColor: layer.config.visConfig[property],
isRange: true,
setColor: (colorRange: ColorRange) => onChange({[property]: colorRange})
}
]}
colorUI={layer.config.colorUI[property]}
setColorUI={newConfig => setColorUI(property, newConfig)}
/>
</SidePanelSection>
);
ChannelByValueSelectorFactory.deps = [VisConfigByFieldSelectorFactory];
export function ChannelByValueSelectorFactory(
VisConfigByFieldSelector: ReturnType<typeof VisConfigByFieldSelectorFactory>
) {
const ChannelByValueSelector = ({
layer,
channel,
onChange,
fields,
description
}: ChannelByValueSelectorProps) => {
const {
channelScaleType,
field,
key,
property,
scale,
defaultMeasure,
supportedFieldTypes
} = channel;
const channelSupportedFieldTypes =
supportedFieldTypes || CHANNEL_SCALE_SUPPORTED_FIELDS[channelScaleType];
const supportedFields = fields.filter(({type}) => channelSupportedFieldTypes.includes(type));
const scaleOptions = layer.getScaleOptions(channel.key);
const showScale = !layer.isAggregated && layer.config[scale] && scaleOptions.length > 1;
const defaultDescription = 'layerConfiguration.defaultDescription';
return (
<VisConfigByFieldSelector
channel={channel.key}
description={description || defaultDescription}
fields={supportedFields}
id={layer.id}
key={`${key}-channel-selector`}
property={property}
placeholder={defaultMeasure || 'placeholder.selectField'}
scaleOptions={scaleOptions}
scaleType={scale ? layer.config[scale] : null}
selectedField={layer.config[field]}
showScale={showScale}
updateField={val => onChange({[field]: val}, key)}
updateScale={val => onChange({[scale]: val}, key)}
/>
);
};
return ChannelByValueSelector;
}
export const AggregationScaleSelector = ({channel, layer, onChange}: AggregationSelectorProps) => {
const {scale, key} = channel;
const scaleOptions = layer.getScaleOptions(key);
return Array.isArray(scaleOptions) && scaleOptions.length > 1 ? (
<DimensionScaleSelector
label={`${key} Scale`}
options={scaleOptions}
scaleType={layer.config[scale]}
onSelect={val => onChange({[scale]: val}, key)}
/>
) : null;
};
export const AggregationTypeSelector = ({channel, layer, onChange}: AggregationSelectorProps) => {
const {field, aggregation, key} = channel;
const selectedField = layer.config[field];
const {visConfig} = layer.config;
// aggregation should only be selectable when field is selected
const aggregationOptions = layer.getAggregationOptions(key);
return (
<SidePanelSection>
<PanelLabel>
<FormattedMessage id={'layer.aggregateBy'} values={{field: selectedField.name}} />
</PanelLabel>
<ItemSelector
selectedItems={visConfig[aggregation as string]}
options={aggregationOptions}
multiSelect={false}
searchable={false}
onChange={value =>
onChange(
{
visConfig: {
...layer.config.visConfig,
[aggregation as string]: value
}
},
channel.key
)
}
/>
</SidePanelSection>
);
};
/* eslint-enable max-params */ | the_stack |
import Vue, { VueConstructor } from "vue"
import { App } from "vue3" // vue3
interface vueUnicomGather {
[propName: string]: VueUnicom // 任意类型
}
// #id 存放id的unicom对象
let unicomGroupByID: vueUnicomGather = {}
/**
* 寄存target(vm)
* @param target
* @param newId
* @param oldId
*/
function updateUnicomGroupByID(target: VueUnicom, newId: string, oldId: string): void {
// 更新 id 触发更新
if (oldId && unicomGroupByID[oldId] == target) {
delete unicomGroupByID[oldId]
}
if (newId) {
unicomGroupByID[newId] = target
}
}
interface vueUnicomGatherName {
[propName: string]: Array<VueUnicom> // 任意类型
}
// @name 存放name的数组对象
let unicomGroupByName: vueUnicomGatherName = {}
/**
* 通过name存放 target(vm)
* @param target
* @param name
*/
function addUnicomGroupByNameOne(target: VueUnicom, name: string): void {
// 加入一个name
let unicoms = unicomGroupByName[name]
if (!unicoms) {
unicoms = unicomGroupByName[name] = []
}
if (unicoms.indexOf(target) < 0) {
unicoms.push(target)
}
}
/**
* 更新unicom name命名
* @param target
* @param newName
* @param oldNamegroup
*/
function updateUnicomGroupByName(target: VueUnicom, newName: Array<string>, oldName: Array<string>) {
// 某个unicom对象更新 name
if (oldName) {
// 移除所有旧的
oldName.forEach(function(name) {
let unicoms = unicomGroupByName[name]
if (unicoms) {
let index = unicoms.indexOf(target)
if (index > -1) {
unicoms.splice(index, 1)
}
}
})
}
if (newName) {
// 加入新的
newName.forEach(function(name) {
addUnicomGroupByNameOne(target, name)
})
}
}
// @all 所有的unicom对象集合,发布指令是待用
let unicomGroup: Array<VueUnicom> = []
function addUnicomGroup(target: VueUnicom): void {
// 添加
unicomGroup.push(target)
}
function removeUnicomGroup(target: VueUnicom): void {
// 移除
let index = unicomGroup.indexOf(target)
if (index > -1) {
unicomGroup.splice(index, 1)
}
}
// 发布指令时产生的事件的类
export class VueUnicomEvent<D = any, T = any> {
from: any
target: T
data: D;
[propName: string]: any
constructor(from: any, args: Array<any>) {
// 来自
this.from = from || null
// 目标绑定的对象,vue中代表vue的实例
this.target = (from && from.target) || null
// 第一号数据
this.data = args[0]
// 多个数据 使用 $index 表示
args.forEach((arg, index) => {
this["$" + (index + 1)] = arg
})
}
}
export type VueUnicomEmitBack<D, T = any> = VueUnicomEvent<D, T> | VueUnicom | VueUnicom[]
function _unicomEmit<D, T extends Vue = Vue>(self: T, query: string, data?: D, args: any[] = []): VueUnicomEmitBack<D, T> {
// 以下是全局触发发布
let type: string = ""
let target: string = ""
let instruct: string = ""
instruct = query.replace(/([@#])([^@#]*)$/, function(s0, s1, s2) {
target = s2
type = s1
return ""
})
let targetUnicom: Array<VueUnicom> = []
if (type == "#") {
// 目标唯一
let one = unicomGroupByID[target]
if (!instruct) {
// 只是获取
return one
}
if (one) {
targetUnicom.push(one)
}
} else if (type == "@") {
// 目标是个分组
let group = unicomGroupByName[target]
if (!instruct) {
// 只是获取
return group
}
if (group) {
targetUnicom.push(...group)
}
} else {
targetUnicom.push(...unicomGroup)
}
args.unshift(data)
let uniEvent = new VueUnicomEvent<D, T>(self, args)
targetUnicom.forEach(function(emit) {
// 每个都触发一遍
emit.emit<VueUnicomEvent>(instruct, uniEvent)
})
return uniEvent
}
export function unicomEmit<D>(query: string, data?: D, ...args: any): VueUnicomEmitBack<D, any> {
return _unicomEmit<D, any>(null, query, data, args)
}
// 监控数据
let monitorArr: Array<[string, string, Function, VueUnicom?]> = []
function monitorExec(that: VueUnicom) {
for (let i = 0; i < monitorArr.length; i += 1) {
let [type, target, callback] = monitorArr[i]
if ((type == "#" && that.id == target) || (type == "@" && that.group.indexOf(target) > -1)) {
// 运行监控回调
callback(that)
}
}
}
export interface IVueUnicomArg {
id?: string
group?: string | Array<string>
target?: any
}
interface vueUnicomInstruct {
[propName: string]: Function[] // 任意类型
}
export interface IVueUnicomBackOption<T> {
[propName: string]: <D>(arg: VueUnicomEvent<D, T>) => void
}
declare module "vue/types/options" {
interface ComponentOptions<V extends Vue> {
unicomId?: string
unicomName?: string | string[]
unicom?: IVueUnicomBackOption<V>
}
}
declare module "vue/types/vue" {
interface Vue {
$unicom: <D>(query: string, data?: D, ...args: any) => VueUnicomEmitBack<D, Vue | App>
// eslint-disable-next-line
_unicom_data_?: vueUnicomData
}
}
declare module "vue" {
// vue3
interface ComponentCustomOptions {
unicomId?: string
unicomName?: string | string[]
unicom?: IVueUnicomBackOption<Vue | App>
}
interface ComponentCustomProperties {
$unicom: <D>(query: string, data?: D, ...args: any) => VueUnicomEmitBack<D, Vue | App>
// eslint-disable-next-line
_unicom_data_?: vueUnicomData
}
}
// 通讯基础类
export class VueUnicom {
static install = vueUnicomInstall
// 事件存放
protected _instruct_: vueUnicomInstruct = {}
// 绑定目标 可以是vue的vm 也可以是任意
target: any
// 唯一的id
id: string = ""
// 属于的分组
group: Array<string>
static emit = unicomEmit
// 私有属性
// eslint-disable-next-line
private _monitor_back_: null | ReturnType<typeof setTimeout> = null
constructor({ id, group, target }: IVueUnicomArg = {}) {
let _instruct_ = this._instruct_
this._instruct_ = {}
if (_instruct_) {
// 克隆一份 事件
// 通过 Unicom.prototype.on() 会把事件写入 Unicom.prototype._instruct_
// 所以要重写,防止全局冲突
for (let n in _instruct_) {
let arr: Function[] = []
arr.push(...(_instruct_[n] as Function[]))
this._instruct_[n] = arr
}
}
// 绑定的目标对象
this.target = target
// 分组
this.group = []
if (id) {
this.setId(id)
}
if (group) {
this.setGroup(group)
}
// 将实例加入到单例的队列
addUnicomGroup(this)
// 查找监控中是否被监控中
this.monitorBack()
}
// 延迟合并执行
monitorBack(): VueUnicom {
clearTimeout(this._monitor_back_)
// eslint-disable-next-line
this._monitor_back_ = setTimeout(() => {
monitorExec(this)
}, 1)
return this
}
// 监听目标创建
monitor(instruct: string, callback: Function): VueUnicom {
let type = instruct.slice(0, 1)
let target = instruct.slice(1, instruct.length)
monitorArr.push([type, target, callback, this])
return this
}
// 销毁监听
monitorOff(instruct?: string, callback?: Function): VueUnicom {
for (let i = 0; i < monitorArr.length; ) {
let [type, target, fn, self] = monitorArr[i]
if (self == this && (!instruct || instruct == type + target) && (!callback || callback == fn)) {
monitorArr.splice(i, 1)
continue
}
i += 1
}
return this
}
// 销毁
destroy(): void {
// 销毁队列
removeUnicomGroup(this)
// 移除
updateUnicomGroupByID(this, "", this.id)
updateUnicomGroupByName(this, [], this.group)
// 监控销毁
this.monitorOff()
// 订阅销毁
this.off()
}
// 唯一标识
setId(id: string): VueUnicom {
if (this.id != id) {
updateUnicomGroupByID(this, id, this.id)
this.id = id
// 运行延后执行
this.monitorBack()
}
return this
}
// 分组
setGroup(group: string | string[]) {
if (typeof group == "string") {
this.group.push(group)
addUnicomGroupByNameOne(this, group)
return this
}
// 重新更新
updateUnicomGroupByName(this, group, this.group)
this.group = group
// 运行延后执行
this.monitorBack()
return this
}
has(type: string): boolean {
let instruct: Function[] = (this._instruct_ || {})[type]
return !!(instruct && instruct.length > 0)
}
// 订阅消息
on<D = any, T = any>(type: string, fn: (arg: VueUnicomEvent<D, T>) => void): VueUnicom {
let instruct = this._instruct_ || (this._instruct_ = {})
instruct[type] || (instruct[type] = [])
instruct[type].push(fn)
return this
}
// 移除订阅
off(type?: string, fn?: Function): VueUnicom {
let instruct = this._instruct_
if (instruct) {
if (fn) {
let es = instruct[type as string]
if (es) {
let index = es.indexOf(fn)
if (index > -1) {
es.splice(index, 1)
}
if (es.length == 0) {
delete instruct[type as string]
}
}
} else if (type) {
delete instruct[type]
} else {
delete this._instruct_
}
}
return this
}
// 触发订阅
emit<D>(query: string, data?: D, ...args: any): VueUnicomEmitBack<D> {
if (data && data instanceof VueUnicomEvent) {
// 只需要负责自己
let es = (this._instruct_ && this._instruct_[query]) || []
es.forEach(channelFn => {
channelFn.call(this.target, data)
})
return data
}
// 以下是全局触发发布
return _unicomEmit<D>(this.target, query, data, args)
}
}
// vue 安装插槽
let unicomInstalled: boolean = false
// vue中指令
interface vueInstruct {
[propName: string]: (arg: VueUnicomEvent) => void
}
// vue临时存储数据
interface vueUnicomData {
isIgnore: boolean
// 分组
initGroup?: Array<string>
// 指令
instructs?: Array<vueInstruct>
// 绑定的unicom对象
unicom?: VueUnicom
}
export function vueUnicomInstall(V: VueConstructor | App, { useProps = true } = {}) {
if (unicomInstalled) {
// 防止重复install
return
}
unicomInstalled = true
let name = "unicom"
function uniconExe(this: any, query: string, ...args: any) {
return this._unicom_data_.unicom.emit(query, ...args)
}
let is3 = V.version.indexOf("3") == 0
let destroyed = "destroyed"
if (is3) {
destroyed = "unmounted"
let vA = V as App
vA.config.globalProperties["$" + name] = uniconExe
} else {
// 添加原型方法
let vV = V as VueConstructor
vV.prototype["$" + name] = uniconExe
}
// unicom-id
let unicomIdName = name + "Id"
// 分组 unicom-name
let unicomGroupName = name + "Name"
// 组合分组
function getGroup(target: any) {
let unicomData = target._unicom_data_
let names = target[unicomGroupName] || []
return unicomData.initGroup.concat(names)
}
let mixin = {
// 创建的时候,加入事件机制
beforeCreate() {
// 屏蔽不需要融合的 节点
let isIgnore = !is3 && (!this.$vnode || /-transition$/.test(this.$vnode.tag as string))
// unicomData 数据存放
let unicomData: vueUnicomData = {
// 不需要,忽略
isIgnore
}
// eslint-disable-next-line
this._unicom_data_ = unicomData
if (isIgnore) {
return
}
let opt: any = this.$options
unicomData.initGroup = opt[unicomGroupName] || []
unicomData.instructs = opt[name] || []
// 触发器
// unicomData.self = new Unicom({target: this})
},
created(this: any) {
let unicomData = this._unicom_data_ as vueUnicomData
if (unicomData.isIgnore) {
// 忽略
return
}
// 初始化
let unicom = (unicomData.unicom = new VueUnicom({ target: this, id: this[unicomIdName], group: getGroup(this) }))
// 订阅事件
let instructs = unicomData.instructs || []
instructs.forEach(function(subs) {
for (let n in subs) {
unicom.on(n, subs[n] as any)
}
})
},
// 全局混合, 销毁实例的时候,销毁事件
[destroyed](this: any) {
let unicomData = this._unicom_data_ as vueUnicomData
if (unicomData.isIgnore) {
// 忽略
return
}
// 销毁 unicom 对象
let unicom = unicomData.unicom
if (unicom) {
unicom.destroy()
}
}
}
if (useProps) {
Object.assign(mixin, {
props: {
// 命名
[unicomIdName]: {
type: String,
default: ""
},
// 分组
[unicomGroupName]: {
type: [String, Array],
default: ""
}
},
watch: {
[unicomIdName](nv) {
let ud = this._unicom_data_ as any
if (ud && ud.unicom) {
ud.unicom.setId(nv)
}
},
[unicomGroupName]() {
let ud = this._unicom_data_ as any
if (ud && ud.unicom) {
ud.unicom.setGroup(getGroup(this))
}
}
}
})
}
// 全局混入 vue
V.mixin(mixin)
interface unicomInObj {
[propName: string]: (arg: VueUnicomEvent) => VueUnicomEvent
}
// 自定义属性合并策略
let merge = V.config.optionMergeStrategies
merge[name] = function(parentVal?: unicomInObj[], childVal?: unicomInObj) {
let arr = parentVal || []
if (childVal) {
arr.push(childVal)
}
return arr
}
merge[unicomGroupName] = function(parentVal?: string[], childVal?: string | string[]) {
let arr = parentVal || []
if (childVal) {
if (typeof childVal == "string") {
arr.push(childVal)
} else {
arr.push(...childVal)
}
}
return arr
}
}
export default VueUnicom | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { KeySet } from '../ojkeyset';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojSunburst<K, D extends ojSunburst.Node<K> | any> extends dvtBaseComponent<ojSunburstSettableProperties<K, D>> {
animationDuration?: number;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
animationUpdateColor?: string;
as?: string;
colorLabel?: string;
data: DataProvider<K, D> | null;
displayLevels?: number;
drilling?: 'on' | 'off';
expanded?: KeySet<K>;
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightMode?: 'categories' | 'descendants';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
hoverBehaviorDelay?: number;
nodeDefaults?: {
borderColor?: string;
borderWidth?: number;
hoverColor?: string;
labelDisplay?: 'horizontal' | 'rotated' | 'off' | 'auto';
labelHalign?: 'inner' | 'outer' | 'center';
labelMinLength?: number;
labelStyle?: Partial<CSSStyleDeclaration>;
selectedInnerColor?: string;
selectedOuterColor?: string;
showDisclosure?: 'on' | 'off';
};
rootNode?: any;
rootNodeContent?: {
renderer: ((context: ojSunburst.RootNodeContext<K, D>) => ({
insert: Element | string;
}));
};
rotation?: 'off' | 'on';
selection?: any[];
selectionMode?: 'none' | 'single' | 'multiple';
sizeLabel?: string;
sorting?: 'on' | 'off';
startAngle?: number;
tooltip?: {
renderer: ((context: ojSunburst.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelColor?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tooltipCollapse?: string;
tooltipExpand?: string;
};
addEventListener<T extends keyof ojSunburstEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojSunburstEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojSunburstSettableProperties<K, D>>(property: T): ojSunburst<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSunburstSettableProperties<K, D>>(property: T, value: ojSunburstSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSunburstSettableProperties<K, D>>): void;
setProperties(properties: ojSunburstSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojSunburst.NodeContext | null;
}
export namespace ojSunburst {
interface ojBeforeCollapse<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojBeforeDrill<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojBeforeExpand<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojCollapse<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojDrill<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojExpand<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojRotateInput extends CustomEvent<{
value: number;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type animationUpdateColorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationUpdateColor"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type colorLabelChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["colorLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type displayLevelsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["displayLevels"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type expandedChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["expanded"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightModeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["highlightMode"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorDelayChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["hoverBehaviorDelay"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeDefaultsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["nodeDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type rootNodeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["rootNode"]>;
// tslint:disable-next-line interface-over-type-literal
type rootNodeContentChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["rootNodeContent"]>;
// tslint:disable-next-line interface-over-type-literal
type rotationChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["rotation"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type sizeLabelChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["sizeLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type sortingChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["sorting"]>;
// tslint:disable-next-line interface-over-type-literal
type startAngleChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["startAngle"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends Node<K> | any> = dvtBaseComponent.trackResizeChanged<ojSunburstSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type DataContext = {
color: string;
label: string;
selected: boolean;
size: number;
tooltip: string;
};
// tslint:disable-next-line interface-over-type-literal
type Node<K, D = any> = {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
drilling?: 'inherit' | 'off' | 'on';
id?: K;
label?: string;
labelDisplay?: 'auto' | 'horizontal' | 'off' | 'rotated';
labelHalign?: 'center' | 'inner' | 'outer';
labelStyle?: Partial<CSSStyleDeclaration>;
nodes?: Array<Node<K>>;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
radius?: number;
selectable?: 'auto' | 'off';
shortDesc?: (string | ((context: NodeShortDescContext<K, D>) => string));
showDisclosure?: 'inherit' | 'off' | 'on';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
indexPath: number[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeShortDescContext<K, D> = {
data: Node<K>;
id: K;
itemData: D;
label: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
parentData: any[];
parentKey: any;
};
// tslint:disable-next-line interface-over-type-literal
type RootNodeContext<K, D> = {
componentElement: Element;
data: Node<K>;
id: K;
innerBounds: {
height: number;
width: number;
x: number;
y: number;
};
itemData: D;
outerBounds: {
height: number;
width: number;
x: number;
y: number;
};
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D> = {
color: string;
componentElement: Element;
data: Node<K>;
id: K;
itemData: D;
label: string;
parentElement: Element;
radius: number;
value: number;
};
}
export interface ojSunburstEventMap<K, D extends ojSunburst.Node<K> | any> extends dvtBaseComponentEventMap<ojSunburstSettableProperties<K, D>> {
'ojBeforeCollapse': ojSunburst.ojBeforeCollapse<K, D>;
'ojBeforeDrill': ojSunburst.ojBeforeDrill<K, D>;
'ojBeforeExpand': ojSunburst.ojBeforeExpand<K, D>;
'ojCollapse': ojSunburst.ojCollapse<K, D>;
'ojDrill': ojSunburst.ojDrill<K, D>;
'ojExpand': ojSunburst.ojExpand<K, D>;
'ojRotateInput': ojSunburst.ojRotateInput;
'animationDurationChanged': JetElementCustomEvent<ojSunburst<K, D>["animationDuration"]>;
'animationOnDataChangeChanged': JetElementCustomEvent<ojSunburst<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojSunburst<K, D>["animationOnDisplay"]>;
'animationUpdateColorChanged': JetElementCustomEvent<ojSunburst<K, D>["animationUpdateColor"]>;
'asChanged': JetElementCustomEvent<ojSunburst<K, D>["as"]>;
'colorLabelChanged': JetElementCustomEvent<ojSunburst<K, D>["colorLabel"]>;
'dataChanged': JetElementCustomEvent<ojSunburst<K, D>["data"]>;
'displayLevelsChanged': JetElementCustomEvent<ojSunburst<K, D>["displayLevels"]>;
'drillingChanged': JetElementCustomEvent<ojSunburst<K, D>["drilling"]>;
'expandedChanged': JetElementCustomEvent<ojSunburst<K, D>["expanded"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojSunburst<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojSunburst<K, D>["highlightMatch"]>;
'highlightModeChanged': JetElementCustomEvent<ojSunburst<K, D>["highlightMode"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojSunburst<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojSunburst<K, D>["hoverBehavior"]>;
'hoverBehaviorDelayChanged': JetElementCustomEvent<ojSunburst<K, D>["hoverBehaviorDelay"]>;
'nodeDefaultsChanged': JetElementCustomEvent<ojSunburst<K, D>["nodeDefaults"]>;
'rootNodeChanged': JetElementCustomEvent<ojSunburst<K, D>["rootNode"]>;
'rootNodeContentChanged': JetElementCustomEvent<ojSunburst<K, D>["rootNodeContent"]>;
'rotationChanged': JetElementCustomEvent<ojSunburst<K, D>["rotation"]>;
'selectionChanged': JetElementCustomEvent<ojSunburst<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojSunburst<K, D>["selectionMode"]>;
'sizeLabelChanged': JetElementCustomEvent<ojSunburst<K, D>["sizeLabel"]>;
'sortingChanged': JetElementCustomEvent<ojSunburst<K, D>["sorting"]>;
'startAngleChanged': JetElementCustomEvent<ojSunburst<K, D>["startAngle"]>;
'tooltipChanged': JetElementCustomEvent<ojSunburst<K, D>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojSunburst<K, D>["touchResponse"]>;
'trackResizeChanged': JetElementCustomEvent<ojSunburst<K, D>["trackResize"]>;
}
export interface ojSunburstSettableProperties<K, D extends ojSunburst.Node<K> | any> extends dvtBaseComponentSettableProperties {
animationDuration?: number;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
animationUpdateColor?: string;
as?: string;
colorLabel?: string;
data: DataProvider<K, D> | null;
displayLevels?: number;
drilling?: 'on' | 'off';
expanded?: KeySet<K>;
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightMode?: 'categories' | 'descendants';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
hoverBehaviorDelay?: number;
nodeDefaults?: {
borderColor?: string;
borderWidth?: number;
hoverColor?: string;
labelDisplay?: 'horizontal' | 'rotated' | 'off' | 'auto';
labelHalign?: 'inner' | 'outer' | 'center';
labelMinLength?: number;
labelStyle?: Partial<CSSStyleDeclaration>;
selectedInnerColor?: string;
selectedOuterColor?: string;
showDisclosure?: 'on' | 'off';
};
rootNode?: any;
rootNodeContent?: {
renderer: ((context: ojSunburst.RootNodeContext<K, D>) => ({
insert: Element | string;
}));
};
rotation?: 'off' | 'on';
selection?: any[];
selectionMode?: 'none' | 'single' | 'multiple';
sizeLabel?: string;
sorting?: 'on' | 'off';
startAngle?: number;
tooltip?: {
renderer: ((context: ojSunburst.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelColor?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tooltipCollapse?: string;
tooltipExpand?: string;
};
}
export interface ojSunburstSettablePropertiesLenient<K, D extends ojSunburst.Node<K> | any> extends Partial<ojSunburstSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojSunburstNode<K = any, D = any> extends dvtBaseComponent<ojSunburstNodeSettableProperties<K, D>> {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
drilling?: 'on' | 'off' | 'inherit';
label?: string;
labelDisplay?: 'horizontal' | 'rotated' | 'off' | 'auto';
labelHalign?: 'inner' | 'outer' | 'center';
labelStyle?: Partial<CSSStyleDeclaration>;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
radius?: number;
selectable?: 'off' | 'auto';
shortDesc?: (string | ((context: ojSunburst.NodeShortDescContext<K, D>) => string));
showDisclosure?: 'on' | 'off' | 'inherit';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value: number;
addEventListener<T extends keyof ojSunburstNodeEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojSunburstNodeEventMap<K, D>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojSunburstNodeSettableProperties<K, D>>(property: T): ojSunburstNode<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSunburstNodeSettableProperties<K, D>>(property: T, value: ojSunburstNodeSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSunburstNodeSettableProperties<K, D>>): void;
setProperties(properties: ojSunburstNodeSettablePropertiesLenient<K, D>): void;
}
export namespace ojSunburstNode {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelDisplayChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["labelDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type labelHalignChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["labelHalign"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type radiusChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["radius"]>;
// tslint:disable-next-line interface-over-type-literal
type selectableChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["selectable"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type showDisclosureChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["showDisclosure"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["value"]>;
}
export interface ojSunburstNodeEventMap<K = any, D = any> extends dvtBaseComponentEventMap<ojSunburstNodeSettableProperties<K, D>> {
'borderColorChanged': JetElementCustomEvent<ojSunburstNode<K, D>["borderColor"]>;
'borderWidthChanged': JetElementCustomEvent<ojSunburstNode<K, D>["borderWidth"]>;
'categoriesChanged': JetElementCustomEvent<ojSunburstNode<K, D>["categories"]>;
'colorChanged': JetElementCustomEvent<ojSunburstNode<K, D>["color"]>;
'drillingChanged': JetElementCustomEvent<ojSunburstNode<K, D>["drilling"]>;
'labelChanged': JetElementCustomEvent<ojSunburstNode<K, D>["label"]>;
'labelDisplayChanged': JetElementCustomEvent<ojSunburstNode<K, D>["labelDisplay"]>;
'labelHalignChanged': JetElementCustomEvent<ojSunburstNode<K, D>["labelHalign"]>;
'labelStyleChanged': JetElementCustomEvent<ojSunburstNode<K, D>["labelStyle"]>;
'patternChanged': JetElementCustomEvent<ojSunburstNode<K, D>["pattern"]>;
'radiusChanged': JetElementCustomEvent<ojSunburstNode<K, D>["radius"]>;
'selectableChanged': JetElementCustomEvent<ojSunburstNode<K, D>["selectable"]>;
'shortDescChanged': JetElementCustomEvent<ojSunburstNode<K, D>["shortDesc"]>;
'showDisclosureChanged': JetElementCustomEvent<ojSunburstNode<K, D>["showDisclosure"]>;
'svgClassNameChanged': JetElementCustomEvent<ojSunburstNode<K, D>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojSunburstNode<K, D>["svgStyle"]>;
'valueChanged': JetElementCustomEvent<ojSunburstNode<K, D>["value"]>;
}
export interface ojSunburstNodeSettableProperties<K = any, D = any> extends dvtBaseComponentSettableProperties {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
drilling?: 'on' | 'off' | 'inherit';
label?: string;
labelDisplay?: 'horizontal' | 'rotated' | 'off' | 'auto';
labelHalign?: 'inner' | 'outer' | 'center';
labelStyle?: Partial<CSSStyleDeclaration>;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
radius?: number;
selectable?: 'off' | 'auto';
shortDesc?: (string | ((context: ojSunburst.NodeShortDescContext<K, D>) => string));
showDisclosure?: 'on' | 'off' | 'inherit';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value: number;
}
export interface ojSunburstNodeSettablePropertiesLenient<K = any, D = any> extends Partial<ojSunburstNodeSettableProperties<K, D>> {
[key: string]: any;
}
export type SunburstElement<K, D extends ojSunburst.Node<K> | any> = ojSunburst<K, D>;
export type SunburstNodeElement<K = any, D = any> = ojSunburstNode<K, D>;
export namespace SunburstElement {
interface ojBeforeCollapse<K, D> extends CustomEvent<{
data: ojSunburst.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojBeforeDrill<K, D> extends CustomEvent<{
data: ojSunburst.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojBeforeExpand<K, D> extends CustomEvent<{
data: ojSunburst.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojCollapse<K, D> extends CustomEvent<{
data: ojSunburst.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojDrill<K, D> extends CustomEvent<{
data: ojSunburst.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojExpand<K, D> extends CustomEvent<{
data: ojSunburst.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojRotateInput extends CustomEvent<{
value: number;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type animationUpdateColorChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["animationUpdateColor"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type colorLabelChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["colorLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type displayLevelsChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["displayLevels"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type expandedChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["expanded"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightModeChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["highlightMode"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorDelayChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["hoverBehaviorDelay"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeDefaultsChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["nodeDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type rootNodeChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["rootNode"]>;
// tslint:disable-next-line interface-over-type-literal
type rootNodeContentChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["rootNodeContent"]>;
// tslint:disable-next-line interface-over-type-literal
type rotationChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["rotation"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type sizeLabelChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["sizeLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type sortingChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["sorting"]>;
// tslint:disable-next-line interface-over-type-literal
type startAngleChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["startAngle"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends ojSunburst.Node<K> | any> = JetElementCustomEvent<ojSunburst<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojSunburst.Node<K> | any> = dvtBaseComponent.trackResizeChanged<ojSunburstSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type DataContext = {
color: string;
label: string;
selected: boolean;
size: number;
tooltip: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
indexPath: number[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
parentData: any[];
parentKey: any;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D> = {
color: string;
componentElement: Element;
data: ojSunburst.Node<K>;
id: K;
itemData: D;
label: string;
parentElement: Element;
radius: number;
value: number;
};
}
export namespace SunburstNodeElement {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelDisplayChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["labelDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type labelHalignChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["labelHalign"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type radiusChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["radius"]>;
// tslint:disable-next-line interface-over-type-literal
type selectableChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["selectable"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type showDisclosureChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["showDisclosure"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any, D = any> = JetElementCustomEvent<ojSunburstNode<K, D>["value"]>;
}
export interface SunburstIntrinsicProps extends Partial<Readonly<ojSunburstSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojBeforeCollapse?: (value: ojSunburstEventMap<any, any>['ojBeforeCollapse']) => void;
onojBeforeDrill?: (value: ojSunburstEventMap<any, any>['ojBeforeDrill']) => void;
onojBeforeExpand?: (value: ojSunburstEventMap<any, any>['ojBeforeExpand']) => void;
onojCollapse?: (value: ojSunburstEventMap<any, any>['ojCollapse']) => void;
onojDrill?: (value: ojSunburstEventMap<any, any>['ojDrill']) => void;
onojExpand?: (value: ojSunburstEventMap<any, any>['ojExpand']) => void;
onojRotateInput?: (value: ojSunburstEventMap<any, any>['ojRotateInput']) => void;
onanimationDurationChanged?: (value: ojSunburstEventMap<any, any>['animationDurationChanged']) => void;
onanimationOnDataChangeChanged?: (value: ojSunburstEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojSunburstEventMap<any, any>['animationOnDisplayChanged']) => void;
onanimationUpdateColorChanged?: (value: ojSunburstEventMap<any, any>['animationUpdateColorChanged']) => void;
onasChanged?: (value: ojSunburstEventMap<any, any>['asChanged']) => void;
oncolorLabelChanged?: (value: ojSunburstEventMap<any, any>['colorLabelChanged']) => void;
ondataChanged?: (value: ojSunburstEventMap<any, any>['dataChanged']) => void;
ondisplayLevelsChanged?: (value: ojSunburstEventMap<any, any>['displayLevelsChanged']) => void;
ondrillingChanged?: (value: ojSunburstEventMap<any, any>['drillingChanged']) => void;
onexpandedChanged?: (value: ojSunburstEventMap<any, any>['expandedChanged']) => void;
onhiddenCategoriesChanged?: (value: ojSunburstEventMap<any, any>['hiddenCategoriesChanged']) => void;
onhighlightMatchChanged?: (value: ojSunburstEventMap<any, any>['highlightMatchChanged']) => void;
onhighlightModeChanged?: (value: ojSunburstEventMap<any, any>['highlightModeChanged']) => void;
onhighlightedCategoriesChanged?: (value: ojSunburstEventMap<any, any>['highlightedCategoriesChanged']) => void;
onhoverBehaviorChanged?: (value: ojSunburstEventMap<any, any>['hoverBehaviorChanged']) => void;
onhoverBehaviorDelayChanged?: (value: ojSunburstEventMap<any, any>['hoverBehaviorDelayChanged']) => void;
onnodeDefaultsChanged?: (value: ojSunburstEventMap<any, any>['nodeDefaultsChanged']) => void;
onrootNodeChanged?: (value: ojSunburstEventMap<any, any>['rootNodeChanged']) => void;
onrootNodeContentChanged?: (value: ojSunburstEventMap<any, any>['rootNodeContentChanged']) => void;
onrotationChanged?: (value: ojSunburstEventMap<any, any>['rotationChanged']) => void;
onselectionChanged?: (value: ojSunburstEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojSunburstEventMap<any, any>['selectionModeChanged']) => void;
onsizeLabelChanged?: (value: ojSunburstEventMap<any, any>['sizeLabelChanged']) => void;
onsortingChanged?: (value: ojSunburstEventMap<any, any>['sortingChanged']) => void;
onstartAngleChanged?: (value: ojSunburstEventMap<any, any>['startAngleChanged']) => void;
ontooltipChanged?: (value: ojSunburstEventMap<any, any>['tooltipChanged']) => void;
ontouchResponseChanged?: (value: ojSunburstEventMap<any, any>['touchResponseChanged']) => void;
ontrackResizeChanged?: (value: ojSunburstEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface SunburstNodeIntrinsicProps extends Partial<Readonly<ojSunburstNodeSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onborderColorChanged?: (value: ojSunburstNodeEventMap<any, any>['borderColorChanged']) => void;
onborderWidthChanged?: (value: ojSunburstNodeEventMap<any, any>['borderWidthChanged']) => void;
oncategoriesChanged?: (value: ojSunburstNodeEventMap<any, any>['categoriesChanged']) => void;
oncolorChanged?: (value: ojSunburstNodeEventMap<any, any>['colorChanged']) => void;
ondrillingChanged?: (value: ojSunburstNodeEventMap<any, any>['drillingChanged']) => void;
onlabelChanged?: (value: ojSunburstNodeEventMap<any, any>['labelChanged']) => void;
onlabelDisplayChanged?: (value: ojSunburstNodeEventMap<any, any>['labelDisplayChanged']) => void;
onlabelHalignChanged?: (value: ojSunburstNodeEventMap<any, any>['labelHalignChanged']) => void;
onlabelStyleChanged?: (value: ojSunburstNodeEventMap<any, any>['labelStyleChanged']) => void;
onpatternChanged?: (value: ojSunburstNodeEventMap<any, any>['patternChanged']) => void;
onradiusChanged?: (value: ojSunburstNodeEventMap<any, any>['radiusChanged']) => void;
onselectableChanged?: (value: ojSunburstNodeEventMap<any, any>['selectableChanged']) => void;
onshortDescChanged?: (value: ojSunburstNodeEventMap<any, any>['shortDescChanged']) => void;
onshowDisclosureChanged?: (value: ojSunburstNodeEventMap<any, any>['showDisclosureChanged']) => void;
onsvgClassNameChanged?: (value: ojSunburstNodeEventMap<any, any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojSunburstNodeEventMap<any, any>['svgStyleChanged']) => void;
onvalueChanged?: (value: ojSunburstNodeEventMap<any, any>['valueChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-sunburst": SunburstIntrinsicProps;
"oj-sunburst-node": SunburstNodeIntrinsicProps;
}
}
} | the_stack |
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type CommerceBuyerOfferActionEnum = "OFFER_ACCEPTED" | "OFFER_ACCEPTED_CONFIRM_NEEDED" | "OFFER_RECEIVED" | "OFFER_RECEIVED_CONFIRM_NEEDED" | "PAYMENT_FAILED" | "PROVISIONAL_OFFER_ACCEPTED" | "%future added value";
export type Conversation_conversation = {
readonly id: string;
readonly internalID: string | null;
readonly from: {
readonly name: string;
readonly email: string;
};
readonly to: {
readonly name: string;
readonly initials: string | null;
};
readonly initialMessage: string;
readonly lastMessageID: string | null;
readonly fromLastViewedMessageID: string | null;
readonly isLastMessageToUser: boolean | null;
readonly unread: boolean | null;
readonly orderConnection: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly internalID: string;
readonly updatedAt: string;
readonly buyerAction?: CommerceBuyerOfferActionEnum | null;
} | null;
} | null> | null;
readonly " $fragmentRefs": FragmentRefs<"ConversationMessages_events">;
} | null;
readonly messagesConnection: {
readonly pageInfo: {
readonly startCursor: string | null;
readonly endCursor: string | null;
readonly hasPreviousPage: boolean;
readonly hasNextPage: boolean;
};
readonly edges: ReadonlyArray<{
readonly node: {
readonly id: string;
} | null;
} | null> | null;
readonly totalCount: number | null;
readonly " $fragmentRefs": FragmentRefs<"ConversationMessages_messages">;
} | null;
readonly items: ReadonlyArray<{
readonly item: {
readonly __typename: string;
readonly id?: string;
readonly isOfferableFromInquiry?: boolean | null;
readonly internalID?: string;
readonly " $fragmentRefs": FragmentRefs<"Item_item">;
} | null;
readonly liveArtwork: ({
readonly isOfferableFromInquiry: boolean | null;
readonly internalID: string;
readonly __typename: "Artwork";
} | {
/*This will never be '%other', but we need some
value in case none of the concrete values match.*/
readonly __typename: "%other";
}) | null;
} | null> | null;
readonly " $fragmentRefs": FragmentRefs<"ConversationCTA_conversation">;
readonly " $refType": "Conversation_conversation";
};
export type Conversation_conversation$data = Conversation_conversation;
export type Conversation_conversation$key = {
readonly " $data"?: Conversation_conversation$data;
readonly " $fragmentRefs": FragmentRefs<"Conversation_conversation">;
};
const node: ReaderFragment = (function(){
var v0 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v1 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isOfferableFromInquiry",
"storageKey": null
};
return {
"argumentDefinitions": [
{
"defaultValue": 30,
"kind": "LocalArgument",
"name": "count",
"type": "Int"
},
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "after",
"type": "String"
}
],
"kind": "Fragment",
"metadata": {
"connection": [
{
"count": "count",
"cursor": "after",
"direction": "forward",
"path": [
"messagesConnection"
]
}
]
},
"name": "Conversation_conversation",
"selections": [
(v0/*: any*/),
(v1/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "ConversationInitiator",
"kind": "LinkedField",
"name": "from",
"plural": false,
"selections": [
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "email",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ConversationResponder",
"kind": "LinkedField",
"name": "to",
"plural": false,
"selections": [
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "initials",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "initialMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lastMessageID",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "fromLastViewedMessageID",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isLastMessageToUser",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "unread",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 10
},
{
"kind": "Literal",
"name": "participantType",
"value": "BUYER"
},
{
"kind": "Literal",
"name": "states",
"value": [
"APPROVED",
"FULFILLED",
"SUBMITTED",
"REFUNDED",
"CANCELED"
]
}
],
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v1/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "updatedAt",
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "buyerAction",
"storageKey": null
}
],
"type": "CommerceOfferOrder"
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ConversationMessages_events"
}
],
"storageKey": "orderConnection(first:10,participantType:\"BUYER\",states:[\"APPROVED\",\"FULFILLED\",\"SUBMITTED\",\"REFUNDED\",\"CANCELED\"])"
},
{
"alias": "messagesConnection",
"args": null,
"concreteType": "MessageConnection",
"kind": "LinkedField",
"name": "__Messages_messagesConnection_connection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "startCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasPreviousPage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "MessageEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Message",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v0/*: any*/),
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "totalCount",
"storageKey": null
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ConversationMessages_messages"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ConversationItem",
"kind": "LinkedField",
"name": "items",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "item",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v0/*: any*/),
(v4/*: any*/),
(v1/*: any*/)
],
"type": "Artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "Item_item"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "liveArtwork",
"plural": false,
"selections": [
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/),
(v1/*: any*/),
(v3/*: any*/)
],
"type": "Artwork"
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ConversationCTA_conversation"
}
],
"type": "Conversation"
};
})();
(node as any).hash = '3ba3d5c05fa28d7e0e212562c89a5f4b';
export default node; | the_stack |
namespace SpeedIndexComputer {
const navTimingsSupported = ("performance" in window) && ("timing" in window.performance);
/**
* Collects the speedindex and the firstPaint event, storign the min the pageLoadRequest.
*/
export function init() {
if (navTimingsSupported) {
Instrumentation.runWithout(function () {
// force the beacon service to wait until we have collected the data
pageLoadRequest.require("speedIndex");
const onLoadCallback = Instrumentation.disableFor(function () {
setTimeout(Instrumentation.disableFor(function () {
pageLoadRequest.navigationTimings = pageLoadRequest.navigationTimings || {};
const rumSI = RUMSpeedIndex();
pageLoadRequest.navigationTimings.navigationStart = window.performance.timing.navigationStart;
// check if the speedindex "si" and firstpaint "fp" were successfully computed
if (rumSI.si !== 0 && rumSI.fp !== 0) {
pageLoadRequest.navigationTimings.speedIndex = rumSI.si;
pageLoadRequest.navigationTimings.firstPaint = window.performance.timing.navigationStart + rumSI.fp;
}
pageLoadRequest.markComplete("speedIndex");
}), 100);
});
window.addEventListener("load", onLoadCallback);
});
}
}
interface ISpeedIndexResult {
/**
* Speedindex.
*/
si: number;
/**
* First-Paint.
*/
fp: number;
}
/*tslint:disable*/
/******************************************************************************
Copyright (c) 2014, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <ORGANIZATION> nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/******************************************************************************
*******************************************************************************
Calculates the Speed Index for a page by:
- Collecting a list of visible rectangles for elements that loaded
external resources (images, background images, fonts)
- Gets the time when the external resource for those elements loaded
through Resource Timing
- Calculates the likely time that the background painted
- Runs the various paint rectangles through the SpeedIndex calculation:
https://sites.google.com/a/webpagetest.org/docs/using-webpagetest/metrics/speed-index
TODO:
- Improve the start render estimate
- Handle overlapping rects (though maybe counting the area as multiple paints
will work out well)
- Detect elements with Custom fonts and the time that the respective font
loaded
- Better error handling for browsers that don't support resource timing
*******************************************************************************
******************************************************************************/
var RUMSpeedIndex = function (win?: any) {
win = win || window;
var doc = win.document;
/****************************************************************************
Support Routines
****************************************************************************/
// Get the rect for the visible portion of the provided DOM element
var GetElementViewportRect = function (el: any) {
var intersect: any = false;
if (el.getBoundingClientRect) {
var elRect = el.getBoundingClientRect();
intersect = {
'top': Math.max(elRect.top, 0),
'left': Math.max(elRect.left, 0),
'bottom': Math.min(elRect.bottom, (win.innerHeight || doc.documentElement.clientHeight)),
'right': Math.min(elRect.right, (win.innerWidth || doc.documentElement.clientWidth))
};
if (intersect.bottom <= intersect.top ||
intersect.right <= intersect.left) {
intersect = false;
} else {
intersect.area = (intersect.bottom - intersect.top) * (intersect.right - intersect.left);
}
}
return intersect;
};
// Check a given element to see if it is visible
var CheckElement = function (el: any, url: any) {
if (url) {
var rect = GetElementViewportRect(el);
if (rect) {
rects.push({
'url': url,
'area': rect.area,
'rect': rect
});
}
}
};
// Get the visible rectangles for elements that we care about
var GetRects = function () {
// Walk all of the elements in the DOM (try to only do this once)
var elements = doc.getElementsByTagName('*');
var re = /url\(.*(http.*)\)/ig;
for (var i = 0; i < elements.length; i++) {
var el = elements[i];
var style = win.getComputedStyle(el);
// check for Images
if (el.tagName == 'IMG') {
CheckElement(el, el.src);
}
// Check for background images
if (style as any['background-image']) {
re.lastIndex = 0;
var matches = re.exec(style as any['background-image']);
if (matches && matches.length > 1)
CheckElement(el, matches[1].replace('"', ''));
}
// recursively walk any iFrames
if (el.tagName == 'IFRAME') {
try {
var rect = GetElementViewportRect(el);
if (rect) {
var tm = RUMSpeedIndex((el as any).contentWindow);
if (tm) {
rects.push({
'tm': tm,
'area': rect.area,
'rect': rect
});
}
}
} catch (e) {
}
}
}
};
// Get the time at which each external resource loaded
var GetRectTimings = function () {
var timings: any = {};
var requests = win.performance.getEntriesByType("resource");
for (var i = 0; i < requests.length; i++)
(timings as any)[requests[i].name] = requests[i].responseEnd;
for (var j = 0; j < rects.length; j++) {
if (!('tm' in rects[j]))
rects[j].tm = timings[rects[j].url] !== undefined ? timings[rects[j].url] : 0;
}
};
// Get the first paint time.
var GetFirstPaint = function () {
// If the browser supports a first paint event, just use what the browser reports
if ('msFirstPaint' in win.performance.timing)
firstPaint = win.performance.timing.msFirstPaint - navStart;
if ('chrome' in win && 'loadTimes' in win.chrome) {
var chromeTimes = (win as any).chrome.loadTimes();
if ('firstPaintTime' in chromeTimes && chromeTimes.firstPaintTime > 0) {
var startTime = chromeTimes.startLoadTime;
if ('requestTime' in chromeTimes)
startTime = chromeTimes.requestTime;
if (chromeTimes.firstPaintTime >= startTime)
firstPaint = (chromeTimes.firstPaintTime - startTime) * 1000.0;
}
}
// For browsers that don't support first-paint or where we get insane values,
// use the time of the last non-async script or css from the head.
if (firstPaint === undefined || firstPaint < 0 || firstPaint > 120000) {
firstPaint = win.performance.timing.responseStart - navStart;
var headURLs: any = {};
var headElements = doc.getElementsByTagName('head')[0].children;
for (var i = 0; i < headElements.length; i++) {
var el = headElements[i];
if (el.tagName == 'SCRIPT' && el.src && !el.async)
headURLs[el.src] = true;
if (el.tagName == 'LINK' && el.rel == 'stylesheet' && el.href)
headURLs[el.href] = true;
}
var requests = win.performance.getEntriesByType("resource");
var doneCritical = false;
for (var j = 0; j < requests.length; j++) {
if (!doneCritical &&
headURLs[requests[j].name] &&
(requests[j].initiatorType == 'script' || requests[j].initiatorType == 'link')) {
var requestEnd = requests[j].responseEnd;
if (firstPaint === undefined || requestEnd > firstPaint)
firstPaint = requestEnd;
} else {
doneCritical = true;
}
}
}
firstPaint = Math.max(firstPaint, 0);
};
// Sort and group all of the paint rects by time and use them to
// calculate the visual progress
var CalculateVisualProgress = function () {
var paints: any = { '0': 0 };
var total = 0;
for (var i = 0; i < rects.length; i++) {
var tm = firstPaint;
if ('tm' in rects[i] && rects[i].tm > firstPaint)
tm = rects[i].tm;
if (paints[tm] === undefined)
paints[tm] = 0;
paints[tm] += rects[i].area;
total += rects[i].area;
}
// Add a paint area for the page background (count 10% of the pixels not
// covered by existing paint rects.
var pixels = Math.max(doc.documentElement.clientWidth, win.innerWidth || 0) *
Math.max(doc.documentElement.clientHeight, win.innerHeight || 0);
if (pixels > 0) {
pixels = Math.max(pixels - total, 0) * pageBackgroundWeight;
if (paints[firstPaint] === undefined)
paints[firstPaint] = 0;
paints[firstPaint] += pixels;
total += pixels;
}
// Calculate the visual progress
if (total) {
for (var time in paints) {
if (paints.hasOwnProperty(time)) {
progress.push({ 'tm': time, 'area': paints[time] });
}
}
progress.sort(function (a, b) { return a.tm - b.tm; });
var accumulated = 0;
for (var j = 0; j < progress.length; j++) {
accumulated += progress[j].area;
progress[j].progress = accumulated / total;
}
}
};
// Given the visual progress information, Calculate the speed index.
var CalculateSpeedIndex = function () {
if (progress.length) {
SpeedIndex = 0;
var lastTime = 0;
var lastProgress = 0;
for (var i = 0; i < progress.length; i++) {
var elapsed = progress[i].tm - lastTime;
if (elapsed > 0 && lastProgress < 1)
SpeedIndex += (1 - lastProgress) * elapsed;
lastTime = progress[i].tm;
lastProgress = progress[i].progress;
}
} else {
SpeedIndex = firstPaint;
}
};
/****************************************************************************
Main flow
****************************************************************************/
var rects: any[] = [];
var progress: any[] = [];
var firstPaint: any;
var SpeedIndex: any;
var pageBackgroundWeight = 0.1;
try {
var navStart = win.performance.timing.navigationStart;
GetRects();
GetRectTimings();
GetFirstPaint();
CalculateVisualProgress();
CalculateSpeedIndex();
} catch (e) {
}
/* Debug output for testing
var dbg = '';
dbg += "Paint Rects\n";
for (var i = 0; i < rects.length; i++)
dbg += '(' + rects[i].area + ') ' + rects[i].tm + ' - ' + rects[i].url + "\n";
dbg += "Visual Progress\n";
for (var i = 0; i < progress.length; i++)
dbg += '(' + progress[i].area + ') ' + progress[i].tm + ' - ' + progress[i].progress + "\n";
dbg += 'First Paint: ' + firstPaint + "\n";
dbg += 'Speed Index: ' + SpeedIndex + "\n";
console.log(dbg);
*/
return {
si: SpeedIndex!,
fp: firstPaint!
}
};
}
InspectITPlugin.registerPlugin(SpeedIndexComputer); | the_stack |
import * as ts from 'typescript';
import * as base from './base';
import {FacadeConverter} from './facade_converter';
/**
* To support arbitrary d.ts files in Dart we often have to merge two TypeScript
* types into a single Dart type because Dart lacks features such as method
* overloads, type aliases, and union types.
*/
export class MergedType {
constructor(private fc: FacadeConverter) {}
merge(t?: ts.TypeNode) {
if (t) {
// TODO(jacobr): get a better unique name for a type.
switch (t.kind) {
case ts.SyntaxKind.NullKeyword:
// No need to include the null type as all Dart types are nullable anyway.
return;
case ts.SyntaxKind.UnionType:
let union = <ts.UnionTypeNode>t;
union.types.forEach(this.merge.bind(this));
return;
case ts.SyntaxKind.IntersectionType:
// Arbitrarily pick the first type of the intersection type as the merged type.
// TODO(jacobr): re-evaluate this logic.
let intersection = <ts.IntersectionTypeNode>t;
this.merge(intersection.types[0]);
return;
case ts.SyntaxKind.TypePredicate:
this.merge((t as ts.TypePredicateNode).type);
return;
case ts.SyntaxKind.TypeReference:
// We need to follow Alias types as Dart does not support them for non
// function types. TODO(jacobr): handle them for Function types?
const typeRef = <ts.TypeReferenceNode>t;
const decl =
this.fc.getTypeDeclarationOfSymbol(this.fc.getSymbolAtLocation(typeRef.typeName));
if (decl && ts.isTypeAliasDeclaration(decl)) {
const alias = decl;
if (!base.supportedTypeDeclaration(alias)) {
if (typeRef.typeArguments) {
console.log(
'Warning: typeReference with arguements not supported yet:' + t.getText());
}
this.merge(alias.type);
}
return;
}
break;
default:
break;
}
this.types.set(this.fc.generateDartTypeName(t, {insideComment: true}), t);
}
}
toTypeNode(): ts.TypeNode {
let names = Array.from(this.types.keys());
if (names.length === 0) {
return null;
}
if (names.length === 1) {
return this.types.get(names[0]);
}
let union = <ts.UnionTypeNode>ts.createNode(ts.SyntaxKind.UnionType);
base.copyLocation(this.types.get(names[0]), union);
union.types = ts.createNodeArray(Array.from(this.types.values()));
return union;
}
/**
* Generate a type node where we have stripped out type features that Dart does not support.
* Currently this means stripping out union types.
*/
toSimpleTypeNode(): ts.TypeNode {
let merged = this.toTypeNode();
if (merged == null) return null;
if (ts.isUnionTypeNode(merged)) {
// For union types find a Dart type that satisfies all the types.
let types = merged.types;
// Generate a common base type for an array of types.
// The implemented is currently incomplete often returning null when there
// might really be a valid common base type.
let common: ts.TypeNode = types[0];
for (let i = 1; i < types.length && common != null; ++i) {
let type = types[i];
common = this.fc.findCommonType(type, common);
}
return common;
}
return merged;
}
private types: Map<string, ts.TypeNode> = new Map();
}
/**
* Handle a parameter that is the result of merging parameter declarations from
* multiple method overloads.
*/
export class MergedParameter {
constructor(param: ts.ParameterDeclaration, fc: FacadeConverter) {
this.type = new MergedType(fc);
this.textRange = param;
this.merge(param);
}
merge(param: ts.ParameterDeclaration) {
this.name.add(base.ident(param.name));
if (!this.optional) {
this.optional = !!param.questionToken;
}
this.type.merge(param.type);
}
toParameterDeclaration(): ts.ParameterDeclaration {
let ret = <ts.ParameterDeclaration>ts.createNode(ts.SyntaxKind.Parameter);
let nameIdentifier = <ts.Identifier>ts.createNode(ts.SyntaxKind.Identifier);
nameIdentifier.escapedText = ts.escapeLeadingUnderscores(Array.from(this.name).join('_'));
ret.name = nameIdentifier;
if (this.optional) {
ret.questionToken = ts.createToken(ts.SyntaxKind.QuestionToken);
}
base.copyLocation(this.textRange, ret);
ret.type = this.type.toTypeNode();
return ret;
}
setOptional() {
this.optional = true;
}
private name: Set<string> = new Set();
private type: MergedType;
private optional = false;
private textRange: ts.Node;
}
/**
* Handle a parameter that is the result of merging parameter declarations from
* multiple method overloads.
*/
export class MergedTypeParameter {
constructor(param: ts.TypeParameterDeclaration, fc: FacadeConverter) {
this.constraint = new MergedType(fc);
this.textRange = param;
this.merge(param);
this.name = base.ident(param.name);
}
merge(param: ts.TypeParameterDeclaration) {
this.constraint.merge(param.constraint);
// We ignore param.expression as it is not supported by Dart.
}
toTypeParameterDeclaration(): ts.TypeParameterDeclaration {
let ret = <ts.TypeParameterDeclaration>ts.createNode(ts.SyntaxKind.TypeParameter);
let nameIdentifier = <ts.Identifier>ts.createNode(ts.SyntaxKind.Identifier);
nameIdentifier.escapedText = ts.escapeLeadingUnderscores(this.name);
ret.name = nameIdentifier;
base.copyLocation(this.textRange, ret);
let constraint = this.constraint.toTypeNode();
// TODO(jacobr): remove this check once we have support for union types within comments.
// We can't currently handle union types in merged type parameters as the comments for type
// parameters in function types are not there for documentation and impact strong mode.
if (constraint && !ts.isUnionTypeNode(constraint)) {
ret.constraint = constraint;
}
return ret;
}
private name: string;
private constraint: MergedType;
private textRange: ts.Node;
}
/**
* Handle a parameter that is the result of merging parameter declarations from
* multiple method overloads.
*/
export class MergedTypeParameters {
private mergedParameters: Map<string, MergedTypeParameter> = new Map();
private textRange: ts.TextRange;
constructor(private fc: FacadeConverter) {}
merge(params: ts.NodeArray<ts.TypeParameterDeclaration>) {
if (!params) return;
if (!this.textRange) {
this.textRange = params;
}
for (let i = 0; i < params.length; i++) {
let param = params[i];
let name = base.ident(param.name);
if (this.mergedParameters.has(name)) {
let merged = this.mergedParameters.get(name);
if (merged) {
merged.merge(param);
}
} else {
this.mergedParameters.set(name, new MergedTypeParameter(param, this.fc));
}
}
}
toTypeParameters(): ts.NodeArray<ts.TypeParameterDeclaration> {
if (this.mergedParameters.size === 0) {
return undefined;
}
const parameters: ts.TypeParameterDeclaration[] = [];
this.mergedParameters.forEach((mergedParameter) => {
parameters.push(mergedParameter.toTypeParameterDeclaration());
});
const ret = ts.createNodeArray(parameters);
base.copyNodeArrayLocation(this.textRange, ret);
return ret;
}
}
/**
* Represents a merged class member. If the member was not overloaded, the constituents array
* will contain only the original declaration and mergedDeclaration will just be the original
* declaration. If the member was an overloaded method, the constituents array will contain all
* overloaded declarations and mergedDeclaration will contain the result of merging the overloads.
*/
export class MergedMember {
constructor(
public constituents: ts.SignatureDeclaration[],
public mergedDeclaration: ts.SignatureDeclaration) {}
isOverloaded(): boolean {
return this.constituents.length > 1;
}
}
/**
* Normalize a SourceFile.
*/
export function normalizeSourceFile(
f: ts.SourceFile, fc: FacadeConverter, fileSet: Set<string>, renameConflictingTypes = false,
explicitStatic = false) {
const nodeReplacements: Map<ts.Node, ts.Node> = new Map();
const modules: Map<string, ts.ModuleDeclaration> = new Map();
// Merge top level modules.
for (let i = 0; i < f.statements.length; ++i) {
const statement = f.statements[i];
if (!ts.isModuleDeclaration(statement)) {
continue;
}
const moduleDecl: ts.ModuleDeclaration = statement;
const name = base.getModuleName(moduleDecl);
const moduleBlock = base.getModuleBlock(moduleDecl);
if (modules.has(name)) {
const srcBodyBlock = base.getModuleBlock(modules.get(name));
Array.prototype.push.apply(srcBodyBlock.statements, moduleBlock.statements);
} else {
modules.set(name, moduleDecl);
}
}
function addModifier(n: ts.Node, modifier: ts.Node) {
if (!n.modifiers) {
n.modifiers = ts.createNodeArray();
}
modifier.parent = n;
// Small hack to get around NodeArrays being readonly
Array.prototype.push.call(n.modifiers, modifier);
}
/**
* Searches for a constructor member within a type literal or an interface. If found, it returns
* that member. Otherwise, it returns undefined.
*/
function findConstructorInType(declaration: ts.TypeLiteralNode|
ts.InterfaceDeclaration): base.Constructor|undefined {
// Example TypeScript definition matching the type literal case:
//
// declare interface XType {
// a: string;
// b: number;
// c(): boolean;
// }
//
// declare var X: {
// prototype: XType,
// new(a: string, b: number): XType,
// };
//
// Possible underlying implementation:
// var X = class {
// constructor(public a: string, public b: number) {}
// c(): boolean { return this.b.toString() === this.a }
// }
//
// In TypeScript you could just write new X('abc', 123) and create an instance of
// XType. Dart doesn't support this when X is a variable, so X must be upgraded to be
// a class.
// Example TypeScript definition matching the interface case:
//
// interface XType {
// a: string;
// b: number;
// c(): boolean;
// }
//
// interface X {
// new (a: string, b: number): XType;
// }
//
// declare var X: X;
//
// Possible underlying implementation:
// var X: X = class {
// constructor(public a: string, public b: number) {}
// c(): boolean { return this.b.toString() === this.a }
// }
//
// In TypeScript you could just write new X('abc', 123) and create an instance of
// XType. Dart doesn't support this when X is a variable, so X must be upgraded to
// be a class.
return declaration.members.find(base.isConstructor) as base.Constructor;
}
/**
* Returns the type of object created by a given constructor.
*/
function getConstructedObjectType(constructor: base.Constructor): ts.ObjectTypeDeclaration|
undefined {
const constructedTypeSymbol: ts.Symbol = constructor &&
ts.isTypeReferenceNode(constructor.type) &&
fc.tc.getTypeAtLocation(constructor.type).getSymbol();
if (!constructedTypeSymbol) {
return;
}
// The constructed type can be a type literal, an interface, or a class.
return constructedTypeSymbol.declarations.find((member: ts.TypeElement) => {
if (ts.isTypeLiteralNode(member)) {
return true;
} else if (ts.isInterfaceDeclaration(member)) {
// Check if the interface was declared within a user-specified input file to
// prevent emitting classes for TS internal library types.
const fileName = member.getSourceFile().fileName;
return fileSet.has(fileName);
} else if (ts.isClassDeclaration(member)) {
return true;
}
return false;
}) as ts.ObjectTypeDeclaration |
undefined;
}
function mergeVariablesIntoClasses(n: ts.Node, classes: Map<string, base.ClassLike>) {
// In TypeScript, a constructor may be represented by an object whose type contains a "new"
// method. When a variable has a type with a "new" method, it means that the variable must
// either be an ES6 class or the equivalent desugared constructor function. As Dart does not
// support calling arbitrary functions like constructors, we need to upgrade the variable to be
// a class with the appropriate members so that we can invoke the constructor on that class.
if (ts.isVariableStatement(n)) {
const statement = n;
statement.declarationList.declarations.forEach((variableDecl: ts.VariableDeclaration) => {
if (ts.isIdentifier(variableDecl.name)) {
const name = base.ident(variableDecl.name);
const variableType = variableDecl.type;
if (!variableType) {
return;
}
// We need to find the declaration of the variable's type in order to acccess the
// members of that type.
let variableTypeDeclaration: ts.TypeLiteralNode|ts.InterfaceDeclaration;
if (ts.isTypeReferenceNode(variableType)) {
variableTypeDeclaration =
fc.getDeclarationOfReferencedType(variableType, (declaration: ts.Declaration) => {
return ts.isTypeLiteralNode(declaration) ||
ts.isInterfaceDeclaration(declaration);
}) as ts.TypeLiteralNode | ts.InterfaceDeclaration;
} else if (ts.isTypeLiteralNode(variableType)) {
variableTypeDeclaration = variableType;
}
if (!variableTypeDeclaration) {
return;
}
// Try to find a Constructor within the variable's type.
const constructor: base.Constructor = findConstructorInType(variableTypeDeclaration);
if (constructor) {
// Get the type of object that the constructor creates.
const constructedType = getConstructedObjectType(constructor);
if (classes.has(name)) {
const existing = classes.get(name);
// If a class or interface with the same name as the variable already exists, we
// should suppress that declaration because it will be cloned into a stub class or
// interface below.
nodeReplacements.set(existing, undefined);
}
// These properties do not exist on TypeLiteralNodes.
let clazzTypeParameters, clazzHeritageClauses;
if (ts.isClassDeclaration(constructedType) ||
ts.isInterfaceDeclaration(constructedType)) {
clazzTypeParameters = base.cloneNodeArray(constructedType.typeParameters);
clazzHeritageClauses = base.cloneNodeArray(constructedType.heritageClauses);
}
let clazz: ts.InterfaceDeclaration|ts.ClassDeclaration;
if (ts.isClassDeclaration(constructedType)) {
clazz = ts.createClassDeclaration(
base.cloneNodeArray(constructedType.decorators),
base.cloneNodeArray(constructedType.modifiers),
ts.createIdentifier(base.ident(variableDecl.name)),
base.cloneNodeArray(clazzTypeParameters),
base.cloneNodeArray(clazzHeritageClauses),
base.cloneNodeArray(constructedType.members));
} else if (
ts.isTypeLiteralNode(constructedType) ||
ts.isInterfaceDeclaration(constructedType)) {
// TODO(derekx): Try creating abstract class declarations in these cases.
// InterfaceDeclarations get emitted as abstract classes regardless, it would just
// make the JSON output more accurate.
clazz = ts.createInterfaceDeclaration(
base.cloneNodeArray(constructedType.decorators),
base.cloneNodeArray(constructedType.modifiers),
ts.createIdentifier(base.ident(variableDecl.name)),
base.cloneNodeArray(clazzTypeParameters),
base.cloneNodeArray(clazzHeritageClauses),
base.cloneNodeArray(constructedType.members));
(clazz as base.ExtendedInterfaceDeclaration).constructedType = constructedType;
}
base.copyLocation(variableDecl, clazz);
clazz.flags = variableDecl.flags;
nodeReplacements.set(n, clazz);
classes.set(name, clazz);
} else {
if (renameConflictingTypes) {
// If we cannot find a constructor within the variable's type and the
// --rename-conflicting-types flag is set, we need to check whether or not a type
// with the same name as the variable already exists. If it does, we must rename it.
// That type is not directly associated with this variable, so they cannot be
// combined.
const variableSymbol = fc.getSymbolAtLocation(variableDecl.name);
if (variableSymbol.getDeclarations()) {
for (const declaration of variableSymbol.getDeclarations()) {
if (ts.isInterfaceDeclaration(declaration) ||
ts.isTypeAliasDeclaration(declaration)) {
declaration.name.escapedText = ts.escapeLeadingUnderscores(name + 'Type');
}
}
}
return;
} else if (!renameConflictingTypes && classes.has(name)) {
// If we cannot find a constructor and there exists a class with the exact same name,
// we assume by default that the variable and type are related as they have the exact
// same name. Thus, the variable declaration is suppressed and the members of its type
// are merged into the existing class below.
nodeReplacements.set(variableDecl, undefined);
}
}
// Merge the members of the variable's type into the existing class.
const existing = classes.get(name);
if (!existing) {
return;
}
const members = existing.members;
variableTypeDeclaration.members.forEach((member: ts.TypeElement|ts.ClassElement) => {
// Array.prototype.push is used below as a small hack to get around NodeArrays being
// readonly.
switch (member.kind) {
case ts.SyntaxKind.Constructor:
case ts.SyntaxKind.ConstructorType:
case ts.SyntaxKind.ConstructSignature: {
const clonedConstructor = ts.getMutableClone(member);
clonedConstructor.name = ts.getMutableClone(variableDecl.name) as ts.PropertyName;
clonedConstructor.parent = existing;
const existingConstructIndex = members.findIndex(base.isConstructor);
if (existingConstructIndex === -1) {
Array.prototype.push.call(members, clonedConstructor);
} else {
Array.prototype.splice.call(members, existingConstructIndex, clonedConstructor);
}
} break;
case ts.SyntaxKind.MethodSignature:
member.parent = existing;
Array.prototype.push.call(members, member);
break;
case ts.SyntaxKind.PropertySignature:
// TODO(derekx): This should also be done to methods.
if (!explicitStatic) {
// Finds all existing declarations of this property in the inheritance
// hierarchy of this class.
const existingDeclarations =
findPropertyInHierarchy(base.ident(member.name), existing, classes);
if (existingDeclarations.size) {
for (const existingDecl of existingDeclarations) {
addModifier(existingDecl, ts.createModifier(ts.SyntaxKind.StaticKeyword));
}
}
}
// If needed, add declaration of property to the interface that we are
// currently handling.
if (!findPropertyInClass(base.ident(member.name), existing)) {
if (!explicitStatic) {
addModifier(member, ts.createModifier(ts.SyntaxKind.StaticKeyword));
}
member.parent = existing;
Array.prototype.push.call(members, member);
}
break;
case ts.SyntaxKind.IndexSignature:
member.parent = existing;
Array.prototype.push.call(members, member);
break;
case ts.SyntaxKind.CallSignature:
member.parent = existing;
Array.prototype.push.call(members, member);
break;
default:
throw 'Unhandled TypeLiteral member type:' + member.kind;
}
});
} else {
throw 'Unexpected VariableStatement identifier kind';
}
});
} else if (ts.isModuleBlock(n)) {
ts.forEachChild(n, (child) => mergeVariablesIntoClasses(child, classes));
}
}
function findPropertyInClass(propName: string, classLike: base.ClassLike): ts.ClassElement|
undefined {
const members = classLike.members as ts.NodeArray<ts.ClassElement>;
return members.find((member: ts.ClassElement) => {
if (member.name && base.ident(member.name) === propName) {
return true;
}
});
}
function findPropertyInHierarchy(
propName: string, classLike: base.ClassLike,
classes: Map<string, base.ClassLike>): Set<ts.ClassElement> {
const propertyDeclarations = new Set<ts.ClassElement>();
const declaration = findPropertyInClass(propName, classLike);
if (declaration) propertyDeclarations.add(declaration);
const heritageClauses = classLike.heritageClauses || ts.createNodeArray();
for (const clause of heritageClauses) {
if (clause.token !== ts.SyntaxKind.ExtendsKeyword) {
continue;
}
const name = base.ident(clause.types[0].expression);
// TODO(derekx): We currently only look up ancestor nodes using the classes map. This is
// because the classes map contains references to the modified versions of nodes. If the
// ancestor is declared in a different file, it won't be found this way. Determine a way to
// resolve this issue. One possibility would be to refactor the classes map so that it could
// be shared among all files.
if (!classes.has(name)) {
continue;
}
const declarationsInAncestors = findPropertyInHierarchy(propName, classes.get(name), classes);
if (declarationsInAncestors.size) {
declarationsInAncestors.forEach(decl => propertyDeclarations.add(decl));
}
}
return propertyDeclarations;
}
function gatherClasses(n: ts.Node, classes: Map<string, base.ClassLike>) {
if (ts.isClassExpression(n) || ts.isClassDeclaration(n) || ts.isInterfaceDeclaration(n)) {
let classDecl = <base.ClassLike>n;
let name = classDecl.name.text;
// TODO(jacobr): validate that the classes have consistent
// modifiers, etc.
if (classes.has(name)) {
let existing = classes.get(name);
(classDecl.members as ts.NodeArray<ts.ClassElement>).forEach((e: ts.ClassElement) => {
// Small hack to get around NodeArrays being readonly
Array.prototype.push.call(existing.members, e);
e.parent = existing;
});
nodeReplacements.set(classDecl, undefined);
} else {
classes.set(name, classDecl);
// Perform other class level post processing here.
}
} else if (ts.isModuleDeclaration(n) || ts.isSourceFile(n)) {
const moduleClasses: Map<string, base.ClassLike> = new Map();
ts.forEachChild(n, (child) => gatherClasses(child, moduleClasses));
ts.forEachChild(n, (child) => mergeVariablesIntoClasses(child, moduleClasses));
} else if (ts.isModuleBlock(n)) {
ts.forEachChild(n, (child) => gatherClasses(child, classes));
}
}
/**
* AST transformer that handles nodes that we have marked for removal or replacement during
* mergeVariablesIntoClasses.
*/
function handleModifiedNodes(context: ts.TransformationContext) {
const visit: ts.Visitor = (node: ts.Node) => {
if (nodeReplacements.has(node)) {
return nodeReplacements.get(node);
}
return ts.visitEachChild(node, (child) => visit(child), context);
};
return (node: ts.SourceFile) => ts.visitNode(node, visit);
}
gatherClasses(f, new Map());
return ts.transform(f, [handleModifiedNodes]).transformed[0];
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/storageAccountCredentialsMappers";
import * as Parameters from "../models/parameters";
import { DataBoxEdgeManagementClientContext } from "../dataBoxEdgeManagementClientContext";
/** Class representing a StorageAccountCredentials. */
export class StorageAccountCredentials {
private readonly client: DataBoxEdgeManagementClientContext;
/**
* Create a StorageAccountCredentials.
* @param {DataBoxEdgeManagementClientContext} client Reference to the service client.
*/
constructor(client: DataBoxEdgeManagementClientContext) {
this.client = client;
}
/**
* @summary Gets all the storage account credentials in a Data Box Edge/Data Box Gateway device.
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceResponse>
*/
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceResponse>;
/**
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @param callback The callback
*/
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.StorageAccountCredentialList>): void;
/**
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @param options The optional parameters
* @param callback The callback
*/
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageAccountCredentialList>): void;
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageAccountCredentialList>, callback?: msRest.ServiceCallback<Models.StorageAccountCredentialList>): Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceResponse> {
return this.client.sendOperationRequest(
{
deviceName,
resourceGroupName,
options
},
listByDataBoxEdgeDeviceOperationSpec,
callback) as Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceResponse>;
}
/**
* Gets the properties of the specified storage account credential.
* @param deviceName The device name.
* @param name The storage account credential name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.StorageAccountCredentialsGetResponse>
*/
get(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageAccountCredentialsGetResponse>;
/**
* @param deviceName The device name.
* @param name The storage account credential name.
* @param resourceGroupName The resource group name.
* @param callback The callback
*/
get(deviceName: string, name: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.StorageAccountCredential>): void;
/**
* @param deviceName The device name.
* @param name The storage account credential name.
* @param resourceGroupName The resource group name.
* @param options The optional parameters
* @param callback The callback
*/
get(deviceName: string, name: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageAccountCredential>): void;
get(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageAccountCredential>, callback?: msRest.ServiceCallback<Models.StorageAccountCredential>): Promise<Models.StorageAccountCredentialsGetResponse> {
return this.client.sendOperationRequest(
{
deviceName,
name,
resourceGroupName,
options
},
getOperationSpec,
callback) as Promise<Models.StorageAccountCredentialsGetResponse>;
}
/**
* Creates or updates the storage account credential.
* @param deviceName The device name.
* @param name The storage account credential name.
* @param storageAccountCredential The storage account credential.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.StorageAccountCredentialsCreateOrUpdateResponse>
*/
createOrUpdate(deviceName: string, name: string, storageAccountCredential: Models.StorageAccountCredential, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageAccountCredentialsCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(deviceName,name,storageAccountCredential,resourceGroupName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.StorageAccountCredentialsCreateOrUpdateResponse>;
}
/**
* Deletes the storage account credential.
* @param deviceName The device name.
* @param name The storage account credential name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(deviceName,name,resourceGroupName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Creates or updates the storage account credential.
* @param deviceName The device name.
* @param name The storage account credential name.
* @param storageAccountCredential The storage account credential.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(deviceName: string, name: string, storageAccountCredential: Models.StorageAccountCredential, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
name,
storageAccountCredential,
resourceGroupName,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Deletes the storage account credential.
* @param deviceName The device name.
* @param name The storage account credential name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
name,
resourceGroupName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* @summary Gets all the storage account credentials in a Data Box Edge/Data Box Gateway device.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceNextResponse>
*/
listByDataBoxEdgeDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByDataBoxEdgeDeviceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.StorageAccountCredentialList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByDataBoxEdgeDeviceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageAccountCredentialList>): void;
listByDataBoxEdgeDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageAccountCredentialList>, callback?: msRest.ServiceCallback<Models.StorageAccountCredentialList>): Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByDataBoxEdgeDeviceNextOperationSpec,
callback) as Promise<Models.StorageAccountCredentialsListByDataBoxEdgeDeviceNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByDataBoxEdgeDeviceOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccountCredentials",
urlParameters: [
Parameters.deviceName,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageAccountCredentialList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccountCredentials/{name}",
urlParameters: [
Parameters.deviceName,
Parameters.name,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageAccountCredential
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccountCredentials/{name}",
urlParameters: [
Parameters.deviceName,
Parameters.name,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "storageAccountCredential",
mapper: {
...Mappers.StorageAccountCredential,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.StorageAccountCredential
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccountCredentials/{name}",
urlParameters: [
Parameters.deviceName,
Parameters.name,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByDataBoxEdgeDeviceNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageAccountCredentialList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import {GaxiosOptions} from 'gaxios';
import {AwsRequestSigner} from './awsrequestsigner';
import {
BaseExternalAccountClient,
BaseExternalAccountClientOptions,
} from './baseexternalclient';
import {RefreshOptions, Headers} from './oauth2client';
/**
* AWS credentials JSON interface. This is used for AWS workloads.
*/
export interface AwsClientOptions extends BaseExternalAccountClientOptions {
credential_source: {
environment_id: string;
// Region can also be determined from the AWS_REGION or AWS_DEFAULT_REGION
// environment variables.
region_url?: string;
// The url field is used to determine the AWS security credentials.
// This is optional since these credentials can be retrieved from the
// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN
// environment variables.
url?: string;
regional_cred_verification_url: string;
// The imdsv2 session token url is used to fetch session token from AWS
// which is later sent through headers for metadata requests. If the
// field is missing, then session token won't be fetched and sent with
// the metadata requests.
// The session token is required for IMDSv2 but optional for IMDSv1
imdsv2_session_token_url?: string;
};
}
/**
* Interface defining the AWS security-credentials endpoint response.
*/
interface AwsSecurityCredentials {
Code: string;
LastUpdated: string;
Type: string;
AccessKeyId: string;
SecretAccessKey: string;
Token: string;
Expiration: string;
}
/**
* AWS external account client. This is used for AWS workloads, where
* AWS STS GetCallerIdentity serialized signed requests are exchanged for
* GCP access token.
*/
export class AwsClient extends BaseExternalAccountClient {
private readonly environmentId: string;
private readonly regionUrl?: string;
private readonly securityCredentialsUrl?: string;
private readonly regionalCredVerificationUrl: string;
private readonly imdsV2SessionTokenUrl?: string;
private awsRequestSigner: AwsRequestSigner | null;
private region: string;
/**
* Instantiates an AwsClient instance using the provided JSON
* object loaded from an external account credentials file.
* An error is thrown if the credential is not a valid AWS credential.
* @param options The external account options object typically loaded
* from the external account JSON credential file.
* @param additionalOptions Optional additional behavior customization
* options. These currently customize expiration threshold time and
* whether to retry on 401/403 API request errors.
*/
constructor(options: AwsClientOptions, additionalOptions?: RefreshOptions) {
super(options, additionalOptions);
this.environmentId = options.credential_source.environment_id;
// This is only required if the AWS region is not available in the
// AWS_REGION or AWS_DEFAULT_REGION environment variables.
this.regionUrl = options.credential_source.region_url;
// This is only required if AWS security credentials are not available in
// environment variables.
this.securityCredentialsUrl = options.credential_source.url;
this.regionalCredVerificationUrl =
options.credential_source.regional_cred_verification_url;
this.imdsV2SessionTokenUrl =
options.credential_source.imdsv2_session_token_url;
const match = this.environmentId?.match(/^(aws)(\d+)$/);
if (!match || !this.regionalCredVerificationUrl) {
throw new Error('No valid AWS "credential_source" provided');
} else if (parseInt(match[2], 10) !== 1) {
throw new Error(
`aws version "${match[2]}" is not supported in the current build.`
);
}
this.awsRequestSigner = null;
this.region = '';
}
/**
* Triggered when an external subject token is needed to be exchanged for a
* GCP access token via GCP STS endpoint.
* This uses the `options.credential_source` object to figure out how
* to retrieve the token using the current environment. In this case,
* this uses a serialized AWS signed request to the STS GetCallerIdentity
* endpoint.
* The logic is summarized as:
* 1. If imdsv2_session_token_url is provided in the credential source, then
* fetch the aws session token and include it in the headers of the
* metadata requests. This is a requirement for IDMSv2 but optional
* for IDMSv1.
* 2. Retrieve AWS region from availability-zone.
* 3a. Check AWS credentials in environment variables. If not found, get
* from security-credentials endpoint.
* 3b. Get AWS credentials from security-credentials endpoint. In order
* to retrieve this, the AWS role needs to be determined by calling
* security-credentials endpoint without any argument. Then the
* credentials can be retrieved via: security-credentials/role_name
* 4. Generate the signed request to AWS STS GetCallerIdentity action.
* 5. Inject x-goog-cloud-target-resource into header and serialize the
* signed request. This will be the subject-token to pass to GCP STS.
* @return A promise that resolves with the external subject token.
*/
async retrieveSubjectToken(): Promise<string> {
// Initialize AWS request signer if not already initialized.
if (!this.awsRequestSigner) {
const metadataHeaders: Headers = {};
if (this.imdsV2SessionTokenUrl) {
metadataHeaders['x-aws-ec2-metadata-token'] =
await this.getImdsV2SessionToken();
}
this.region = await this.getAwsRegion(metadataHeaders);
this.awsRequestSigner = new AwsRequestSigner(async () => {
// Check environment variables for permanent credentials first.
// https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html
if (
process.env['AWS_ACCESS_KEY_ID'] &&
process.env['AWS_SECRET_ACCESS_KEY']
) {
return {
accessKeyId: process.env['AWS_ACCESS_KEY_ID']!,
secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY']!,
// This is normally not available for permanent credentials.
token: process.env['AWS_SESSION_TOKEN'],
};
}
// Since the role on a VM can change, we don't need to cache it.
const roleName = await this.getAwsRoleName(metadataHeaders);
// Temporary credentials typically last for several hours.
// Expiration is returned in response.
// Consider future optimization of this logic to cache AWS tokens
// until their natural expiration.
const awsCreds = await this.getAwsSecurityCredentials(
roleName,
metadataHeaders
);
return {
accessKeyId: awsCreds.AccessKeyId,
secretAccessKey: awsCreds.SecretAccessKey,
token: awsCreds.Token,
};
}, this.region);
}
// Generate signed request to AWS STS GetCallerIdentity API.
// Use the required regional endpoint. Otherwise, the request will fail.
const options = await this.awsRequestSigner.getRequestOptions({
url: this.regionalCredVerificationUrl.replace('{region}', this.region),
method: 'POST',
});
// The GCP STS endpoint expects the headers to be formatted as:
// [
// {key: 'x-amz-date', value: '...'},
// {key: 'Authorization', value: '...'},
// ...
// ]
// And then serialized as:
// encodeURIComponent(JSON.stringify({
// url: '...',
// method: 'POST',
// headers: [{key: 'x-amz-date', value: '...'}, ...]
// }))
const reformattedHeader: {key: string; value: string}[] = [];
const extendedHeaders = Object.assign(
{
// The full, canonical resource name of the workload identity pool
// provider, with or without the HTTPS prefix.
// Including this header as part of the signature is recommended to
// ensure data integrity.
'x-goog-cloud-target-resource': this.audience,
},
options.headers
);
// Reformat header to GCP STS expected format.
for (const key in extendedHeaders) {
reformattedHeader.push({
key,
value: extendedHeaders[key],
});
}
// Serialize the reformatted signed request.
return encodeURIComponent(
JSON.stringify({
url: options.url,
method: options.method,
headers: reformattedHeader,
})
);
}
/**
* @return A promise that resolves with the IMDSv2 Session Token.
*/
private async getImdsV2SessionToken(): Promise<string> {
const opts: GaxiosOptions = {
url: this.imdsV2SessionTokenUrl,
method: 'PUT',
responseType: 'text',
headers: {'x-aws-ec2-metadata-token-ttl-seconds': '300'},
};
const response = await this.transporter.request<string>(opts);
return response.data;
}
/**
* @param headers The headers to be used in the metadata request.
* @return A promise that resolves with the current AWS region.
*/
private async getAwsRegion(headers: Headers): Promise<string> {
// Priority order for region determination:
// AWS_REGION > AWS_DEFAULT_REGION > metadata server.
if (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']) {
return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'])!;
}
if (!this.regionUrl) {
throw new Error(
'Unable to determine AWS region due to missing ' +
'"options.credential_source.region_url"'
);
}
const opts: GaxiosOptions = {
url: this.regionUrl,
method: 'GET',
responseType: 'text',
headers: headers,
};
const response = await this.transporter.request<string>(opts);
// Remove last character. For example, if us-east-2b is returned,
// the region would be us-east-2.
return response.data.substr(0, response.data.length - 1);
}
/**
* @param headers The headers to be used in the metadata request.
* @return A promise that resolves with the assigned role to the current
* AWS VM. This is needed for calling the security-credentials endpoint.
*/
private async getAwsRoleName(headers: Headers): Promise<string> {
if (!this.securityCredentialsUrl) {
throw new Error(
'Unable to determine AWS role name due to missing ' +
'"options.credential_source.url"'
);
}
const opts: GaxiosOptions = {
url: this.securityCredentialsUrl,
method: 'GET',
responseType: 'text',
headers: headers,
};
const response = await this.transporter.request<string>(opts);
return response.data;
}
/**
* Retrieves the temporary AWS credentials by calling the security-credentials
* endpoint as specified in the `credential_source` object.
* @param roleName The role attached to the current VM.
* @param headers The headers to be used in the metadata request.
* @return A promise that resolves with the temporary AWS credentials
* needed for creating the GetCallerIdentity signed request.
*/
private async getAwsSecurityCredentials(
roleName: string,
headers: Headers
): Promise<AwsSecurityCredentials> {
const response = await this.transporter.request<AwsSecurityCredentials>({
url: `${this.securityCredentialsUrl}/${roleName}`,
responseType: 'json',
headers: headers,
});
return response.data;
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Users } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { GraphRbacManagementClient } from "../graphRbacManagementClient";
import {
User,
UsersListNextOptionalParams,
UsersListOptionalParams,
UserGetMemberGroupsParameters,
UsersGetMemberGroupsOptionalParams,
UserCreateParameters,
UsersCreateOptionalParams,
UsersCreateResponse,
UsersListResponse,
UsersGetOptionalParams,
UsersGetResponse,
UserUpdateParameters,
UsersUpdateOptionalParams,
UsersDeleteOptionalParams,
UsersGetMemberGroupsResponse,
UsersListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Users operations. */
export class UsersImpl implements Users {
private readonly client: GraphRbacManagementClient;
/**
* Initialize a new instance of the class Users class.
* @param client Reference to the service client
*/
constructor(client: GraphRbacManagementClient) {
this.client = client;
}
/**
* Gets list of users for the current tenant.
* @param options The options parameters.
*/
public list(
options?: UsersListOptionalParams
): PagedAsyncIterableIterator<User> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: UsersListOptionalParams
): AsyncIterableIterator<User[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.odataNextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.odataNextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: UsersListOptionalParams
): AsyncIterableIterator<User> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Gets a collection that contains the object IDs of the groups of which the user is a member.
* @param objectId The object ID of the user for which to get group membership.
* @param parameters User filtering parameters.
* @param options The options parameters.
*/
public listMemberGroups(
objectId: string,
parameters: UserGetMemberGroupsParameters,
options?: UsersGetMemberGroupsOptionalParams
): PagedAsyncIterableIterator<string> {
const iter = this.getMemberGroupsPagingAll(objectId, parameters, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getMemberGroupsPagingPage(objectId, parameters, options);
}
};
}
private async *getMemberGroupsPagingPage(
objectId: string,
parameters: UserGetMemberGroupsParameters,
options?: UsersGetMemberGroupsOptionalParams
): AsyncIterableIterator<string[]> {
let result = await this._getMemberGroups(objectId, parameters, options);
yield result.value || [];
}
private async *getMemberGroupsPagingAll(
objectId: string,
parameters: UserGetMemberGroupsParameters,
options?: UsersGetMemberGroupsOptionalParams
): AsyncIterableIterator<string> {
for await (const page of this.getMemberGroupsPagingPage(
objectId,
parameters,
options
)) {
yield* page;
}
}
/**
* Gets a list of users for the current tenant.
* @param nextLink Next link for the list operation.
* @param options The options parameters.
*/
public listNext(
nextLink: string,
options?: UsersListNextOptionalParams
): PagedAsyncIterableIterator<User> {
const iter = this.listNextPagingAll(nextLink, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listNextPagingPage(nextLink, options);
}
};
}
private async *listNextPagingPage(
nextLink: string,
options?: UsersListNextOptionalParams
): AsyncIterableIterator<User[]> {
let result = await this._listNext(nextLink, options);
yield result.value || [];
let continuationToken = result.odataNextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.odataNextLink;
yield result.value || [];
}
}
private async *listNextPagingAll(
nextLink: string,
options?: UsersListNextOptionalParams
): AsyncIterableIterator<User> {
for await (const page of this.listNextPagingPage(nextLink, options)) {
yield* page;
}
}
/**
* Create a new user.
* @param parameters Parameters to create a user.
* @param options The options parameters.
*/
create(
parameters: UserCreateParameters,
options?: UsersCreateOptionalParams
): Promise<UsersCreateResponse> {
return this.client.sendOperationRequest(
{ parameters, options },
createOperationSpec
);
}
/**
* Gets list of users for the current tenant.
* @param options The options parameters.
*/
private _list(options?: UsersListOptionalParams): Promise<UsersListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Gets user information from the directory.
* @param upnOrObjectId The object ID or principal name of the user for which to get information.
* @param options The options parameters.
*/
get(
upnOrObjectId: string,
options?: UsersGetOptionalParams
): Promise<UsersGetResponse> {
return this.client.sendOperationRequest(
{ upnOrObjectId, options },
getOperationSpec
);
}
/**
* Updates a user.
* @param upnOrObjectId The object ID or principal name of the user to update.
* @param parameters Parameters to update an existing user.
* @param options The options parameters.
*/
update(
upnOrObjectId: string,
parameters: UserUpdateParameters,
options?: UsersUpdateOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ upnOrObjectId, parameters, options },
updateOperationSpec
);
}
/**
* Delete a user.
* @param upnOrObjectId The object ID or principal name of the user to delete.
* @param options The options parameters.
*/
delete(
upnOrObjectId: string,
options?: UsersDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ upnOrObjectId, options },
deleteOperationSpec
);
}
/**
* Gets a collection that contains the object IDs of the groups of which the user is a member.
* @param objectId The object ID of the user for which to get group membership.
* @param parameters User filtering parameters.
* @param options The options parameters.
*/
private _getMemberGroups(
objectId: string,
parameters: UserGetMemberGroupsParameters,
options?: UsersGetMemberGroupsOptionalParams
): Promise<UsersGetMemberGroupsResponse> {
return this.client.sendOperationRequest(
{ objectId, parameters, options },
getMemberGroupsOperationSpec
);
}
/**
* Gets a list of users for the current tenant.
* @param nextLink Next link for the list operation.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: UsersListNextOptionalParams
): Promise<UsersListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/users",
httpMethod: "POST",
responses: {
201: {
bodyMapper: Mappers.User
},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters11,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.tenantID],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/users",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.UserListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [Parameters.$host, Parameters.tenantID],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/users/{upnOrObjectId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.User
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.upnOrObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/users/{upnOrObjectId}",
httpMethod: "PATCH",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters12,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.upnOrObjectId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/users/{upnOrObjectId}",
httpMethod: "DELETE",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.upnOrObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const getMemberGroupsOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/users/{objectId}/getMemberGroups",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.UserGetMemberGroupsResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters13,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.tenantID, Parameters.objectId],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.UserListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.tenantID, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [managedblockchain](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonmanagedblockchain.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Managedblockchain extends PolicyStatement {
public servicePrefix = 'managedblockchain';
/**
* Statement provider for service [managedblockchain](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonmanagedblockchain.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a member of an Amazon Managed Blockchain network
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_CreateMember.html
*/
public toCreateMember() {
return this.to('CreateMember');
}
/**
* Grants permission to create an Amazon Managed Blockchain network
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_CreateNetwork.html
*/
public toCreateNetwork() {
return this.to('CreateNetwork');
}
/**
* Grants permission to create a node within a member of an Amazon Managed Blockchain network
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_CreateNode.html
*/
public toCreateNode() {
return this.to('CreateNode');
}
/**
* Grants permission to create a proposal that other blockchain network members can vote on to add or remove a member in an Amazon Managed Blockchain network
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_CreateProposal.html
*/
public toCreateProposal() {
return this.to('CreateProposal');
}
/**
* Grants permission to delete a member and all associated resources from an Amazon Managed Blockchain network
*
* Access Level: Write
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_DeleteMember.html
*/
public toDeleteMember() {
return this.to('DeleteMember');
}
/**
* Grants permission to delete a node from a member of an Amazon Managed Blockchain network
*
* Access Level: Write
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_DeleteNode.html
*/
public toDeleteNode() {
return this.to('DeleteNode');
}
/**
* Grants permission to return detailed information about a member of an Amazon Managed Blockchain network
*
* Access Level: Read
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_GetMember.html
*/
public toGetMember() {
return this.to('GetMember');
}
/**
* Grants permission to return detailed information about an Amazon Managed Blockchain network
*
* Access Level: Read
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_GetNetwork.html
*/
public toGetNetwork() {
return this.to('GetNetwork');
}
/**
* Grants permission to return detailed information about a node within a member of an Amazon Managed Blockchain network
*
* Access Level: Read
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_GetNode.html
*/
public toGetNode() {
return this.to('GetNode');
}
/**
* Grants permission to return detailed information about a proposal of an Amazon Managed Blockchain network
*
* Access Level: Read
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_GetProposal.html
*/
public toGetProposal() {
return this.to('GetProposal');
}
/**
* Grants permission to list the invitations extended to the active AWS account from any Managed Blockchain network
*
* Access Level: List
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListInvitations.html
*/
public toListInvitations() {
return this.to('ListInvitations');
}
/**
* Grants permission to list the members of an Amazon Managed Blockchain network and the properties of their memberships
*
* Access Level: List
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListMembers.html
*/
public toListMembers() {
return this.to('ListMembers');
}
/**
* Grants permission to list the Amazon Managed Blockchain networks in which the current AWS account participates
*
* Access Level: List
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListNetworks.html
*/
public toListNetworks() {
return this.to('ListNetworks');
}
/**
* Grants permission to list the nodes within a member of an Amazon Managed Blockchain network
*
* Access Level: List
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListNodes.html
*/
public toListNodes() {
return this.to('ListNodes');
}
/**
* Grants permission to list all votes for a proposal, including the value of the vote and the unique identifier of the member that cast the vote for the given Amazon Managed Blockchain network
*
* Access Level: Read
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListProposalVotes.html
*/
public toListProposalVotes() {
return this.to('ListProposalVotes');
}
/**
* Grants permission to list proposals for the given Amazon Managed Blockchain network
*
* Access Level: List
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListProposals.html
*/
public toListProposals() {
return this.to('ListProposals');
}
/**
* Grants permission to view tags associated with an Amazon Managed Blockchain resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to reject the invitation to join the blockchain network
*
* Access Level: Write
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_RejectInvitation.html
*/
public toRejectInvitation() {
return this.to('RejectInvitation');
}
/**
* Grants permission to add tags to an Amazon Managed Blockchain resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove tags from an Amazon Managed Blockchain resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a member of an Amazon Managed Blockchain network
*
* Access Level: Write
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_UpdateMember.html
*/
public toUpdateMember() {
return this.to('UpdateMember');
}
/**
* Grants permission to update a node from a member of an Amazon Managed Blockchain network
*
* Access Level: Write
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_UpdateNode.html
*/
public toUpdateNode() {
return this.to('UpdateNode');
}
/**
* Grants permission to cast a vote for a proposal on behalf of the blockchain network member specified
*
* Access Level: Write
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_VoteOnProposal.html
*/
public toVoteOnProposal() {
return this.to('VoteOnProposal');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateMember",
"CreateNetwork",
"CreateNode",
"CreateProposal",
"DeleteMember",
"DeleteNode",
"RejectInvitation",
"UpdateMember",
"UpdateNode",
"VoteOnProposal"
],
"Read": [
"GetMember",
"GetNetwork",
"GetNode",
"GetProposal",
"ListProposalVotes",
"ListTagsForResource"
],
"List": [
"ListInvitations",
"ListMembers",
"ListNetworks",
"ListNodes",
"ListProposals"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type network to the statement
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_Network.html
*
* @param networkId - Identifier for the networkId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onNetwork(networkId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:managedblockchain:${Region}::networks/${NetworkId}';
arn = arn.replace('${NetworkId}', networkId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type member to the statement
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_Member.html
*
* @param memberId - Identifier for the memberId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onMember(memberId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:managedblockchain:${Region}:${Account}:members/${MemberId}';
arn = arn.replace('${MemberId}', memberId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type node to the statement
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_Node.html
*
* @param nodeId - Identifier for the nodeId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onNode(nodeId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:managedblockchain:${Region}:${Account}:nodes/${NodeId}';
arn = arn.replace('${NodeId}', nodeId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type proposal to the statement
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_Proposal.html
*
* @param proposalId - Identifier for the proposalId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onProposal(proposalId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:managedblockchain:${Region}::proposals/${ProposalId}';
arn = arn.replace('${ProposalId}', proposalId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type invitation to the statement
*
* https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/API_Invitation.html
*
* @param invitationId - Identifier for the invitationId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onInvitation(invitationId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:managedblockchain:${Region}:${Account}:invitations/${InvitationId}';
arn = arn.replace('${InvitationId}', invitationId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import i18next from "i18next";
import { action, computed, runInAction } from "mobx";
import URI from "urijs";
import isDefined from "../../../Core/isDefined";
import loadJson from "../../../Core/loadJson";
import runLater from "../../../Core/runLater";
import CatalogMemberMixin from "../../../ModelMixins/CatalogMemberMixin";
import GroupMixin from "../../../ModelMixins/GroupMixin";
import UrlMixin from "../../../ModelMixins/UrlMixin";
import ModelReference from "../../../Traits/ModelReference";
import {
InfoSectionTraits,
MetadataUrlTraits
} from "../../../Traits/TraitsClasses/CatalogMemberTraits";
import SocrataCatalogGroupTraits, {
FacetFilterTraits
} from "../../../Traits/TraitsClasses/SocrataCatalogGroupTraits";
import CatalogGroup from "../CatalogGroup";
import CommonStrata from "../../Definition/CommonStrata";
import CreateModel from "../../Definition/CreateModel";
import createStratumInstance from "../../Definition/createStratumInstance";
import CsvCatalogItem from "../CatalogItems/CsvCatalogItem";
import GeoJsonCatalogItem from "../CatalogItems/GeoJsonCatalogItem";
import LoadableStratum from "../../Definition/LoadableStratum";
import { BaseModel } from "../../Definition/Model";
import proxyCatalogItemUrl from "../proxyCatalogItemUrl";
import SocrataMapViewCatalogItem from "../CatalogItems/SocrataMapViewCatalogItem";
import StratumOrder from "../../Definition/StratumOrder";
import TerriaError, { networkRequestError } from "../../../Core/TerriaError";
export interface Facet {
facet: string;
count: number;
values: { value: string; count: number }[];
}
export interface ResultResponse {
resultSetSize: number;
timings: unknown;
results: Result[];
}
export interface Result {
resource: {
name: string;
id: string;
parent_fxf: unknown;
description?: string;
attribution?: string;
attribution_link?: string;
contact_email?: string;
type: "dataset" | "map" | undefined;
updatedAt: string;
createdAt: string;
metadata_updated_at: string;
data_updated_at: string;
// publication_date: string; not sure if this is official
page_views: {
page_views_last_week: number;
page_views_last_month: number;
page_views_total: number;
page_views_last_week_log: number;
page_views_last_month_log: number;
page_views_total_log: number;
};
columns_name: string[];
columns_field_name: string[];
columns_datatype: string[];
columns_description: string[];
columns_format: {
precisionStyle?: string;
noCommas?: string;
align?: string;
}[];
download_count: number;
provenance: string;
lens_view_type:
| "tabular"
| "blobby"
| "href"
| "geo"
| "story"
| "measure"
| "gateway_plugin"
| undefined;
blob_mime_type: null | string;
hide_from_data_json: boolean;
};
classification: {
categories: string[];
tags: string[];
domain_category: string;
domain_tags: string[];
domain_metadata: { key: string; value: string }[];
};
metadata: {
domain: string;
license: string;
};
permalink: string;
link: string;
owner?: {
id: string;
user_type?: string;
display_name: string;
};
creator?: {
id: string;
user_type?: string;
display_name: string;
};
}
export interface SocrataError {
code?: string;
error: true | string;
message?: string;
}
export class SocrataCatalogStratum extends LoadableStratum(
SocrataCatalogGroupTraits
) {
static stratumName = "socrataCatalog";
static async load(
catalogGroup: SocrataCatalogGroup
): Promise<SocrataCatalogStratum> {
if (!catalogGroup.url) throw "`url` must be set";
const filterQuery = Object.assign({}, catalogGroup.filterQuery, {
only: "dataset,map"
});
const domain = URI(catalogGroup.url).hostname();
let facets: Facet[] = [];
let results: Result[] = [];
// If not facet filters have been set - get facets
if (
!isDefined(catalogGroup.facetFilters) ||
catalogGroup.facetFilters.length === 0
) {
const facetsToUse = catalogGroup.facetGroups;
const facetUri = URI(
`${catalogGroup.url}/api/catalog/v1/domains/${domain}/facets`
).addQuery(filterQuery);
const facetResponse = await loadJson(
proxyCatalogItemUrl(catalogGroup, facetUri.toString())
);
if (facetResponse.error) {
throw facetResponse.message ?? facetResponse.error;
}
facets = facetResponse;
if (!Array.isArray(facets))
throw `Could not fetch facets for domain ${domain}`;
facets = facets.filter(f => facetsToUse.includes(f.facet));
if (facets.length === 0)
throw `Could not find any facets for domain ${domain}`;
}
// If facetFilter is set, use it to search for datasets (aka resources)
else {
const resultsUri = URI(
`${catalogGroup.url}/api/catalog/v1?search_context=${domain}`
).addQuery(filterQuery);
catalogGroup.facetFilters.forEach(({ name, value }) =>
name && isDefined(value) ? resultsUri.addQuery(name, value) : null
);
const resultsResponse = await loadJson(
proxyCatalogItemUrl(catalogGroup, resultsUri.toString())
);
if (resultsResponse.error) {
throw resultsResponse.message ?? resultsResponse.error;
}
results = (resultsResponse as ResultResponse).results;
if (!Array.isArray(results) || results.length === 0)
throw `Could not find any results for domain ${domain} and facets: ${catalogGroup.facetFilters
.map(({ name, value }) => `${name} = ${value}`)
.join(", ")}`;
}
return new SocrataCatalogStratum(catalogGroup, facets, results);
}
duplicateLoadableStratum(model: BaseModel): this {
return new SocrataCatalogStratum(
model as SocrataCatalogGroup,
this.facets,
this.results
) as this;
}
constructor(
private readonly catalogGroup: SocrataCatalogGroup,
private readonly facets: Facet[],
private readonly results: Result[]
) {
super();
}
@computed
get members(): ModelReference[] {
// If we only have one facet, return it's children instead of a single facet group
if (this.facets.length === 1)
return this.facets[0].values.map(
facetValue => `${this.getFacetId(this.facets[0])}/${facetValue.value}`
);
return [
...this.facets.map(f => this.getFacetId(f)),
...this.results.map(r => this.getResultId(r))
];
}
createMembers() {
this.facets.forEach(facet => this.createGroupFromFacet(facet));
this.results.forEach(result => this.createItemFromResult(result));
}
/** Turn facet into SocrataCatalogGroup */
@action
createGroupFromFacet(facet: Facet) {
const facetGroupId = this.getFacetId(facet);
// Create group for Facet
let facetGroup = this.catalogGroup.terria.getModelById(
CatalogGroup,
facetGroupId
);
if (facetGroup === undefined) {
facetGroup = new CatalogGroup(
facetGroupId,
this.catalogGroup.terria,
undefined
);
this.catalogGroup.terria.addModel(facetGroup);
}
// Replace the stratum inherited from the parent group.
const stratum = CommonStrata.underride;
facetGroup.strata.delete(stratum);
facetGroup.setTrait(stratum, "name", facet.facet);
// Create child groups for Facet values
facet.values.forEach(facetValue => {
const facetValueId = `${facetGroupId}/${facetValue.value}`;
let facetValueGroup = this.catalogGroup.terria.getModelById(
SocrataCatalogGroup,
facetValueId
);
if (facetValueGroup === undefined) {
facetValueGroup = new SocrataCatalogGroup(
facetValueId,
this.catalogGroup.terria,
undefined
);
this.catalogGroup.terria.addModel(facetValueGroup);
}
// Replace the stratum inherited from the parent group.
const stratum = CommonStrata.underride;
facetValueGroup.strata.delete(stratum);
facetValueGroup.setTrait(
stratum,
"name",
`${facetValue.value}${
facetValue.count ? ` (${facetValue.count ?? 0})` : ""
}`
);
facetValueGroup.setTrait(stratum, "url", this.catalogGroup.url);
facetValueGroup.setTrait(stratum, "facetFilters", [
createStratumInstance(FacetFilterTraits, {
name: facet.facet,
value: facetValue.value
})
]);
facetGroup!.add(CommonStrata.underride, facetValueGroup);
});
}
/** Turn Result into catalog item
* If type is 'dataset':
* - If has geometery -> create GeoJSONCatalogItem
* - Otherwise -> create CsvCatalogItem
* If type is 'map' -> SocrataMapViewCatalogItem
* - Then the Socrata `views` API will be used to fetch data (this mimics how Socrata portal map visualisation works - it isn't an official API)
*/
@action
createItemFromResult(result: Result) {
const resultId = this.getResultId(result);
const stratum = CommonStrata.underride;
let resultModel:
| CsvCatalogItem
| GeoJsonCatalogItem
| SocrataMapViewCatalogItem
| undefined;
// If dataset resource
// - If has geometery - create GeoJSONCatalogItem
// - Otherwise - create CsvCatalogItem
if (result.resource.type === "dataset") {
if (
result.resource.columns_datatype.find(type =>
[
"Point",
"Line",
"Polygon",
"MultiLine",
"MultiPoint",
"MultiPolygon",
"Location"
].includes(type)
)
) {
resultModel = this.catalogGroup.terria.getModelById(
GeoJsonCatalogItem,
resultId
);
if (resultModel === undefined) {
resultModel = new GeoJsonCatalogItem(
resultId,
this.catalogGroup.terria,
undefined
);
this.catalogGroup.terria.addModel(resultModel);
}
// Replace the stratum inherited from the parent group.
resultModel.strata.delete(stratum);
resultModel.setTrait(
stratum,
"url",
`${this.catalogGroup.url}/resource/${result.resource.id}.geojson?$limit=10000`
);
} else {
resultModel = this.catalogGroup.terria.getModelById(
CsvCatalogItem,
resultId
);
if (resultModel === undefined) {
resultModel = new CsvCatalogItem(
resultId,
this.catalogGroup.terria,
undefined
);
this.catalogGroup.terria.addModel(resultModel);
}
// Replace the stratum inherited from the parent group.
resultModel.strata.delete(stratum);
resultModel.setTrait(
stratum,
"url",
`${this.catalogGroup.url}/resource/${result.resource.id}.csv?$limit=10000`
);
}
// If type is 'map' -> SocrataMapViewCatalogItem
} else if (result.resource.type === "map") {
resultModel = this.catalogGroup.terria.getModelById(
SocrataMapViewCatalogItem,
resultId
);
if (resultModel === undefined) {
resultModel = new SocrataMapViewCatalogItem(
resultId,
this.catalogGroup.terria,
undefined
);
this.catalogGroup.terria.addModel(resultModel);
}
// Replace the stratum inherited from the parent group.
resultModel.strata.delete(stratum);
resultModel.setTrait(stratum, "url", this.catalogGroup.url);
resultModel.setTrait(stratum, "resourceId", result.resource.id);
}
if (resultModel) {
resultModel.setTrait(stratum, "name", result.resource.name);
resultModel.setTrait(stratum, "description", result.resource.description);
resultModel.setTrait(stratum, "attribution", result.resource.attribution);
resultModel.setTrait(stratum, "info", [
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.socrataServer.licence"),
content: result.metadata.license
}),
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.socrataServer.tags"),
content: result.classification.tags.join(", ")
}),
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.socrataServer.attributes"),
content: result.resource.columns_name.join(", ")
})
]);
resultModel.setTrait(stratum, "metadataUrls", [
createStratumInstance(MetadataUrlTraits, {
title: i18next.t("models.openDataSoft.viewDatasetPage"),
url: result.permalink
})
]);
}
}
getFacetId(facet: Facet) {
return `${this.catalogGroup.uniqueId}/${facet.facet}`;
}
getResultId(result: Result) {
return `${this.catalogGroup.uniqueId}/${result.resource.id}`;
}
}
StratumOrder.addLoadStratum(SocrataCatalogStratum.stratumName);
export default class SocrataCatalogGroup extends UrlMixin(
GroupMixin(CatalogMemberMixin(CreateModel(SocrataCatalogGroupTraits)))
) {
static readonly type = "socrata-group";
get type() {
return SocrataCatalogGroup.type;
}
protected async forceLoadMetadata(): Promise<void> {
try {
if (!this.strata.has(SocrataCatalogStratum.stratumName)) {
const stratum = await SocrataCatalogStratum.load(this);
runInAction(() => {
this.strata.set(SocrataCatalogStratum.stratumName, stratum);
});
}
} catch (e) {
networkRequestError(
TerriaError.from(e, {
message: { key: "models.socrataServer.retrieveErrorMessage" }
})
);
}
}
protected async forceLoadMembers() {
const socrataServerStratum = <SocrataCatalogStratum | undefined>(
this.strata.get(SocrataCatalogStratum.stratumName)
);
if (socrataServerStratum) {
await runLater(() => socrataServerStratum.createMembers());
}
}
} | the_stack |
// this file is for drawing score.
module Inknote {
function getBarLength(bar: Model.Bar): number {
var length = 20;
for (var i = 0; i < bar.items.length; i++) {
var item = bar.items[i];
if (item instanceof Model.Clef) {
length += requiredClefSpace(item, 10);
}
if (item instanceof Model.Note) {
length += requiredNoteSpace(item, 10);
}
if (item instanceof Model.Rest) {
length += requiredRestSpace(item, 10);
}
if (item instanceof Model.TimeSignature) {
length += requiredTimeSignatureSpace(item, 10);
}
}
return length;
}
function getMinBarLengths(instruments: Model.Instrument[]): number[] {
var barLengths = [];
for (var i = 0; i < instruments[0].bars.length; i++) {
var maxBarLength = 0;
for (var j = 0; j < instruments.length; j++) {
var barLength = getBarLength(instruments[j].bars[i]);
maxBarLength = Math.max(maxBarLength, barLength);
}
barLengths.push(maxBarLength);
}
return barLengths;
}
class BarLine {
minLength: number = 0;
barLengths: number[] = [];
barIndices: number[] = [];
}
function splitBarsToLines(barLengths: number[], splitLength: number): BarLine[] {
var barLines: BarLine[] = [];
var tempBarLine = new BarLine();
for (var i = 0; i < barLengths.length; i++) {
if (tempBarLine.minLength + barLengths[i] > splitLength) {
barLines.push(tempBarLine);
tempBarLine = new BarLine();
}
tempBarLine.minLength += barLengths[i];
tempBarLine.barIndices.push(i);
tempBarLine.barLengths.push(barLengths[i]);
}
barLines.push(tempBarLine);
return barLines;
}
// will store all score drawable items and update when necessary.
export class ScoringService {
private static _instance: ScoringService;
static get Instance(): ScoringService {
if (!ScoringService._instance) {
ScoringService._instance = new ScoringService();
}
return ScoringService._instance;
}
private _refresh: boolean = false;
private _projectID: string;
private _items: IDrawable[] = [];
// use this instead of normal push.
addItem(item: IDrawable) {
this._items.push(item);
}
hoverID: string;
selectID: string;
maxScrollPosition: number = 0;
oldScrollY: number = 0;
// todo: ensure
// should refresh on:
// change of window size -- actions -> windowResize.
// change of project -- Done in here inside getItems().
// change of score.
// (but not on change of hover/select
// -- that should be handled in individual objects).
refresh(): void {
this._refresh = true;
}
updateItems(): void {
if (!DrawService.Instance) {
// depends on drawservice.
log("draw service not instantiated", MessageType.Error);
return;
}
// scrolling is handled in get items function.
this.oldScrollY = 0;
var currentProject = Managers.ProjectManager.Instance.currentProject;
this._projectID = currentProject.ID;
// must clear items!
this._items = [];
var visibleInstruments = <Model.Instrument[]>getItemsWhere(currentProject.instruments,
function (instrument: Model.Instrument) {
return instrument.visible;
});
if (visibleInstruments.length === 0) {
return;
}
var barMinLengths = getMinBarLengths(visibleInstruments);
var topLineHeight = 180;
var marginLeft = 50;
if (DrawService.Instance.canvas.width < 600) {
marginLeft = 0;
}
var barX = 0;
var barIndex = 0;
var maxWidth = DrawService.Instance.canvas.width - 2 * marginLeft;
var clefAdditionalPosition = 0;
var lines = splitBarsToLines(barMinLengths, maxWidth);
// loop through lines
for (var i = 0; i < lines.length; i++) {
var tempLine = lines[i];
// loop through instruments
for (var j = 0; j < visibleInstruments.length; j++) {
var tempInstrument = visibleInstruments[j];
if (tempInstrument["clefAdditionalPosition"]) {
clefAdditionalPosition = tempInstrument["clefAdditionalPosition"];
}
else {
clefAdditionalPosition = 0;
}
// add stave
var drawStave = new Drawing.Stave(topLineHeight, tempInstrument.name);
drawStave.x = marginLeft;
drawStave.width = maxWidth;
this.addItem(drawStave);
// loop through bars in line
// warning: do not use k. use the barIndex values.
for (var k = 0; k < tempLine.barIndices.length; k++) {
var tempBarLength = tempLine.barLengths[k];
var bar = tempInstrument.bars[tempLine.barIndices[k]];
// add bar drawing.
var drawBar = new Drawing.Bar();
drawBar.ID = bar.ID;
drawBar.height = 40;
drawBar.y = topLineHeight;
drawBar.x = marginLeft + barX;
drawBar.width = tempBarLength;
if (j == 0 && tempLine.barIndices[k] % 5 == 4) {
drawBar.barNumber = tempLine.barIndices[k] + 1;
}
if (TimeSignatureService.Instance.barHasError(bar, tempInstrument)) {
drawBar.hasError = true;
}
this.addItem(drawBar);
// for getting note position.
var itemX = 20;
for (var l = 0; l < bar.items.length; l++) {
var item = bar.items[l];
if (item instanceof Model.Clef) {
var drawClefItem = Drawing.getDrawingFromClef(item);
drawClefItem.ID = item.ID;
drawClefItem.x = marginLeft + barX + itemX;
drawClefItem.y = topLineHeight + 5 * drawClefItem.drawPosition;
clefAdditionalPosition = 5 * item.positionFromTreble;
tempInstrument["clefAdditionalPosition"] = clefAdditionalPosition;
this.addItem(drawClefItem);
itemX += requiredClefSpace(item, 10);
}
if (item instanceof Model.TimeSignature) {
var timeSignatureItem = <Model.TimeSignature>item;
var drawTimeSignatureItem = new Drawing.TimeSignature(timeSignatureItem.top, timeSignatureItem.bottom);
drawTimeSignatureItem.ID = timeSignatureItem.ID;
drawTimeSignatureItem.x = marginLeft + barX + itemX;
drawTimeSignatureItem.y = topLineHeight + 20;
this.addItem(drawTimeSignatureItem);
itemX += requiredTimeSignatureSpace(item, 10);
}
if (item instanceof Model.Note) {
var isBlack = Model.IsBlackKey(item.value);
var intervalDistance = getIntervalDistance(new Model.Note(Model.NoteValue.F, 5, Model.NoteLength.Crotchet), item);
if (isBlack) {
var drawBlack = new Drawing.Flat();
drawBlack.x = marginLeft + barX + itemX;
drawBlack.y = topLineHeight - 5 * intervalDistance + clefAdditionalPosition;
this.addItem(drawBlack);
// move forwards.
itemX += 10;
}
// add note drawing.
var drawNoteItem = getDrawingItemFromNote(item);
drawNoteItem.x = marginLeft + barX + itemX;
drawNoteItem.y = topLineHeight - 5 * intervalDistance + clefAdditionalPosition;
for (var lineSpace = 5 * intervalDistance - clefAdditionalPosition; lineSpace <= -50; lineSpace += 5) {
if (lineSpace / 10 === Math.round(lineSpace / 10)) {
var ledgerLine = new Drawing.LedgerLine(drawNoteItem.x, topLineHeight - lineSpace);
this.addItem(ledgerLine);
drawNoteItem.attach(ledgerLine);
}
}
for (var lineSpace = 5 * intervalDistance - clefAdditionalPosition; lineSpace >= 10; lineSpace -= 5){
if (lineSpace / 10 === Math.round(lineSpace / 10)) {
var ledgerLine = new Drawing.LedgerLine(drawNoteItem.x, topLineHeight - lineSpace);
this.addItem(ledgerLine);
drawNoteItem.attach(ledgerLine);
}
}
drawNoteItem.isPlaying = item.isPlaying;
drawNoteItem.stemUp = - 5 * intervalDistance + clefAdditionalPosition >= 20;
if (isBlack) {
drawNoteItem.attach(drawBlack);
}
this.addItem(drawNoteItem);
// move forwards
itemX += requiredNoteSpace(item, 10);
if (isBlack) {
// move back a bit if sharp or flat.
itemX -= 10;
}
}
if (item instanceof Model.Rest) {
// add rest drawing.
var drawRestItem = getDrawingItemFromRest(item);
drawRestItem.x = marginLeft + barX + itemX;
drawRestItem.y = topLineHeight + 20;
this.addItem(drawRestItem);
// move forwards.
itemX += requiredRestSpace(item, 10);
}
if (item instanceof Model.Chord) {
// add chord drawing.
}
if (item instanceof Model.Text) {
var scoreText = new Drawing.DrawText();
scoreText.content = item.content;
scoreText.ID = item.ID;
var lastItem = this._items[this._items.length - 1];
scoreText.x = lastItem.x;
scoreText.y = Math.max(lastItem.y + 20, topLineHeight + 70);
this.addItem(scoreText);
}
}
// increase bar position after looping through items.
barX += tempBarLength;
}
// iterate height between instruments;
topLineHeight += 120;
barX = 0;
}
// next group of staves quite a bit lower.
topLineHeight += 60;
}
this.maxScrollPosition = topLineHeight - 200;
}
get SelectedItem(): IDrawable {
for (var i = 0; i < this._items.length; i++) {
if (this._items[i].ID == this.selectID) {
if (this._items[i]["attachedToID"] == null) {
return this._items[i];
}
}
}
return null;
}
set SelectedItem(item: IDrawable) {
this.selectID = item.ID;
}
getPrintItems(): IDrawable[] {
if (this._projectID != Managers.ProjectManager.Instance.currentProject.ID) {
this.refresh();
}
if (this.refresh) {
this.updateItems();
}
return this._items;
}
getItems(): IDrawable[] {
if (this._projectID != Managers.ProjectManager.Instance.currentProject.ID) {
this.refresh();
}
if (this._refresh) {
// get items from project
this.updateItems();
}
var visibleItems = [];
// deals with scrolling.
for (var i = 0; i < this._items.length; i++) {
this._items[i].y = this._items[i].y + this.oldScrollY - ScrollService.Instance.y;
if (this._items[i].y > -50 && this._items[i].y < DrawService.Instance.canvas.height + 50) {
visibleItems.push(this._items[i]);
}
}
this.oldScrollY = ScrollService.Instance.y;
this._refresh = false;
return visibleItems;
}
cursorLeft() {
var lastID = null;
for (var i = 0; i < this._items.length; i++) {
if (this._items[i] instanceof Drawing.Stave) {
continue;
}
var id = this._items[i].ID;
if (id == this.selectID) {
this.selectID = lastID;
break;
}
lastID = id;
}
}
cursorRight() {
var lastID = null;
var gone = false;
for (var i = 0; i < this._items.length; i++) {
if (this._items[i] instanceof Drawing.Stave) {
continue;
}
var id = this._items[i].ID;
if (lastID == this.selectID && id != lastID) {
this.selectID = id;
gone = true;
break;
}
lastID = id;
}
if (!gone) {
this.selectID = null;
}
}
constructor() {
this.refresh();
}
}
} | the_stack |
module Scripting {
var gameObjects: Obj[]|null = null
var mapVars: any = null
var globalVars: any = {
0: 50, // GVAR_PLAYER_REPUTATION
//10: 1, // GVAR_START_ARROYO_TRIAL (1 = TRIAL_FIGHT)
531: 1, // GVAR_TALKED_TO_ELDER
452: 2, // GVAR_DEN_VIC_KNOWN
88: 0, // GVAR_VAULT_RAIDERS
83: 2, // GVAR_VAULT_PLANT_STATUS (9 = PLANT_REPAIRED, 2 = PLANT_ACCEPTED_QUEST)
616: 0, // GVAR_GECKO_FIND_WOODY (0 = WOODY_UNKNOWN)
345: 16, // GVAR_NEW_RENO_FLAG_2 (16 = know_mordino_bit)
357: 2, // GVAR_NEW_RENO_LIL_JESUS_REFERS (lil_jesus_refers_yes)
}
var currentMapID: number|null = null
var currentMapObject: Script|null = null
var mapFirstRun = true
var scriptMessages: { [scriptName: string]: { [msgID: number]: string } } = {}
var dialogueOptionProcs: (() => void)[] = [] // Maps dialogue options to handler callbacks
var currentDialogueObject: Obj|null = null
export var timeEventList: TimedEvent[] = []
let overrideStartPos: StartPos|null = null
export interface StartPos {
position: Point;
orientation: number;
elevation: number;
}
export interface TimedEvent {
obj: Obj|null;
ticks: number;
userdata: any;
fn: () => void;
}
var statMap: { [stat: number]: string } = {
0: "STR", 1: "PER", 2: "END", 3: "CHA", 4: "INT",
5: "AGI", 6: "LUK",
35: "HP", 7: "Max HP"
}
type DebugLogShowType = keyof typeof Config.scripting.debugLogShowType;
function stub(name: string, args: IArguments, type?: DebugLogShowType) {
if(Config.scripting.debugLogShowType.stub === false || Config.scripting.debugLogShowType[type] === false) return
var a = ""
for(var i = 0; i < args.length; i++)
if(i === args.length-1) a += args[i]
else a += args[i] + ", "
console.log("STUB: " + name + ": " + a)
}
function log(name: string, args: IArguments, type?: DebugLogShowType) {
if(Config.scripting.debugLogShowType.log === false || Config.scripting.debugLogShowType[type] === false) return
var a = ""
for(var i = 0; i < args.length; i++)
if(i === args.length-1) a += args[i]
else a += args[i] + ", "
console.log("log: " + name + ": " + a)
}
function warn(msg: string, type?: DebugLogShowType, script?: Script) {
if(type !== undefined && Config.scripting.debugLogShowType[type] === false) return
if(script)
console.log(`WARNING [${(script as any)._vm.intfile.name}]: ${msg}`)
else
console.log(`WARNING: ${msg}`)
}
export function info(msg: string, type?: DebugLogShowType, script?: Script) {
if(type !== undefined && Config.scripting.debugLogShowType[type] === false) return
if(script)
console.log(`INFO [${(script as any)._vm.intfile.name}]: ${msg}`)
else
console.log(`INFO: ${msg}`)
}
// http://stackoverflow.com/a/23304189/1958152
function seed(s: number) {
Math.random = () => {
s = Math.sin(s) * 10000;
return s - Math.floor(s)
}
}
export function getGlobalVar(gvar: number): any {
return (globalVars[gvar] !== undefined) ? globalVars[gvar] : 0
}
export function getGlobalVars(): any {
return globalVars
}
function isGameObject(obj: any) {
// TODO: just use isinstance Obj?
if(obj === undefined || obj === null) return false
if(obj.isPlayer === true) return true
if(obj.type === "item" || obj.type === "critter" || obj.type === "scenery" ||
obj.type === "wall" || obj.type === "tile" || obj.type === "misc")
return true
//warn("is NOT GO: " + obj.toString())
console.log("is NOT GO: %o", obj)
return false
}
function isSpatial(obj: any): boolean {
if(!obj)
return false
return obj.isSpatial === true
}
function getScriptName(id: number): string {
// return getLstId("scripts/scripts", id - 1).split(".")[0].toLowerCase()
return lookupScriptName(id);
}
function getScriptMessage(id: number, msg: string|number) {
if(typeof msg === "string") // passed in a string message
return msg
var name = getScriptName(id)
if(name === null) {
warn("getScriptMessage: no script with ID " + id)
return null
}
if(scriptMessages[name] === undefined)
loadMessageFile(name)
if(scriptMessages[name] === undefined)
throw "getScriptMessage: loadMessageFile failed?"
if(scriptMessages[name][msg] === undefined)
throw "getScriptMessage: no message " + msg + " for script " + id + " (" + name + ")"
return scriptMessages[name][msg]
}
export function dialogueReply(id: number): void {
var f = dialogueOptionProcs[id]
dialogueOptionProcs = []
f()
// by this point we may have already exited dialogue
if(currentDialogueObject !== null && dialogueOptionProcs.length === 0) {
// after running the option procedure we have no options...
// so close the dialogue
console.log("[dialogue exit via dialogueReply (no replies)]")
dialogueExit()
}
}
export function dialogueEnd() {
// dialogue exited from [Done] or the UI
console.log("[dialogue exit via dialogueExit]")
dialogueExit()
}
function dialogueExit() {
uiEndDialogue()
info("[dialogue exit]")
if(currentDialogueObject) {
// resume from when we halted in gsay_end
var vm = currentDialogueObject._script!._vm!
vm.pc = vm.popAddr()
info(`[resuming from gsay_end (pc=0x${vm.pc.toString(16)})]`)
vm.run()
}
currentDialogueObject = null
}
function canSee(obj: Obj, target: Obj): boolean {
const dir = Math.abs(obj.orientation - hexDirectionTo(obj.position, target.position));
return [0, 1, 5].indexOf(dir) !== -1;
}
// TODO: Thoroughly test these functions (dealing with critter LOS)
function isWithinPerception(obj: Critter, target: Critter): boolean {
const dist = hexDistance(obj.position, target.position);
const perception = critterGetStat(obj, "PER");
const sneakSkill = critterGetSkill(target, "Sneak");
let reqDist;
// TODO: Implement all of the conditionals here
if(canSee(obj, target)) {
reqDist = perception*5;
if(false /* some target flags & 2 */)
// @ts-ignore: Unreachable code error (this isn't implemented yet)
reqDist /= 2;
if(target === player) {
if(false /* is_pc_sneak_working */) {
// @ts-ignore: Unreachable code error (this isn't implemented yet)
reqDist /= 4;
if(sneakSkill > 120)
reqDist--;
}
else if(false /* is_sneaking */)
// @ts-ignore: Unreachable code error (this isn't implemented yet)
reqDist = reqDist * 2 / 3;
}
if(dist <= reqDist)
return true;
}
reqDist = inCombat ? perception*2 : perception;
if(target === player) {
if(false /* is_pc_sneak_working */) {
// @ts-ignore: Unreachable code error (this isn't implemented yet)
reqDist /= 4;
if(sneakSkill > 120)
reqDist--;
}
else if(false /* is_sneaking */)
// @ts-ignore: Unreachable code error (this isn't implemented yet)
reqDist = reqDist * 2 / 3;
}
return dist <= reqDist;
}
function objCanSeeObj(obj: Critter, target: Obj): boolean {
// Is target within obj's perception, or is it a non-critter object (without perception)?
if(target.type !== "critter" || isWithinPerception(obj, target as Critter)) {
// Then, is anything blocking obj from drawing a straight line to target?
const hit = hexLinecast(obj.position, target.position);
return !hit;
}
return false;
}
export interface SerializedScript {
name: string;
lvars: { [lvar: number]: any };
}
interface ScriptableObj {
_script: Script;
}
export class Script {
// Stuff we hacked in
_didOverride = false; // Did the procedure call override the default action?
scriptName!: string;
lvars!: { [lvar: number]: any };
_vm?: ScriptVM;
_mapScript?: Script;
// Special built-in variables
self_obj!: { _script: Script };
self_tile!: number;
cur_map_index!: number|null;
fixed_param!: number;
source_obj!: Obj|0;
target_obj!: Obj;
action_being_used!: number;
game_time_hour!: number;
combat_is_initialized!: 0 | 1;
game_time!: number;
// Script procedure prototypes
start!: () => void;
map_enter_p_proc!: () => void;
map_update_p_proc!: () => void;
timed_event_p_proc!: () => void;
critter_p_proc!: () => void;
spatial_p_proc!: () => void;
use_p_proc!: () => void;
talk_p_proc!: () => void;
pickup_p_proc!: () => void;
combat_p_proc!: () => void;
damage_p_proc!: () => void;
destroy_p_proc!: () => void;
use_skill_on_p_proc!: () => void;
// Actual scripting engine API implementations
set_global_var(gvar: number, value: any) {
globalVars[gvar] = value
info("set_global_var: " + gvar + " = " + value, "gvars")
log("set_global_var", arguments, "gvars")
}
set_local_var(lvar: number, value: any) {
this.lvars[lvar] = value
info("set_local_var: " + lvar + " = " + value + " [" + this.scriptName + "]", "lvars")
log("set_local_var", arguments, "lvars")
}
local_var(lvar: number) {
log("local_var", arguments, "lvars")
if(this.lvars[lvar] === undefined) {
warn("local_var: setting default value (0) for LVAR " + lvar, "lvars")
this.lvars[lvar] = 0
}
return this.lvars[lvar]
}
map_var(mvar: number) {
if(this._mapScript === undefined) {
warn("map_var: no map script")
return
}
var scriptName = this._mapScript.scriptName
if(scriptName === undefined) {
warn("map_var: map script has no name")
return
}
else if(mapVars[scriptName] === undefined)
mapVars[scriptName] = {}
else if(mapVars[scriptName][mvar] === undefined) {
warn("map_var: setting default value (0) for MVAR " + mvar, "mvars")
mapVars[scriptName][mvar] = 0
}
return mapVars[scriptName][mvar]
}
set_map_var(mvar: number, value: any) {
if(!this._mapScript) throw Error("set_map_var: no map script")
var scriptName = this._mapScript.scriptName
if(scriptName === undefined) {
warn("map_var: map script has no name")
return
}
info("set_map_var: " + mvar + " = " + value, "mvars")
if(mapVars[scriptName] === undefined)
mapVars[scriptName] = {}
mapVars[scriptName][mvar] = value
}
global_var(gvar: number) {
if(globalVars[gvar] === undefined) {
warn("global_var: unknown gvar " + gvar + ", using default (0)", "gvars")
globalVars[gvar] = 0
}
return globalVars[gvar]
}
random(min: number, max: number) { log("random", arguments); return getRandomInt(min, max) }
debug_msg(msg: string) { log("debug_msg", arguments); info("DEBUG MSG: [" + this.scriptName + "]: " + msg, "debugMessage") }
display_msg(msg: string) { log("display_msg", arguments); info("DISPLAY MSG: " + msg, "displayMessage"); uiLog(msg) }
message_str(msgList: number, msgNum: number) { return getScriptMessage(msgList, msgNum) }
metarule(id: number, target: number): any {
switch(id) {
case 14: return mapFirstRun // map_first_run
case 15: // elevator
if(target !== -1)
throw "elevator given explicit type"
useElevator()
break
case 17: stub("metarule", arguments); return 0 // is area known? (TODO)
case 18: return 0 // is the critter under the influence of drugs? (TODO)
case 22: return 0 // is_game_loading
case 46: return 0 // METARULE_CURRENT_TOWN (TODO: return current city ID)
case 48: return 2 // METARULE_VIOLENCE_FILTER (2 = VLNCLVL_NORMAL)
case 49: // METARULE_W_DAMAGE_TYPE
switch(objectGetDamageType(target)) {
case "explosion": return 6 // DMG_explosion
default: throw "unknown damage type"
}
default: stub("metarule", arguments); break
}
}
metarule3(id: number, obj: any, userdata: any, radius: number): any {
if(id === 100) { // METARULE3_CLR_FIXED_TIMED_EVENTS
for(var i = 0; i < timeEventList.length; i++) {
if(timeEventList[i].obj === obj &&
timeEventList[i].userdata === userdata) { // todo: game object equals
info("removing timed event (userdata " + userdata + ")", "timer")
timeEventList.splice(i, 1)
return
}
}
}
else if(id === 106) { // METARULE3_TILE_GET_NEXT_CRITTER
// As far as I know, with lastCritter == 0, it just grabs the critter that is not the player at the tile. TODO: Test this!
// TODO: use elevation
var tile = obj, elevation = userdata, lastCritter = radius
var objs = objectsAtPosition(fromTileNum(tile))
log("metarule3 106 (tile_get_next_critter)", arguments)
for(var i = 0; i < objs.length; i++) {
if(objs[i].type === "critter" && !(<Critter>objs[i]).isPlayer)
return objs[i]
}
return 0 // no critter found at that position (TODO: test)
}
stub("metarule3", arguments)
}
script_overrides() {
log("script_overrides", arguments)
info("[SCRIPT OVERRIDES]")
this._didOverride = true
}
// player
give_exp_points(xp: number) { stub("give_exp_points", arguments) }
// critters
get_critter_stat(obj: Critter, stat: number) {
if(stat === 34) { // STAT_gender
if(obj.isPlayer)
return (<Player>obj).gender === "female" ? 1 : 0
return 0 // Default to male
}
var namedStat = statMap[stat]
if(namedStat !== undefined)
return critterGetStat(obj, namedStat)
stub("get_critter_stat", arguments)
return 5
}
has_trait(traitType: number, obj: Obj, trait: number) {
if(!isGameObject(obj)) {
warn("has_trait: not game object: " + obj, undefined, this)
return 0
}
if(traitType === 1) { // TRAIT_OBJECT
switch(trait) {
case 5: break // OBJECT_AI_PACKET (TODO)
case 6: break // OBJECT_TEAM_NUM (TODO)
case 10: return obj.orientation // OBJECT_CUR_ROT
case 666: // OBJECT_VISIBILITY
return (obj.visible === false) ? 0 : 1 // 1 = visible, 0 = invisible
case 669: break // OBJECT_CUR_WEIGHT (TODO)
}
}
stub("has_trait", arguments)
return 0
}
critter_add_trait(obj: Obj, traitType: number, trait: number, amount: number) {
stub("critter_add_trait", arguments)
if(!isGameObject(obj)) {
warn("critter_add_trait: not game object: " + obj, undefined, this)
return
}
if(obj.type !== "critter") {
warn("critter_add_trait: not a critter: " + obj, undefined, this)
return
}
if(traitType === 1) { // TRAIT_OBJECT
switch(trait) {
case 5: // OBJECT_AI_PACKET
// Set critter's AI packet number
info("Setting critter AI packet to " + amount, undefined, this);
(<Critter>obj).aiNum = amount
break
case 6: // OBJECT_TEAM_NUM
// Set critter's team number
info("Setting critter team to " + amount, undefined, this);
(<Critter>obj).teamNum = amount
break
case 10: break // OBJECT_CUR_ROT (TODO)
case 666: break // OBJECT_VISIBILITY (TODO)
case 669: break // OBJECT_CUR_WEIGHT (TODO)
}
}
}
item_caps_total(obj: Obj) {
if(!isGameObject(obj)) throw "item_caps_total: not game object"
return objectGetMoney(obj)
}
item_caps_adjust(obj: Obj, amount: number) { stub("item_caps_adjust", arguments) }
move_obj_inven_to_obj(obj: Obj, other: Obj) {
if(obj === null || other === null) {
warn("move_obj_inven_to_obj: null pointer passed in")
return
}
if(!isGameObject(obj) || !isGameObject(other)) {
warn("move_obj_inven_to_obj: not game object")
return
}
info("move_obj_inven_to_obj: " + obj.inventory.length + " to " + other.inventory.length, "inventory")
other.inventory = obj.inventory
obj.inventory = []
}
obj_is_carrying_obj_pid(obj: Obj, pid: number) { // Number of inventory items with matching PID
log("obj_is_carrying_obj_pid", arguments)
if(!isGameObject(obj)) {
warn("obj_is_carrying_obj_pid: not a game object")
return 0
} else if(obj.inventory === undefined) {
warn("obj_is_carrying_obj_pid: object has no inventory!")
return 0
}
//info("obj_is_carrying_obj_pid: " + pid, "inventory")
var count = 0
for(var i = 0; i < obj.inventory.length; i++) {
if(obj.inventory[i].pid === pid) count++
}
return count
}
add_mult_objs_to_inven(obj: Obj, item: Obj, count: number) { // Add count copies of item to obj's inventory
if(!isGameObject(obj)) {
warn("add_mult_objs_to_inven: not a game object")
return
} else if(!isGameObject(item)) {
warn("add_mult_objs_to_inven: item not a game object: " + item)
return
} else if(obj.inventory === undefined) {
warn("add_mult_objs_to_inven: object has no inventory!")
return
}
//info("add_mult_objs_to_inven: " + count + " counts of " + item.toString(), "inventory")
console.log("add_mult_objs_to_inven: %d counts of %o to %o", count, item, obj)
obj.addInventoryItem(item, count)
}
rm_mult_objs_from_inven(obj: Obj, item: Obj, count: number) { // Remove count copies of item from obj's inventory
stub("rm_mult_objs_from_inven", arguments)
}
add_obj_to_inven(obj: Obj, item: Obj) {
this.add_mult_objs_to_inven(obj, item, 1)
}
rm_obj_from_inven(obj: Obj, item: Obj) {
this.rm_mult_objs_from_inven(obj, item, 1)
}
obj_carrying_pid_obj(obj: Obj, pid: number) {
log("obj_carrying_pid_obj", arguments)
if(!isGameObject(obj)) {
warn("obj_carrying_pid_obj: not a game object: " + obj)
return 0
}
for(var i = 0; i < obj.inventory.length; i++) {
if(obj.inventory[i].pid === pid)
return obj.inventory[i]
}
return 0
}
elevation(obj: Obj) { if(isSpatial(obj) || isGameObject(obj)) return currentElevation
else { warn("elevation: not an object: " + obj); return -1 } }
obj_can_see_obj(a: Critter, b: Critter) {
log("obj_can_see_obj", arguments);
if(!isGameObject(a) || !isGameObject(b)) {
warn(`obj_can_see_obj: not game object: a=${a} b=${b}`, undefined, this);
return 0;
}
return +objCanSeeObj(a, b);
}
obj_can_hear_obj(a: Obj, b: Obj) { /*stub("obj_can_hear_obj", arguments);*/ return 0 }
critter_mod_skill(obj: Obj, skill: number, amount: number) { stub("critter_mod_skill", arguments); return 0 }
using_skill(obj: Obj, skill: number) { stub("using_skill", arguments); return 0 }
has_skill(obj: Obj, skill: number) { stub("has_skill", arguments); return 100 }
roll_vs_skill(obj: Obj, skill: number, bonus: number) { stub("roll_vs_skill", arguments); return 1 }
do_check(obj: Obj, check: number, modifier: number) { stub("do_check", arguments); return 1 }
is_success(roll: number) { stub("is_success", arguments); return 1 }
is_critical(roll: number) { stub("is_critical", arguments); return 0 }
critter_inven_obj(obj: Critter, where: number) {
if(!isGameObject(obj)) throw "critter_inven_obj: not game object"
if(where === 0) {} // INVEN_TYPE_WORN
else if(where === 1) return obj.rightHand // INVEN_TYPE_RIGHT_HAND
else if(where === 2) return obj.leftHand // INVEN_TYPE_LEFT_HAND
else if(where === -2) { warn("INVEN_TYPE_INV_COUNT", "inventory", this); return 0; /*throw "INVEN_TYPE_INV_COUNT"*/ }
stub("critter_inven_obj", arguments)
return null
}
inven_cmds(obj: Critter, invenCmd: number, itemIndex: number): Obj|null {
stub("inven_cmds", arguments, "inventory");
assert(invenCmd === 13 /* INVEN_CMD_INDEX_PTR */, "Invalid invenCmd");
return null;
}
critter_attempt_placement(obj: Obj, tileNum: number, elevation: number) {
stub("critter_attempt_placement", arguments)
// TODO: it should find a place around tileNum if it's occupied
return this.move_to(obj, tileNum, elevation)
}
critter_state(obj: Critter) {
/*stub("critter_state", arguments);*/
if(!isGameObject(obj)) {
warn("critter_state: not game object: " + obj)
return 0
}
var state = 0
if(obj.dead === true)
state |= 1
// TODO: if obj is prone, state |= 2
return state
}
kill_critter(obj: Critter, deathFrame: number) {
log("kill_critter", arguments)
critterKill(obj)
}
get_poison(obj: Obj) { stub("get_poison", arguments); return 0 }
get_pc_stat(pcstat: number) {
switch(pcstat) {
case 0: // PCSTAT_unspent_skill_points
case 1: // PCSTAT_level
case 2: // PCSTAT_experience
case 3: // PCSTAT_reputation
case 4: // PCSTAT_karma
case 5: // PCSTAT_max_pc_stat
stub("get_pc_stat", arguments)
return 0
default: throw `get_pc_stat: unhandled ${pcstat}`
}
}
critter_injure(obj: Obj, how: number) { stub("critter_injure", arguments) }
critter_is_fleeing(obj: Obj) { stub("critter_is_fleeing", arguments); return 0 }
wield_obj_critter(obj: Obj, item: Obj) { stub("wield_obj_critter", arguments) }
critter_dmg(obj: Critter, damage: number, damageType: string) {
if(!isGameObject(obj)) {
warn("critter_dmg: not game object: " + obj)
return
}
critterDamage(obj, damage, this.self_obj as Critter, true, true, damageType)
}
critter_heal(obj: Obj, amount: number) {
stub("critter_heal", arguments)
}
poison(obj: Obj, amount: number) { stub("poison", arguments) }
radiation_dec(obj: Obj, amount: number) { stub("radiation_dec", arguments) }
// combat
attack_complex(obj: Obj, calledShot: number, numAttacks: number, bonus: number,
minDmg: number, maxDmg: number, attackerResults: number, targetResults: number) {
info("[enter combat via attack_complex]")
//stub("attack_complex", arguments)
// since this isn't actually used beyond its basic form, we're not going to bother
// implementing all of it
// begin combat, turn starting with us
if(Config.engine.doCombat)
Combat.start(this.self_obj as Critter)
}
terminate_combat() {
info("[terminate_combat]")
if(combat) combat.end()
}
critter_set_flee_state(obj: Obj, isFleeing: number) { stub("critter_set_flee_state", arguments) }
// objects
obj_is_locked(obj: Obj) {
log("obj_is_locked", arguments);
if(!isGameObject(obj)) {
warn("obj_is_locked: not game object: " + obj, undefined, this)
return 1
}
return obj.locked ? 1 : 0
}
obj_lock(obj: Obj) {
log("obj_lock", arguments);
if(!isGameObject(obj)) {
warn("obj_lock: not game object: " + obj, undefined, this)
return
}
obj.locked = true
}
obj_unlock(obj: Obj) {
log("obj_unlock", arguments);
if(!isGameObject(obj)) {
warn("obj_unlock: not game object: " + obj, undefined, this)
return
}
obj.locked = false
}
obj_is_open(obj: Obj) {
log("obj_is_open", arguments)
if(!isGameObject(obj)) {
warn("obj_is_open: not game object: " + obj, undefined, this)
return 0
}
return obj.open ? 1 : 0
}
obj_close(obj: Obj) {
if(!isGameObject(obj)) {
warn("obj_close: not game object: " + obj)
return
}
info("obj_close")
if(!obj.open) return
useObject(obj, this.self_obj as Critter, false)
//stub("obj_close", arguments)
}
obj_open(obj: Obj) {
if(!isGameObject(obj)) {
warn("obj_open: not game object: " + obj)
return
}
info("obj_open")
if(obj.open) return
useObject(obj, this.self_obj as Critter, false)
//stub("obj_open", arguments)
}
proto_data(pid: number, data_member: number): any { stub("proto_data", arguments); return null }
create_object_sid(pid: number, tile: number, elev: number, sid: number) { // Create object of pid and possibly script
info("create_object_sid: pid=" + pid + " tile=" + tile + " elev=" + elev + " sid=" + sid, undefined, this)
if(elev < 0 || elev > 2)
throw "create_object_sid: elev out of range: elev=" + elev
var obj = createObjectWithPID(pid, sid)
if(!obj) {
warn("create_object_sid: couldn't create object", undefined, this)
return null
}
obj.position = fromTileNum(tile)
//stub("create_object_sid", arguments)
// TODO: if tile is valid...
/*if(elevation !== currentElevation) {
warn("create_object_sid: want to create object on another elevation (current=" + currentElevation + ", elev=" + elevation + ")")
return
}*/
// add it to the map
gMap.addObject(obj, elev)
return obj
}
obj_name(obj: Obj) { return obj.name }
obj_item_subtype(obj: Obj) {
if(!isGameObject(obj)) {
warn("obj_item_subtype: not game object: " + obj)
return null
}
if(obj.type === "item" && obj.pro !== undefined)
return obj.pro.extra.subtype
stub("obj_item_subtype", arguments)
return null
}
anim_busy(obj: Obj) {
log("anim_busy", arguments)
if(!isGameObject(obj)) {
warn("anim_busy: not game object: " + obj)
return false
}
return obj.inAnim()
}
obj_art_fid(obj: Obj) { stub("obj_art_fid", arguments); return 0 }
art_anim(fid: number): number { stub("art_anim", arguments); return 0 }
set_obj_visibility(obj: Obj, visibility: number) {
if(!isGameObject(obj)) {
warn("set_obj_visibility: not a game object: " + obj)
return
}
obj.visible = !visibility
}
use_obj_on_obj(obj: Obj, who: Obj) { stub("use_obj_on_obj", arguments) }
use_obj(obj: Obj) { stub("use_obj", arguments) }
anim(obj: Obj, anim: number, param: number) {
if(!isGameObject(obj)) {
warn("anim: not a game object: " + obj)
return
}
stub("anim", arguments)
if(anim === 1000) // set rotation
obj.orientation = param
else if(anim === 1010) // set frame
obj.frame = param
else
warn("anim: unknown anim request: " + anim)
}
// environment
set_light_level(level: number) { stub("set_light_level", arguments) }
obj_set_light_level(obj: Obj, intensity: number, distance: number) { stub("obj_set_light_level", arguments) }
override_map_start(x: number, y: number, elevation: number, rotation: number) {
log("override_map_start", arguments)
info(`override_map_start: ${x}, ${y} / elevation ${elevation}`);
overrideStartPos = { position: {x, y}, orientation: rotation, elevation };
}
obj_pid(obj: Obj) {
if(!isGameObject(obj)) {
warn("obj_pid: not game object: " + obj, undefined, this)
return null
}
return obj.pid
}
obj_on_screen(obj: Obj) {
log("obj_on_screen", arguments)
if(!isGameObject(obj)) {
warn("obj_on_screen: not a game object: " + obj)
return 0
}
return objectOnScreen(obj) ? 1 : 0
}
obj_type(obj: Obj) {
if(!isGameObject(obj)) { warn("obj_type: not game object: " + obj); return null }
else if(obj.type === "critter") return 1 // critter
else if(obj.pid === undefined) { warn("obj_type: no PID"); return null }
return (obj.pid >> 24) & 0xff
}
destroy_object(obj: Obj) { // destroy object from world
log("destroy_object", arguments)
gMap.destroyObject(obj)
}
set_exit_grids(onElev: number, mapID: number, elevation: number, tileNum: number, rotation: number) {
stub("set_exit_grids", arguments)
for(var i = 0; i < gameObjects!.length; i++) {
var obj = gameObjects![i]
if(obj.type === "misc" && obj.extra && obj.extra.exitMapID !== undefined) {
obj.extra.exitMapID = mapID
obj.extra.startingPosition = tileNum
obj.extra.startingElevation = elevation
}
}
}
// tiles
tile_distance_objs(a: Obj, b: Obj) {
if((!isSpatial(a) && !isSpatial(b)) && (!isGameObject(a) || !isGameObject(b))) {
warn("tile_distance_objs: " + a + " or " + b + " are not game objects")
return null
}
return hexDistance(a.position, b.position)
}
tile_distance(a: number, b: number) {
if(a === -1 || b === -1)
return 9999
return hexDistance(fromTileNum(a), fromTileNum(b))
}
tile_num(obj: Obj) {
if(!isSpatial(obj) && !isGameObject(obj)) {
warn("tile_num: not a game object: " + obj, undefined, this)
return null
}
return toTileNum(obj.position)
}
tile_contains_pid_obj(tile: number, elevation: number, pid: number): any {
stub("tile_contains_pid_obj", arguments, "tiles")
var pos = fromTileNum(tile)
var objects = gMap.getObjects(elevation)
for(var i = 0; i < objects.length; i++) {
if(objects[i].position.x === pos.x && objects[i].position.y === pos.y &&
objects[i].pid === pid) {
return objects[i]
}
}
return 0 // it's not there
}
tile_is_visible(tile: number) {
stub("tile_is_visible", arguments, "tiles")
return 1
}
tile_num_in_direction(tile: number, direction: number, distance: number) {
if(distance === 0) {
//warn("tile_num_in_direction: distance=" + distance)
return -1
}
let newTile = hexInDirection(fromTileNum(tile), direction)
for(var i = 0; i < distance-1; i++) // repeat for each further distance
newTile = hexInDirection(newTile, direction)
return toTileNum(newTile)
}
tile_in_tile_rect(ul: number, ur: number, ll: number, lr: number, t: number) {
//stub("tile_in_tile_rect", arguments, "tiles")
const _ul = fromTileNum(ul), _ur = fromTileNum(ur)
const _ll = fromTileNum(ll), _lr = fromTileNum(lr)
const _t = fromTileNum(t)
return (tile_in_tile_rect(_t, _ur, _lr, _ll, _ul) ? 1 : 0)
}
tile_contains_obj_pid(tile: number, elevation: number, pid: number) {
if(elevation !== currentElevation) {
warn("tile_contains_obj_pid: not same elevation")
return 0
}
var objs = objectsAtPosition(fromTileNum(tile))
for(var i = 0; i < objs.length; i++) {
if(objs[i].pid === pid)
return 1
}
return 0
}
rotation_to_tile(srcTile: number, destTile: number) {
var src = fromTileNum(srcTile), dest = fromTileNum(destTile)
var hex = hexNearestNeighbor(src, dest)
if(hex !== null)
return hex.direction
warn("rotation_to_tile: invalid hex: " + srcTile + " / " + destTile)
return -1 // TODO/XXX: what does this return if invalid?
}
move_to(obj: Obj, tileNum: number, elevation: number) {
if(!isGameObject(obj)) {
warn("move_to: not a game object: " + obj)
return
}
if(elevation !== currentElevation) {
info("move_to: moving to elevation " + elevation)
if(obj instanceof Critter && obj.isPlayer)
gMap.changeElevation(elevation, true)
else {
gMap.removeObject(obj)
gMap.addObject(obj, elevation)
}
}
obj.position = fromTileNum(tileNum)
if(obj instanceof Critter && obj.isPlayer)
centerCamera(obj.position)
}
// combat
node998() { // enter combat
console.log("[enter combat]")
}
// dialogue
node999() { // exit dialogue
info("DIALOGUE EXIT (Node999)")
dialogueExit()
}
gdialog_set_barter_mod(mod: number) { stub("gdialog_set_barter_mod", arguments) }
gdialog_mod_barter(mod: number) { // switch to barter mode
log("gdialog_mod_barter", arguments)
console.log("--> barter mode")
if(!this.self_obj) throw "need self_obj"
uiBarterMode(this.self_obj as Critter)
}
start_gdialog(msgFileID: number, obj: Obj, mood: number, headNum: number, backgroundID: number) {
log("start_gdialog", arguments)
info("DIALOGUE START", "dialogue")
if(!this.self_obj) throw "no self_obj for start_gdialog"
currentDialogueObject = this.self_obj as Critter
uiStartDialogue(false, this.self_obj as Critter)
//stub("start_gdialog", arguments)
}
gsay_start() { stub("gSay_Start", arguments) }
//gSay_Option(msgList, msgID, target, reaction) { stub("gSay_Option", arguments) },
gsay_reply(msgList: number, msgID: string|number) {
log("gSay_Reply", arguments)
var msg = getScriptMessage(msgList, msgID)
if(msg === null) throw Error("gsay_reply: msg is null");
info("REPLY: " + msg, "dialogue")
uiSetDialogueReply(msg)
}
gsay_message(msgList: number, msgID: string|number, reaction: number) {
// TODO: update this for ui
log("gsay_message", arguments)
/*
// message with [Done] option
var msg = msgID
if(typeof msgID !== "string")
msg = getScriptMessage(msgList, msgID)
*/
// TODO: XXX: This has bitrotted, #dialogue no longer exists. [Done] needs testing.
// $("#dialogue").append(" \"" + msg + "\"<br><a href=\"javascript:dialogueEnd()\">[Done]</a><br>")
// appendHTML($id("dialogue"), ` "${msg}"<br><a href="javascript:dialogueEnd()">[Done]</a><br>`);
}
gsay_end() { stub("gSay_End", arguments) }
end_dialogue() { stub("end_dialogue", arguments) }
giq_option(iqTest: number, msgList: number, msgID: string|number, target: any, reaction: number) {
log("giQ_Option", arguments)
var msg = getScriptMessage(msgList, msgID)
if(msg === null) { console.warn("giq_option: msg is null"); return; }
info("DIALOGUE OPTION: " + msg +
" [INT " + ((iqTest >= 0) ? (">="+iqTest) : ("<="+-iqTest)) + "]", "dialogue")
var INT = critterGetStat(player, "INT")
if((iqTest > 0 && INT < iqTest) || (iqTest < 0 && INT > -iqTest))
return // not enough intelligence for this option
dialogueOptionProcs.push(target.bind(this))
uiAddDialogueOption(msg, dialogueOptionProcs.length - 1)
}
dialogue_system_enter() {
log("dialogue_system_enter", arguments)
if(!this.self_obj) {
warn("dialogue_system_enter: no self_obj")
return
}
talk(this.self_obj._script, this.self_obj as Obj)
}
float_msg(obj: Obj, msg: string, type: number) {
log("float_msg", arguments)
//info("FLOAT MSG: " + msg, "floatMessage")
if(!isGameObject(obj)) {
warn("float_msg: not game object: " + obj)
return
}
var colorMap: { [color: number]: string } = {
// todo: take the exact values from some palette. also, yellow is ugly.
0: "white", //0: "yellow",
1: "black",
2: "red",
3: "green",
4: "blue",
5: "purple",
6: "white",
7: "red",
8: "white",//8: "yellow",
9: "white",
10: "dark gray",
11: "dark gray",
12: "light gray"
}
var color = colorMap[type]
if(type === -2 /* FLOAT_MSG_WARNING */ || type === -1 /* FLOAT_MSG_SEQUENTIAL */)
color = colorMap[9]
floatMessages.push({msg: msg, obj: this.self_obj as Obj, startTime: heart.timer.getTime(),
color: color})
}
// animation
reg_anim_func(_1: any, _2: any) { stub("reg_anim_func", arguments, "animation") }
reg_anim_animate(obj: Obj, anim: number, delay: number) { stub("reg_anim_animate", arguments, "animation") }
reg_anim_animate_forever(obj: Obj, anim: number) {
log("reg_anim_animate_forever", arguments, "animation")
if(!isGameObject(obj)) {
warn("reg_anim_animate_forever: not a game object")
return
}
//console.log("ANIM FOREVER: " + obj.art + " / " + anim)
if(anim !== 0)
warn("reg_anim_animate_forever: anim = " + anim)
function animate() { objectSingleAnim(obj, false, animate) }
animate()
}
animate_move_obj_to_tile(obj: Critter, tileNum: any, isRun: number) {
log("animate_move_obj_to_tile", arguments, "movement")
if(!isGameObject(obj)) {
warn("animate_move_obj_to_tile: not a game object", "movement", this)
return
}
// XXX: is this correct? FCMALPNK passes a procedure name
// but is it a call (wouldn't make sense for NOption) or
// a procedure reference that this should call?
if(typeof(tileNum) === "function")
tileNum = tileNum.call(this)
if(isNaN(tileNum)) {
warn("animate_move_obj_to_tile: invalid tile num", "movement", this)
return
}
var tile = fromTileNum(tileNum)
if(tile.x < 0 || tile.x >= 200 || tile.y < 0 || tile.y >= 200) {
warn("animate_move_obj_to_tile: invalid tile: " + tile.x +
", " + tile.y + " (" + tileNum + ")", "movement", this)
return
}
if(!obj.walkTo(tile, !!isRun)) {
warn("animate_move_obj_to_tile: no path", "movement", this)
return
}
}
reg_anim_obj_move_to_tile(obj: Obj, tileNum: number, delay: number) { stub("reg_anim_obj_move_to_tile", arguments, "movement") }
animate_stand_obj(obj: Critter) {
stub("animate_stand_obj", arguments, "animation");
// TODO: Play idle animation (animation 0)
}
explosion(tile: number, elevation: number, damage: number) {
log("explosion", arguments)
// TODO: objectExplode should defer to an auxillary tile explode function, which we should use
// Make dummy object so we can explode at the tile
var explosives = createObjectWithPID(makePID(0 /* items */, 85 /* Plastic Explosives */), -1)
explosives.position = fromTileNum(tile)
gMap.addObject(explosives)
objectExplode(explosives, explosives, 0, 100) // TODO: min/max dmg?
gMap.removeObject(explosives)
}
gfade_out(time: number) { stub("gfade_out", arguments) }
gfade_in(time: number) { stub("gfade_in", arguments) }
// timing
add_timer_event(obj: Obj, ticks: number, userdata: any) {
log("add_timer_event", arguments)
if(!obj || !obj._script) {
warn("add_timer_event: not a scriptable object: " + obj)
return
}
info("timer event added in " + ticks + " ticks (userdata " + userdata + ")", "timer")
// trigger timedEvent in `ticks` game ticks
timeEventList.push({ticks: ticks, obj: obj, userdata: userdata, fn: function() {
timedEvent(obj._script!, userdata)
}.bind(this)})
}
rm_timer_event(obj: Obj) {
log("rm_timer_event", arguments)
info("rm_timer_event: " + obj + ", " + obj.pid)
for(var i = 0; i < timeEventList.length; i++) {
const timedEvent = timeEventList[i];
if(timedEvent.obj && timedEvent.obj.pid === obj.pid) { // TODO: better object equality
info("removing timed event for obj")
timeEventList.splice(i--, 1)
break
}
}
}
game_ticks(seconds: number) { return seconds*10 }
game_time_advance(ticks: number) {
log("game_time_advance", arguments)
info("advancing time " + ticks + " ticks " + "(" + ticks/10 + " seconds)")
gameTickTime += ticks
}
// game
load_map(map: number|string, startLocation: number) {
log("load_map", arguments)
info("load_map: " + map)
if(typeof map === "string")
gMap.loadMap(map.split(".")[0].toLowerCase())
else
gMap.loadMapByID(map)
}
play_gmovie(movieID: number) { stub("play_gmovie", arguments) }
mark_area_known(areaType: number, area: number, markState: number) {
if(areaType === 0) { // MARK_TYPE_TOWN
switch(markState) {
case 0: break // MARK_STATE_UNKNOWN
case 1: // MARK_STATE_KNOWN
info("TODO: Mark area " + area + " on map")
return
case 2: break // MARK_STATE_VISITED
case -66: break // MARK_STATE_INVISIBLE
}
stub("mark_area_known", arguments)
}
else if(areaType === 1) { // MARK_TYPE_MAP
stub("mark_area_known", arguments)
}
else throw "mark_area_known: invalid area type " + areaType
}
wm_area_set_pos(area: number, x: number, y: number) { stub("wm_area_set_pos", arguments) }
game_ui_disable() { stub("game_ui_disable", arguments) }
game_ui_enable() { stub("game_ui_enable", arguments) }
// sound
play_sfx(sfx: string) { stub("play_sfx", arguments) }
// party
party_member_obj(pid: number) {
log("party_member_obj", arguments, "party")
return gParty.getPartyMemberByPID(pid) || 0
}
party_add(obj: Critter) {
log("party_add", arguments)
gParty.addPartyMember(obj)
}
party_remove(obj: Critter) {
log("party_remove", arguments)
gParty.removePartyMember(obj)
}
_serialize(): SerializedScript {
return {name: this.scriptName,
lvars: Object.assign({}, this.lvars)}
}
}
export function deserializeScript(obj: SerializedScript): Script {
var script = loadScript(obj.name)
script.lvars = obj.lvars
// TODO: do some kind of logic like enterMap/updateMap
return script
}
function loadMessageFile(name: string) {
name = name.toLowerCase()
info("loading message file: " + name, "load")
var msg = getFileText("data/text/english/dialog/" + name + ".msg")
if(scriptMessages[name] === undefined)
scriptMessages[name] = {}
// parse message file
var lines = msg.split(/\r|\n/)
// preprocess and merge lines
for(var i = 0; i < lines.length; i++) {
// comments/blanks
if(lines[i][0] === '#' || lines[i].trim() === '') {
lines.splice(i--, 1)
continue
}
// probably a continuation -- merge it with the last line
if(lines[i][0] !== '{') {
lines[i-1] += lines[i]
lines.splice(i--, 1)
continue
}
}
for(var i = 0; i < lines.length; i++) {
// e.g. {100}{}{You have entered a dark cave in the side of a mountain.}
var m = lines[i].match(/\{(\d+)\}\{.*\}\{(.*)\}/)
if(m === null)
throw "message parsing: not a valid line: " + lines[i]
// HACK: replace unicode replacement character with an apostrophe (because the Web sucks at character encodings)
scriptMessages[name][parseInt(m[1])] = m[2].replace(/\ufffd/g, "'")
}
}
export function setMapScript(script: Script) {
currentMapObject = script
}
export function loadScript(name: string): Script {
info("loading script " + name, "load")
var path = "data/scripts/" + name.toLowerCase() + ".int"
var data: DataView = getFileBinarySync(path)
var reader = new BinaryReader(data)
//console.log("[%s] loaded %d bytes", name, reader.length)
var intfile = parseIntFile(reader, name.toLowerCase())
//console.log("%s int file: %o", name, intfile)
if(!currentMapObject)
console.log("note: using current script (%s) as map script for this object", intfile.name);
reader.seek(0)
var vm = new ScriptVMBridge.GameScriptVM(reader, intfile)
vm.scriptObj.scriptName = name
vm.scriptObj.lvars = {}
vm.scriptObj._mapScript = currentMapObject || vm.scriptObj // map scripts are their own map scripts
vm.scriptObj._vm = vm
vm.run()
// return the scriptObj, which is a clone of ScriptProto
// which will be patched by the GameScriptVM to allow
// transparent procedure calls
return vm.scriptObj
}
export function initScript(script: Script, obj: Obj) {
script.self_obj = obj as ScriptableObj
script.cur_map_index = currentMapID!
if(script.start !== undefined)
script.start()
}
export function timedEvent(script: Script, userdata: any): boolean {
info("timedEvent: " + script.scriptName + ": " + userdata, "timer")
if(script.timed_event_p_proc === undefined) {
warn(`timedEvent called on script without a timed_event_p_proc! script: ${script.scriptName} userdata: ${userdata}`)
return false
}
script.fixed_param = userdata
script._didOverride = false
script.timed_event_p_proc()
return script._didOverride
}
export function use(obj: Obj, source: Obj): boolean|null {
if(!obj._script || obj._script.use_p_proc === undefined)
return null
obj._script.source_obj = source
obj._script.self_obj = obj as ScriptableObj
obj._script._didOverride = false
obj._script.use_p_proc()
return obj._script._didOverride
}
export function talk(script: Script, obj: Obj): boolean {
script.self_obj = obj as ScriptableObj
script.game_time = Math.max(1, gameTickTime)
script.cur_map_index = currentMapID
script._didOverride = false
script.talk_p_proc()
return script._didOverride
}
export function updateCritter(script: Script, obj: Critter): boolean {
// critter heartbeat (critter_p_proc)
if(!script.critter_p_proc)
return false // TODO: Should we override or not if it doesn't exist? Probably not.
script.game_time = gameTickTime
script.cur_map_index = currentMapID
script._didOverride = false
script.self_obj = obj as ScriptableObj
script.self_tile = toTileNum(obj.position)
script.critter_p_proc()
return script._didOverride
}
export function spatial(spatialObj: Obj, source: Obj) { // TODO: Spatial type
const script = spatialObj._script
if(!script) throw Error("spatial without a script being triggered");
if(!script.spatial_p_proc)
throw Error("spatial script without a spatial_p_proc triggered")
script.game_time = gameTickTime
script.cur_map_index = currentMapID
script.source_obj = source
script.self_obj = spatialObj as ScriptableObj
script.spatial_p_proc()
}
export function destroy(obj: Obj, source?: Obj) {
if(!obj._script || !obj._script.destroy_p_proc)
return null
obj._script.self_obj = obj as ScriptableObj
obj._script.source_obj = source || 0
obj._script.game_time = Math.max(1, gameTickTime)
obj._script.cur_map_index = currentMapID
obj._script._didOverride = false
obj._script.destroy_p_proc()
return obj._script._didOverride
}
export function damage(obj: Obj, target: Obj, source: Obj, damage: number) {
if(!obj._script || obj._script.damage_p_proc === undefined)
return null
obj._script.self_obj = obj as ScriptableObj
obj._script.target_obj = target
obj._script.source_obj = source
obj._script.game_time = Math.max(1, gameTickTime)
obj._script.cur_map_index = currentMapID
obj._script._didOverride = false
obj._script.damage_p_proc()
return obj._script._didOverride
}
export function useSkillOn(who: Critter, skillId: number, obj: Obj): boolean {
if(!obj._script) throw Error("useSkillOn: Object has no script");
obj._script.self_obj = obj as ScriptableObj
obj._script.source_obj = who
obj._script.cur_map_index = currentMapID
obj._script._didOverride = false
obj._script.action_being_used = skillId
obj._script.use_skill_on_p_proc()
return obj._script._didOverride
}
export function pickup(obj: Obj, source: Critter): boolean {
if(!obj._script) throw Error("pickup: Object has no script");
obj._script.self_obj = obj as ScriptableObj
obj._script.source_obj = source
obj._script.cur_map_index = currentMapID
obj._script._didOverride = false
obj._script.pickup_p_proc()
return obj._script._didOverride
}
export function combatEvent(obj: Obj, event: "turnBegin"): boolean {
if(!obj._script) throw Error("combatEvent: Object has no script");
let fixed_param: number|null = null
switch(event) {
case "turnBegin": fixed_param = 4; break // COMBAT_SUBTYPE_TURN
default: throw "combatEvent: unknown event " + event
}
if(!obj._script.combat_p_proc)
return false
info("[COMBAT EVENT " + event + "]")
obj._script.combat_is_initialized = 1
obj._script.fixed_param = fixed_param
obj._script.self_obj = obj as ScriptableObj
obj._script.game_time = Math.max(1, gameTickTime)
obj._script.cur_map_index = currentMapID
obj._script._didOverride = false
// TODO: script_overrides
// hack so that the procedure is allowed to finish before
// we actually terminate combat
var doTerminate: any = false // did combat_p_proc terminate combat?
obj._script.terminate_combat = function() { doTerminate = true }
obj._script.combat_p_proc()
if(doTerminate) {
console.log("DUH DUH TERMINATE!")
Script.prototype.terminate_combat.call(obj._script) // call original
}
return doTerminate
}
export function updateMap(mapScript: Script, objects: Obj[], elevation: number) {
gameObjects = objects
mapFirstRun = false
if(mapScript) {
mapScript.combat_is_initialized = inCombat ? 1 : 0
if(mapScript.map_update_p_proc !== undefined) {
mapScript.self_obj = {_script: mapScript}
mapScript.map_update_p_proc()
}
}
var updated = 0
for(var i = 0; i < gameObjects.length; i++) {
var script = gameObjects[i]._script
if(script !== undefined && script.map_update_p_proc !== undefined) {
script.combat_is_initialized = inCombat ? 1 : 0
script.self_obj = gameObjects[i] as ScriptableObj
script.game_time = Math.max(1, gameTickTime)
script.game_time_hour = 1200 // hour of the day
script.cur_map_index = currentMapID
script.map_update_p_proc()
updated++
}
}
// info("updated " + updated + " objects")
}
export function enterMap(mapScript: Script, objects: Obj[], elevation: number, mapID: number, isFirstRun: boolean): StartPos|null {
gameObjects = objects
currentMapID = mapID
mapFirstRun = isFirstRun
if(mapScript && mapScript.map_enter_p_proc !== undefined) {
info("calling map enter")
mapScript.self_obj = {_script: mapScript}
mapScript.map_enter_p_proc()
}
if(overrideStartPos) {
const r = overrideStartPos
overrideStartPos = null
return r
}
// XXX: caller should do this for all objects, which is better?
/*for(var i = 0; i < gameObjects.length; i++) {
objectEnterMap(gameObjects[i], elevation, mapID)
}*/
return null
}
export function objectEnterMap(obj: Obj, elevation: number, mapID: number) {
var script = obj._script
if(script !== undefined && script.map_enter_p_proc !== undefined) {
script.combat_is_initialized = 0
script.self_obj = obj as ScriptableObj
script.game_time = Math.max(1, gameTickTime)
script.game_time_hour = 1200 // hour of the day
script.cur_map_index = currentMapID
script.map_enter_p_proc()
}
}
export function reset(mapName: string, mapID?: number) {
timeEventList.length = 0 // clear timed events
dialogueOptionProcs.length = 0
gameObjects = null
currentMapObject = null
currentMapID = (mapID !== undefined) ? mapID : null
mapVars = {}
}
export function init(mapName: string, mapID?: number) {
seed(123)
reset(mapName, mapID)
}
} | the_stack |
import {
CreateChannelMessage,
MethodResults,
NodeResponses,
RebalanceProfile as RebalanceProfileType,
StateChannelJSON,
DepositAppName,
DepositAppState,
FreeBalanceResponse,
} from "@connext/types";
import {
getSignerAddressFromPublicIdentifier,
stringify,
calculateExchangeWad,
maxBN,
} from "@connext/utils";
import { Injectable, HttpService } from "@nestjs/common";
import { AxiosResponse } from "axios";
import { BigNumber, constants, utils, providers } from "ethers";
import { CFCoreService } from "../cfCore/cfCore.service";
import { ConfigService } from "../config/config.service";
import { LoggerService } from "../logger/logger.service";
import { WithdrawService } from "../withdraw/withdraw.service";
import { DepositService } from "../deposit/deposit.service";
import { RebalanceProfile } from "../rebalanceProfile/rebalanceProfile.entity";
import { DEFAULT_DECIMALS } from "../constants";
import { Channel } from "./channel.entity";
import { ChannelRepository } from "./channel.repository";
const { AddressZero, Zero } = constants;
const { getAddress, toUtf8Bytes, sha256 } = utils;
export enum RebalanceType {
COLLATERALIZE = "COLLATERALIZE",
RECLAIM = "RECLAIM",
}
@Injectable()
export class ChannelService {
constructor(
private readonly cfCoreService: CFCoreService,
private readonly channelRepository: ChannelRepository,
private readonly configService: ConfigService,
private readonly withdrawService: WithdrawService,
private readonly depositService: DepositService,
private readonly log: LoggerService,
private readonly httpService: HttpService,
) {
this.log.setContext("ChannelService");
}
/**
* Returns all channel records.
* @param available available value of channel
*/
async findAll(available: boolean = true): Promise<Channel[]> {
return this.channelRepository.findAll(available);
}
// NOTE: this is used by the `channel.provider`. if you use the
// repository at that level, there is some ordering weirdness
// where an empty array is returned from the query call, then
// the provider method returns, and the query is *ACTUALLY* executed
async getByUserPublicIdentifier(
userIdentifier: string,
chainId: number,
): Promise<NodeResponses.GetChannel | undefined> {
const channel = await this.channelRepository.findByUserPublicIdentifierAndChain(
userIdentifier,
chainId,
);
this.log.debug(`Got channel for ${userIdentifier}: ${stringify(channel, true)}`);
return !channel || !channel.multisigAddress
? undefined
: {
available: channel.available,
multisigAddress: channel.multisigAddress,
nodeIdentifier: channel.nodeIdentifier,
userIdentifier: channel.userIdentifier,
};
}
/**
* Starts create channel process within CF core
* @param counterpartyIdentifier
*/
async create(
counterpartyIdentifier: string,
chainId: number,
): Promise<MethodResults.CreateChannel> {
this.log.info(`create ${counterpartyIdentifier} started`);
const existing = await this.channelRepository.findByUserPublicIdentifierAndChain(
counterpartyIdentifier,
chainId,
);
if (existing) {
throw new Error(
`Channel already exists for ${counterpartyIdentifier} on ${chainId}: ${existing.multisigAddress}`,
);
}
const createResult = await this.cfCoreService.createChannel(counterpartyIdentifier, chainId);
this.log.info(
`create ${counterpartyIdentifier} on ${chainId} finished: ${JSON.stringify(createResult)}`,
);
return createResult;
}
async rebalance(
multisigAddress: string,
assetId: string = AddressZero,
rebalanceType: RebalanceType,
requestedTarget?: BigNumber,
): Promise<
| {
completed?: () => Promise<FreeBalanceResponse>;
transaction?: providers.TransactionResponse;
appIdentityHash?: string;
}
| undefined
> {
const channel = await this.channelRepository.findByMultisigAddressOrThrow(multisigAddress);
this.log.info(
`Rebalance type ${rebalanceType} for ${channel.userIdentifier} asset ${assetId} started on chain ${channel.chainId} for ${multisigAddress}`,
);
const normalizedAssetId = getAddress(assetId);
const depositApps = await this.cfCoreService.getAppInstancesByAppDefinition(
multisigAddress,
this.cfCoreService.getAppInfoByNameAndChain(DepositAppName, channel.chainId)!
.appDefinitionAddress,
);
const signerAddr = await this.configService.getSignerAddress();
const ours = depositApps.find((app) => {
const latestState = app.latestState as DepositAppState;
return (
latestState.assetId === normalizedAssetId && latestState.transfers[0].to === signerAddr
);
});
if (ours && rebalanceType === RebalanceType.COLLATERALIZE) {
this.log.warn(
`Channel ${channel.multisigAddress} has collateralization in flight for ${normalizedAssetId} on chain ${channel.chainId}, doing nothing. App: ${ours.identityHash}`,
);
return undefined;
}
const rebalancingTargets = await this.getRebalancingTargets(
channel.userIdentifier,
channel.chainId,
normalizedAssetId,
);
const { collateralizeThreshold, target: profileTarget, reclaimThreshold } = rebalancingTargets;
if (
(collateralizeThreshold.gt(profileTarget) || reclaimThreshold.lt(profileTarget)) &&
!reclaimThreshold.isZero()
) {
throw new Error(`Rebalancing targets not properly configured: ${rebalancingTargets}`);
}
const {
[this.cfCoreService.cfCore.signerAddress]: nodeFreeBalance,
} = await this.cfCoreService.getFreeBalance(
channel.userIdentifier,
channel.multisigAddress,
normalizedAssetId,
);
let rebalanceRes: {
completed?: () => Promise<FreeBalanceResponse>;
transaction?: providers.TransactionResponse;
appIdentityHash?: string;
} = {};
const targetToUse = requestedTarget ? requestedTarget : profileTarget;
const thresholdToUse = requestedTarget
? requestedTarget
: rebalanceType === RebalanceType.COLLATERALIZE
? collateralizeThreshold
: reclaimThreshold;
if (rebalanceType === RebalanceType.COLLATERALIZE) {
// If free balance is too low, collateralize up to upper bound
// make sure requested target is under reclaim threshold
if (requestedTarget?.gt(reclaimThreshold)) {
throw new Error(
`Requested target ${requestedTarget.toString()} is greater than reclaim threshold ${reclaimThreshold.toString()}`,
);
}
if (nodeFreeBalance.lt(thresholdToUse)) {
this.log.info(
`nodeFreeBalance ${nodeFreeBalance.toString()} < thresholdToUse ${thresholdToUse.toString()}, depositing to target ${targetToUse.toString()}`,
);
const amount = targetToUse.sub(nodeFreeBalance);
rebalanceRes = (await this.depositService.deposit(channel, amount, normalizedAssetId))!;
} else {
this.log.info(
`Free balance ${nodeFreeBalance} is greater than or equal to lower collateralization bound: ${thresholdToUse.toString()}`,
);
}
} else if (rebalanceType === RebalanceType.RECLAIM) {
// If free balance is too high, reclaim down to lower bound
if (nodeFreeBalance.gt(thresholdToUse) && thresholdToUse.gte(0)) {
this.log.info(
`nodeFreeBalance ${nodeFreeBalance.toString()} > reclaimThreshold ${thresholdToUse.toString()}, withdrawing`,
);
const amount = nodeFreeBalance.sub(targetToUse);
const transaction = await this.withdrawService.withdraw(channel, amount, normalizedAssetId);
rebalanceRes.transaction = transaction;
} else {
this.log.info(
`Free balance ${nodeFreeBalance} is less than or equal to upper reclaim bound: ${reclaimThreshold.toString()}`,
);
}
}
this.log.info(
`Rebalance finished for ${channel.userIdentifier} on chain ${channel.chainId}, assetId: ${assetId}`,
);
return rebalanceRes;
}
async getCollateralAmountToCoverPaymentAndRebalance(
userPublicIdentifier: string,
chainId: number,
assetId: string,
paymentAmount: BigNumber,
currentBalance: BigNumber,
): Promise<BigNumber> {
const { collateralizeThreshold, target } = await this.getRebalancingTargets(
userPublicIdentifier,
chainId,
assetId,
);
// if the payment reduces the nodes current balance to below the lower
// collateral bound, then on the next uninstall the node will try to
// deposit again
const resultingBalance = currentBalance.sub(paymentAmount);
if (resultingBalance.lte(target)) {
const requiredAmount = collateralizeThreshold.add(paymentAmount).sub(currentBalance);
this.log.warn(`Need extra collateral to cover payment: ${requiredAmount.toString()}`);
// return proper amount for balance to be the collateral limit
// after the payment is performed
return requiredAmount;
}
// always default to the greater collateral value
return paymentAmount.gt(collateralizeThreshold)
? paymentAmount.sub(currentBalance)
: collateralizeThreshold.sub(currentBalance);
}
async getRebalancingTargets(
userPublicIdentifier: string,
chainId: number,
assetId: string = AddressZero,
): Promise<RebalanceProfileType> {
this.log.debug(
`Getting rebalancing targets for user: ${userPublicIdentifier} on ${chainId}, assetId: ${assetId}`,
);
let targets: RebalanceProfileType | undefined;
// option 1: rebalancing service, option 2: rebalance profile, option 3: default
targets = await this.getDataFromRebalancingService(userPublicIdentifier, assetId);
if (!targets) {
this.log.debug(`Unable to get rebalancing targets from service, falling back to profile`);
targets = await this.channelRepository.getRebalanceProfileForChannelAndAsset(
userPublicIdentifier,
chainId,
assetId,
);
}
if (!targets) {
this.log.debug(`No profile for this channel and asset, falling back to default profile`);
targets = await this.configService.getDefaultRebalanceProfile(assetId);
}
if (!targets) {
throw new Error(
`Node is not configured to rebalance asset ${assetId} for user ${userPublicIdentifier}`,
);
}
// convert targets to proper units for token
if (assetId !== AddressZero) {
const decimals = await this.configService.getTokenDecimals(chainId, assetId);
if (decimals !== DEFAULT_DECIMALS) {
this.log.info(`Token has ${decimals} decimals, converting rebalance targets`);
targets.collateralizeThreshold = calculateExchangeWad(
targets.collateralizeThreshold,
DEFAULT_DECIMALS,
"1",
decimals,
);
targets.target = calculateExchangeWad(targets.target, DEFAULT_DECIMALS, "1", decimals);
targets.reclaimThreshold = calculateExchangeWad(
targets.reclaimThreshold,
DEFAULT_DECIMALS,
"1",
decimals,
);
this.log.warn(`Converted rebalance targets: ${stringify(targets)}`);
}
}
this.log.info(`Rebalancing target for ${assetId} on ${chainId}: ${stringify(targets)}`);
return targets;
}
async addRebalanceProfileToChannel(
userPublicIdentifier: string,
chainId: number,
profile: RebalanceProfileType,
): Promise<RebalanceProfile> {
this.log.info(
`addRebalanceProfileToChannel for ${userPublicIdentifier} on ${chainId} with ${stringify(
profile,
false,
0,
)}`,
);
const { assetId, collateralizeThreshold, target, reclaimThreshold } = profile;
if (
(!reclaimThreshold.isZero() && reclaimThreshold.lt(target)) ||
collateralizeThreshold.gt(target)
) {
throw new Error(`Rebalancing targets not properly configured: ${stringify(profile)}`);
}
// reclaim targets cannot be less than collateralize targets, otherwise we get into a loop of
// collateralize/reclaim
if (!reclaimThreshold.isZero() && reclaimThreshold.lt(collateralizeThreshold)) {
throw new Error(
`Reclaim targets cannot be less than collateralize targets: ${stringify(profile)}`,
);
}
const rebalanceProfile = new RebalanceProfile();
rebalanceProfile.assetId = getAddress(assetId);
rebalanceProfile.collateralizeThreshold = collateralizeThreshold;
rebalanceProfile.target = target;
rebalanceProfile.reclaimThreshold = reclaimThreshold;
const result = await this.channelRepository.addRebalanceProfileToChannel(
userPublicIdentifier,
chainId,
rebalanceProfile,
);
this.log.info(
`addRebalanceProfileToChannel for ${userPublicIdentifier} on ${chainId} complete: ${stringify(
result,
false,
0,
)}`,
);
return result;
}
/**
* Creates a channel in the database with data from CF core event CREATE_CHANNEL
* and marks it as available
* @param creationData event data
*/
async makeAvailable(creationData: CreateChannelMessage): Promise<void> {
this.log.info(`makeAvailable ${JSON.stringify(creationData)} start`);
const existing = await this.channelRepository.findByMultisigAddress(
creationData.data.multisigAddress,
);
if (!existing) {
throw new Error(
`Did not find existing channel, meaning "PERSIST_STATE_CHANNEL" failed in setup protocol`,
);
}
const existingOwners = [
getSignerAddressFromPublicIdentifier(existing!.nodeIdentifier),
getSignerAddressFromPublicIdentifier(existing!.userIdentifier),
];
if (
!creationData.data.owners.includes(existingOwners[0]) ||
!creationData.data.owners.includes(existingOwners[1])
) {
throw new Error(
`Channel has already been created with owners ${stringify(
existingOwners,
)}. Event data: ${stringify(creationData)}`,
);
}
if (existing.available) {
this.log.debug(`Channel is already available, doing nothing`);
return;
}
this.log.debug(`Channel already exists in database, marking as available`);
existing.available = true;
await this.channelRepository.save(existing);
this.log.info(`makeAvailable ${JSON.stringify(creationData)} complete`);
}
async getDataFromRebalancingService(
userPublicIdentifier: string,
assetId: string,
): Promise<RebalanceProfileType | undefined> {
this.log.info(
`getDataFromRebalancingService for ${userPublicIdentifier} asset ${assetId} start`,
);
const rebalancingServiceUrl = this.configService.getRebalancingServiceUrl();
if (!rebalancingServiceUrl) {
this.log.info(`Rebalancing service URL not configured for ${userPublicIdentifier}`);
return undefined;
}
const hashedPublicIdentifier = sha256(toUtf8Bytes(userPublicIdentifier));
const {
data: rebalancingTargets,
status,
}: AxiosResponse<RebalanceProfileType> = await this.httpService
.get(
`${rebalancingServiceUrl}/api/v1/recommendations/asset/${assetId}/channel/${hashedPublicIdentifier}`,
)
.toPromise();
if (status !== 200) {
this.log.warn(
`Rebalancing service returned a non-200 response for ${userPublicIdentifier}: ${status}`,
);
return undefined;
}
const response: RebalanceProfileType = {
assetId: rebalancingTargets.assetId,
collateralizeThreshold: BigNumber.from(rebalancingTargets.collateralizeThreshold),
target: BigNumber.from(rebalancingTargets.target),
reclaimThreshold: BigNumber.from(rebalancingTargets.reclaimThreshold),
};
this.log.info(
`getDataFromRebalancingService for ${userPublicIdentifier} asset ${assetId} complete: ${JSON.stringify(
response,
)}`,
);
return response;
}
async getRebalanceProfileForChannelAndAsset(
userIdentifier: string,
chainId: number,
assetId: string = AddressZero,
): Promise<RebalanceProfile | undefined> {
// try to get rebalance profile configured
const profile = await this.channelRepository.getRebalanceProfileForChannelAndAsset(
userIdentifier,
chainId,
assetId,
);
return profile;
}
async getStateChannel(userIdentifier: string, chainId: number): Promise<StateChannelJSON> {
const channel = await this.channelRepository.findByUserPublicIdentifierAndChainOrThrow(
userIdentifier,
chainId,
);
const { data: state } = await this.cfCoreService.getStateChannel(channel.multisigAddress);
return state;
}
async getStateChannelByMultisig(multisigAddress: string): Promise<StateChannelJSON> {
const channel = await this.channelRepository.findByMultisigAddress(multisigAddress);
if (!channel) {
throw new Error(`No channel exists for multisigAddress ${multisigAddress}`);
}
const { data: state } = await this.cfCoreService.getStateChannel(multisigAddress);
return state;
}
async getAllChannels(): Promise<Channel[]> {
const channels = await this.channelRepository.findAll();
if (!channels) {
throw new Error(`No channels found. This should never happen`);
}
return channels;
}
} | the_stack |
import cheerio from "cheerio";
import UrlParse from "url-parse";
import puppeteer from "puppeteer";
import fetch from "node-fetch";
import { baseUrl } from "./constants";
const maxConcurrentRequests = 3;
export type Item = {
id: string;
name: string;
size: string;
link: string;
category: string;
seeders: string;
leechers: string;
uploadDate: string;
magnetLink: string;
subcategory?: string;
uploader: string;
verified?: string;
description: string;
uploaderLink: string;
};
export type SubCategory = {
id: string;
name: string;
};
export type Categories = {
name: string;
id: string;
subcategories: Array<SubCategory>;
};
/**
* @private
*/
export function parseTorrentIsVIP(element: Cheerio): boolean {
return element.find('img[title="VIP"]').attr("title") === "VIP";
}
export function parseTorrentIsTrusted(element: Cheerio): boolean {
return element.find('img[title="Trusted"]').attr("title") === "Trusted";
}
/**
* @private
*/
export function isTorrentVerified(element: Cheerio): boolean {
return parseTorrentIsVIP(element) || parseTorrentIsTrusted(element);
}
export async function getProxyList(): Promise<Array<string>> {
const response = await fetch("https://proxybay.tv/").then(res => res.text());
const $ = cheerio.load(response);
const links = $('[rel="nofollow"]')
.map(function getElementLinks(_, el) {
return $(el).attr("href");
})
.get()
.filter((_, index) => index < maxConcurrentRequests);
return links;
}
export type ParseResult<T> = Array<T> | T;
export type ParseCallback<T> = (
resultsHTML: string,
filter?: Record<string, any>
) => ParseResult<T>;
export function parsePage<T>(
url: string,
parseCallback: ParseCallback<T>,
filter: Record<string, any> = {},
method = "GET",
formData: string | NodeJS.ReadableStream = ""
): Promise<ParseResult<T>> {
const attempt = async (error?: string) => {
if (error) console.log(error);
const proxyUrls = [
"https://thepiratebay.org",
"https://thepiratebay.se",
"https://pirateproxy.one",
"https://ahoy.one"
];
const requests = proxyUrls
.map(
_url =>
new UrlParse(url).set("hostname", new UrlParse(_url).hostname).href
)
.map(async _url => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(_url).catch(async () => {
await browser.close();
throw Error(
"Database maintenance, Cloudflare problems, 403 or 502 error"
);
});
const result = await page.$eval("html", (e: any) => e.outerHTML);
await browser.close();
return result.includes("502: Bad gateway") ||
result.includes("403 Forbidden") ||
result.includes("Database maintenance") ||
result.includes("Checking your browser before accessing") ||
result.includes("Origin DNS error")
? new Error(
"Database maintenance, Cloudflare problems, 403 or 502 error"
)
: Promise.resolve(result);
});
const abandonFailedResponses = (index: number) => {
const p = requests.splice(index, 1)[0];
p.catch(() => {});
};
const race = (): Promise<string | void | Error> => {
if (requests.length < 1) {
console.warn("None of the proxy requests were successful");
// throw new Error("None of the proxy requests were successful");
}
const indexedRequests = requests.map((p, index) =>
p.catch(() => {
throw index;
})
);
return Promise.race(indexedRequests).catch(index => {
abandonFailedResponses(index);
return race();
});
};
return race();
};
return attempt()
.catch(() => attempt("Failed, retrying"))
.then(response => parseCallback(response as string, filter));
}
export type ParseOpts = {
filter?: boolean;
verified?: boolean;
};
export function parseResults(
resultsHTML: string,
filter: ParseOpts = {}
): Array<Item> {
const $ = cheerio.load(resultsHTML);
const rawResults = $("ol#torrents li.list-entry");
const results = rawResults.map(function getRawResults(_, el) {
const name: string =
$(el)
.find(".item-title a")
.text() || "";
const uploadDate: string = $(el)
?.find(".item-uploaded")
?.text();
const size: string = $(el)
.find(".item-size")
.text();
const seeders: string = $(el)
.find(".item-seed")
.first()
.text();
const leechers: string = $(el)
.find(".item-leech")
.text();
const relativeLink: string =
$(el)
.find(".item-title a")
.attr("href") || "";
const link: string = baseUrl + relativeLink;
const id = String(
parseInt(/(?:id=)(\d*)/.exec(relativeLink)?.[1] || "", 10)
);
const magnetLink: string =
$(el)
.find(".item-icons a")
.first()
.attr("href") || "";
const uploader: string = $(el)
.find(".item-user a")
.text();
const uploaderLink: string =
baseUrl +
$(el)
.find(".item-user a")
.attr("href");
const verified: boolean = isTorrentVerified($(el));
const category = {
id:
$(el)
.find(".item-type a")
.first()
.attr("href")
?.match(/(?:category:)(\d*)/)?.[1] || "",
name: $(el)
.find(".item-type a")
.first()
.text()
};
const subcategory = {
id:
$(el)
.find(".item-type a")
.last()
.attr("href")
?.match(/(?:category:)(\d*)/)?.[1] || "",
name: $(el)
.find(".item-type a")
.last()
.text()
};
return {
id,
name,
size,
link,
category,
seeders,
leechers,
uploadDate,
magnetLink,
subcategory,
uploader,
verified,
uploaderLink
};
});
const parsedResultsArray = results
.get()
.filter(result => !result.uploaderLink.includes("undefined"));
return filter.verified === true
? parsedResultsArray.filter(result => result.verified === true)
: parsedResultsArray;
}
export type Torrent = {
title: string;
link: string;
id: string;
};
export type ParsedTvShow = {
title: string;
torrents: Array<Torrent>;
};
export type ParsedTvShowWithSeasons = {
title: string;
seasons: string[];
};
export function parseTvShow(tvShowPage: string): Array<ParsedTvShow> {
const $ = cheerio.load(tvShowPage);
const seasons: string[] = $("dt a")
.map((_, el) => $(el).text())
.get();
const rawLinks = $("dd");
const torrents = rawLinks
.map((_, element) =>
$(element)
.find("a")
.map(() => ({
title: $(element).text(),
link: baseUrl + $(element).attr("href"),
id: $(element)
.attr("href")
?.match(/\/torrent\/(\d+)/)?.[1]
}))
.get()
)
.get();
return seasons.map((season, index) => ({
title: season,
torrents: torrents[index]
}));
}
export function parseTorrentPage(torrentPage: string): Item {
const $ = cheerio.load(torrentPage);
const name = $("#name")
.text()
.trim();
const size = $("dt:contains(Size:) + dd")
.text()
.trim();
const uploadDate = $("dt:contains(Uploaded:) + dd")
.text()
.trim();
const uploader = $("dt:contains(By:) + dd")
.text()
.trim();
const uploaderLink = baseUrl + $("dt:contains(By:) + dd a").attr("href");
const seeders = $("dt:contains(Seeders:) + dd")
.text()
.trim();
const leechers = $("dt:contains(Leechers:) + dd")
.text()
.trim();
const id = $("input[name=id]").attr("value") || "";
const link = `${baseUrl}/torrent/${id}`;
const magnetLink = $('a:contains("Get This Torrent")').attr("href") || "";
const description =
$("#descr")
.text()
.trim() || "";
return {
category: "",
name,
size,
seeders,
leechers,
uploadDate,
magnetLink,
link,
id,
description,
uploader,
uploaderLink
};
}
export function parseTvShows(tvShowsPage: string): ParsedTvShowWithSeasons[] {
const $ = cheerio.load(tvShowsPage);
const rawTitles = $("dt a");
const series = rawTitles
.map((_, element) => ({
title: $(element).text(),
id: $(element)
.attr("href")
?.match(/\/tv\/(\d+)/)?.[1]
}))
.get();
const rawSeasons: Cheerio = $("dd");
const seasons = rawSeasons
.map((_, element) =>
$(element)
.find("a")
.text()
.match(/S\d+/g)
)
.get();
return series.map((s, index) => ({
title: s.title,
id: s.id,
seasons: seasons[index]
}));
}
export function parseCategories(categoriesHTML: string): Array<Categories> {
const $ = cheerio.load(categoriesHTML);
const categoriesContainer = $(".browse .category_list");
const categories: Categories[] = [];
categoriesContainer.find("div").each((_, element) => {
const category: Categories = {
name: $(element)
.find("dt a")
.text(),
id:
$(element)
.find("dt a")
.attr("href")
?.match(/(?:category:)(\d*)/)?.[1] || "",
subcategories: $(element)
.find("dd a:not(:contains('(?!)'))")
.map((i, el) => {
return {
id:
$(el)
.attr("href")
?.match(/(?:category:)(\d*)/)?.[1] || "",
name: $(el).text()
};
})
.get()
};
categories.push(category);
});
return categories;
}
export type ParseCommentsPage = {
user: string;
comment: string;
};
export function parseCommentsPage(
commentsHTML: string
): Array<ParseCommentsPage> {
const $ = cheerio.load(commentsHTML);
const comments = $.root()
.contents()
.map((_, el) => {
const comment = $(el)
.find("div.comment")
.text()
.trim();
const user = $(el)
.find("a")
.text()
.trim();
return {
user,
comment
};
});
return comments.get();
} | the_stack |
import React, { useEffect, useState } from 'react';
import Graphin, { Behaviors } from '@antv/graphin';
import { ContextMenu } from '@antv/graphin-components';
import G6 from '@antv/g6';
import cloneDeep from '../../../../lib/utils/cloneDeep';
const { DragCombo } = Behaviors;
const { Menu } = ContextMenu;
const COMBO_STATE_STYLES = {
'selected': {
lineWidth: 3,
'text-shape': {
fontWeight: 500
}
},
'active': {
lineWidth: 3,
'text-shape': {
fontWeight: 500
}
},
'hightlight': {
lineWidth: 3,
'text-shape': {
fontWeight: 500
}
},
'inactive': {
lineWidth: 1,
fillOpacity: 0,
strokeOpacity: 0.2,
'text-shape': {
opacity: 0.3
}
}
}
const colors = [
'#5F95FF',
'#61DDAA',
'#65789B',
'#F6BD16',
'#7262FD',
'#78D3F8',
'#9661BC',
'#F6903D',
'#008685',
'#F08BB4',
]
/** 数据 */
const data = {
nodes: [
{
id: '0',
label: '0',
comboId: 'a',
},
{
id: '1',
label: '1',
comboId: 'a',
},
{
id: '2',
label: '2',
comboId: 'a',
},
{
id: '3',
label: '3',
comboId: 'a',
},
{
id: '4',
label: '4',
comboId: 'a',
},
{
id: '5',
label: '5',
comboId: 'a',
},
{
id: '6',
label: '6',
comboId: 'a',
},
{
id: '7',
label: '7',
comboId: 'a',
},
{
id: '8',
label: '8',
comboId: 'a',
},
{
id: '9',
label: '9',
comboId: 'a',
},
{
id: '10',
label: '10',
comboId: 'a',
},
{
id: '11',
label: '11',
comboId: 'a',
},
{
id: '12',
label: '12',
comboId: 'a',
},
{
id: '13',
label: '13',
comboId: 'b',
},
{
id: '14',
label: '14',
comboId: 'b',
},
{
id: '15',
label: '15',
comboId: 'b',
},
{
id: '16',
label: '16',
comboId: 'b',
},
{
id: '17',
label: '17',
comboId: 'b',
},
{
id: '18',
label: '18',
comboId: 'c',
},
{
id: '19',
label: '19',
comboId: 'c',
},
{
id: '20',
label: '20',
comboId: 'c',
},
{
id: '21',
label: '21',
comboId: 'c',
},
{
id: '22',
label: '22',
comboId: 'c',
},
{
id: '23',
label: '23',
comboId: 'c',
},
{
id: '24',
label: '24',
comboId: 'c',
},
{
id: '25',
label: '25',
comboId: 'c',
},
{
id: '26',
label: '26',
comboId: 'c',
},
{
id: '27',
label: '27',
comboId: 'c',
},
{
id: '28',
label: '28',
comboId: 'c',
},
{
id: '29',
label: '29',
comboId: 'c',
},
{
id: '30',
label: '30',
comboId: 'c',
},
{
id: '31',
label: '31',
comboId: 'd',
},
{
id: '32',
label: '32',
comboId: 'd',
},
{
id: '33',
label: '33',
comboId: 'd',
},
],
edges: [
{
source: 'a',
target: 'b',
size: 3,
style: {
stroke: 'red',
},
},
{
source: 'a',
target: '33',
size: 3,
style: {
stroke: 'blue',
},
},
{
source: '0',
target: '1',
},
{
source: '0',
target: '2',
},
{
source: '0',
target: '3',
},
{
source: '0',
target: '4',
},
{
source: '0',
target: '5',
},
{
source: '0',
target: '7',
},
{
source: '0',
target: '8',
},
{
source: '0',
target: '9',
},
{
source: '0',
target: '10',
},
{
source: '0',
target: '11',
},
{
source: '0',
target: '13',
},
{
source: '0',
target: '14',
},
{
source: '0',
target: '15',
},
{
source: '0',
target: '16',
},
{
source: '2',
target: '3',
},
{
source: '4',
target: '5',
},
{
source: '4',
target: '6',
},
{
source: '5',
target: '6',
},
{
source: '7',
target: '13',
},
{
source: '8',
target: '14',
},
{
source: '9',
target: '10',
},
{
source: '10',
target: '22',
},
{
source: '10',
target: '14',
},
{
source: '10',
target: '12',
},
{
source: '10',
target: '24',
},
{
source: '10',
target: '21',
},
{
source: '10',
target: '20',
},
{
source: '11',
target: '24',
},
{
source: '11',
target: '22',
},
{
source: '11',
target: '14',
},
{
source: '12',
target: '13',
},
{
source: '16',
target: '17',
},
{
source: '16',
target: '18',
},
{
source: '16',
target: '21',
},
{
source: '16',
target: '22',
},
{
source: '17',
target: '18',
},
{
source: '17',
target: '20',
},
{
source: '18',
target: '19',
},
{
source: '19',
target: '20',
},
{
source: '19',
target: '33',
},
{
source: '19',
target: '22',
},
{
source: '19',
target: '23',
},
{
source: '20',
target: '21',
},
{
source: '21',
target: '22',
},
{
source: '22',
target: '24',
},
{
source: '22',
target: '25',
},
{
source: '22',
target: '26',
},
{
source: '22',
target: '23',
},
{
source: '22',
target: '28',
},
{
source: '22',
target: '30',
},
{
source: '22',
target: '31',
},
{
source: '22',
target: '32',
},
{
source: '22',
target: '33',
},
{
source: '23',
target: '28',
},
{
source: '23',
target: '27',
},
{
source: '23',
target: '29',
},
{
source: '23',
target: '30',
},
{
source: '23',
target: '31',
},
{
source: '23',
target: '33',
},
{
source: '32',
target: '33',
},
],
combos: [
{
id: 'a',
label: 'combo a',
},
{
id: 'b',
label: 'combo b',
},
{
id: 'c',
label: 'combo c',
},
{
id: 'd',
label: 'combo d',
parentId: 'b',
},
],
}
let comboPositionCache = {};
const defaultLayout = {
type: 'comboCombined',
animation: false,
comboPadding: 120,
innerLayout: new G6.Layout['concentric']({ sortBy: 'degree' }),
outerLayout: new G6.Layout['gForce']({
preventOverlap: true,
animate: false, // for gForce and fruchterman
gravity: 1,
factor: 2,
nodeStrength: 100,
linkDistance: (edge, source, target) => {
const nodeSize = ((source.size?.[0] || 40) + (target.size?.[0] || 40)) / 2;
return Math.min(nodeSize * 1.5 + 150, 700);
},
}),
refresh: 0
}
const Demo = () => {
const graphinRef = React.createRef();
const [comboMap, setComboMap] = useState({});
const [comboChildMap, setComboChildMap] = useState({});
const [nodeMap, setNodeMap] = useState({});
const [graphData, setGraphData] = useState({});
const [comboAction, setComboAction] = useState();
const [uncomboedList, setUncomboedList] = useState([]);
const [layout, setLayout] = useState(defaultLayout);
useEffect(() => {
// 合并跨 combo 边
const gData = processData();
setGraphData(gData);
bindGraphEvents(gData);
const { graph } = graphinRef.current;
setTimeout(() => {
if (graph && !graph.destroyed) {
graph.getEdges().forEach(edge => edge.refresh());
}
}, 501);
}, []);
useEffect(() => {
const { delay, item, action } = comboAction || {};
const { graph } = graphinRef.current;
if (!item || !graph || graph.destroyed) return;
if (action === 'uncombo') {
uncombo(item, delay);
} else if (action === 'add-combo') {
addCombo(item.getModel());
}
}, [comboAction])
const processData = () => {
const map = {};
const cMap = {};
const nMap = {};
data.nodes.forEach(node => nMap[node.id] = node);
data.combos.forEach(combo => cMap[combo.id] = combo);
const gData = {
nodes: cloneDeep(data.nodes),
combos: cloneDeep(data.combos),
edges: []
}
gData.edges = processEdges(gData, nMap, []);
gData.nodes.forEach(node => {
nMap[node.id] = node;
if (node.comboId) {
if (!map[node.comboId]) map[node.comboId] = [];
map[node.comboId].push(node);
}
});
gData.combos.forEach(combo => {
combo.isCombo = true;
cMap[combo.id] = combo;
if (combo.parentId) {
if (!map[combo.parentId]) map[combo.parentId] = [];
map[combo.parentId].push(combo);
}
});
// 处理颜色
Object.keys(map).forEach((comboId, i) => {
const color = cMap[comboId]?.color || colors[i % colors.length];
cMap[comboId].color = color;
cMap[comboId].style = {
fill: color,
stroke: color,
fillOpacity: 0.2
}
map[comboId].forEach(child => {
child.color = color;
child.style = {
keyshape: {
fill: color,
stroke: color,
fillOpacity: 0.2
}
}
});
});
setComboChildMap(map);
setComboMap(cMap);
setNodeMap(nMap);
return gData;
}
const bindGraphEvents = (gData) => {
const { graph } = graphinRef.current;
if (graph && !graph.destroyed) {
// 双击 combo 解散,恢复相关的边(包括内部元素到其他 combo 的边)
graph.on('combo:dblclick', e => {
setComboAction({
item: e.item,
delay: 200,
action: 'uncombo'
});
});
// 接收从 contextmenu 传过来的合并事件
graph.on('comboparent', e => {
const { currentItem } = e;
setComboAction({
item: currentItem,
action: 'add-combo'
});
});
}
}
const uncombo = (combo, delay = 0) => {
const { graph } = graphinRef.current;
const comboId = combo.getID();
const comboChildren = combo.getChildren();
const children = comboChildren.nodes.concat(comboChildren.combos);
const childNodeIds = children.map(child => child.getID());
// 更新数据之前的动画:combo 缩小+渐隐动画
combo.getKeyShape().animate(
{ r: 1, opacity: 0 },
{
duration: 300,
delay,
easing: 'easeCubic',
}
);
const newUncomboedList = [...uncomboedList, comboId];
// 在重新布局前,为节点增加 mass 等参数,保证重新布局的稳定
const newData = {
nodes: graphData.nodes,
combos: graphData.combos.filter(combo => combo.id !== comboId),
edges: []
}
newData.edges = processEdges(newData, nodeMap, newUncomboedList);
newData.nodes.forEach(node => {
if (childNodeIds.includes(node.id)) {
delete node.fx;
delete node.fy;
node.mass = 200;
return;
}
if (!isNaN(nodeMap[node.id]?.x) && !isNaN(nodeMap[node.id]?.x)) {
node.fx = nodeMap[node.id]?.x;
node.fy = nodeMap[node.id]?.y;
node.mass = 300;
}
});
comboPositionCache = {};
graph.getCombos().forEach(item => {
const model = item.getModel();
if (childNodeIds.includes(model.id)) {
delete comboMap[model.id].parentId;
return;
}
comboPositionCache[model.id] = {
x: model.x,
y: model.y
}
});
// 触发重新布局
setTimeout(() => {
setGraphData(newData);
setLayout({
...defaultLayout,
refresh: Math.random()
})
setUncomboedList(newUncomboedList);
}, 300 + delay);
}
const addCombo = (nodeModel) => {
const { graph } = graphinRef.current;
// 找到该节点原先所在 combo id
const comboId = nodeModel.comboId;
if (!comboId) return;
// 计算该 combo 子元素的平均中心
const meanCenter = { x: 0, y: 0, count: 0 };
comboChildMap[comboId].forEach(child => {
meanCenter.x += (child.x || 0);
meanCenter.y += (child.y || 0);
meanCenter.count++;
});
meanCenter.x /= meanCenter.count;
meanCenter.y /= meanCenter.count;
const newUncomboedList = [...uncomboedList];
const comboIdIdx = newUncomboedList.indexOf(comboId);
newUncomboedList.splice(comboIdIdx, 1);
const newData = {
nodes: graphData.nodes,
combos: graphData.combos,
edges: []
}
// 新增 combo
const newCombo = {
id: comboId,
label: comboId,
x: meanCenter.x,
y: meanCenter.y,
mass: 300,
color: nodeModel.color,
style: {
fill: nodeModel.color,
stroke: nodeModel.color,
fillOpacity: 0.2
}
};
comboMap[comboId] = newCombo;
newData.combos.push(newCombo);
comboChildMap[comboId].forEach(child => {
if (comboMap[child.id]) {
comboMap[child.id].parentId = comboId;
}
const childItem = graph.findById(child.id);
if (!childItem) return;
graph.updateComboTree(child.id, comboId);
});
// 恢复边
newData.edges = processEdges(newData, nodeMap, newUncomboedList);
setUncomboedList(newUncomboedList);
setGraphData(newData);
setLayout({
...defaultLayout,
refresh: Math.random()
});
}
const processEdges = (currentData, nMap, filterList = []) => {
const edges = [];
const currentDataMap = {};
currentData.nodes.concat(currentData.combos).forEach(model => currentDataMap[model.id] = model);
const edgeMap = {};
data.edges.forEach(edge => {
let sourceId = edge.source;
let targetId = edge.target;
const sourceComboId = nMap[sourceId]?.comboId;
const targetComboId = nMap[targetId]?.comboId;
let comboEnd = false;
let currentEdge = edge;
// 若端点是在 combo 中,将边连接到 combo 上
if (sourceComboId && filterList.indexOf(sourceComboId) < 0) {
sourceId = sourceComboId;
comboEnd = true;
}
if (targetComboId && filterList.indexOf(targetComboId) < 0) {
targetId = targetComboId;
comboEnd = true;
}
if (comboEnd) {
const key = `${edge.source}-${edge.target}`;
if (!edgeMap[key]) {
const isLoop = sourceComboId === targetComboId;
currentEdge = {
...edge,
source: sourceId,
target: targetId,
weight: 1,
type: isLoop ? 'loop' : 'line',
loopCfg: {
position: 'top',
dist: 80,
},
style: {
lineWidth: 1,
lineDash: [15, 15]
}
};
edgeMap[key] = currentEdge;
} else {
edgeMap[key].style.lineWidth ++;
}
}
// 若起点、终点都存在于数据中,则加入该边
if (currentDataMap[currentEdge.source] && currentDataMap[currentEdge.target]) {
edges.push(currentEdge);
}
});
return edges;
}
return (
<div className="App">
<Graphin
ref={graphinRef}
data={graphData}
layout={layout}
groupByTypes={false}
defaultCombo={{
style: {
opacity: 0.6
}
}}
comboStateStyles={COMBO_STATE_STYLES}
animate={true}
animateCfg={{
duration: 800,
easing: 'easeCubic'
}}
>
<DragCombo />
<ContextMenu>
<Menu
bindType="node"
options={[
{
key: 'combo',
name: '合并到父 combo',
},
]}
onChange={(menuItem, nodeModel) => addCombo(nodeModel)}
/>
</ContextMenu>
</Graphin>
</div>
);
};
export default Demo; | the_stack |
import { css, useTheme } from '@emotion/react';
import { Theme } from '@sumup/design-tokens';
import {
FC,
Fragment,
Ref,
useEffect,
useMemo,
useRef,
useState,
KeyboardEvent,
AnchorHTMLAttributes,
ButtonHTMLAttributes,
} from 'react';
import useLatest from 'use-latest';
import usePrevious from 'use-previous';
import { usePopper } from 'react-popper';
import { Placement, State, Modifier } from '@popperjs/core';
import isPropValid from '@emotion/is-prop-valid';
import { IconProps } from '@sumup/icons';
import { useClickTrigger } from '@sumup/collector';
import { ClickEvent } from '../../types/events';
import { EmotionAsPropType } from '../../types/prop-types';
import styled, { StyleProps } from '../../styles/styled';
import { listItem, shadow, typography } from '../../styles/style-mixins';
import { uniqueId } from '../../util/id';
import { useClickEvent, TrackingProps } from '../../hooks/useClickEvent';
import { useEscapeKey } from '../../hooks/useEscapeKey';
import { useClickOutside } from '../../hooks/useClickOutside';
import { useFocusList } from '../../hooks/useFocusList';
import { isArrowDown, isArrowUp } from '../../util/key-codes';
import { useComponents } from '../ComponentsContext';
import Portal from '../Portal';
import Hr from '../Hr';
import { useStackContext } from '../StackContext';
import { isFunction } from '../../util/type-check';
export interface BaseProps {
/**
* The Popover item label.
*/
children: string;
/**
* Function that's called when the item is clicked.
*/
onClick?: (event: ClickEvent) => void;
/**
* Display an icon in addition to the label. Designed for 24px icons from `@sumup/icons`.
*/
icon?: FC<IconProps>;
/**
* Destructive variant, changes the color of label and icon from blue to red to signal to the user that the action
* is irreversible or otherwise dangerous. Interactive states are the same for destructive variant.
*/
destructive?: boolean;
/**
* Disabled variant. Visually and functionally disable the button.
*/
disabled?: boolean;
/**
* Additional data that is dispatched with the tracking event.
*/
tracking?: TrackingProps;
/**
* The ref to the HTML DOM element
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ref?: Ref<any>;
}
type LinkElProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'onClick'>;
type ButtonElProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'>;
export type PopoverItemProps = BaseProps & LinkElProps & ButtonElProps;
type PopoverItemWrapperProps = LinkElProps & ButtonElProps;
const itemWrapperStyles = () => css`
display: flex;
justify-content: flex-start;
align-items: center;
width: 100%;
`;
const PopoverItemWrapper = styled('button', {
shouldForwardProp: isPropValid,
})<PopoverItemWrapperProps>(listItem, itemWrapperStyles, typography('one'));
const iconStyles = (theme: Theme) => css`
margin-right: ${theme.spacings.kilo};
`;
export const PopoverItem = ({
children,
icon: Icon,
onClick,
tracking,
...props
}: PopoverItemProps): JSX.Element => {
const { Link } = useComponents();
const handleClick = useClickEvent(onClick, tracking, 'popover-item');
return (
<PopoverItemWrapper
as={props.href ? (Link as EmotionAsPropType) : 'button'}
onClick={handleClick}
role="menuitem"
{...props}
>
{Icon && <Icon css={iconStyles} size="24" />}
{children}
</PopoverItemWrapper>
);
};
const TriggerElement = styled.div`
display: inline-block;
`;
const menuBaseStyles = ({ theme }: StyleProps) => css`
padding: ${theme.spacings.byte} 0px;
border: 1px solid ${theme.colors.n200};
box-sizing: border-box;
border-radius: ${theme.borderRadius.byte};
background-color: ${theme.colors.white};
visibility: hidden;
opacity: 0;
${theme.mq.untilKilo} {
opacity: 1;
transform: translateY(100%);
transition: transform ${theme.transitions.default},
visibility ${theme.transitions.default};
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
`;
type OpenProps = { isOpen: boolean };
const menuOpenStyles = ({ theme, isOpen }: StyleProps & OpenProps) =>
isOpen &&
css`
opacity: 1;
visibility: inherit;
${theme.mq.untilKilo} {
transform: translateY(0);
}
`;
const PopoverMenu = styled('div')<OpenProps>(
shadow,
menuBaseStyles,
menuOpenStyles,
);
const dividerStyles = (theme: Theme) => css`
margin: ${theme.spacings.byte} ${theme.spacings.mega};
width: calc(100% - ${theme.spacings.mega}*2);
`;
const overlayStyles = ({ theme }: StyleProps) => css`
${theme.mq.untilKilo} {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: ${theme.colors.overlay};
visibility: hidden;
opacity: 0;
transition: opacity ${theme.transitions.default},
visibility ${theme.transitions.default};
}
`;
const overlayOpenStyles = ({ theme, isOpen }: StyleProps & OpenProps) =>
isOpen &&
css`
${theme.mq.untilKilo} {
visibility: inherit;
opacity: 1;
}
`;
const Overlay = styled.div<OpenProps>(overlayStyles, overlayOpenStyles);
const popperStyles = ({ isOpen }: OpenProps) => css`
pointer-events: ${isOpen ? 'all' : 'none'};
`;
const Popper = styled.div<OpenProps>(popperStyles);
type Divider = { type: 'divider' };
type Action = PopoverItemProps | Divider;
function isDivider(action: Action): action is Divider {
return 'type' in action && action.type === 'divider';
}
type OnToggle = (open: boolean | ((prevOpen: boolean) => boolean)) => void;
export interface PopoverProps {
/**
* Determines whether the Popover is open or closed.
*/
isOpen: boolean;
/**
* Function that is called when toggles the Popover.
*/
onToggle: OnToggle;
/**
* An array of PopoverItem or Divider.
*/
actions: Action[];
/**
* One of the accepted placement values. Defaults to bottom.
*/
placement?: Placement;
/**
* The placements to fallback to when there is not enough space for the
* Popover. Defaults to ['top', 'right', 'left'].
*/
fallbackPlacements?: Placement[];
/**
* Modifiers are plugins for Popper.js to modify its default behavior.
* [Read the docs](https://popper.js.org/docs/v2/modifiers/).
*/
modifiers?: Partial<Modifier<string, Record<string, unknown>>>[];
/**
* The element that toggles the Popover when clicked.
*/
component: (props: {
'onClick': (event: ClickEvent) => void;
'onKeyDown': (event: KeyboardEvent) => void;
'id': string;
'aria-haspopup': boolean;
'aria-controls': string;
'aria-expanded': boolean;
}) => JSX.Element;
/**
* Additional data that is dispatched with the tracking event.
*/
tracking?: TrackingProps;
}
type TriggerKey = 'ArrowUp' | 'ArrowDown';
export const Popover = ({
isOpen = false,
onToggle,
actions,
placement = 'bottom',
fallbackPlacements = ['top', 'right', 'left'],
component: Component,
modifiers = [],
tracking,
...props
}: PopoverProps): JSX.Element | null => {
const theme = useTheme();
const zIndex = useStackContext();
const triggerKey = useRef<TriggerKey | null>(null);
const triggerEl = useRef<HTMLDivElement>(null);
const menuEl = useRef<HTMLDivElement>(null);
const triggerId = useMemo(() => uniqueId('trigger_'), []);
const menuId = useMemo(() => uniqueId('popover_'), []);
const sendEvent = useClickTrigger();
const handleToggle: OnToggle = (state) => {
onToggle((prev) => {
const next = isFunction(state) ? state(prev) : state;
if (tracking && tracking.label) {
sendEvent({
component: 'popover',
...tracking,
label: `${tracking.label}|${next ? 'open' : 'close'}`,
});
}
return next;
});
};
// Custom Popper.js modifier that switches to a bottom sheet on mobile.
// useMemo prevents a render loop:
// https://popper.js.org/react-popper/v2/faq/#why-i-get-render-loop-whenever-i-put-a-function-inside-the-popper-configuration
const mobilePosition: Modifier<'mobilePosition', { state: State }> = useMemo(
() => ({
name: 'mobilePosition',
enabled: true,
phase: 'write',
fn({ state }) {
if (window.matchMedia(`${theme.breakpoints.untilKilo}`).matches) {
// eslint-disable-next-line no-param-reassign
state.styles.popper = {
width: '100%',
left: '0px',
right: '0px',
bottom: '0px',
position: 'fixed',
zIndex: (zIndex || theme.zIndex.popover).toString(),
};
} else {
// eslint-disable-next-line no-param-reassign
state.styles.popper.width = 'auto';
// eslint-disable-next-line no-param-reassign
state.styles.popper.zIndex = (
zIndex || theme.zIndex.popover
).toString();
}
},
}),
[theme, zIndex],
);
// Flip the popover if there is no space for the default placement.
// https://popper.js.org/docs/v2/modifiers/flip/
const flip = {
name: 'flip',
options: {
fallbackPlacements,
},
};
// Disable the scroll and resize listeners when the popover is closed.
// https://popper.js.org/docs/v2/modifiers/event-listeners/
const eventListeners = {
name: 'eventListeners',
options: { scroll: isOpen, resize: isOpen },
};
// Note: the usePopper hook intentionally takes a DOM node, not a ref, in
// order to update when the node changes. We use a callback ref for this.
const [popperElement, setPopperElement] = useState<HTMLElement | null>(null);
const { styles, attributes, update } = usePopper(
triggerEl.current,
popperElement,
{
strategy: 'fixed',
placement,
modifiers: [mobilePosition, flip, eventListeners, ...modifiers],
},
);
// This is a performance optimization to prevent event listeners from being
// re-attached on every render.
const popperRef = useLatest(popperElement);
useEscapeKey(() => handleToggle(false), isOpen);
useClickOutside(popperRef, () => handleToggle(false), isOpen);
const prevOpen = usePrevious(isOpen);
useEffect(() => {
if (update) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
update();
}
// Focus the first or last element after opening
if (!prevOpen && isOpen) {
const element = (
triggerKey.current && triggerKey.current === 'ArrowUp'
? menuEl.current && menuEl.current.lastElementChild
: menuEl.current && menuEl.current.firstElementChild
) as HTMLElement;
if (element) {
element.focus();
}
}
// Focus the trigger button after closing
if (prevOpen && !isOpen) {
const triggerButton = (triggerEl.current &&
triggerEl.current.firstElementChild) as HTMLElement;
triggerButton.focus();
}
triggerKey.current = null;
}, [isOpen, prevOpen, update]);
const focusProps = useFocusList();
const handleTriggerClick = (event: ClickEvent) => {
// This prevents the event from bubbling which would trigger the
// useClickOutside above and would prevent the popover from closing.
event.stopPropagation();
handleToggle((prev) => !prev);
};
const handleTriggerKeyDown = (event: KeyboardEvent) => {
if (isArrowDown(event)) {
triggerKey.current = 'ArrowDown';
handleToggle(true);
}
if (isArrowUp(event)) {
triggerKey.current = 'ArrowUp';
handleToggle((prev) => !prev);
}
};
const handlePopoverItemClick = (
event: ClickEvent,
onClick: BaseProps['onClick'],
) => {
if (onClick) {
onClick(event);
}
handleToggle(false);
};
return (
<Fragment>
<TriggerElement ref={triggerEl}>
<Component
id={triggerId}
aria-haspopup={true}
aria-controls={menuId}
aria-expanded={isOpen}
onClick={handleTriggerClick}
onKeyDown={handleTriggerKeyDown}
/>
</TriggerElement>
<Portal>
<Overlay
isOpen={isOpen}
style={{ zIndex: zIndex || theme.zIndex.popover }}
/>
<Popper
{...props}
ref={setPopperElement}
isOpen={isOpen}
style={styles.popper}
{...attributes.popper}
>
<PopoverMenu
id={menuId}
ref={menuEl}
isOpen={isOpen}
aria-labelledby={triggerId}
role="menu"
>
{actions.map((action, index) =>
isDivider(action) ? (
<Hr css={dividerStyles} key={index} />
) : (
<PopoverItem
key={index}
{...action}
{...focusProps}
onClick={(event) =>
handlePopoverItemClick(event, action.onClick)
}
/>
),
)}
</PopoverMenu>
</Popper>
</Portal>
</Fragment>
);
}; | the_stack |
import { BriefcaseDb, Element, IModelDb, IModelHost, IModelJsNative, Relationship, SnapshotDb, SQLiteDb } from "@itwin/core-backend";
import * as BackendTestUtils from "@itwin/core-backend/lib/cjs/test";
import { AccessToken, DbResult, GuidString, Id64, Id64String, StopWatch } from "@itwin/core-bentley";
import { ChangesetId, ElementProps } from "@itwin/core-common";
import { assert, expect } from "chai";
import * as sinon from "sinon";
import { IModelImporter } from "../../IModelImporter";
import { IModelExporter } from "../../IModelExporter";
import { IModelTransformer, IModelTransformOptions } from "../../IModelTransformer";
import { assertIdentityTransformation, HubWrappers, IModelTransformerTestUtils } from "../IModelTransformerUtils";
import { HubMock } from "../HubMock";
const formatter = new Intl.NumberFormat("en-US", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
});
/** format a proportion (number between 0 and 1) to a percent */
const percent = (n: number) => `${formatter.format(100 * n)}%`;
class CountingImporter extends IModelImporter {
public owningTransformer: CountingTransformer | undefined;
public override importElement(elementProps: ElementProps): Id64String {
if (this.owningTransformer === undefined)
throw Error("uninitialized, '_owningTransformer' must have been set before transformations");
++this.owningTransformer.importedEntities;
return super.importElement(elementProps);
}
}
/** this class services two functions,
* 1. make sure transformations can be resumed by subclasses with different constructor argument types
* 2. count operations that should not be reperformed by a resumed transformation
*/
class CountingTransformer extends IModelTransformer {
public importedEntities = 0;
public exportedEntities = 0;
constructor(opts: {
source: IModelDb;
target: IModelDb;
options?: IModelTransformOptions;
}) {
super(
opts.source,
new CountingImporter(opts.target),
opts.options
);
(this.importer as CountingImporter).owningTransformer = this;
}
public override onExportElement(sourceElement: Element) {
++this.exportedEntities;
return super.onExportElement(sourceElement);
}
public override onExportRelationship(sourceRelationship: Relationship) {
++this.exportedEntities;
return super.onExportRelationship(sourceRelationship);
}
}
/** a transformer that executes a callback after X element exports */
class CountdownTransformer extends IModelTransformer {
public relationshipExportsUntilCall: number | undefined;
public elementExportsUntilCall: number | undefined;
public callback: (() => Promise<void>) | undefined;
public constructor(...args: ConstructorParameters<typeof IModelTransformer>) {
super(...args);
const _this = this; // eslint-disable-line @typescript-eslint/no-this-alias
const oldExportElem = this.exporter.exportElement; // eslint-disable-line @typescript-eslint/unbound-method
this.exporter.exportElement = async function (...args) {
if (_this.elementExportsUntilCall === 0) await _this.callback?.();
if (_this.elementExportsUntilCall !== undefined)
_this.elementExportsUntilCall--;
return oldExportElem.call(this, ...args);
};
const oldExportRel = this.exporter.exportRelationship; // eslint-disable-line @typescript-eslint/unbound-method
this.exporter.exportRelationship = async function (...args) {
if (_this.relationshipExportsUntilCall === 0) await _this.callback?.();
if (_this.relationshipExportsUntilCall !== undefined)
_this.relationshipExportsUntilCall--;
return oldExportRel.call(this, ...args);
};
}
}
/** a transformer that crashes on the nth element export, set `elementExportsUntilCall` to control the count */
class CountdownToCrashTransformer extends CountdownTransformer {
public constructor(...args: ConstructorParameters<typeof CountdownTransformer>) {
super(...args);
this.callback = () => { throw Error("crash"); };
}
}
/**
* Wraps all IModel native addon functions and constructors in a randomly throwing wrapper,
* as well as all IModelTransformer functions
* @note you must call sinon.restore at the end of any test that uses this
*/
function setupCrashingNativeAndTransformer({
methodCrashProbability = 1 / 800,
onCrashableCallMade,
}: {
methodCrashProbability?: number;
onCrashableCallMade?(): void;
} = {}) {
let crashingEnabled = false;
for (const [key, descriptor] of Object.entries(
Object.getOwnPropertyDescriptors(IModelHost.platform)
) as [keyof typeof IModelHost["platform"], PropertyDescriptor][]) {
const superValue: unknown = descriptor.value;
if (typeof superValue === "function" && descriptor.writable) {
sinon.replace(
IModelHost.platform,
key,
function (this: IModelJsNative.DgnDb, ...args: any[]) {
onCrashableCallMade?.();
if (crashingEnabled) {
// this does not at all test mid-method crashes... that might be doable by racing timeouts on async functions...
if (crashingEnabled && Math.random() <= methodCrashProbability)
throw Error("fake native crash");
}
const isConstructor = (o: Function): o is new (...a: any[]) => any =>
"prototype" in o;
if (isConstructor(superValue)) return new superValue(...args);
else return superValue.call(this, ...args);
}
);
}
}
for (const [key, descriptor] of Object.entries(
Object.getOwnPropertyDescriptors(IModelTransformer.prototype)
) as [keyof IModelTransformer, PropertyDescriptor][]) {
const superValue: unknown = descriptor.value;
if (typeof superValue === "function" && descriptor.writable) {
sinon.replace(
IModelTransformer.prototype,
key,
function (this: IModelTransformer, ...args: any[]) {
onCrashableCallMade?.();
if (crashingEnabled) {
// this does not at all test mid-method crashes... that might be doable by racing timeouts on async functions...
if (crashingEnabled && Math.random() <= methodCrashProbability)
throw Error("fake crash");
}
return superValue.call(this, ...args);
}
);
}
}
return {
enableCrashes: (val = true) => {
crashingEnabled = val;
},
};
}
async function transformWithCrashAndRecover<
Transformer extends IModelTransformer,
DbType extends IModelDb
>({
sourceDb,
targetDb,
transformer,
disableCrashing,
transformerProcessing = async (t, time = 0) => {
if (time === 0) await t.processSchemas();
await t.processAll();
},
}: {
sourceDb: DbType;
targetDb: DbType;
transformer: Transformer;
/* what processing to do for the transform; default impl is above */
transformerProcessing?: (transformer: Transformer, time?: number) => Promise<void>;
disableCrashing?: (transformer: Transformer) => void;
}) {
let crashed = false;
try {
await transformerProcessing(transformer);
} catch (transformerErr) {
expect((transformerErr as Error).message).to.equal("crash");
crashed = true;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"transformer-state.db"
);
transformer.saveStateToFile(dumpPath);
// eslint-disable-next-line @typescript-eslint/naming-convention
const TransformerClass = transformer.constructor as typeof IModelTransformer;
transformer = TransformerClass.resumeTransformation(dumpPath, sourceDb, targetDb) as Transformer;
disableCrashing?.(transformer);
await transformerProcessing(transformer);
}
expect(crashed).to.be.true;
return targetDb;
}
/** this utility is for consistency and readability, it doesn't provide any actual abstraction */
async function transformNoCrash<
Transformer extends IModelTransformer
>({
targetDb,
transformer,
transformerProcessing = async (t) => { await t.processSchemas(); await t.processAll(); },
}: {
sourceDb: IModelDb;
targetDb: IModelDb;
transformer: Transformer;
transformerProcessing?: (transformer: Transformer) => Promise<void>;
}): Promise<IModelDb> {
await transformerProcessing(transformer);
return targetDb;
}
describe("test resuming transformations", () => {
let iTwinId: GuidString;
let accessToken: AccessToken;
let seedDbId: GuidString;
let seedDb: BriefcaseDb;
before(async () => {
HubMock.startup("IModelTransformerResumption");
iTwinId = HubMock.iTwinId;
accessToken = await HubWrappers.getAccessToken(BackendTestUtils.TestUserType.Regular);
const seedPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformerResumption", "seed.bim");
SnapshotDb.createEmpty(seedPath, { rootSubject: { name: "resumption-tests-seed" }});
seedDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "ResumeTestsSeed", description: "seed for resumption tests", version0: seedPath, noLocks: true });
seedDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: seedDbId });
await BackendTestUtils.ExtensiveTestScenario.prepareDb(seedDb);
BackendTestUtils.ExtensiveTestScenario.populateDb(seedDb);
seedDb.saveChanges();
await seedDb.pushChanges({accessToken, description: "populated seed db"});
});
after(async () => {
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, seedDb);
HubMock.shutdown();
});
it("resume old state after partially committed changes", async () => {
const sourceDb = seedDb;
const [regularTransformer, regularTarget] = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb2", description: "non crashing target", noLocks: true });
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new IModelTransformer(sourceDb, targetDb);
await transformNoCrash({sourceDb, targetDb, transformer});
targetDb.saveChanges();
return [transformer, targetDb] as const;
})();
const [resumedTransformer, resumedTarget] = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb1", description: "crashingTarget", noLocks: true });
let targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
let changesetId: ChangesetId;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformerResumption", "transformer-state.db");
let transformer = new CountdownTransformer(sourceDb, targetDb);
// after exporting 10 elements, save and push changes
transformer.elementExportsUntilCall = 10;
transformer.callback = async () => {
targetDb.saveChanges();
await targetDb.pushChanges({accessToken, description: "early state save"});
transformer.saveStateToFile(dumpPath);
changesetId = targetDb.changeset.id;
// now after another 10 exported elements, interrupt for resumption
transformer.elementExportsUntilCall = 10;
transformer.callback = () => {
throw Error("interrupt");
};
};
let interrupted = false;
try {
await transformer.processSchemas();
// will trigger the callback after 10 exported elements, which triggers another
// callback to be installed for after 20 elements, to throw an error to interrupt the transformation
await transformer.processAll();
} catch (transformerErr) {
expect((transformerErr as Error).message).to.equal("interrupt");
interrupted = true;
// redownload to simulate restarting without any JS state
expect(targetDb.nativeDb.hasUnsavedChanges()).to.be.true;
targetDb.close();
targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
expect(targetDb.nativeDb.hasUnsavedChanges()).to.be.false;
expect(targetDb.changeset.id).to.equal(changesetId!);
// eslint-disable-next-line @typescript-eslint/naming-convention
const TransformerClass = transformer.constructor as typeof IModelTransformer;
transformer = TransformerClass.resumeTransformation(dumpPath, sourceDb, targetDb) as CountdownTransformer;
await transformer.processAll();
targetDb.saveChanges();
return [transformer, targetDb] as const;
}
expect(interrupted, "should have interrupted rather than completing").to.be.true;
throw Error("unreachable");
})();
const regularToResumedIdMap = new Map<Id64String, Id64String>();
for (const [className, findMethod] of [["bis.Element", "findTargetElementId"], ["bis.CodeSpec", "findTargetCodeSpecId"]] as const) {
for await (const [sourceElemId] of sourceDb.query(`SELECT ECInstanceId from ${className}`)) {
const idInRegular = regularTransformer.context[findMethod](sourceElemId);
const idInResumed = resumedTransformer.context[findMethod](sourceElemId);
regularToResumedIdMap.set(idInRegular, idInResumed);
}
}
await assertIdentityTransformation(regularTarget, resumedTarget, (id) => regularToResumedIdMap.get(id) ?? Id64.invalid);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, resumedTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, regularTarget);
});
it("simple single crash transform resumption", async () => {
const sourceDbId = await IModelHost.hubAccess.createNewIModel({
iTwinId,
iModelName: "sourceDb1",
description: "a db called sourceDb1",
noLocks: true,
version0: seedDb.pathName,
});
const sourceDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: sourceDbId });
const crashingTarget = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb1", description: "crashingTarget", noLocks: true });
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new CountdownToCrashTransformer(sourceDb, targetDb);
transformer.elementExportsUntilCall = 10;
await transformWithCrashAndRecover({sourceDb, targetDb, transformer, disableCrashing(t) {
t.elementExportsUntilCall = undefined;
}});
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
const regularTarget = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb2", description: "non crashing target", noLocks: true });
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new IModelTransformer(sourceDb, targetDb);
await transformNoCrash({sourceDb, targetDb, transformer});
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
await assertIdentityTransformation(regularTarget, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, sourceDb);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, regularTarget);
});
it("should fail to resume from an old target", async () => {
const sourceDbId = await IModelHost.hubAccess.createNewIModel({
iTwinId,
iModelName: "sourceDb1",
description: "a db called sourceDb1",
noLocks: true,
version0: seedDb.pathName,
});
const sourceDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: sourceDbId });
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb1", description: "crashingTarget", noLocks: true });
let targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new CountdownToCrashTransformer(sourceDb, targetDb);
transformer.elementExportsUntilCall = 10;
let crashed = false;
try {
await transformer.processSchemas();
await transformer.processAll();
} catch (transformerErr) {
expect((transformerErr as Error).message).to.equal("crash");
crashed = true;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"transformer-state.db"
);
transformer.saveStateToFile(dumpPath);
// eslint-disable-next-line @typescript-eslint/naming-convention
const TransformerClass = transformer.constructor as typeof IModelTransformer;
// redownload targetDb so that it is reset to the old state
targetDb.close();
targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
expect(
() => TransformerClass.resumeTransformation(dumpPath, sourceDb, targetDb)
).to.throw(/does not have the expected provenance/);
}
expect(crashed).to.be.true;
transformer.dispose();
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, sourceDb);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, targetDb);
return targetDb;
});
/* eslint-disable @typescript-eslint/naming-convention */
it("should fail to resume from a different(ly named) transformer classes", async () => {
async function testResumeCrashTransformerWithClasses({
StartTransformerClass = IModelTransformer,
StartImporterClass = IModelImporter,
StartExporterClass = IModelExporter,
ResumeTransformerClass = StartTransformerClass,
ResumeImporterClass = StartImporterClass,
ResumeExporterClass = StartExporterClass,
}: {
StartTransformerClass?: typeof IModelTransformer;
StartImporterClass?: typeof IModelImporter;
StartExporterClass?: typeof IModelExporter;
ResumeTransformerClass?: typeof IModelTransformer;
ResumeImporterClass?: typeof IModelImporter;
ResumeExporterClass?: typeof IModelExporter;
} = {}) {
const sourceDb = seedDb;
const targetDb = SnapshotDb.createFrom(
seedDb,
IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"ResumeDifferentClass.bim"
)
);
const transformer = new StartTransformerClass(new StartExporterClass(sourceDb), new StartImporterClass(targetDb));
let crashed = false;
try {
await transformer.processSchemas();
await transformer.processAll();
} catch (transformerErr) {
expect((transformerErr as Error).message).to.equal("crash");
crashed = true;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"transformer-state.db"
);
transformer.saveStateToFile(dumpPath);
expect(() =>
ResumeTransformerClass.resumeTransformation(
dumpPath,
new ResumeExporterClass(sourceDb),
new ResumeImporterClass(targetDb),
)
).to.throw(/it is not.*valid to resume with a different.*class/);
}
expect(crashed).to.be.true;
transformer.dispose();
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, targetDb);
}
class CrashOn2Transformer extends CountdownToCrashTransformer {
public constructor(...args: ConstructorParameters<typeof CountdownToCrashTransformer>) {
super(...args);
this.elementExportsUntilCall = 2;
}
}
class DifferentTransformerClass extends CrashOn2Transformer {}
class DifferentImporterClass extends IModelImporter {}
class DifferentExporterClass extends IModelExporter {}
await testResumeCrashTransformerWithClasses({ StartTransformerClass: CrashOn2Transformer, ResumeTransformerClass: DifferentTransformerClass });
await testResumeCrashTransformerWithClasses({ StartTransformerClass: CrashOn2Transformer, ResumeImporterClass: DifferentImporterClass });
await testResumeCrashTransformerWithClasses({ StartTransformerClass: CrashOn2Transformer, ResumeExporterClass: DifferentExporterClass });
});
/* eslint-enable @typescript-eslint/naming-convention */
it("should save custom additional state", async () => {
class AdditionalStateImporter extends IModelImporter {
public state1 = "importer";
protected override getAdditionalStateJson() { return { state1: this.state1 }; }
protected override loadAdditionalStateJson(additionalState: any) { this.state1 = additionalState.state1; }
}
class AdditionalStateExporter extends IModelExporter {
public state1 = "exporter";
protected override getAdditionalStateJson() { return { state1: this.state1 }; }
protected override loadAdditionalStateJson(additionalState: any) { this.state1 = additionalState.state1; }
}
class AdditionalStateTransformer extends IModelTransformer {
public state1 = "default";
public state2 = 42;
protected override saveStateToDb(db: SQLiteDb): void {
super.saveStateToDb(db);
db.executeSQL("CREATE TABLE additionalState (state1 TEXT, state2 INTEGER)");
db.saveChanges();
db.withSqliteStatement(`INSERT INTO additionalState (state1) VALUES (?)`, (stmt) => {
stmt.bindString(1, this.state1);
expect(stmt.step()).to.equal(DbResult.BE_SQLITE_DONE);
});
}
protected override loadStateFromDb(db: SQLiteDb): void {
super.loadStateFromDb(db);
db.withSqliteStatement(`SELECT state1 FROM additionalState`, (stmt) => {
expect(stmt.step()).to.equal(DbResult.BE_SQLITE_ROW);
this.state1 = stmt.getValueString(0);
});
}
protected override getAdditionalStateJson() { return { state2: this.state2 }; }
protected override loadAdditionalStateJson(additionalState: any) { this.state2 = additionalState.state2; }
}
const sourceDb = seedDb;
const targetDb = SnapshotDb.createEmpty(
IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"CustomAdditionalState.bim"
),
{ rootSubject: { name: "CustomAdditionalStateTest" } }
);
const transformer = new AdditionalStateTransformer(new AdditionalStateExporter(sourceDb), new AdditionalStateImporter(targetDb));
transformer.state1 = "transformer-state-1";
transformer.state2 = 43;
(transformer.importer as AdditionalStateImporter).state1 = "importer-state-1";
(transformer.exporter as AdditionalStateExporter).state1 = "exporter-state-1";
const dumpPath = IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"transformer-state.db"
);
transformer.saveStateToFile(dumpPath);
// eslint-disable-next-line @typescript-eslint/naming-convention
const TransformerClass = transformer.constructor as typeof AdditionalStateTransformer;
transformer.dispose();
const resumedTransformer = TransformerClass.resumeTransformation(dumpPath, new AdditionalStateExporter(sourceDb), new AdditionalStateImporter(targetDb));
expect(resumedTransformer).not.to.equal(transformer);
expect(resumedTransformer.state1).to.equal(transformer.state1);
expect(resumedTransformer.state2).to.equal(transformer.state2);
expect((resumedTransformer.importer as AdditionalStateImporter).state1).to.equal((transformer.importer as AdditionalStateImporter).state1);
expect((resumedTransformer.exporter as AdditionalStateExporter).state1).to.equal((transformer.exporter as AdditionalStateExporter).state1);
resumedTransformer.dispose();
targetDb.close();
});
it("should fail to resume from an old target while processing relationships", async () => {
const sourceDb = seedDb;
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb1", description: "crashingTarget", noLocks: true });
let targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new CountdownToCrashTransformer(sourceDb, targetDb);
transformer.relationshipExportsUntilCall = 2;
let crashed = false;
try {
await transformer.processSchemas();
await transformer.processAll();
} catch (transformerErr) {
expect((transformerErr as Error).message).to.equal("crash");
crashed = true;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"transformer-state.db"
);
transformer.saveStateToFile(dumpPath);
// eslint-disable-next-line @typescript-eslint/naming-convention
const TransformerClass = transformer.constructor as typeof IModelTransformer;
transformer.dispose();
// redownload targetDb so that it is reset to the old state
targetDb.close();
targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
expect(
() => TransformerClass.resumeTransformation(dumpPath, sourceDb, targetDb)
).to.throw(/does not have the expected provenance/);
}
expect(crashed).to.be.true;
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, targetDb);
return targetDb;
});
it("should succeed to resume from an up-to-date target while processing relationships", async () => {
const sourceDb = seedDb;
const crashingTarget = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb1", description: "crashingTarget", noLocks: true });
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new CountdownToCrashTransformer(sourceDb, targetDb);
transformer.relationshipExportsUntilCall = 2;
let crashed = false;
try {
await transformer.processSchemas();
await transformer.processAll();
} catch (transformerErr) {
expect((transformerErr as Error).message).to.equal("crash");
crashed = true;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile(
"IModelTransformerResumption",
"transformer-state.db"
);
transformer.saveStateToFile(dumpPath);
// eslint-disable-next-line @typescript-eslint/naming-convention
const TransformerClass = transformer.constructor as typeof CountdownToCrashTransformer;
TransformerClass.resumeTransformation(dumpPath, sourceDb, targetDb);
transformer.relationshipExportsUntilCall = undefined;
await transformer.processAll();
}
expect(crashed).to.be.true;
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
const regularTarget = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName: "targetDb2", description: "non crashing target", noLocks: true });
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new IModelTransformer(sourceDb, targetDb);
await transformNoCrash({sourceDb, targetDb, transformer});
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
await assertIdentityTransformation(regularTarget, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, regularTarget);
});
it("processChanges crash and resume", async () => {
const sourceDbId = await IModelHost.hubAccess.createNewIModel({
iTwinId,
iModelName: "sourceDb1",
description: "a db called sourceDb1",
noLocks: true,
});
const sourceDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: sourceDbId });
await BackendTestUtils.ExtensiveTestScenario.prepareDb(sourceDb);
BackendTestUtils.ExtensiveTestScenario.populateDb(sourceDb);
sourceDb.saveChanges();
await sourceDb.pushChanges({accessToken, description: "populated source db"});
const targetDbRev0Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformerResumption", "processChanges-targetDbRev0.bim");
const targetDbRev0 = SnapshotDb.createFrom(sourceDb, targetDbRev0Path);
const provenanceTransformer = new IModelTransformer(sourceDb, targetDbRev0, { wasSourceIModelCopiedToTarget: true });
await provenanceTransformer.processAll();
provenanceTransformer.dispose();
targetDbRev0.saveChanges();
BackendTestUtils.ExtensiveTestScenario.updateDb(sourceDb);
sourceDb.saveChanges();
await sourceDb.pushChanges({accessToken, description: "updated source db"});
const regularTarget = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({
iTwinId,
iModelName: "targetDb1",
description: "non crashing target",
noLocks: true,
version0: targetDbRev0Path,
});
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new IModelTransformer(sourceDb, targetDb);
await transformNoCrash({
sourceDb, targetDb, transformer,
async transformerProcessing(t) {
await t.processChanges(accessToken);
},
});
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
const crashingTarget = await (async () => {
const targetDbId = await IModelHost.hubAccess.createNewIModel({
iTwinId,
iModelName: "targetDb2",
description: "crashing target",
noLocks: true,
version0: targetDbRev0Path,
});
const targetDb = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId: targetDbId });
const transformer = new CountdownToCrashTransformer(sourceDb, targetDb);
transformer.elementExportsUntilCall = 10;
await transformWithCrashAndRecover({sourceDb, targetDb, transformer, disableCrashing(t) {
t.elementExportsUntilCall = undefined;
}, async transformerProcessing(t) {
await t.processChanges(accessToken);
}});
targetDb.saveChanges();
await targetDb.pushChanges({accessToken, description: "completed transformation that crashed"});
transformer.dispose();
return targetDb;
})();
await assertIdentityTransformation(regularTarget, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, regularTarget);
});
// env variables:
// TRANSFORMER_RESUMPTION_TEST_SINGLE_MODEL_ELEMENTS_BEFORE_CRASH (defaults to 2_500_000)
// TRANSFORMER_RESUMPTION_TEST_SINGLE_MODEL_PATH (defaults to the likely invalid "huge-model.bim")
// change "skip" to "only" to test local models
it.skip("local test single model", async () => {
const sourceDb = SnapshotDb.openFile("./huge-model.bim");
const crashingTarget = await (async () => {
const targetDbPath = "/tmp/huge-model-out.bim";
const targetDb = SnapshotDb.createEmpty(targetDbPath, sourceDb);
const transformer = new CountdownToCrashTransformer(sourceDb, targetDb);
transformer.elementExportsUntilCall = Number(process.env.TRANSFORMER_RESUMPTION_TEST_SINGLE_MODEL_ELEMENTS_BEFORE_CRASH) || 2_500_000;
await transformWithCrashAndRecover({sourceDb, targetDb, transformer, disableCrashing(t) {
t.elementExportsUntilCall = undefined;
}});
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
const regularTarget = await (async () => {
const targetDbPath = "/tmp/huge-model-out.bim";
const targetDb = SnapshotDb.createEmpty(targetDbPath, sourceDb);
const transformer = new IModelTransformer(sourceDb, targetDb);
await transformNoCrash({sourceDb, targetDb, transformer});
targetDb.saveChanges();
transformer.dispose();
return targetDb;
})();
await assertIdentityTransformation(regularTarget, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, regularTarget);
});
// replace "skip" with "only" to run several transformations with random native platform and transformer api method errors thrown
// you may control the amount of tests ran with the following environment variables
// TRANSFORMER_RESUMPTION_TEST_TOTAL_NON_CRASHING_TRANSFORMATIONS (defaults to 5)
// TRANSFORMER_RESUMPTION_TEST_TARGET_TOTAL_CRASHING_TRANSFORMATIONS (defaults to 50)
// TRANSFORMER_RESUMPTION_TEST_MAX_CRASHING_TRANSFORMATIONS (defaults to 200)
it.skip("crashing transforms stats gauntlet", async () => {
let crashableCallsMade = 0;
const { enableCrashes } = setupCrashingNativeAndTransformer({ onCrashableCallMade() { ++crashableCallsMade; } });
// TODO: don't run a new control test to compare with every crash test,
// right now trying to run assertIdentityTransform against the control transform target dbs in the control loop yields
// BE_SQLITE_ERROR: Failed to prepare 'select * from (SELECT ECInstanceId FROM bis.Element) limit :sys_ecdb_count offset :sys_ecdb_offset'. The data source ECDb (parameter 'dataSourceECDb') must be a connection to the same ECDb file as the ECSQL parsing ECDb connection (parameter 'ecdb').
// until that is investigated/fixed, the slow method here is used
async function runAndCompareWithControl(crashingEnabledForThisTest: boolean) {
const sourceFileName = IModelTransformerTestUtils.resolveAssetFile("CompatibilityTestSeed.bim");
const sourceDb = SnapshotDb.openFile(sourceFileName);
async function transformWithMultipleCrashesAndRecover() {
const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformerResumption", "ResumeTransformationCrash.bim");
const targetDb = SnapshotDb.createEmpty(targetDbPath, sourceDb);
let transformer = new CountingTransformer({ source: sourceDb, target: targetDb });
const MAX_ITERS = 100;
let crashCount = 0;
let timer: StopWatch;
enableCrashes(crashingEnabledForThisTest);
for (let i = 0; i <= MAX_ITERS; ++i) {
timer = new StopWatch();
timer.start();
try {
await transformer.processSchemas();
await transformer.processAll();
break;
} catch (transformerErr) {
crashCount++;
const dumpPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformerResumption", "transformer-state.db");
enableCrashes(false);
transformer.saveStateToFile(dumpPath);
transformer = CountingTransformer.resumeTransformation(dumpPath, { source: sourceDb, target: targetDb });
enableCrashes(true);
crashableCallsMade = 0;
console.log(`crashed after ${timer.elapsed.seconds} seconds`); // eslint-disable-line no-console
}
if (i === MAX_ITERS) assert.fail("crashed too many times");
}
console.log(`completed after ${crashCount} crashes`); // eslint-disable-line no-console
const result = {
resultDb: targetDb,
finalTransformationTime: timer!.elapsedSeconds,
finalTransformationCallsMade: crashableCallsMade,
crashCount,
importedEntityCount: transformer.importedEntities,
exportedEntityCount: transformer.exportedEntities,
};
crashableCallsMade = 0;
return result;
}
const { resultDb: crashingTarget, ...crashingTransformResult } = await transformWithMultipleCrashesAndRecover();
const regularTarget = await (async () => {
const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformerResumption", "ResumeTransformationNoCrash.bim");
const targetDb = SnapshotDb.createEmpty(targetDbPath, sourceDb);
const transformer = new IModelTransformer(sourceDb, targetDb);
enableCrashes(false);
return transformNoCrash({sourceDb, targetDb, transformer});
})();
await assertIdentityTransformation(regularTarget, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, crashingTarget);
await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, regularTarget);
return crashingTransformResult;
}
let totalCrashableCallsMade = 0;
let totalNonCrashingTransformationsTime = 0.0;
let totalImportedEntities = 0;
let totalExportedEntities = 0;
const totalNonCrashingTransformations = Number(process.env.TRANSFORMER_RESUMPTION_TEST_TOTAL_NON_CRASHING_TRANSFORMATIONS) || 5;
for (let i = 0; i < totalNonCrashingTransformations; ++i) {
// eslint-disable-next-line @typescript-eslint/no-shadow
const result = await runAndCompareWithControl(false);
totalCrashableCallsMade += result.finalTransformationCallsMade;
totalNonCrashingTransformationsTime += result.finalTransformationTime;
totalImportedEntities += result.importedEntityCount;
totalExportedEntities += result.exportedEntityCount;
}
const avgNonCrashingTransformationsTime = totalNonCrashingTransformationsTime / totalNonCrashingTransformations;
const avgCrashableCallsMade = totalCrashableCallsMade / totalNonCrashingTransformations;
const avgImportedEntityCount = totalImportedEntities / totalNonCrashingTransformations;
const avgExportedEntityCount = totalExportedEntities / totalNonCrashingTransformations;
// eslint-disable-next-line no-console
console.log(`the average non crashing transformation took ${
formatter.format(avgNonCrashingTransformationsTime)
} and made ${
formatter.format(avgCrashableCallsMade)
} native calls.`);
let totalCrashingTransformationsTime = 0.0;
const targetTotalCrashingTransformations = Number(process.env.TRANSFORMER_RESUMPTION_TEST_TARGET_TOTAL_CRASHING_TRANSFORMATIONS) || 50;
const MAX_CRASHING_TRANSFORMS = Number(process.env.TRANSFORMER_RESUMPTION_TEST_MAX_CRASHING_TRANSFORMATIONS) || 200;
let totalCrashingTransformations = 0;
for (let i = 0; i < MAX_CRASHING_TRANSFORMS && totalCrashingTransformations < targetTotalCrashingTransformations; ++i) {
// eslint-disable-next-line @typescript-eslint/no-shadow
const result = await runAndCompareWithControl(true);
if (result.crashCount === 0) continue;
totalCrashingTransformations++;
const proportionOfNonCrashingTransformTime = result.finalTransformationTime / avgNonCrashingTransformationsTime;
const proportionOfNonCrashingTransformCalls = result.finalTransformationCallsMade / avgCrashableCallsMade;
const proportionOfNonCrashingEntityImports = result.importedEntityCount / avgImportedEntityCount;
expect(result.exportedEntityCount ).to.equal(avgExportedEntityCount);
const _ratioOfCallsToTime = proportionOfNonCrashingTransformCalls / proportionOfNonCrashingTransformTime;
const _ratioOfImportsToTime = proportionOfNonCrashingEntityImports / proportionOfNonCrashingTransformTime;
/* eslint-disable no-console */
console.log(`final resuming transformation took | ${
percent(proportionOfNonCrashingTransformTime)
} time | ${
percent(proportionOfNonCrashingTransformCalls)
} calls | ${
percent(proportionOfNonCrashingEntityImports)
} element imports |`);
/* eslint-enable no-console */
totalCrashingTransformationsTime += result.finalTransformationTime;
}
const avgCrashingTransformationsTime = totalCrashingTransformationsTime / totalCrashingTransformations;
/* eslint-disable no-console */
console.log(`avg crashable calls made: ${avgCrashableCallsMade}`);
console.log(`avg non-crashing transformations time: ${avgNonCrashingTransformationsTime}`);
console.log(`avg crash-resuming+completing transformations time: ${avgCrashingTransformationsTime}`);
/* eslint-enable no-console */
sinon.restore();
});
}); | the_stack |
import * as React from "react";
import { SortableListHeader } from "../SortableListHeader";
import {
Datatype,
AttributeAddon,
AttributeInput,
Primitives,
makeUniqueId,
buildDefaultAddonsValue,
validateAttribute,
SchemaInput,
} from "@codotype/core";
import { Droppable, DragDropContext } from "react-beautiful-dnd";
import { AttributeFormModal } from "./AttributeFormModal";
import { AttributeDeleteModal } from "./AttributeDeleteModal";
import { AttributeListItem } from "./AttributeListItem";
import { AttributeForm } from "./AttributeForm";
import { Hotkey } from "../Hotkey";
import { reorder } from "./reorder";
import { SortableListEmpty } from "../SortableListEmpty";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faKeyboard } from "@fortawesome/free-regular-svg-icons";
// // // //
/**
* disableSubmit
* @param label
*/
export function disableSubmit(params: {
attributeInput: AttributeInput;
attributeCollection: AttributeInput[];
}): boolean {
return validateAttribute(params).length > 0;
}
// // // //
interface AttributeEditorState {
attributes: AttributeInput[];
lastUpdatedAt: null | number;
}
interface AttributeEditorProps {
selectedSchema: SchemaInput;
attributes: AttributeInput[];
addons: AttributeAddon[];
supportedDatatypes: Datatype[];
onChange: (updatedAttributes: AttributeInput[]) => void;
}
export function AttributeEditor(props: AttributeEditorProps) {
const [state, setState] = React.useState<AttributeEditorState>({
attributes: props.attributes,
lastUpdatedAt: null,
});
const [attributeInput, setAttributeInput] = React.useState<AttributeInput>(
new Primitives.AttributeInput({ id: "" }),
);
const [
showingDeleteModal,
showDeleteModal,
] = React.useState<AttributeInput | null>(null);
const [showingInputModal, showInputModal] = React.useState<boolean>(false);
// Sets props.attributes when props.attributes changes
React.useEffect(() => {
setState({ ...state, attributes: props.attributes });
}, [props.attributes]);
// Fires off props.onChange
React.useEffect(() => {
props.onChange(state.attributes);
}, [state.lastUpdatedAt]);
// // // //
// Defines saveAttribute function
function saveAttribute(params: {
saveAndContinue: boolean;
newAttributeData: AttributeInput;
}) {
// Insert new Attribute
if (
params.newAttributeData.id === "" ||
params.newAttributeData.id === null
) {
if (params.newAttributeData.datatype === null) {
return;
}
const newAttributeParams = {
...params.newAttributeData,
id: makeUniqueId(),
datatype: params.newAttributeData.datatype,
addons: {
...buildDefaultAddonsValue({
properties: props.addons.map(a => a.property),
}),
...params.newAttributeData.addons,
},
};
const newAttribute: AttributeInput = new Primitives.AttributeInput(
newAttributeParams,
);
setState({
lastUpdatedAt: Date.now(),
attributes: [...props.attributes, newAttribute],
});
setAttributeInput(new Primitives.AttributeInput({ id: "" }));
if (params.saveAndContinue) {
setTimeout(() => {
setAttributeInput(
new Primitives.AttributeInput({ id: "" }),
);
}, 150);
return;
}
showInputModal(false);
return;
}
// Update existing attribute
setState({
lastUpdatedAt: Date.now(),
attributes: props.attributes.map((a: AttributeInput) => {
if (a.id === params.newAttributeData.id) {
return params.newAttributeData;
}
return a;
}),
});
setAttributeInput(new Primitives.AttributeInput({ id: "" }));
}
// // // //
return (
<div
className="card"
style={{
borderBottom: "none",
borderBottomLeftRadius: "0px",
borderBottomRightRadius: "0px",
}}
>
<SortableListHeader
label="Attributes"
tooltip={
<p>
<FontAwesomeIcon icon={faKeyboard} className="pr-2" />
<span className="font-light">{"SHIFT + A"}</span>
</p>
}
locked={props.selectedSchema.locked}
onClick={() => {
const newAttribute: AttributeInput = new Primitives.AttributeInput(
{ id: "" },
);
setAttributeInput(newAttribute);
showInputModal(true);
}}
/>
{/* Renders AttributeFormModal */}
<AttributeFormModal
attributeInput={attributeInput}
show={showingInputModal}
disableSubmit={disableSubmit({
attributeInput,
attributeCollection: props.attributes,
})}
errors={validateAttribute({
attributeInput,
attributeCollection: props.attributes,
})}
onCancel={() => {
showInputModal(false);
// Leave a lil' room for the Modal-Close UI animation!
setTimeout(() => {
setAttributeInput(
new Primitives.AttributeInput({ id: "" }),
);
}, 300);
}}
onSubmit={({ saveAndContinue }) => {
saveAttribute({
saveAndContinue,
newAttributeData: {
...attributeInput,
},
});
}}
>
<AttributeForm
attributes={props.attributes}
attributeInput={attributeInput}
onChange={(updatedAttributeInput: AttributeInput) => {
setAttributeInput(updatedAttributeInput);
}}
onKeydownEnter={() => {
if (
disableSubmit({
attributeInput,
attributeCollection: props.attributes,
})
) {
return;
}
// Save attribute on keydown "Enter"
saveAttribute({
saveAndContinue: true,
newAttributeData: attributeInput,
});
}}
addons={props.addons}
supportedDatatypes={props.supportedDatatypes}
/>
</AttributeFormModal>
{props.attributes.length > 0 && (
<React.Fragment>
<AttributeDeleteModal
show={showingDeleteModal !== null}
onClose={() => showDeleteModal(null)}
onConfirm={() => {
if (showingDeleteModal !== null) {
setState({
attributes: props.attributes.filter(
(a: AttributeInput) => {
return (
a.id !== showingDeleteModal.id
);
},
),
lastUpdatedAt: Date.now(),
});
}
showDeleteModal(null);
}}
/>
<DragDropContext
onDragEnd={result => {
if (!result.destination) {
return;
}
if (
result.destination.index === result.source.index
) {
return;
}
const updatedAttributes = reorder<AttributeInput>(
props.attributes,
result.source.index,
result.destination.index,
);
// Invoke props.onChange directly, prevents multiple re-renders
props.onChange(updatedAttributes);
}}
>
<Droppable droppableId="attribute-list">
{(provided: any) => {
return (
<ul
className="flex flex-col pl-0 mb-0 rounded-none"
ref={provided.innerRef}
{...provided.droppableProps}
>
{props.attributes.map(
(
a: AttributeInput,
index: number,
) => {
return (
<AttributeListItem
key={a.id}
attribute={a}
index={index}
addons={props.addons}
onClickEdit={(
attributeToBeEdited: AttributeInput,
) => {
setAttributeInput({
...attributeToBeEdited,
});
showInputModal(
true,
);
}}
onClickDelete={(
attributeToDelete: AttributeInput,
) => {
showDeleteModal(
attributeToDelete,
);
}}
/>
);
},
)}
{provided.placeholder}
</ul>
);
}}
</Droppable>
</DragDropContext>
</React.Fragment>
)}
{/* Render empty state */}
{props.attributes.length === 0 && (
<SortableListEmpty
title="No Attributes added yet"
body="Define properties on this data model"
cta="Add Attribute"
onClick={() => {
const newAttribute: AttributeInput = new Primitives.AttributeInput(
{ id: "" },
);
setAttributeInput(newAttribute);
showInputModal(true);
}}
/>
)}
<Hotkey
keyName="shift+a"
onKeyDown={() => {
const newAttribute: AttributeInput = new Primitives.AttributeInput(
{ id: "" },
);
setAttributeInput(newAttribute);
showInputModal(true);
}}
/>
</div>
);
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import '../rxjs-operators';
import { Appointment } from '../model/appointment';
import { AppointmentExamination } from '../model/appointmentExamination';
import { Attendance } from '../model/attendance';
import { Examination } from '../model/examination';
import { InlineResponse200 } from '../model/inlineResponse200';
import { InlineResponse2001 } from '../model/inlineResponse2001';
import { InlineResponse2002 } from '../model/inlineResponse2002';
import { InlineResponse2003 } from '../model/inlineResponse2003';
import { InlineResponse2004 } from '../model/inlineResponse2004';
import { Patient } from '../model/patient';
import { Room } from '../model/room';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
@Injectable()
export class AppointmentService {
protected basePath = 'http://localhost:3000/api';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
}
/**
*
* Extends object by coping non-existing properties.
* @param objA object to be extended
* @param objB source object
*/
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
(objA as any)[key] = (objB as any)[key];
}
}
return <T1&T2>objA;
}
/**
* @param consumes string[] mime-types
* @return true: consumes contains 'multipart/form-data', false: otherwise
*/
private canConsumeForm(consumes: string[]): boolean {
const form = 'multipart/form-data';
for (let consume of consumes) {
if (form === consume) {
return true;
}
}
return false;
}
/**
* Accepts an offer by passing over the respective secret.
*
* @param offerSecret
*/
public appointmentAcceptOffer(offerSecret: string, extraHttpRequestParams?: any): Observable<any> {
return this.appointmentAcceptOfferWithHttpInfo(offerSecret, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Count instances of the model matched by where from the data source.
*
* @param where Criteria to match model instances
*/
public appointmentCount(where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> {
return this.appointmentCountWithHttpInfo(where, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Create a new instance of the model and persist it into the data source.
*
* @param data Model instance data
*/
public appointmentCreate(data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentCreateWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Create a change stream.
*
* @param options
*/
public appointmentCreateChangeStreamGetAppointmentsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> {
return this.appointmentCreateChangeStreamGetAppointmentsChangeStreamWithHttpInfo(options, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.blob();
}
});
}
/**
* Create a change stream.
*
* @param options
*/
public appointmentCreateChangeStreamPostAppointmentsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> {
return this.appointmentCreateChangeStreamPostAppointmentsChangeStreamWithHttpInfo(options, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.blob();
}
});
}
/**
* Deletes all data.
*
*/
public appointmentDeleteAllAppointments(extraHttpRequestParams?: any): Observable<InlineResponse2003> {
return this.appointmentDeleteAllAppointmentsWithHttpInfo(extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Delete a model instance by {{id}} from the data source.
*
* @param id Model id
*/
public appointmentDeleteById(id: string, extraHttpRequestParams?: any): Observable<any> {
return this.appointmentDeleteByIdWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public appointmentExistsGetAppointmentsidExists(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> {
return this.appointmentExistsGetAppointmentsidExistsWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public appointmentExistsHeadAppointmentsid(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> {
return this.appointmentExistsHeadAppointmentsidWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find all instances of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public appointmentFind(filter?: string, extraHttpRequestParams?: any): Observable<Array<Appointment>> {
return this.appointmentFindWithHttpInfo(filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find a model instance by {{id}} from the data source.
*
* @param id Model id
* @param filter Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public appointmentFindById(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentFindByIdWithHttpInfo(id, filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find all instances of the model matched by filter from the data source, including resolved related instances.
*
* @param filter
*/
public appointmentFindDeep(filter?: string, extraHttpRequestParams?: any): Observable<any> {
return this.appointmentFindDeepWithHttpInfo(filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find first instance of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public appointmentFindOne(filter?: string, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentFindOneWithHttpInfo(filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Finds free slots for an appointment with the specified duration.
*
* @param duration
* @param examinationId
* @param roomId
* @param startDate
*/
public appointmentFindTime(duration: string, examinationId?: number, roomId?: number, startDate?: Date, extraHttpRequestParams?: any): Observable<any> {
return this.appointmentFindTimeWithHttpInfo(duration, examinationId, roomId, startDate, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Deletes all data.
*
* @param freeDays
* @param startDate
* @param endDate
*/
public appointmentGenerateRandomAppointments(freeDays?: string, startDate?: Date, endDate?: Date, extraHttpRequestParams?: any): Observable<InlineResponse2004> {
return this.appointmentGenerateRandomAppointmentsWithHttpInfo(freeDays, startDate, endDate, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Patch an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public appointmentPatchOrCreate(data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentPatchOrCreateWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Counts examinations of Appointment.
*
* @param id Appointment id
* @param where Criteria to match model instances
*/
public appointmentPrototypeCountExaminations(id: string, where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> {
return this.appointmentPrototypeCountExaminationsWithHttpInfo(id, where, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Creates a new instance in attendance of this model.
*
* @param id Appointment id
* @param data
*/
public appointmentPrototypeCreateAttendance(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> {
return this.appointmentPrototypeCreateAttendanceWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Creates a new instance in examinations of this model.
*
* @param id Appointment id
* @param data
*/
public appointmentPrototypeCreateExaminations(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Examination> {
return this.appointmentPrototypeCreateExaminationsWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Deletes all examinations of this model.
*
* @param id Appointment id
*/
public appointmentPrototypeDeleteExaminations(id: string, extraHttpRequestParams?: any): Observable<{}> {
return this.appointmentPrototypeDeleteExaminationsWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Deletes attendance of this model.
*
* @param id Appointment id
*/
public appointmentPrototypeDestroyAttendance(id: string, extraHttpRequestParams?: any): Observable<{}> {
return this.appointmentPrototypeDestroyAttendanceWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Delete a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeDestroyByIdExaminations(id: string, fk: string, extraHttpRequestParams?: any): Observable<{}> {
return this.appointmentPrototypeDestroyByIdExaminationsWithHttpInfo(id, fk, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Check the existence of examinations relation to an item by id.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeExistsExaminations(id: string, fk: string, extraHttpRequestParams?: any): Observable<boolean> {
return this.appointmentPrototypeExistsExaminationsWithHttpInfo(id, fk, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeFindByIdExaminations(id: string, fk: string, extraHttpRequestParams?: any): Observable<Examination> {
return this.appointmentPrototypeFindByIdExaminationsWithHttpInfo(id, fk, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Fetches hasOne relation attendance.
*
* @param id Appointment id
* @param refresh
*/
public appointmentPrototypeGetAttendance(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Attendance> {
return this.appointmentPrototypeGetAttendanceWithHttpInfo(id, refresh, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Queries examinations of Appointment.
*
* @param id Appointment id
* @param filter
*/
public appointmentPrototypeGetExaminations(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Array<Examination>> {
return this.appointmentPrototypeGetExaminationsWithHttpInfo(id, filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Fetches belongsTo relation patient.
*
* @param id Appointment id
* @param refresh
*/
public appointmentPrototypeGetPatient(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Patient> {
return this.appointmentPrototypeGetPatientWithHttpInfo(id, refresh, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Fetches belongsTo relation room.
*
* @param id Appointment id
* @param refresh
*/
public appointmentPrototypeGetRoom(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Room> {
return this.appointmentPrototypeGetRoomWithHttpInfo(id, refresh, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Add a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
* @param data
*/
public appointmentPrototypeLinkExaminations(id: string, fk: string, data?: AppointmentExamination, extraHttpRequestParams?: any): Observable<AppointmentExamination> {
return this.appointmentPrototypeLinkExaminationsWithHttpInfo(id, fk, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Patch attributes for a model instance and persist it into the data source.
*
* @param id Appointment id
* @param data An object of model property name/value pairs
*/
public appointmentPrototypePatchAttributes(id: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentPrototypePatchAttributesWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Remove the examinations relation to an item by id.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeUnlinkExaminations(id: string, fk: string, extraHttpRequestParams?: any): Observable<{}> {
return this.appointmentPrototypeUnlinkExaminationsWithHttpInfo(id, fk, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update attendance of this model.
*
* @param id Appointment id
* @param data
*/
public appointmentPrototypeUpdateAttendance(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> {
return this.appointmentPrototypeUpdateAttendanceWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
* @param data
*/
public appointmentPrototypeUpdateByIdExaminations(id: string, fk: string, data?: Examination, extraHttpRequestParams?: any): Observable<Examination> {
return this.appointmentPrototypeUpdateByIdExaminationsWithHttpInfo(id, fk, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public appointmentReplaceByIdPostAppointmentsidReplace(id: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentReplaceByIdPostAppointmentsidReplaceWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public appointmentReplaceByIdPutAppointmentsid(id: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentReplaceByIdPutAppointmentsidWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public appointmentReplaceOrCreatePostAppointmentsReplaceOrCreate(data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentReplaceOrCreatePostAppointmentsReplaceOrCreateWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public appointmentReplaceOrCreatePutAppointments(data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentReplaceOrCreatePutAppointmentsWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update instances of the model matched by {{where}} from the data source.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public appointmentUpdateAll(where?: string, data?: Appointment, extraHttpRequestParams?: any): Observable<InlineResponse2002> {
return this.appointmentUpdateAllWithHttpInfo(where, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update an existing model instance or insert a new one into the data source based on the where criteria.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public appointmentUpsertWithWhere(where?: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Appointment> {
return this.appointmentUpsertWithWhereWithHttpInfo(where, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Accepts an offer by passing over the respective secret.
*
* @param offerSecret
*/
public appointmentAcceptOfferWithHttpInfo(offerSecret: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/acceptOffer';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'offerSecret' is not null or undefined
if (offerSecret === null || offerSecret === undefined) {
throw new Error('Required parameter offerSecret was null or undefined when calling appointmentAcceptOffer.');
}
if (offerSecret !== undefined) {
queryParameters.set('offerSecret', <any>offerSecret);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Count instances of the model matched by where from the data source.
*
* @param where Criteria to match model instances
*/
public appointmentCountWithHttpInfo(where?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/count';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Create a new instance of the model and persist it into the data source.
*
* @param data Model instance data
*/
public appointmentCreateWithHttpInfo(data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Create a change stream.
*
* @param options
*/
public appointmentCreateChangeStreamGetAppointmentsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/change-stream';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (options !== undefined) {
queryParameters.set('options', <any>options);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
responseType: ResponseContentType.Blob,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Create a change stream.
*
* @param options
*/
public appointmentCreateChangeStreamPostAppointmentsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/change-stream';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
'application/json',
'application/x-www-form-urlencoded',
'application/xml',
'text/xml'
];
let canConsumeForm = this.canConsumeForm(consumes);
let useForm = false;
let formParams = new (useForm ? FormData : URLSearchParams as any)() as {
set(param: string, value: any): void;
};
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
if (options !== undefined) {
formParams.set('options', <any>options);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams,
responseType: ResponseContentType.Blob,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Deletes all data.
*
*/
public appointmentDeleteAllAppointmentsWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/deleteAll';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Delete a model instance by {{id}} from the data source.
*
* @param id Model id
*/
public appointmentDeleteByIdWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentDeleteById.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public appointmentExistsGetAppointmentsidExistsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/exists'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentExistsGetAppointmentsidExists.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public appointmentExistsHeadAppointmentsidWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentExistsHeadAppointmentsid.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Head,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find all instances of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public appointmentFindWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find a model instance by {{id}} from the data source.
*
* @param id Model id
* @param filter Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public appointmentFindByIdWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentFindById.');
}
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find all instances of the model matched by filter from the data source, including resolved related instances.
*
* @param filter
*/
public appointmentFindDeepWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/findDeep';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find first instance of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public appointmentFindOneWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/findOne';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Finds free slots for an appointment with the specified duration.
*
* @param duration
* @param examinationId
* @param roomId
* @param startDate
*/
public appointmentFindTimeWithHttpInfo(duration: string, examinationId?: number, roomId?: number, startDate?: Date, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/findTime';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'duration' is not null or undefined
if (duration === null || duration === undefined) {
throw new Error('Required parameter duration was null or undefined when calling appointmentFindTime.');
}
if (duration !== undefined) {
queryParameters.set('duration', <any>duration);
}
if (examinationId !== undefined) {
queryParameters.set('examinationId', <any>examinationId);
}
if (roomId !== undefined) {
queryParameters.set('roomId', <any>roomId);
}
if (startDate !== undefined) {
queryParameters.set('startDate', <any>startDate.toISOString());
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Deletes all data.
*
* @param freeDays
* @param startDate
* @param endDate
*/
public appointmentGenerateRandomAppointmentsWithHttpInfo(freeDays?: string, startDate?: Date, endDate?: Date, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/generateRandomAppointments';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (freeDays !== undefined) {
queryParameters.set('freeDays', <any>freeDays);
}
if (startDate !== undefined) {
queryParameters.set('startDate', <any>startDate.toISOString());
}
if (endDate !== undefined) {
queryParameters.set('endDate', <any>endDate.toISOString());
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Patch an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public appointmentPatchOrCreateWithHttpInfo(data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Patch,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Counts examinations of Appointment.
*
* @param id Appointment id
* @param where Criteria to match model instances
*/
public appointmentPrototypeCountExaminationsWithHttpInfo(id: string, where?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/count'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeCountExaminations.');
}
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Creates a new instance in attendance of this model.
*
* @param id Appointment id
* @param data
*/
public appointmentPrototypeCreateAttendanceWithHttpInfo(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/attendance'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeCreateAttendance.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Creates a new instance in examinations of this model.
*
* @param id Appointment id
* @param data
*/
public appointmentPrototypeCreateExaminationsWithHttpInfo(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeCreateExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Deletes all examinations of this model.
*
* @param id Appointment id
*/
public appointmentPrototypeDeleteExaminationsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeDeleteExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Deletes attendance of this model.
*
* @param id Appointment id
*/
public appointmentPrototypeDestroyAttendanceWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/attendance'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeDestroyAttendance.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Delete a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeDestroyByIdExaminationsWithHttpInfo(id: string, fk: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/${fk}'
.replace('${' + 'id' + '}', String(id))
.replace('${' + 'fk' + '}', String(fk));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeDestroyByIdExaminations.');
}
// verify required parameter 'fk' is not null or undefined
if (fk === null || fk === undefined) {
throw new Error('Required parameter fk was null or undefined when calling appointmentPrototypeDestroyByIdExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Check the existence of examinations relation to an item by id.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeExistsExaminationsWithHttpInfo(id: string, fk: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/rel/${fk}'
.replace('${' + 'id' + '}', String(id))
.replace('${' + 'fk' + '}', String(fk));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeExistsExaminations.');
}
// verify required parameter 'fk' is not null or undefined
if (fk === null || fk === undefined) {
throw new Error('Required parameter fk was null or undefined when calling appointmentPrototypeExistsExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Head,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeFindByIdExaminationsWithHttpInfo(id: string, fk: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/${fk}'
.replace('${' + 'id' + '}', String(id))
.replace('${' + 'fk' + '}', String(fk));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeFindByIdExaminations.');
}
// verify required parameter 'fk' is not null or undefined
if (fk === null || fk === undefined) {
throw new Error('Required parameter fk was null or undefined when calling appointmentPrototypeFindByIdExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Fetches hasOne relation attendance.
*
* @param id Appointment id
* @param refresh
*/
public appointmentPrototypeGetAttendanceWithHttpInfo(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/attendance'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeGetAttendance.');
}
if (refresh !== undefined) {
queryParameters.set('refresh', <any>refresh);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Queries examinations of Appointment.
*
* @param id Appointment id
* @param filter
*/
public appointmentPrototypeGetExaminationsWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeGetExaminations.');
}
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Fetches belongsTo relation patient.
*
* @param id Appointment id
* @param refresh
*/
public appointmentPrototypeGetPatientWithHttpInfo(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/patient'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeGetPatient.');
}
if (refresh !== undefined) {
queryParameters.set('refresh', <any>refresh);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Fetches belongsTo relation room.
*
* @param id Appointment id
* @param refresh
*/
public appointmentPrototypeGetRoomWithHttpInfo(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/room'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeGetRoom.');
}
if (refresh !== undefined) {
queryParameters.set('refresh', <any>refresh);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Add a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
* @param data
*/
public appointmentPrototypeLinkExaminationsWithHttpInfo(id: string, fk: string, data?: AppointmentExamination, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/rel/${fk}'
.replace('${' + 'id' + '}', String(id))
.replace('${' + 'fk' + '}', String(fk));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeLinkExaminations.');
}
// verify required parameter 'fk' is not null or undefined
if (fk === null || fk === undefined) {
throw new Error('Required parameter fk was null or undefined when calling appointmentPrototypeLinkExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Patch attributes for a model instance and persist it into the data source.
*
* @param id Appointment id
* @param data An object of model property name/value pairs
*/
public appointmentPrototypePatchAttributesWithHttpInfo(id: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypePatchAttributes.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Patch,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Remove the examinations relation to an item by id.
*
* @param id Appointment id
* @param fk Foreign key for examinations
*/
public appointmentPrototypeUnlinkExaminationsWithHttpInfo(id: string, fk: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/rel/${fk}'
.replace('${' + 'id' + '}', String(id))
.replace('${' + 'fk' + '}', String(fk));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeUnlinkExaminations.');
}
// verify required parameter 'fk' is not null or undefined
if (fk === null || fk === undefined) {
throw new Error('Required parameter fk was null or undefined when calling appointmentPrototypeUnlinkExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Update attendance of this model.
*
* @param id Appointment id
* @param data
*/
public appointmentPrototypeUpdateAttendanceWithHttpInfo(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/attendance'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeUpdateAttendance.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Update a related item by id for examinations.
*
* @param id Appointment id
* @param fk Foreign key for examinations
* @param data
*/
public appointmentPrototypeUpdateByIdExaminationsWithHttpInfo(id: string, fk: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/examinations/${fk}'
.replace('${' + 'id' + '}', String(id))
.replace('${' + 'fk' + '}', String(fk));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentPrototypeUpdateByIdExaminations.');
}
// verify required parameter 'fk' is not null or undefined
if (fk === null || fk === undefined) {
throw new Error('Required parameter fk was null or undefined when calling appointmentPrototypeUpdateByIdExaminations.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public appointmentReplaceByIdPostAppointmentsidReplaceWithHttpInfo(id: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}/replace'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentReplaceByIdPostAppointmentsidReplace.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public appointmentReplaceByIdPutAppointmentsidWithHttpInfo(id: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling appointmentReplaceByIdPutAppointmentsid.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public appointmentReplaceOrCreatePostAppointmentsReplaceOrCreateWithHttpInfo(data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/replaceOrCreate';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public appointmentReplaceOrCreatePutAppointmentsWithHttpInfo(data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Update instances of the model matched by {{where}} from the data source.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public appointmentUpdateAllWithHttpInfo(where?: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/update';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Update an existing model instance or insert a new one into the data source based on the where criteria.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public appointmentUpsertWithWhereWithHttpInfo(where?: string, data?: Appointment, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/appointments/upsertWithWhere';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
} | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { environment } from '../../../../../environments/environment';
import { Subscription } from 'rxjs/Subscription';
import { AssetGroupObservableService } from '../../../../core/services/asset-group-observable.service';
import { LoggerService } from '../../../../shared/services/logger.service';
import { CommonResponseService } from '../../../../shared/services/common-response.service';
import { Router, ActivatedRoute } from '@angular/router';
import {RefactorFieldsService} from '../../../../shared/services/refactor-fields.service';
import { ErrorHandlingService } from '../../../../shared/services/error-handling.service';
import { DownloadService } from '../../../../shared/services/download.service';
import { UtilsService } from '../../../../shared/services/utils.service';
import { WorkflowService } from '../../../../core/services/workflow.service';
import { DomainTypeObservableService } from '../../../../core/services/domain-type-observable.service';
@Component({
selector: 'app-recommendations-details',
templateUrl: './recommendations-details.component.html',
styleUrls: ['./recommendations-details.component.css']
})
export class RecommendationsDetailsComponent implements OnInit, OnDestroy {
AssetGroupSubscription: Subscription;
domainSubscription: Subscription;
recommandationsInfoSubscription: Subscription;
recommandationsDetailsSubscription: Subscription;
selectedAssetGroup;
selectedDomain;
recommendationParams;
recommendationInfoData;
recommendationDetailsData;
public errorMessage: string;
public responseStatus: any = 0;
responseStatusInfo = 0;
showGenericMessage = false;
allColumns = [];
public outerArr: any;
totalRows = 0;
currentPointer = 0;
currentBucket: any = [];
firstPaginator = 1;
lastPaginator: number;
paginatorSize = 10;
bucketNumber = 0;
pageLevel = 0;
backButtonRequired;
popRows: any = ['Download Data'];
tableDataLoaded = false;
searchTxt = '';
public agAndDomain = {};
constructor(private assetGroupObservableService: AssetGroupObservableService,
private domainObservableService: DomainTypeObservableService,
private logger: LoggerService,
private activRoute: ActivatedRoute,
private downloadService: DownloadService,
private errorHandling: ErrorHandlingService,
private refactorFieldsService: RefactorFieldsService,
private commonResponseService: CommonResponseService,
private utils: UtilsService,
private router: Router,
private workflowService: WorkflowService) {
this.AssetGroupSubscription = this.assetGroupObservableService.getAssetGroup().subscribe(assetGroupName => {
this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(
this.pageLevel
);
this.selectedAssetGroup = assetGroupName;
this.agAndDomain['ag'] = this.selectedAssetGroup;
});
this.domainSubscription = this.domainObservableService.getDomainType().subscribe(domain => {
this.selectedDomain = domain;
this.agAndDomain['domain'] = this.selectedDomain;
this.recommendationParams = this.activRoute.snapshot.params;
this.getRecommandationsInfoData();
this.updateComponent();
});
}
ngOnInit() {
}
getRecommandationsInfoData() {
this.responseStatusInfo = 0;
if (this.recommandationsInfoSubscription) {
this.recommandationsInfoSubscription.unsubscribe();
}
const recommendationsInfoUrl = environment.recommendationsInfo.url;
const recommendationsInfoMethod = environment.recommendationsInfo.method;
const queryParams = {
'ag': this.selectedAssetGroup,
'recommendationId': this.recommendationParams['recommendationId'],
'general': this.recommendationParams['general']
};
try {
this.recommandationsInfoSubscription = this.commonResponseService.getData(recommendationsInfoUrl, recommendationsInfoMethod, {}, queryParams).subscribe(
response => {
try {
this.recommendationInfoData = response;
this.responseStatusInfo = 1;
} catch (e) {
this.errorMessage = 'jsError';
this.responseStatusInfo = -1;
this.logger.log('error', e);
}
},
error => {
this.errorMessage = error;
this.responseStatusInfo = -1;
});
} catch (error) {
this.errorMessage = 'jsError';
this.responseStatusInfo = -1;
this.logger.log('error', error);
}
}
getRecommandationsDetailsData() {
this.responseStatus = 0;
if (this.recommandationsDetailsSubscription) {
this.recommandationsDetailsSubscription.unsubscribe();
}
const recommendationsdetailsUrl = environment.recommendationsDetails.url;
const recommendationsdetailsMethod = environment.recommendationsDetails.method;
const queryParams = {
'ag': this.selectedAssetGroup,
'filter': {
'recommendationId': this.recommendationParams['recommendationId'],
'general': this.recommendationParams['general']
},
'from': (this.bucketNumber) * this.paginatorSize,
'size': this.paginatorSize,
'searchtext': this.searchTxt
};
try {
if (this.recommendationParams['tags.Application.keyword']) {
queryParams['filter']['application'] = this.recommendationParams['tags.Application.keyword'];
} else if (this.recommendationParams['filter'] && this.recommendationParams.filter.includes('Application')) {
const filter = this.utils.processFilterObj(
this.recommendationParams
);
queryParams['filter']['application'] = filter['tags.Application.keyword'];
}
this.recommandationsInfoSubscription = this.commonResponseService.getData(recommendationsdetailsUrl, recommendationsdetailsMethod, queryParams, {}).subscribe(
response => {
try {
this.showGenericMessage = false;
this.tableDataLoaded = false;
this.recommendationDetailsData = response.data.response;
if (response.data.response.length === 0) {
this.responseStatus = -1;
this.outerArr = [];
this.allColumns = [];
this.totalRows = 0;
this.errorMessage = 'noDataAvailable';
}
if (response.data.response.length > 0) {
this.totalRows = response.data.total;
this.firstPaginator = (this.bucketNumber * this.paginatorSize) + 1;
this.lastPaginator = (this.bucketNumber * this.paginatorSize) + this.paginatorSize;
this.currentPointer = this.bucketNumber;
if (this.lastPaginator > this.totalRows) {
this.lastPaginator = this.totalRows;
}
const updatedResponse = this.massageData(response.data.response);
this.currentBucket[this.bucketNumber] = updatedResponse;
this.processData(updatedResponse);
this.responseStatus = 1;
}
} catch (e) {
this.errorMessage = 'jsError';
this.responseStatus = -1;
this.logger.log('error', e);
}
},
error => {
this.responseStatus = -1;
this.errorMessage = 'apiResponseError';
});
} catch (error) {
this.showGenericMessage = true;
this.errorMessage = 'jsError';
this.responseStatus = -1;
this.logger.log('error', error);
}
}
massageData(data) {
/*
* the function replaces keys of the table header data to a readable format
*/
const refactoredService = this.refactorFieldsService;
const newData = [];
data.map(function(eachRow) {
const KeysTobeChanged = Object.keys(eachRow);
let newObj = {};
KeysTobeChanged.forEach(element => {
const elementnew =
refactoredService.getDisplayNameForAKey(element.toLocaleLowerCase()) || element;
newObj = Object.assign(newObj, { [elementnew]: eachRow[element] });
});
newData.push(newObj);
});
return newData;
}
processData(data) {
try {
let innerArr = {};
const totalVariablesObj = {};
let cellObj = {};
this.outerArr = [];
const getData = data;
let getCols;
if (getData.length) {
getCols = Object.keys(getData[0]);
}
for (let row = 0; row < getData.length; row++) {
innerArr = {};
for (let col = 0; col < getCols.length; col++) {
if (
getCols[col].toLowerCase() === 'resource id' ||
getCols[col].toLowerCase() === 'resourceid'
) {
cellObj = {
link: 'View Asset Details',
properties: {
'text-shadow': '0.1px 0',
'text-transform': 'lowercase'
},
colName: getCols[col],
hasPreImg: false,
imgLink: '',
text: getData[row][getCols[col]],
valText: getData[row][getCols[col]]
};
} else if (getCols[col].toLowerCase() === 'severity') {
if (getData[row][getCols[col]] === 'low') {
cellObj = {
link: '',
properties: {
color: '',
'text-transform': 'capitalize',
},
colName: getCols[col],
hasPreImg: true,
imgLink: '',
text: getData[row][getCols[col]],
valText: 1,
statusProp: {
'background-color': '#50C17C'
}
};
} else if (getData[row][getCols[col]] === 'medium') {
cellObj = {
link: '',
properties: {
color: '',
'text-transform': 'capitalize'
},
colName: getCols[col],
hasPreImg: true,
imgLink: '',
valText: 2,
text: getData[row][getCols[col]],
statusProp: {
'background-color': '#289CF7'
}
};
} else if (getData[row][getCols[col]] === 'high') {
cellObj = {
link: '',
properties: {
color: '',
'text-transform': 'capitalize'
},
colName: getCols[col],
hasPreImg: true,
valText: 3,
imgLink: '',
text: getData[row][getCols[col]],
statusProp: {
'background-color': '#F58544'
}
};
} else {
cellObj = {
link: '',
properties: {
color: '',
'text-transform': 'capitalize'
},
colName: getCols[col],
hasPreImg: true,
imgLink: '',
valText: 4,
text: getData[row][getCols[col]],
statusProp: {
'background-color': '#F2425F'
}
};
}
}else if (getCols[col].toLowerCase() === 'monthlysavings') {
cellObj = {
link: '',
properties: {
color: '#50c17c',
},
colName: getCols[col],
hasPreImg: false,
imgLink: '',
text: '$' + getData[row][getCols[col]],
valText: getData[row][getCols[col]]
};
} else {
cellObj = {
link: '',
properties: {
color: '',
},
colName: getCols[col],
hasPreImg: false,
imgLink: '',
text: getData[row][getCols[col]],
valText: getData[row][getCols[col]]
};
}
innerArr[getCols[col]] = cellObj;
totalVariablesObj[getCols[col]] = '';
}
this.outerArr.push(innerArr);
}
if (this.outerArr.length > getData.length) {
const halfLength = this.outerArr.length / 2;
this.outerArr = this.outerArr.splice(halfLength);
}
this.allColumns = Object.keys(totalVariablesObj);
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.logger.log('error', error);
}
}
prevPg() {
this.currentPointer--;
this.processData(this.currentBucket[this.currentPointer]);
this.firstPaginator = (this.currentPointer * this.paginatorSize) + 1;
this.lastPaginator = (this.currentPointer * this.paginatorSize) + this.paginatorSize;
}
nextPg() {
if (this.currentPointer < this.bucketNumber) {
this.currentPointer++;
this.processData(this.currentBucket[this.currentPointer]);
this.firstPaginator = (this.currentPointer * this.paginatorSize) + 1;
this.lastPaginator = (this.currentPointer * this.paginatorSize) + this.paginatorSize;
if (this.lastPaginator > this.totalRows) {
this.lastPaginator = this.totalRows;
}
} else {
this.bucketNumber++;
this.getRecommandationsDetailsData();
}
}
searchCalled(search) {
this.searchTxt = search;
}
callNewSearch() {
this.bucketNumber = 0;
this.currentBucket = [];
this.getRecommandationsDetailsData();
}
handlePopClick(rowText) {
const fileType = 'csv';
try {
let queryParams;
queryParams = {
'fileFormat': 'csv',
'serviceId': 15,
'fileType': fileType,
};
const downloadRequest = {
'ag': this.selectedAssetGroup,
'filter': {
'recommendationId': this.recommendationParams['recommendationId'],
'general': this.recommendationParams['general']
},
'from': 0,
'size': this.totalRows,
'searchtext': this.searchTxt
};
if (this.recommendationParams['filter'] && this.recommendationParams.filter.includes('Application')) {
let arr = [];
arr = this.recommendationParams.filter.split('=');
downloadRequest['filter']['application'] = arr.length > 1 ? arr[1] : '';
}
const downloadUrl = environment.download.url;
const downloadMethod = environment.download.method;
this.downloadService.requestForDownload(queryParams, downloadUrl, downloadMethod, downloadRequest, 'Recommendations Detail', this.totalRows);
} catch (error) {
this.logger.log('error', error);
}
}
updateComponent() {
/* All functions variables which are required to be set for component to be reloaded should go here */
this.outerArr = [];
this.currentBucket = [];
this.recommendationDetailsData = [];
this.tableDataLoaded = false;
this.bucketNumber = 0;
this.firstPaginator = 1;
this.currentPointer = 0;
this.responseStatus = 0;
this.showGenericMessage = false;
this.searchTxt = '';
this.getRecommandationsDetailsData();
}
navigateBack() {
try {
this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root);
} catch (error) {
this.logger.log('error', error);
}
}
goToDetails(row) {
try {
this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root);
if (row.col.toLowerCase() === 'resource id') {
const resourceType = row.row['type'].text;
const resourceId = encodeURIComponent(row.row['Resource ID'].text);
this.router.navigate(
['../../../../../assets/assets-details', resourceType, resourceId],
{ relativeTo: this.activRoute, queryParams: this.agAndDomain, queryParamsHandling: 'merge' }
).then(response => {
this.logger.log('info', 'Successfully navigated to asset details page: ' + response);
})
.catch(error => {
this.logger.log('error', 'Error in navigation - ' + error);
});
}
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.logger.log('error', error);
}
// try {
// this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root);
// if (row.col.toLowerCase() === 'resource id') {
// const resourceType = row.row['type'].text;
// const resourceId = encodeURIComponent(row.row['Resource ID'].text);
// this.router.navigate(
// ['pl', { outlets: { details: ['assets-details', resourceType, resourceId] } }],
// { queryParams: this.agAndDomain, queryParamsHandling: 'merge' }
// ).then(response => {
// this.logger.log('info', 'Successfully navigated to asset details page: ' + response);
// })
// .catch(error => {
// this.logger.log('error', 'Error in navigation - ' + error);
// });
// }
// } catch (error) {
// this.errorMessage = this.errorHandling.handleJavascriptError(error);
// this.logger.log('error', error);
// }
}
ngOnDestroy() {
try {
this.AssetGroupSubscription.unsubscribe();
if (this.recommandationsInfoSubscription) {
this.recommandationsInfoSubscription.unsubscribe();
}
if (this.recommandationsDetailsSubscription) {
this.recommandationsDetailsSubscription.unsubscribe();
}
} catch (error) {
this.logger.log('error', error);
}
}
} | the_stack |
import {renderHook, act} from '@testing-library/react-hooks'
import {createCache, useCache, CacheExport} from './index'
beforeAll(() => {
jest.useFakeTimers()
})
afterAll(() => {
jest.useRealTimers()
})
describe('createCache()', () => {
it('should load a key', async () => {
const cache = createCache((string) => Promise.resolve(string))
const expected = {id: 0, status: 'success', value: 'foo', error: undefined}
expect(await cache.load('foo')).toEqual(expected)
expect(cache.read('foo')).toEqual(expected)
})
it('should load a key w/ args', async () => {
const cache = createCache((string) => Promise.resolve(string))
const expected = {id: 0, status: 'success', value: 'foo', error: undefined}
expect(await cache.load('foo')).toEqual(expected)
expect(cache.read('foo')).toEqual(expected)
})
it('should subscribe to a key', async () => {
const cache = createCache((string) => Promise.resolve(string))
const subscriber1 = jest.fn() // subcribed to 'foo'
const subscriber2 = jest.fn() // subcribed to 'foo'
const subscriber3 = jest.fn() // NOT subcribed to 'foo'
const expected1 = {
id: 0,
status: 'loading',
value: undefined,
error: undefined,
}
const expected2 = {id: 0, status: 'success', value: 'foo', error: undefined}
cache.subscribe('foo', subscriber1)
cache.subscribe('foo', subscriber2)
cache.subscribe('bar', subscriber3)
await cache.load('foo')
expect(subscriber1).toBeCalledWith(expected1)
expect(subscriber1).toBeCalledWith(expected2)
expect(subscriber1).toBeCalledTimes(2)
expect(subscriber2).toBeCalledWith(expected1)
expect(subscriber2).toBeCalledWith(expected2)
expect(subscriber2).toBeCalledTimes(2)
expect(subscriber3).not.toBeCalled()
})
it('should unsubscribe from a key', async () => {
const cache = createCache((string) => Promise.resolve(string))
const subscriber = jest.fn()
cache.subscribe('foo', subscriber)
cache.unsubscribe('foo', subscriber)
await cache.load('foo')
expect(subscriber).not.toBeCalled()
})
it('should readAll for SSR', async () => {
const cache = createCache((string) => Promise.resolve(string))
const expected = {
foo: {id: 0, status: 'success', value: 'foo', error: undefined},
bar: {id: 1, status: 'success', value: 'bar', error: undefined},
}
await cache.load('foo')
await cache.load('bar')
expect(cache.readAll()).toEqual(expected)
})
it('should write from SSR', async () => {
const cache = createCache((string) => Promise.resolve(string))
const expected: CacheExport<string> = {
foo: {id: 0, status: 'success', value: 'foo', error: undefined},
bar: {id: 1, status: 'success', value: 'bar', error: undefined},
}
cache.write(expected)
expect(cache.readAll()).toEqual(expected)
})
it('should alert subscribers during write from SSR', async () => {
const cache = createCache((string) => Promise.resolve(string))
const expected: CacheExport<string> = {
foo: {id: 0, status: 'success', value: 'foo', error: undefined},
bar: {id: 1, status: 'success', value: 'bar', error: undefined},
}
const subscriber = jest.fn()
cache.subscribe('foo', subscriber)
cache.write(expected)
expect(subscriber).toBeCalledTimes(1)
expect(subscriber).toBeCalledWith(expected.foo)
})
it('should not cancel a non-pending action', async () => {
const cache = createCache((string) => Promise.resolve(string))
cache.cancel('foo')
expect(cache.read('foo')).toBeUndefined()
})
it('should not add a success status if the request has already been cancelled', async () => {
const cache = createCache(
(key) =>
new Promise((resolve) => {
setTimeout(() => resolve(key), 300)
})
)
const p = cache.load('foo')
jest.advanceTimersByTime(300)
cache.cancel('foo')
await p
expect(cache.read('foo')).toEqual({
error: undefined,
id: 0,
status: 'cancelled',
value: undefined,
})
})
it('should not add an error status if the request has already been cancelled', async () => {
const cache = createCache(
(key) =>
new Promise((resolve, reject) => {
setTimeout(() => reject(key), 300)
})
)
const p = cache.load('foo')
jest.advanceTimersByTime(300)
cache.cancel('foo')
await p
expect(cache.read('foo')).toEqual({
error: undefined,
id: 0,
status: 'cancelled',
value: undefined,
})
})
it('should not reload a key while the key is already loading', async () => {
const cache = createCache(
(key) =>
new Promise((resolve) => {
setTimeout(() => resolve(key), 300)
})
)
cache.load('foo')
const p2 = await cache.load('foo')
expect(p2.id).toBe(0)
})
})
describe('useCache', () => {
it('should handle Promise.resolve', async () => {
const cache = createCache(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(true), 1000)
})
)
const {result, waitForNextUpdate} = renderHook(() => useCache(cache, 'foo'))
expect(result.current[0].status).toBe('idle')
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
act(() => jest.advanceTimersByTime(1000))
await waitForNextUpdate()
expect(result.current[0].value).toBe(true)
expect(result.current[0].status).toBe('success')
expect(result.current[0].error).toBe(undefined)
})
it('should persist between hooks', async () => {
const cache = createCache(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(true), 1000)
})
)
const {result, waitForNextUpdate} = renderHook(() => useCache(cache, 'foo'))
expect(result.current[0].status).toBe('idle')
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
act(() => jest.advanceTimersByTime(1000))
await waitForNextUpdate()
expect(result.current[0].value).toBe(true)
expect(result.current[0].status).toBe('success')
expect(result.current[0].error).toBe(undefined)
const {result: result2} = renderHook(() => useCache(cache, 'foo'))
expect(result2.current[0].value).toBe(true)
expect(result2.current[0].status).toBe('success')
})
it('should cancel the callback despite success', async () => {
const cache = createCache(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(true), 1000)
})
)
const {result} = renderHook(() => useCache(cache, 'foo'))
let cancelled
act(() => {
cancelled = result.current[1]()
})
expect(result.current[0].status).toBe('loading')
act(() => {
result.current[0].cancel()
})
act(() => jest.advanceTimersByTime(1000))
await cancelled
expect(result.current[0].status).toBe('cancelled')
expect(result.current[0].value).toBe(undefined)
})
it('should cancel the callback despite errors', async () => {
const cache = createCache(
() =>
new Promise((_, reject) => {
setTimeout(() => reject('Uh oh'), 1000)
})
)
const {result} = renderHook(() => useCache(cache, 'foo'))
let cancelled
act(() => {
cancelled = result.current[1]()
})
expect(result.current[0].status).toBe('loading')
act(() => {
result.current[0].cancel()
})
act(() => jest.advanceTimersByTime(1000))
await cancelled
expect(result.current[0].status).toBe('cancelled')
expect(result.current[0].value).toBe(undefined)
})
it('should restart after cancel', async () => {
const cache = createCache(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(true), 1000)
})
)
const {result, waitForNextUpdate} = renderHook(() => useCache(cache, 'foo'))
// Initial cancellation
act(() => {
result.current[1]()
})
act(() => {
result.current[0].cancel()
})
act(() => jest.advanceTimersByTime(1000))
expect(result.current[0].status).toBe('cancelled')
expect(result.current[0].value).toBe(undefined)
// Try again
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
act(() => jest.advanceTimersByTime(1000))
await waitForNextUpdate()
expect(result.current[0].status).toBe('success')
expect(result.current[0].value).toBe(true)
})
it('should handle thrown exceptions', async () => {
const cache = createCache(async () => {
throw new Error('Uh oh')
})
const {result, waitForNextUpdate} = renderHook(() => useCache(cache, 'foo'))
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
await waitForNextUpdate()
expect(result.current[0].status).toBe('error')
expect(result.current[0].value).toBe(undefined)
expect(result.current[0].error).toBeInstanceOf(Error)
expect(result.current[0].error.message).toBe('Uh oh')
})
it('should handle Promise.reject', async () => {
const cache = createCache(
() =>
new Promise((_, reject) => {
setTimeout(() => reject('Uh oh'), 1000)
})
)
const {result, waitForNextUpdate} = renderHook(() => useCache(cache, 'foo'))
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
act(() => jest.advanceTimersByTime(1000))
await waitForNextUpdate()
expect(result.current[0].status).toBe('error')
expect(result.current[0].value).toBe(undefined)
expect(result.current[0].error).toBe('Uh oh')
})
it('should update the cache when it changes', async () => {
const cache1 = createCache(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(1), 1000)
})
)
const cache2 = createCache(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(2), 1000)
})
)
const {result, rerender} = renderHook(({cache}) => useCache(cache, 'foo'), {
initialProps: {cache: cache1},
})
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
rerender({cache: cache2})
act(() => jest.advanceTimersByTime(1000))
expect(result.current[0].status).toBe('idle')
})
it('should update the key when it changes', async () => {
const cache = createCache(
(key) =>
new Promise((resolve) => {
setTimeout(() => resolve(key), 1000)
})
)
cache.load('1')
const {result, rerender, waitForNextUpdate} = renderHook(
({key}) => useCache(cache, key),
{
initialProps: {key: '0'},
}
)
act(() => {
result.current[1]()
})
expect(result.current[0].status).toBe('loading')
rerender({key: '1'})
expect(result.current[0].status).toBe('loading')
expect(result.current[0].value).toBe(undefined)
act(() => jest.advanceTimersByTime(1000))
await waitForNextUpdate()
expect(result.current[0].status).toBe('success')
expect(result.current[0].value).toBe('1')
})
}) | the_stack |
import { ADD_ITEM, REMOVE_ITEM, SET } from "#SRC/js/constants/TransactionTypes";
import { parseIntValue } from "#SRC/js/utils/ReducerUtil";
import Transaction from "#SRC/js/structs/Transaction";
import * as ValidatorUtil from "#SRC/js/utils/ValidatorUtil";
import {
COMMAND,
HTTP,
HTTPS,
TCP,
} from "../../constants/HealthCheckProtocols";
import MesosCommandTypes from "../../constants/MesosCommandTypes";
/**
* JSON Parser Fragment for `HttpHealthCheck` type
*
* @param {Object} healthCheck - The healthcheck data to parse
* @param {Array} path - The path prefix to the transaction
* @returns {Array} - Returns an array with the new transactions to append
*/
function parseHttpHealthCheck(healthCheck, path) {
const memo = [];
if (healthCheck.endpoint != null) {
memo.push(
new Transaction(path.concat(["endpoint"]), healthCheck.endpoint, SET)
);
}
if (healthCheck.path != null) {
memo.push(new Transaction(path.concat(["path"]), healthCheck.path, SET));
}
if (healthCheck.scheme != null) {
memo.push(
new Transaction(path.concat(["https"]), healthCheck.scheme === HTTPS, SET)
);
}
return memo;
}
function reduceHttpHealthCheck(state, field, value) {
const newState = {
...state,
};
newState.http = {
...(newState.http || {}),
};
switch (field) {
case "endpoint":
newState.http.endpoint = value;
break;
case "path":
newState.http.path = value;
break;
case "https":
if (value) {
newState.http.scheme = HTTPS;
} else {
newState.http.scheme = HTTP;
}
break;
}
return newState;
}
function reduceFormHttpHealthCheck(state, field, value) {
const newState = {
...state,
};
newState.http = {
...(newState.http || {}),
};
switch (field) {
case "https":
newState.http.https = value;
break;
}
return newState;
}
/**
* JSON Parser Fragment for `TcpHealthCheck` type
*
* @param {Object} healthCheck - The healthcheck data to parse
* @param {Array} path - The path prefix to the transaction
* @returns {Array} - Returns an array with the new transactions to append
*/
function parseTcpHealthCheck(healthCheck, path) {
const memo = [];
if (healthCheck.endpoint != null) {
memo.push(
new Transaction(path.concat(["endpoint"]), healthCheck.endpoint, SET)
);
}
return memo;
}
function reduceTcpHealthCheck(state, field, value) {
const newState = {
...state,
};
newState.tcp = {
...(newState.tcp || {}),
};
switch (field) {
case "endpoint":
newState.tcp.endpoint = value;
break;
}
return newState;
}
/**
* JSON Parser Fragment for `CommandHealthCheck` type
*
* @param {Object} healthCheck - The healthcheck data to parse
* @param {Array} path - The path prefix to the transaction
* @returns {Array} - Returns an array with the new transactions to append
*/
function parseCommandHealthCheck(healthCheck, path) {
const memo = [];
const { command = {} } = healthCheck;
if (command.shell != null) {
memo.push(
new Transaction(
path.concat(["command", "type"]),
MesosCommandTypes.SHELL,
SET
)
);
memo.push(
new Transaction(path.concat(["command", "value"]), command.shell, SET)
);
}
if (command.argv != null && Array.isArray(command.argv)) {
memo.push(
new Transaction(
path.concat(["command", "type"]),
MesosCommandTypes.ARGV,
SET
)
);
// Always cast to string, since the UI cannot handle arrays
memo.push(
new Transaction(
path.concat(["command", "value"]),
command.argv.join(" "),
SET
)
);
}
return memo;
}
function reduceCommandHealthCheck(state, field, value) {
const newState = {
...state,
};
newState.exec = {
...(newState.exec || {}),
};
newState.exec.command = {
...(newState.exec.command || {}),
};
const command = newState.exec.command;
switch (field) {
case "type":
// Shell is a meta-field that denotes if we are going to populate
// the argument or the shell field. So, if we encounter an opposite
// field, we should convert and set-up a placeholder
if (value === MesosCommandTypes.SHELL) {
command.shell = "";
if (command.argv != null && Array.isArray(command.argv)) {
command.shell = command.argv.join(" ");
delete command.argv;
}
break;
}
if (value === MesosCommandTypes.ARGV) {
command.argv = [];
if (command.shell != null) {
command.argv = command.shell.split(" ");
delete command.shell;
}
break;
}
break;
case "value":
// By default we are creating `shell`. Only if `argv` exists
// we should create an array
if (command.argv != null) {
command.argv = value.split(" ");
} else {
command.shell = value;
}
break;
}
return newState;
}
function reduceFormCommandHealthCheck(state, field, value) {
const newState = {
...state,
};
newState.exec = {
...(newState.exec || {}),
};
newState.exec.command = {
...(newState.exec.command || {}),
};
const command = newState.exec.command;
switch (field) {
case "type":
command.type = value;
break;
case "value":
command.value = value;
break;
}
return newState;
}
export function JSONSegmentReducer(state, { type, path, value }) {
const newState = { ...state };
const [group, field, secondField] = path;
// ADD_ITEM does nothing more but to define an object as a value,
// since we cannot have more than 1 items.
if (type === ADD_ITEM) {
if (path.length !== 0) {
if (process.env.NODE_ENV !== "production") {
throw new TypeError("Trying to ADD_ITEM on a wrong health path");
}
return newState;
}
return {};
}
// REMOVE_ITEM resets the state back to `null` since we can only
// have one item.
if (type === REMOVE_ITEM) {
if (path.length !== 0) {
if (process.env.NODE_ENV !== "production") {
throw new TypeError("Trying to REMOVE_ITEM on a wrong health path");
}
return newState;
}
return null;
}
// Format object structure according to protocol switch
if (group === "protocol") {
switch (value) {
case COMMAND:
newState.exec = {
command: {},
};
delete newState.http;
delete newState.tcp;
break;
case HTTP:
delete newState.exec;
newState.http = {
scheme: HTTP,
};
delete newState.tcp;
break;
case TCP:
delete newState.exec;
delete newState.http;
newState.tcp = {};
break;
}
return newState;
}
// Assign properties
switch (group) {
case "exec":
return reduceCommandHealthCheck(newState, secondField, value);
case "http":
return reduceHttpHealthCheck(newState, field, value);
case "tcp":
return reduceTcpHealthCheck(newState, field, value);
case "gracePeriodSeconds":
newState.gracePeriodSeconds = parseIntValue(value);
break;
case "intervalSeconds":
newState.intervalSeconds = parseIntValue(value);
break;
case "maxConsecutiveFailures":
newState.maxConsecutiveFailures = parseIntValue(value);
break;
case "timeoutSeconds":
newState.timeoutSeconds = parseIntValue(value);
break;
case "delaySeconds":
newState.delaySeconds = parseIntValue(value);
break;
}
return newState;
}
export function JSONSegmentParser(healthCheck, path) {
let memo = [];
if (ValidatorUtil.isEmpty(healthCheck)) {
return memo;
}
// Add an ADD_ITEM transaction
memo.push(new Transaction(path, null, ADD_ITEM));
// Parse detailed fields according to type
if (healthCheck.http != null) {
memo.push(new Transaction(path.concat(["protocol"]), HTTP, SET));
memo = memo.concat(
parseHttpHealthCheck(healthCheck.http, path.concat(["http"]), memo)
);
}
if (healthCheck.tcp != null) {
memo.push(new Transaction(path.concat(["protocol"]), TCP, SET));
memo = memo.concat(
parseTcpHealthCheck(healthCheck.tcp, path.concat(["tcp"]), memo)
);
}
if (healthCheck.exec != null) {
memo.push(new Transaction(path.concat(["protocol"]), COMMAND, SET));
memo = memo.concat(
parseCommandHealthCheck(healthCheck.exec, path.concat(["exec"]), memo)
);
}
// Parse generic fields
if (healthCheck.gracePeriodSeconds != null) {
memo.push(
new Transaction(
path.concat(["gracePeriodSeconds"]),
parseIntValue(healthCheck.gracePeriodSeconds),
SET
)
);
}
if (healthCheck.intervalSeconds != null) {
memo.push(
new Transaction(
path.concat(["intervalSeconds"]),
parseIntValue(healthCheck.intervalSeconds),
SET
)
);
}
if (healthCheck.maxConsecutiveFailures != null) {
memo.push(
new Transaction(
path.concat(["maxConsecutiveFailures"]),
parseIntValue(healthCheck.maxConsecutiveFailures),
SET
)
);
}
if (healthCheck.timeoutSeconds != null) {
memo.push(
new Transaction(
path.concat(["timeoutSeconds"]),
parseIntValue(healthCheck.timeoutSeconds),
SET
)
);
}
if (healthCheck.delaySeconds != null) {
memo.push(
new Transaction(
path.concat(["delaySeconds"]),
parseIntValue(healthCheck.delaySeconds),
SET
)
);
}
return memo;
}
export function FormReducer(state, { type, path, value }) {
const newState = JSONSegmentReducer.call(this, state, { type, path, value });
// Bail early on nulled cases
if (newState == null) {
return newState;
}
const [group, field, secondField] = path;
// Include additional fields only present in the form
if (group === "protocol") {
newState.protocol = value;
}
// Assign detailed properties
switch (group) {
case "exec":
return reduceFormCommandHealthCheck(newState, secondField, value);
case "http":
return reduceFormHttpHealthCheck(newState, field, value);
}
return newState;
} | the_stack |
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import Tooltip from './index';
jest.useFakeTimers();
// https://github.com/thumbtack/thumbprint/issues/72
// https://github.com/FezVrasta/popper.js/issues/478#issuecomment-341494703
jest.mock('popper.js', () => {
const PopperJS = jest.requireActual('popper.js');
class Popper {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static placements: any;
constructor() {
return {
destroy: (): void => {},
scheduleUpdate: (): void => {},
};
}
}
Popper.placements = PopperJS.placements;
return Popper;
});
describe('Tooltip', () => {
test('renders a closed tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
expect(wrapper).toMatchSnapshot();
});
test('renders an open tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
expect(wrapper).toMatchSnapshot();
button.simulate('blur');
jest.runAllTimers();
});
test('adds `zIndex`', () => {
const wrapper = mount(
<Tooltip text="Goose" zIndex={123}>
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
expect(wrapper).toMatchSnapshot();
button.simulate('blur');
jest.runAllTimers();
});
test('renders an open tooltip with `bottom` placement', () => {
const wrapper = mount(
<Tooltip text="Goose" position="bottom">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
expect(wrapper).toMatchSnapshot();
button.simulate('blur');
jest.runAllTimers();
});
test('renders an open tooltip with a `light` theme', () => {
const wrapper = mount(
<Tooltip text="Goose" theme="light">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
expect(wrapper).toMatchSnapshot();
button.simulate('blur');
jest.runAllTimers();
});
test('renders an inline tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
expect(wrapper).toMatchSnapshot();
button.simulate('blur');
jest.runAllTimers();
});
test('Pressing the `Esc` key closes the tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('focus');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
act(() => {
// NOTE: it seems that Enzyme does not respond to the standard properties on
// `KeyboardEventInit`, either `code: 'Escape'` or `key: 'Escape'`. It only responds to
// the deprecated property `keyCode`, which is not in the type defintion. As such we
// have to cast the type here to prevent an error.
document.dispatchEvent(
new KeyboardEvent('keyup', {
key: 'Escape',
code: 'Escape',
keyCode: 27,
} as KeyboardEventInit),
);
});
wrapper.update();
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test('Events from tooltip element propagate to parent element', () => {
const jestOnClick = jest.fn();
const wrapper = mount(
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={(): void => {
onClick();
jestOnClick();
}}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
expect(jestOnClick).toHaveBeenCalledTimes(0);
wrapper.find('button').simulate('click');
expect(jestOnClick).toHaveBeenCalledTimes(1);
});
test('Events from PositionedTooltip do not propagate to parent container when `container` is `body`', () => {
const jestOnClick = jest.fn();
const wrapper = mount(
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<div onClick={jestOnClick}>
<Tooltip text="Goose" container="body">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>
</div>,
);
expect(jestOnClick).toHaveBeenCalledTimes(0);
wrapper.find('button').simulate('mouseenter');
expect(jestOnClick).toHaveBeenCalledTimes(0);
act(() => {
jest.runAllTimers();
});
wrapper
// Need to manually call update here because setState is called asynchronously in the
// show method.
.update()
.find('[role="tooltip"]')
.simulate('click');
expect(jestOnClick).toHaveBeenCalledTimes(0);
});
test('Events from PositionedTooltip do propagate to parent container when `container` is `inline`', () => {
const jestOnClick = jest.fn();
const wrapper = mount(
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<div onClick={jestOnClick}>
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>
</div>,
);
expect(jestOnClick).toHaveBeenCalledTimes(0);
wrapper.find('button').simulate('mouseenter');
expect(jestOnClick).toHaveBeenCalledTimes(0);
act(() => {
jest.runAllTimers();
});
wrapper
// Need to manually call update here because setState is called asynchronously in the
// show method.
.update()
.find('[role="tooltip"]')
.simulate('click');
expect(jestOnClick).toHaveBeenCalledTimes(1);
});
describe('non-touch devices', () => {
test('`mouseenter` and `mouseleave` open and close the tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('mouseenter');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
act(() => {
jest.runAllTimers();
});
wrapper.update();
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('mouseleave');
act(() => {
jest.runAllTimers();
});
wrapper.update();
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test('`focus` and `blur` open and close the tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('focus');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('blur');
act(() => {
jest.runAllTimers();
});
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test("click doesn't do anything", () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test("click on tooltip body doesn't do anything", () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
wrapper.find('[role="tooltip"]').simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('blur');
jest.runAllTimers();
});
});
describe('touch devices', () => {
beforeAll(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).window.ontouchstart = {};
});
afterAll(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (global as any).window.ontouchstart;
});
test('`click` opens the tooltip on first click and closes on second', () => {
const wrapper = mount(
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('click');
jest.runAllTimers();
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test("focus doesn't do anything", () => {
const wrapper = mount(
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('focus');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test('`blur` closes the tooltip', () => {
const wrapper = mount(
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('blur');
act(() => {
jest.runAllTimers();
});
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test('`mouseleave` closes the tooltip after a 200ms delay', () => {
const delayLength = 200;
const wrapper = mount(
<Tooltip text="Goose" closeDelayLength={delayLength}>
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
const button = wrapper.find('button');
button.simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('mouseleave');
act(() => {
jest.runAllTimers();
});
wrapper.update();
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test('`mouseleave` closes the tooltip immediately if `closeDelayLength` is `0`', () => {
const delayLength = 0;
const wrapper = mount(
<Tooltip text="Goose" closeDelayLength={delayLength}>
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(true);
button.simulate('mouseleave');
act(() => {
jest.advanceTimersByTime(delayLength);
});
wrapper.update();
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test("mouseenter doesn't do anything", () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
button.simulate('mouseenter');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
test('`click` on PositionedTooltip would close it', () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('click');
jest.runAllTimers();
wrapper.find('[role="tooltip"]').simulate('click');
expect(wrapper.find('[role="tooltip"]').exists()).toBe(false);
});
});
test("text can be changed while it's open", () => {
const wrapper = mount(
<Tooltip text="Goose" container="inline">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>,
);
const button = wrapper.find('button');
button.simulate('focus');
jest.runAllTimers();
wrapper.setProps({ text: 'Swan' });
expect(wrapper.find('[role="tooltip"]').text()).toContain('Swan');
});
test("doesn't render a tooltip when server rendered", () => {
const component = (
<Tooltip text="Goose">
{({
ref,
onMouseEnter,
onClick,
onFocus,
onMouseLeave,
onBlur,
ariaLabel,
}): JSX.Element => (
<button
ref={ref}
onMouseEnter={onMouseEnter}
onClick={onClick}
onFocus={onFocus}
onMouseLeave={onMouseLeave}
onBlur={onBlur}
aria-label={ariaLabel}
type="button"
>
Duck
</button>
)}
</Tooltip>
);
const ssrHTML = ReactDOMServer.renderToStaticMarkup(component);
expect(ssrHTML).not.toContain('data-test-id="tooltip"');
});
}); | the_stack |
import angular, {IFilterFilterComparatorFunc, ITimeoutService} from 'angular'
import moment from 'moment'
import GanttArrays from '../util/arrays.service'
import {GanttRow, GanttRowModel} from './row.factory'
import {IGanttFilterService} from '../../../index'
import {Gantt} from '../gantt.factory'
export class GanttRowsManager {
static GanttRow: { new(rowsManager: GanttRowsManager, model: GanttRowModel): GanttRow }
static $filter: IGanttFilterService
static $timeout: ITimeoutService
static ganttArrays: GanttArrays
gantt: Gantt
rowsMap: { [id: string]: GanttRow } = {}
rows: GanttRow[] = []
sortedRows: GanttRow[] = []
filteredRows: GanttRow[] = []
customFilteredRows: GanttRow[] = []
visibleRows: GanttRow[] = []
rowsTaskWatchers: { (): void }[] = []
customRowSorters: { (rows: GanttRow[]): GanttRow[] }[] = []
customRowFilters: { (rows: GanttRow[]): GanttRow[] }[] = []
_defaultFilterImpl: { (sortedRows: GanttRow[], filterRow: GanttRow[], filterRowComparator: (IFilterFilterComparatorFunc<GanttRow> | boolean)): GanttRow[]}
filterImpl: { (sortedRows: GanttRow[], filterRow: GanttRow[], filterRowComparator: (IFilterFilterComparatorFunc<GanttRow> | boolean)): GanttRow[]}
constructor (gantt: Gantt) {
this.gantt = gantt
this._defaultFilterImpl = (sortedRows: GanttRow[], filterRow: GanttRow[], filterRowComparator: IFilterFilterComparatorFunc<GanttRow>|boolean) => {
return GanttRowsManager.$filter('filter')(sortedRows, filterRow, filterRowComparator)
}
this.filterImpl = this._defaultFilterImpl
this.customRowSorters = []
this.customRowFilters = []
this.gantt.$scope.$watchGroup(['filterTask', 'filterTaskComparator'], (newValues, oldValues) => {
if (newValues !== oldValues) {
this.updateVisibleTasks()
}
})
this.gantt.$scope.$watchGroup(['filterRow', 'filterRowComparator'], (newValues, oldValues) => {
if (newValues !== oldValues) {
this.updateVisibleRows()
}
})
this.gantt.$scope.$watch('sortMode', (newValue, oldValue) => {
if (newValue !== oldValue) {
this.sortRows()
}
})
// Listen to vertical scrollbar visibility changes to update columns width
let _oldVScrollbarVisible = this.gantt.scroll.isVScrollbarVisible()
this.gantt.$scope.$watchGroup(['maxHeight', 'gantt.rowsManager.visibleRows.length'], (newValue, oldValue) => {
if (newValue !== oldValue) {
GanttRowsManager.$timeout(() => {
let newVScrollbarVisible = this.gantt.scroll.isVScrollbarVisible()
if (newVScrollbarVisible !== _oldVScrollbarVisible) {
_oldVScrollbarVisible = newVScrollbarVisible
this.gantt.columnsManager.updateColumnsMeta()
}
})
}
})
this.gantt.api.registerMethod('rows', 'sort', GanttRowsManager.prototype.sortRows, this)
this.gantt.api.registerMethod('rows', 'applySort', GanttRowsManager.prototype.applySort, this)
this.gantt.api.registerMethod('rows', 'refresh', GanttRowsManager.prototype.updateVisibleObjects, this)
this.gantt.api.registerMethod('rows', 'removeRowSorter', GanttRowsManager.prototype.removeCustomRowSorter, this)
this.gantt.api.registerMethod('rows', 'addRowSorter', GanttRowsManager.prototype.addCustomRowSorter, this)
this.gantt.api.registerMethod('rows', 'removeRowFilter', GanttRowsManager.prototype.removeCustomRowFilter, this)
this.gantt.api.registerMethod('rows', 'addRowFilter', GanttRowsManager.prototype.addCustomRowFilter, this)
this.gantt.api.registerMethod('rows', 'setFilterImpl', GanttRowsManager.prototype.setFilterImpl, this)
this.gantt.api.registerEvent('tasks', 'add')
this.gantt.api.registerEvent('tasks', 'change')
this.gantt.api.registerEvent('tasks', 'viewChange')
this.gantt.api.registerEvent('tasks', 'beforeRowChange')
this.gantt.api.registerEvent('tasks', 'beforeViewRowChange')
this.gantt.api.registerEvent('tasks', 'rowChange')
this.gantt.api.registerEvent('tasks', 'viewRowChange')
this.gantt.api.registerEvent('tasks', 'remove')
this.gantt.api.registerEvent('tasks', 'filter')
this.gantt.api.registerEvent('tasks', 'displayed')
this.gantt.api.registerEvent('rows', 'add')
this.gantt.api.registerEvent('rows', 'change')
this.gantt.api.registerEvent('rows', 'remove')
this.gantt.api.registerEvent('rows', 'move')
this.gantt.api.registerEvent('rows', 'displayed')
this.gantt.api.registerEvent('rows', 'filter')
this.updateVisibleObjects()
}
resetNonModelLists () {
this.rows = []
this.sortedRows = []
this.filteredRows = []
this.customFilteredRows = []
this.visibleRows = []
}
/**
* Copy to new row (add) or merge with existing (update)
*
* @param rowModel
* @param modelOrderChanged
* @returns {boolean} true if updated, false if added.
*/
addRow (rowModel: GanttRowModel, modelOrderChanged): boolean {
let row
let i
let l
let isUpdate = false
this.gantt.objectModel.cleanRow(rowModel)
if (rowModel.id in this.rowsMap) {
row = this.rowsMap[rowModel.id]
if (modelOrderChanged) {
this.rows.push(row)
this.sortedRows.push(row)
this.filteredRows.push(row)
this.customFilteredRows.push(row)
this.visibleRows.push(row)
}
if (row.model === rowModel) {
return
}
let toRemoveIds = GanttRowsManager.ganttArrays.getRemovedIds(rowModel.tasks, row.model.tasks)
for (i = 0, l = toRemoveIds.length; i < l; i++) {
let toRemoveId = toRemoveIds[i]
row.removeTask(toRemoveId)
}
row.model = rowModel
isUpdate = true
} else {
row = new GanttRowsManager.GanttRow(this, rowModel)
this.rowsMap[rowModel.id] = row
this.rows.push(row)
this.sortedRows.push(row)
this.filteredRows.push(row)
this.customFilteredRows.push(row)
this.visibleRows.push(row)
}
if (rowModel.tasks !== undefined && rowModel.tasks.length > 0) {
for (i = 0, l = rowModel.tasks.length; i < l; i++) {
let taskModel = rowModel.tasks[i]
row.addTask(taskModel)
}
row.updateVisibleTasks()
}
if (isUpdate) {
(this.gantt.api as any).rows.raise.change(row)
} else {
(this.gantt.api as any).rows.raise.add(row)
}
if (!isUpdate) {
let watcher = this.gantt.$scope.$watchCollection(() => {
return rowModel.tasks
}, (newTasks, oldTasks) => {
if (newTasks !== oldTasks) {
let i
let l
let toRemoveIds = GanttRowsManager.ganttArrays.getRemovedIds(newTasks, oldTasks)
for (i = 0, l = toRemoveIds.length; i < l; i++) {
let toRemove = toRemoveIds[i]
row.removeTask(toRemove)
}
if (newTasks !== undefined) {
for (i = 0, l = newTasks.length; i < l; i++) {
let toAdd = newTasks[i]
row.addTask(toAdd)
}
row.updateVisibleTasks()
}
}
})
this.rowsTaskWatchers.push(watcher)
}
return isUpdate
}
removeRow (rowId): GanttRow {
if (rowId in this.rowsMap) {
delete this.rowsMap[rowId]
let removedRow
let indexOf = GanttRowsManager.ganttArrays.indexOfId(this.rows, rowId, ['model', 'id'])
if (indexOf > -1) {
removedRow = this.rows.splice(indexOf, 1)[0] // Remove from array
let unregisterFunction = this.rowsTaskWatchers.splice(indexOf, 1)[0] // Remove watcher
if (unregisterFunction) {
unregisterFunction()
}
}
GanttRowsManager.ganttArrays.removeId(this.sortedRows, rowId, ['model', 'id'])
GanttRowsManager.ganttArrays.removeId(this.filteredRows, rowId, ['model', 'id'])
GanttRowsManager.ganttArrays.removeId(this.customFilteredRows, rowId, ['model', 'id'])
GanttRowsManager.ganttArrays.removeId(this.visibleRows, rowId, ['model', 'id']);
(this.gantt.api as any).rows.raise.remove(removedRow)
return removedRow
}
return undefined
}
removeAll () {
this.rowsMap = {}
this.rows = []
this.sortedRows = []
this.filteredRows = []
this.customFilteredRows = []
this.visibleRows = []
for (let unregisterFunction of this.rowsTaskWatchers) {
unregisterFunction()
}
this.rowsTaskWatchers = []
}
sortRows () {
let expression = this.gantt.options.value('sortMode')
if (expression !== undefined) {
let reverse = false
if ((typeof expression === 'string' || expression instanceof String) && expression.charAt(0) === '-') {
reverse = true
expression = expression.substr(1)
}
let angularOrderBy = GanttRowsManager.$filter('orderBy')
this.sortedRows = angularOrderBy(this.rows, expression, reverse)
} else {
this.sortedRows = this.rows.slice()
}
this.sortedRows = this.applyCustomRowSorters(this.sortedRows)
this.updateVisibleRows()
}
removeCustomRowSorter (sorterFunction: { (rows: GanttRow[]): GanttRow[] }) {
let i = this.customRowSorters.indexOf(sorterFunction)
if (i > -1) {
this.customRowSorters.splice(i, 1)
}
}
addCustomRowSorter (sorterFunction: { (rows: GanttRow[]): GanttRow[] }) {
this.customRowSorters.push(sorterFunction)
}
applyCustomRowSorters (rows: GanttRow[]) {
let sortedRows = rows
for (let customRowSorter of this.customRowSorters) {
sortedRows = customRowSorter(sortedRows)
}
return sortedRows
}
/**
* Applies current view sort to data model.
*/
applySort () {
let data = this.gantt.$scope.data
data.splice(0, data.length) // empty data.
let rows = []
for (let row of this.sortedRows) {
data.push(row.model)
rows.push(row)
}
this.rows = rows
}
moveRow (row, targetRow) {
let sortMode = this.gantt.options.value('sortMode')
if (sortMode !== undefined) {
// Apply current sort to model
this.applySort()
this.gantt.options.set('sortMode', undefined)
}
let targetRowIndex = this.rows.indexOf(targetRow)
let rowIndex = this.rows.indexOf(row)
if (targetRowIndex > -1 && rowIndex > -1 && targetRowIndex !== rowIndex) {
GanttRowsManager.ganttArrays.moveToIndex(this.rows, rowIndex, targetRowIndex)
GanttRowsManager.ganttArrays.moveToIndex(this.rowsTaskWatchers, rowIndex, targetRowIndex)
GanttRowsManager.ganttArrays.moveToIndex(this.gantt.$scope.data, rowIndex, targetRowIndex);
(this.gantt.api as any).rows.raise.change(row);
(this.gantt.api as any).rows.raise.move(row, rowIndex, targetRowIndex)
this.updateVisibleObjects()
this.sortRows()
}
}
updateVisibleObjects () {
this.updateVisibleRows()
this.updateVisibleTasks()
}
updateVisibleRows () {
let oldFilteredRows = this.filteredRows
let filterRow = this.gantt.options.value('filterRow')
if (filterRow) {
if (typeof(filterRow) === 'object') {
filterRow = {model: filterRow}
}
let filterRowComparator = this.gantt.options.value('filterRowComparator')
if (typeof(filterRowComparator) === 'function') {
// fix issue this.gantt is undefined
let gantt = this.gantt
filterRowComparator = (actual, expected) => {
// fix actual.model is undefined
return gantt.options.value('filterRowComparator')(actual, expected)
}
}
this.filteredRows = this.filterImpl(this.sortedRows, filterRow, filterRowComparator)
} else {
this.filteredRows = this.sortedRows.slice(0)
}
let raiseEvent = !angular.equals(oldFilteredRows, this.filteredRows)
this.customFilteredRows = this.applyCustomRowFilters(this.filteredRows)
// TODO: Implement rowLimit like columnLimit to enhance performance for gantt with many rows
this.visibleRows = this.customFilteredRows;
(this.gantt.api as any).rows.raise.displayed(this.sortedRows, this.filteredRows, this.visibleRows)
if (raiseEvent) {
(this.gantt.api as any).rows.raise.filter(this.sortedRows, this.filteredRows)
}
}
removeCustomRowFilter (filterFunction: { (rows: GanttRow[]): GanttRow[] }) {
let i = this.customRowFilters.indexOf(filterFunction)
if (i > -1) {
this.customRowFilters.splice(i, 1)
}
}
addCustomRowFilter (filterFunction: { (rows: GanttRow[]): GanttRow[] }) {
this.customRowFilters.push(filterFunction)
}
applyCustomRowFilters (rows: GanttRow[]) {
let filteredRows = rows
for (let customRowFilter of this.customRowFilters) {
filteredRows = customRowFilter(filteredRows)
}
return filteredRows
}
setFilterImpl (filterImpl) {
if (!filterImpl) {
this.filterImpl = this._defaultFilterImpl
} else {
this.filterImpl = filterImpl
}
}
updateVisibleTasks () {
let oldFilteredTasks = []
let filteredTasks = []
let tasks = []
let visibleTasks = []
for (let row of this.rows) {
oldFilteredTasks = oldFilteredTasks.concat(row.filteredTasks)
row.updateVisibleTasks()
filteredTasks = filteredTasks.concat(row.filteredTasks)
visibleTasks = visibleTasks.concat(row.visibleTasks)
tasks = tasks.concat(row.tasks)
}
(this.gantt.api as any).tasks.raise.displayed(tasks, filteredTasks, visibleTasks)
let filterEvent = !angular.equals(oldFilteredTasks, filteredTasks)
if (filterEvent) {
(this.gantt.api as any).tasks.raise.filter(tasks, filteredTasks, visibleTasks)
}
}
/**
* Update the position/size of all tasks in the Gantt
*/
updateTasksPosAndSize () {
for (let row of this.rows) {
row.updateTasksPosAndSize()
}
}
getExpandedFrom (from?: moment.Moment) {
from = from ? moment(from) : from
let minRowFrom = from
for (let row of this.rows) {
if (minRowFrom === undefined || minRowFrom > row.from) {
minRowFrom = row.from
}
}
if (minRowFrom && (!from || minRowFrom < from)) {
return minRowFrom
}
return from
}
getExpandedTo (to?: moment.Moment) {
to = to ? moment(to) : to
let maxRowTo = to
for (let row of this.rows) {
if (maxRowTo === undefined || maxRowTo < row.to) {
maxRowTo = row.to
}
}
let toDate = this.gantt.options.value('toDate')
if (maxRowTo && (!toDate || maxRowTo > toDate)) {
return maxRowTo
}
return to
}
getDefaultFrom () {
let defaultFrom
for (let row of this.rows) {
if (defaultFrom === undefined || row.from < defaultFrom) {
defaultFrom = row.from
}
}
return defaultFrom
}
getDefaultTo () {
let defaultTo
for (let row of this.rows) {
if (defaultTo === undefined || row.to > defaultTo) {
defaultTo = row.to
}
}
return defaultTo
}
}
export default function (GanttRow: { new(rowsManager: GanttRowsManager, model: GanttRowModel): GanttRow },
ganttArrays: GanttArrays,
$filter: IGanttFilterService,
$timeout: ITimeoutService) {
'ngInject'
GanttRowsManager.GanttRow = GanttRow
GanttRowsManager.$filter = $filter
GanttRowsManager.$timeout = $timeout
GanttRowsManager.ganttArrays = ganttArrays
return GanttRowsManager
} | the_stack |
import { LayoutUtil } from "./layout_utils"
import { ListViewItem } from "./ListViewItem";
export class ListViewTs {
private scrollview: cc.ScrollView;
private mask: cc.Mask;
private content: cc.Node;
private item_tpl: cc.Node;
private item_pool: ListViewItem[];
private dir: number;
private width: number;
private height: number;
private original_width: number;
private original_height: number;
private gap_x: number;
private gap_y: number;
private padding_left: number;
private padding_right: number;
private padding_top: number;
private padding_bottom: number;
private item_anchorX: number;
private item_anchorY: number;
private row: number;
private col: number;
private item_width: number;
private item_height: number;
private content_width: number;
private content_height: number;
private item_class: string;
private cb_host: any;
private scroll_to_end_cb: () => void;
private auto_scrolling: boolean;
private packItems: PackItem[];
private start_index: number;
private stop_index: number;
private _selected_index: number = -1;
private renderDirty: boolean;
private timer: number;
constructor(params: ListViewParams) {
this.scrollview = params.scrollview;
this.mask = params.mask;
this.content = params.content;
this.item_tpl = params.item_tpl;
this.item_tpl.active = false;
this.item_width = this.item_tpl.width;
this.item_height = this.item_tpl.height;
this.dir = params.direction || ListViewDir.Vertical;
this.width = params.width || this.scrollview.node.width;
this.height = params.height || this.scrollview.node.height;
this.gap_x = params.gap_x || 0;
this.gap_y = params.gap_y || 0;
this.padding_left = params.padding_left || 0;
this.padding_right = params.padding_right || 0;
this.padding_top = params.padding_top || 0;
this.padding_bottom = params.padding_bottom || 0;
this.item_anchorX = params.item_anchorX != null ? params.item_anchorX : 0;
this.item_anchorY = params.item_anchorY != null ? params.item_anchorY : 1;
this.row = params.row || 1;
this.col = params.column || 1;
this.cb_host = params.cb_host;
this.scroll_to_end_cb = params.scroll_to_end_cb;
this.item_class = params.item_class;
this.auto_scrolling = params.auto_scrolling || false;
this.item_pool = [];
if (this.dir == ListViewDir.Vertical) {
const content_width = (this.item_width + this.gap_x) * this.col - this.gap_x + this.padding_left + this.padding_right;
if (content_width > this.width) {
cc.log("content_width > width, resize listview to content_width,", this.width, "->", content_width);
this.width = content_width;
}
this.set_content_size(this.width, 0);
}
else {
const content_height = (this.item_height + this.gap_y) * this.row - this.gap_y + this.padding_top + this.padding_bottom;
if (content_height > this.height) {
cc.log("content_height > height, resize listview to content_height,", this.height, "->", content_height);
this.height = content_height;
}
this.set_content_size(0, this.height);
}
this.original_width = this.width;
this.original_height = this.height;
this.mask.node.setContentSize(this.width, this.height);
this.scrollview.node.setContentSize(this.width, this.height);
this.scrollview.vertical = this.dir == ListViewDir.Vertical;
this.scrollview.horizontal = this.dir == ListViewDir.Horizontal;
this.scrollview.inertia = true;
this.scrollview.node.on("scrolling", this.on_scrolling, this);
this.scrollview.node.on("scroll-to-bottom", this.on_scroll_to_end, this);
this.scrollview.node.on("scroll-to-right", this.on_scroll_to_end, this);
this.scrollview.node.on(cc.Node.EventType.TOUCH_START, this.on_scroll_touch_start, this);
this.scrollview.node.on(cc.Node.EventType.TOUCH_END, this.on_scroll_touch_end, this);
this.scrollview.node.on(cc.Node.EventType.TOUCH_CANCEL, this.on_scroll_touch_cancel, this);
}
private _touchBeganPosition: cc.Vec2;
private _touchEndPosition: cc.Vec2;
private on_scroll_touch_start(event: cc.Event.EventTouch) {
this._touchBeganPosition = cc.v2(event.touch.getLocation().x, event.touch.getLocation().y);
}
private on_scroll_touch_cancel(event: cc.Event.EventTouch) {
this._touchEndPosition = event.touch.getLocation();
this.handle_release_logic();
}
private on_scroll_touch_end(event: cc.Event.EventTouch) {
this._touchEndPosition = event.touch.getLocation();
this.handle_release_logic();
}
private handle_release_logic() {
const touchPos = this._touchEndPosition;
const moveOffset = this._touchBeganPosition.sub(this._touchEndPosition);
const dragDirection = this.get_drag_direction(moveOffset);
if (dragDirection != 0) {
return;
}
if (!this.packItems || !this.packItems.length) {
return;
}
//无滑动的情况下点击
const touchPosInContent = this.content.convertToNodeSpaceAR(touchPos);
for (let i = this.start_index; i <= this.stop_index; i++) {
const packItem = this.packItems[i];
if (packItem && packItem.item && packItem.item.node.getBoundingBox().contains(touchPosInContent)) {
packItem.item.onTouchEnd(packItem.item.node.convertToNodeSpaceAR(touchPos), packItem.data, i);
break;
}
}
}
private get_drag_direction(moveOffset: cc.Vec2) {
if (this.dir === ListViewDir.Horizontal) {
if (Math.abs(moveOffset.x) < 3) { return 0; }
return (moveOffset.x > 0 ? 1 : -1);
}
else if (this.dir === ListViewDir.Vertical) {
// 由于滚动 Y 轴的原点在在右上角所以应该是小于 0
if (Math.abs(moveOffset.y) < 3) { return 0; }
return (moveOffset.y < 0 ? 1 : -1);
}
}
private on_scroll_to_end() {
if (this.scroll_to_end_cb) {
this.scroll_to_end_cb.call(this.cb_host);
}
}
private last_content_pos: number;
private on_scrolling() {
let pos: number;
let threshold: number;
if (this.dir == ListViewDir.Vertical) {
pos = this.content.y;
threshold = this.item_height;
}
else {
pos = this.content.x;
threshold = this.item_width;
}
if (this.last_content_pos != null && Math.abs(pos - this.last_content_pos) < threshold) {
return;
}
this.last_content_pos = pos;
this.render();
}
private render() {
if (!this.packItems || !this.packItems.length) {
return;
}
if (this.dir == ListViewDir.Vertical) {
let posy = this.content.y;
// cc.log("onscrolling, content posy=", posy);
if (posy < 0) {
posy = 0;
}
else if (posy > this.content_height - this.height) {
posy = this.content_height - this.height;
}
let viewport_start = -posy;
let viewport_stop = viewport_start - this.height;
// while(this.packItems[start].y - this.item_height > viewport_start)
// {
// start++;
// }
// while(this.packItems[stop].y < viewport_stop)
// {
// stop--;
// }
let start = this.indexFromOffset(viewport_start);
let stop = this.indexFromOffset(viewport_stop);
//expand viewport for better experience
start = Math.max(start - this.col, 0);
stop = Math.min(this.packItems.length - 1, stop + this.col);
if (start != this.start_index) {
this.start_index = start;
this.renderDirty = true;
}
if (stop != this.stop_index) {
this.stop_index = stop;
this.renderDirty = true;
}
}
else {
let posx = this.content.x;
// cc.log("onscrolling, content posx=", posx);
if (posx > 0) {
posx = 0;
}
else if (posx < this.width - this.content_width) {
posx = this.width - this.content_width;
}
let viewport_start = -posx;
let viewport_stop = viewport_start + this.width;
// while(this.packItems[start].x + this.item_width < viewport_start)
// {
// start++;
// }
// while(this.packItems[stop].x > viewport_stop)
// {
// stop--;
// }
let start = this.indexFromOffset(viewport_start);
let stop = this.indexFromOffset(viewport_stop);
//expand viewport for better experience
start = Math.max(start - this.row, 0);
stop = Math.min(this.packItems.length - 1, stop + this.row);
if (start != this.start_index) {
this.start_index = start;
this.renderDirty = true;
}
if (stop != this.stop_index) {
this.stop_index = stop;
this.renderDirty = true;
}
}
}
onUpdate() {
if (this.renderDirty && cc.isValid(this.scrollview.node)) {
cc.log("listView, render_from:", this.start_index, this.stop_index);
this.render_items();
this.renderDirty = false;
}
}
//不支持多行多列
private indexFromOffset(offset: number) {
let low = 0;
let high = 0;
let max_idx = 0;
high = max_idx = this.packItems.length - 1;
if (this.dir == ListViewDir.Vertical) {
while (high >= low) {
const index = low + Math.floor((high - low) / 2);
const itemStart = this.packItems[index].y;
const itemStop = index < max_idx ? this.packItems[index + 1].y : -this.content_height;
if (offset <= itemStart && offset >= itemStop) {
return index;
}
else if (offset > itemStart) {
high = index - 1;
}
else {
low = index + 1;
}
}
}
else {
while (high >= low) {
const index = low + Math.floor((high - low) / 2);
const itemStart = this.packItems[index].x;
const itemStop = index < max_idx ? this.packItems[index + 1].x : this.content_width;
if (offset >= itemStart && offset <= itemStop) {
return index;
}
else if (offset > itemStart) {
low = index + 1;
}
else {
high = index - 1;
}
}
}
return -1;
}
select_data(data) {
const idx = this.packItems.findIndex(item => item.data == data);
if (idx != -1) {
this.select_item(idx);
}
}
select_item(index: number) {
if (index == this._selected_index) {
return;
}
if (this._selected_index != -1) {
this.inner_select_item(this._selected_index, false);
}
this._selected_index = index;
this.inner_select_item(index, true);
}
private inner_select_item(index: number, is_select: boolean) {
let packItem: PackItem = this.packItems[index];
if (!packItem) {
cc.warn("inner_select_item index is out of range{", 0, this.packItems.length - 1, "}", index);
return;
}
packItem.is_select = is_select;
if (packItem.item) {
packItem.item.onSetSelect(is_select, index);
if (is_select) {
packItem.item.onSelected(packItem.data, index);
}
}
}
private spawn_item(index: number): ListViewItem {
let item: ListViewItem = this.item_pool.pop();
if (!item) {
item = cc.instantiate(this.item_tpl).getComponent(this.item_class) as ListViewItem;
item.node.active = true;
//仅仅改变父节点锚点,子元素位置不会随之变化
// item.node.setAnchorPoint(this.item_anchorX, this.item_anchorY);
LayoutUtil.set_pivot_smart(item.node, this.item_anchorX, this.item_anchorY);
item.onInit();
// cc.log("spawn_item", index);
}
item.node.parent = this.content;
return item;
}
private recycle_item(packItem: PackItem) {
const item = packItem.item;
if (item && cc.isValid(item.node)) {
item.onRecycle(packItem.data);
item.node.removeFromParent();
this.item_pool.push(item);
packItem.item = null;
}
}
private clear_items() {
if (this.packItems) {
this.packItems.forEach(packItem => {
this.recycle_item(packItem);
});
}
}
private render_items() {
let packItem: PackItem;
for (let i = 0; i < this.start_index; i++) {
packItem = this.packItems[i];
if (packItem.item) {
// cc.log("recycle_item", i);
this.recycle_item(packItem);
}
}
for (let i = this.packItems.length - 1; i > this.stop_index; i--) {
packItem = this.packItems[i];
if (packItem.item) {
// cc.log("recycle_item", i);
this.recycle_item(packItem);
}
}
for (let i = this.start_index; i <= this.stop_index; i++) {
packItem = this.packItems[i];
if (!packItem.item) {
// cc.log("render_item", i);
packItem.item = this.spawn_item(i);
packItem.item.onSetData(packItem.data, i);
packItem.item.onSetSelect(packItem.is_select, i);
if (packItem.is_select) {
packItem.item.onSelected(packItem.data, i);
}
}
//列表添加与删除时item位置会变化,因此每次render_items都要执行
// packItem.item.node.setPosition(packItem.x, packItem.y);
packItem.item.setLeftTop(packItem.x, packItem.y);
}
}
private pack_item(data: any): PackItem {
return { x: 0, y: 0, data: data, item: null, is_select: false };
}
private layout_items(start: number) {
// cc.log("layout_items, start=", start);
for (let index = start, stop = this.packItems.length; index < stop; index++) {
const packItem = this.packItems[index];
if (this.dir == ListViewDir.Vertical) {
[packItem.x, packItem.y] = LayoutUtil.vertical_layout(index, this.item_width, this.item_height, this.col, this.gap_x, this.gap_y, this.padding_left, this.padding_top);
}
else {
[packItem.x, packItem.y] = LayoutUtil.horizontal_layout(index, this.item_width, this.item_height, this.row, this.gap_x, this.gap_y, this.padding_left, this.padding_top);
}
}
}
private adjust_content() {
if (this.packItems.length <= 0) {
this.set_content_size(0, 0);
return;
}
const last_packItem = this.packItems[this.packItems.length - 1];
if (this.dir == ListViewDir.Vertical) {
const height = Math.max(this.height, this.item_height - last_packItem.y + this.padding_bottom);
this.set_content_size(this.content_width, height);
}
else {
const width = Math.max(this.width, last_packItem.x + this.item_width + this.padding_right);
this.set_content_size(width, this.content_height);
}
}
private set_content_size(width: number, height: number) {
if (this.content_width != width) {
this.content_width = width;
this.content.width = width;
}
if (this.content_height != height) {
this.content_height = height;
this.content.height = height;
}
// cc.log("ListView, set_content_size", width, height, this.content.width, this.content.height);
}
set_viewport(width?: number, height?: number) {
if (width == null) {
width = this.width;
}
else if (width > this.content_width) {
width = this.content_width;
}
if (height == null) {
height = this.height;
}
else if (height > this.content_height) {
height = this.content_height;
}
//设置遮罩区域尺寸
this.width = width;
this.height = height;
this.mask.node.setContentSize(width, height);
this.scrollview.node.setContentSize(width, height);
this.render();
}
renderAll(value: boolean) {
let width: number;
let height: number;
if (value) {
width = this.content_width;
height = this.content_height;
}
else {
width = this.original_width;
height = this.original_height;
}
this.set_viewport(width, height);
}
set_data(datas: any[]) {
if (this.packItems) {
this.clear_items();
this.packItems.length = 0;
}
else {
this.packItems = [];
}
datas.forEach(data => {
let packItem = this.pack_item(data);
this.packItems.push(packItem);
});
this.layout_items(0);
this.adjust_content();
this.start_index = -1;
this.stop_index = -1;
if (this.dir == ListViewDir.Vertical) {
this.content.y = 0;
}
else {
this.content.x = 0;
}
if (this.packItems.length > 0) {
this.render();
}
}
insert_data(index: number, ...datas: any[]) {
if (datas.length == 0) {
cc.log("nothing to insert");
return;
}
if (!this.packItems) {
this.packItems = [];
}
if (index < 0 || index > this.packItems.length) {
cc.warn("insert_data, invalid index", index);
return;
}
let is_append = index == this.packItems.length;
let packItems: PackItem[] = [];
datas.forEach(data => {
let packItem = this.pack_item(data);
packItems.push(packItem);
});
this.packItems.splice(index, 0, ...packItems);
this.layout_items(index);
this.adjust_content();
this.start_index = -1;
this.stop_index = -1;
if (this.auto_scrolling && is_append) {
this.scroll_to_end();
}
this.render();
}
remove_data(index: number, count: number = 1) {
if (!this.packItems) {
cc.log("call set_data before call this method");
return;
}
if (index < 0 || index >= this.packItems.length) {
cc.warn("remove_data, invalid index", index);
return;
}
if (count < 1) {
cc.log("nothing to remove");
return;
}
let old_length = this.packItems.length;
let del_items = this.packItems.splice(index, count);
//回收node
del_items.forEach(packItem => {
this.recycle_item(packItem);
});
//重新排序index后面的
if (index + count < old_length) {
this.layout_items(index);
}
this.adjust_content();
if (this.packItems.length > 0) {
this.start_index = -1;
this.stop_index = -1;
this.render();
}
}
append_data(...datas: any[]) {
if (!this.packItems) {
this.packItems = [];
}
this.insert_data(this.packItems.length, ...datas);
}
scroll_to(index: number, time = 0) {
if (!this.packItems) {
return;
}
const packItem = this.packItems[index];
if (!packItem) {
cc.log("scroll_to, index out of range");
return;
}
if (this.dir == ListViewDir.Vertical) {
const min_y = this.height - this.content_height;
if (min_y >= 0) {
cc.log("no need to scroll");
return;
}
let y = packItem.y;
if (y < min_y) {
y = min_y;
cc.log("content reach bottom");
}
const x = this.content.x;
if (time == 0) {
this.scrollview.setContentPosition(cc.v2(x, -y));
}
else {
this.scrollview.scrollToOffset(cc.v2(x, -y), time);
}
this.render();
}
else {
const max_x = this.content_width - this.width;
if (max_x <= 0) {
cc.log("no need to scroll");
return;
}
let x = packItem.x;
if (x > max_x) {
x = max_x;
cc.log("content reach right");
}
const y = this.content.y;
if (time == 0) {
this.scrollview.setContentPosition(cc.v2(-x, y));
}
else {
this.scrollview.scrollToOffset(cc.v2(-x, y), time);
}
this.render();
}
}
get_scroll_offset() {
const offset = this.scrollview.getScrollOffset();
if (this.dir == ListViewDir.Vertical) {
return offset.y;
}
else {
return offset.x;
}
}
scroll_to_offset(value: number, time = 0) {
if (this.dir == ListViewDir.Vertical) {
const x = this.content.x;
if (time == 0) {
this.scrollview.setContentPosition(cc.v2(x, value));
}
else {
this.scrollview.scrollToOffset(cc.v2(x, value), time);
}
this.render();
}
else {
const y = this.content.y;
if (time == 0) {
this.scrollview.setContentPosition(cc.v2(value, y));
}
else {
this.scrollview.scrollToOffset(cc.v2(value, y), time);
}
this.render();
}
}
scroll_to_end() {
if (this.dir == ListViewDir.Vertical) {
this.scrollview.scrollToBottom();
}
else {
this.scrollview.scrollToRight();
}
}
refresh_item(index: number, data: any) {
const packItem = this.get_pack_item(index);
if (!packItem) {
return;
}
const oldData = packItem.data;
packItem.data = data;
if (packItem.item) {
packItem.item.onRecycle(oldData);
packItem.item.onSetData(data, index);
}
}
reload_item(index: number) {
const packItem = this.get_pack_item(index);
if (packItem && packItem.item) {
packItem.item.onRecycle(packItem.data);
packItem.item.onSetData(packItem.data, index);
}
}
private get_pack_item(index: number) {
if (!this.packItems) {
cc.log("call set_data before call this method");
return null;
}
if (index < 0 || index >= this.packItems.length) {
cc.warn("get_pack_item, invalid index", index);
return null;
}
return this.packItems[index];
}
get_item(index: number) {
const packItem = this.get_pack_item(index);
return packItem ? packItem.item : null;
}
get_data(index: number) {
const packItem = this.get_pack_item(index);
return packItem ? packItem.data : null;
}
find_item(predicate: (data: any) => boolean) {
if (!this.packItems || !this.packItems.length) {
cc.log("call set_data before call this method");
return null;
}
for (let i = this.start_index; i <= this.stop_index; i++) {
const packItem = this.packItems[i];
if (predicate(packItem.data)) {
return packItem.item;
}
}
return null;
}
find_index(predicate: (data: any) => boolean) {
if (!this.packItems || !this.packItems.length) {
cc.log("call set_data before call this method");
return -1;
}
return this.packItems.findIndex(packItem => {
return predicate(packItem.data);
});
}
get renderedItems() {
const items: ListViewItem[] = [];
for (let i = this.start_index; i <= this.stop_index; i++) {
const packItem = this.packItems[i];
if (packItem && packItem.item) {
items.push(packItem.item);
}
}
return items;
}
get length() {
if (!this.packItems) {
cc.log("call set_data before call this method");
return 0;
}
return this.packItems.length;
}
destroy() {
this.clear_items();
this.item_pool.forEach(item => {
item.onUnInit();
item.node.destroy();
});
this.item_pool = null;
this.packItems = null;
this.renderDirty = null;
if (cc.isValid(this.scrollview.node)) {
this.scrollview.node.off("scrolling", this.on_scrolling, this);
this.scrollview.node.off("scroll-to-bottom", this.on_scroll_to_end, this);
this.scrollview.node.off("scroll-to-right", this.on_scroll_to_end, this);
this.scrollview.node.off(cc.Node.EventType.TOUCH_START, this.on_scroll_touch_start, this);
this.scrollview.node.off(cc.Node.EventType.TOUCH_END, this.on_scroll_touch_end, this);
this.scrollview.node.off(cc.Node.EventType.TOUCH_CANCEL, this.on_scroll_touch_cancel, this);
}
}
get selected_index(): number {
return this._selected_index;
}
get selected_data(): any {
let packItem: PackItem = this.packItems[this._selected_index];
if (packItem) {
return packItem.data;
}
return null;
}
set scrollable(value: boolean) {
if (this.dir == ListViewDir.Vertical) {
this.scrollview.vertical = value;
}
else {
this.scrollview.horizontal = value;
}
}
get startIndex() {
return this.start_index;
}
get stopIndex() {
return this.stop_index;
}
}
export enum ListViewDir {
Vertical = 1,
Horizontal = 2,
}
export type ListViewParams = {
scrollview: cc.ScrollView;
mask: cc.Mask;
content: cc.Node;
item_tpl: cc.Node;
item_class: string; //item对应的类型
direction?: ListViewDir;
width?: number;
height?: number;
gap_x?: number;
gap_y?: number;
padding_left?: number;
padding_right?: number;
padding_top?: number;
padding_bottom?: number;
item_anchorX?: number;
item_anchorY?: number;
row?: number; //水平方向排版时,垂直方向上的行数
column?: number; //垂直方向排版时,水平方向上的列数
cb_host?: any; //回调函数host
scroll_to_end_cb?: () => void; //滚动到尽头的回调
auto_scrolling?: boolean; //append时自动滚动到尽头
}
type PackItem = {
x: number;
y: number;
data: any;
is_select: boolean;
item: ListViewItem;
} | the_stack |
import {AfterViewInit, Component, EventEmitter, OnInit, Output} from '@angular/core';
import {Role} from '@app/model/role';
import {UserService} from "@app/services/user.service";
import {ActivatedRoute} from "@angular/router";
import {catchError, filter, map, share, switchMap, tap} from "rxjs/operators";
import {RoleTree} from "@app/model/role-tree";
import {RoleService} from "@app/services/role.service";
import {RoleTemplate} from "@app/model/role-template";
import {from, Observable} from "rxjs";
import {Util} from "@app/modules/shared/shared.module";
import {RoleResult} from './role-result';
import {ErrorResult} from "@app/model/error-result";
import {HttpResponse} from "@angular/common/http";
@Component({
selector: 'app-manage-users-roles',
templateUrl: './manage-users-roles.component.html',
styleUrls: ['./manage-users-roles.component.scss']
})
export class ManageUsersRolesComponent implements OnInit, AfterViewInit {
roles$ : Observable<RoleResult>
currentRoles: RoleResult
guest: Role
registered: Role
templateRoles$: Observable<RoleTemplate[]>;
userid: string;
success:boolean=true;
errors: ErrorResult[]=[];
saved:boolean=false;
@Output()
userIdEvent: EventEmitter<string> = new EventEmitter<string>(true);
constructor(private route : ActivatedRoute, private userService : UserService, private roleService : RoleService) {
}
ngOnInit(): void {
this.roles$ = this.route.params.pipe(
map(params => params.userid), filter(userid => userid != null),
tap(userid => this.userid = userid),
tap(userid=>{
this.userIdEvent.emit(userid)
}),
switchMap(userid => {
return this.userService.userRoleTree(userid)
}),
map(roleTree=>this.parseRoleTree(roleTree)),
// This is to avoid multiple userService.userRoleTree() calls for template and base roles
share()
);
this.templateRoles$ = this.roleService.getTemplates();
}
private parseRoleTree(roleTree:RoleTree): RoleResult {
let roleResult = new RoleResult();
let rootRoles = roleTree.root_roles;
rootRoles.sort((a, b)=>{
if (b.id=='guest') {
return 1;
} else if (b.id=='registered-user') {
return 1;
} else {
return -1;
}
})
for (let rootRole of rootRoles) {
this.recurseTree(rootRole, roleResult, 0, null);
}
return roleResult;
}
private recurseTree(role:Role,roleResult:RoleResult, level:number, parent: Role) : void {
let newLevel=level;
if (parent!=null) {
if (role.root_path==null) {
role.root_path = (parent.root_path == null ? [] : parent.root_path.slice());
}
role.root_path.push(parent.id)
}
role.assigned_origin = role.assigned;
if (role.template_instance) {
newLevel = this.parseTemplateRole(role,roleResult.templateRoleInstances,newLevel)
} else {
newLevel = this.parseBaseRole(role, roleResult.baseRoles, newLevel)
}
for(let childRole of role.children) {
let recurseChild = childRole;
if (childRole.template_instance) {
if (roleResult.templateRoleInstances.has(childRole.resource) && roleResult.templateRoleInstances.get(childRole.resource).has(childRole.model_id)) {
recurseChild = roleResult.templateRoleInstances.get(childRole.resource).get(childRole.model_id)
}
} else {
let existingBaseRole = roleResult.baseRoles.find(role => role.id == childRole.id)
if (existingBaseRole != null) {
recurseChild = existingBaseRole;
}
}
this.recurseTree(recurseChild, roleResult, newLevel, role);
}
}
private parseBaseRole(role:Role, roles : Array<Role>, level:number) : number {
if (role.id=='guest') {
this.guest = role;
} else if (role.id=='registered-user') {
this.registered = role;
}
role.enabled=true;
let newLevel;
if (role.assignable) {
role.level=level
roles.push(role);
newLevel = level+1;
} else {
newLevel = level;
}
return newLevel;
}
private parseTemplateRole(role:Role, roles : Map<string, Map<string, Role>>, level:number) : number {
let newLevel=level;
role.enabled=true;
if (role.assignable) {
role.level=level
let modelRoleMap = roles.get(role.resource)
if (modelRoleMap==null) {
modelRoleMap = new Map<string, Role>();
}
modelRoleMap.set(role.model_id, role);
roles.set(role.resource, modelRoleMap);
newLevel = level + 1;
} else {
newLevel = level;
}
return newLevel;
}
getRoleContent(role:Role) : string {
let level = role.level
let result = "";
for(let _i=0; _i<level; _i++) {
result = result + " <i class='fas fa-angle-double-right'></i> ";
}
if (role.child) {
return result + role.name;
} else {
return "<strong>"+result+role.name+"</strong>"
}
}
changeBaseAssignment(role : Role, event) {
let cLevel=-1
let assignStatus
// Guest is special and exclusive
if (role.id==this.guest.id) {
if (role.assigned) {
this.currentRoles.baseRoles.forEach((cRole:Role)=> {
if (cRole.id != this.guest.id) {
cRole.assigned = false;
cRole.enabled=true;
}
})
role.enabled = false;
this.currentRoles.templateRoleInstances.forEach((value, key)=>{
value.forEach((templateInstance, modelId) => {
templateInstance.assigned = false;
templateInstance.enabled = true;
});
})
}
} else {
this.guest.enabled = true;
this.currentRoles.baseRoles.forEach((cRole)=> {
if (cRole.id == role.id) {
cLevel = cRole.level;
assignStatus = cRole.assigned;
if (assignStatus) {
this.guest.assigned = false;
this.guest.enabled = true;
} else {
if (!this.isAnyAssigned()) {
this.guest.assigned=true;
this.guest.enabled = false;
}
}
} else {
if (cLevel >= 0 && cLevel < cRole.level && cRole.root_path.find(pRoleId => pRoleId==role.id)) {
if (assignStatus) {
cRole.assigned = true;
cRole.enabled = false;
} else {
cRole.enabled = true;
cRole.assigned=cRole.assigned_origin
}
} else if (cLevel >= 0) {
return;
}
}
})
this.currentRoles.templateRoleInstances.forEach((value, key)=>{
value.forEach((templateInstance, modelId) => {
if(templateInstance.root_path.find(roleId => roleId==role.id)) {
if (role.assigned) {
templateInstance.assigned = true;
templateInstance.enabled = false
} else {
templateInstance.enabled = true;
templateInstance.assigned=templateInstance.assigned_origin
}
}
}
)
})
}
}
isAnyAssigned() : boolean {
if (Array.from(this.currentRoles.baseRoles.values()).find(role=>role.assigned)!=null) {
return true;
}
return Array.from(this.currentRoles.templateRoleInstances.values()).map((roleMap: Map<string, Role>) => Array.from(roleMap.values()))
.find(values=>values.find(role=>role.assigned))!=null
}
changeTemplateAssignment(role : Role, event) {
if (role.assigned) {
if (this.guest.assigned) {
this.guest.assigned = false;
this.guest.enabled = true;
}
if (!this.registered.assigned) {
this.registered.assigned=true;
}
} else {
if (!this.isAnyAssigned()) {
this.guest.assigned=true;
this.guest.enabled = false;
}
}
}
getInstanceContent(template:RoleTemplate, roles:Map<string,Role>) : Role {
return roles.get(template.id)
}
saveAssignments() {
this.saved=false;
this.success=true;
this.errors = [];
let assignmentMap : Map<string, Role> = new Map(this.currentRoles.baseRoles.filter(role => role.assigned != role.assigned_origin).map(role => [role.id, role]));
let assignments : Array<Role> = []
let unassignments : Array<Role> = []
assignmentMap.forEach((role, roleId)=>{
if (role.level>0) {
for(let parentId of role.root_path) {
if (assignmentMap.has(parentId) && assignmentMap.get(parentId).assigned) {
return;
}
}
}
if (role.assigned) {
assignments.push(role);
} else {
unassignments.push(role);
}
})
this.currentRoles.templateRoleInstances.forEach((templMap, resource)=> {
templMap.forEach((role, modelId)=> {
if (role.assigned!=role.assigned_origin) {
if (role.level>0) {
for(let parentId of role.root_path) {
if (assignmentMap.has(parentId) && assignmentMap.get(parentId).assigned) {
return;
}
}
}
if (role.assigned) {
assignments.push(role);
} else {
unassignments.push(role);
}
}
})
}
)
from(assignments).pipe(switchMap((role) => this.roleService.assignRole(role.id, this.userid)),
catchError((err: ErrorResult, caught) => {
this.success = false;
this.errors.push(err);
return [];
}
)
).subscribe((result:HttpResponse<Role>)=> {
this.updateRole(result.body, true);
this.saved=true;
}
);
from(unassignments).pipe(switchMap((role) => this.roleService.unAssignRole(role.id, this.userid)),
catchError((err: ErrorResult, caught) => {
this.success = false;
this.errors.push(err);
return [];
}
)
).subscribe(result=>{
this.updateRole(result.body,false);
this.saved=true;
});
this.saved=true;
}
private updateRole(role:Role, assignment:boolean) : void {
if (role!=null) {
if (role.template_instance) {
this.currentRoles.templateRoleInstances.forEach((templMap, resource)=>{
templMap.forEach((tmplRole, modelId)=> {
if (tmplRole.id == role.id) {
Util.deepCopy(role, tmplRole, false);
tmplRole.assigned = assignment;
}
}
)
})
} else {
let target = this.currentRoles.baseRoles.find(baseRole => baseRole.id == role.id);
Util.deepCopy(role, target, false);
target.assigned = assignment;
}
}
}
ngAfterViewInit(): void {
this.roles$.subscribe(roleResult => this.currentRoles = roleResult);
}
} | the_stack |
import { RequestError } from "./botgram";
// Chat / User types
export type Chat =
chatUser |
chatGroup |
chatSupergroup |
chatChannel;
interface ChatBase {
id: number;
type: string;
name: string;
username?: string;
smallPhoto?: File;
bigPhoto?: File;
}
export interface chatUser extends ChatBase {
type: "user";
firstname: string;
lastname: string | null;
language?: string;
}
export interface chatGroup extends ChatBase {
type: "group";
title: string;
allMembersAreAdmins?: boolean;
}
export interface chatSupergroup extends ChatBase {
type: "supergroup";
title: string;
description?: string;
inviteLink?: string;
}
export interface chatChannel extends ChatBase {
type: "channel";
title: string;
description?: string;
inviteLink?: string;
}
export type User = chatUser;
// Message types
export type Message =
messageText |
messageAudio |
messageDocument |
messagePhoto |
messageSticker |
messageVideo |
messageVideoNote |
messageVoice |
messageContact |
messageLocation |
messageVenue |
messageGame |
messageUpdate;
interface MessageBase {
id: number;
type: string | undefined;
date: Date;
editDate?: Date;
queued: boolean;
edited?: boolean;
chat: Chat;
user?: chatUser;
group?: chatGroup | chatSupergroup;
from?: User;
forward?: {
date: Date;
id?: string;
chat?: Chat;
from?: User;
};
reply?: Message;
}
interface messageTextBase extends MessageBase {
type: "text";
text: string;
entities: MessageEntity[];
mentions(): string[];
hashtags(): string[];
mentions(x: string): number;
hashtags(x: string): number;
}
export type messageText = messageNonCommand | messageCommand;
export interface messageNonCommand extends messageTextBase {
command: false;
}
export interface messageCommand extends messageTextBase {
command: string;
args(): string;
args(N: number): string[];
username: string | null;
mine: boolean;
exclusive: boolean;
}
export interface messageAudio extends MessageBase {
type: "audio";
duration: number;
file: File;
performer?: string;
title?: string;
}
export interface messageDocument extends MessageBase {
type: "document";
file: File;
filename?: string;
thumbnail?: Image;
}
export interface messagePhoto extends MessageBase, Photo {
type: "photo";
caption?: string;
}
export interface messageSticker extends MessageBase, Sticker {
type: "sticker";
}
export interface messageVideo extends MessageBase {
type: "video";
file: File;
width: number;
height: number;
duration: number;
thumbnail?: Image;
caption?: string;
}
export interface messageVideoNote extends MessageBase {
type: "videoNote";
length: number;
duration: number;
file: File;
thumbnail?: Image;
}
export interface messageVoice extends MessageBase {
type: "voice";
duration: number;
file: File;
}
export interface messageContact extends MessageBase {
type: "contact";
phone: string;
firstname: string;
lastname?: string;
userId?: number;
}
export interface messageLocation extends MessageBase, Location {
type: "location";
}
export interface messageVenue extends MessageBase {
type: "venue";
location: Location;
title: string;
address: string;
foursquareId?: string;
}
export interface messageGame extends MessageBase {
type: "game";
title: string;
description: string;
photo: Photo;
text?: string;
entities?: MessageEntity[];
animation?: Animation;
}
export type messageUpdate =
messageUpdateMember |
messageUpdateTitle |
messageUpdatePhoto |
messageUpdateChat;
export interface messageUpdateMember extends MessageBase {
type: "update";
subject: "member";
action: "new" | "leave";
member?: User;
members?: User[];
}
export interface messageUpdateTitle extends MessageBase {
type: "update";
subject: "title";
action: "new";
title?: String;
}
export interface messageUpdatePhoto extends MessageBase {
type: "update";
subject: "photo";
action: "new" | "delete";
photo?: Photo;
}
export interface messageUpdateChat extends MessageBase {
type: "update";
subject: "chat";
action: "create" | "migrateTo" | "migrateFrom";
toId?: number;
fromId?: number;
}
export interface messageUpdateMessage extends MessageBase {
type: "update";
subject: "message";
action: "pin";
message?: Message;
}
/**
* This is not included in Message union because it prevents TS from inferring correctly.
* If you need to process unknown messages, cast manually.
*/
export interface messageUnknown extends MessageBase {
type: undefined;
unparsed: any;
}
// MessageEntity
export type MessageEntity =
messageEntityMention |
messageEntityHashtag |
messageEntityBotCommand |
messageEntityUrl |
messageEntityEmail |
messageEntityBold |
messageEntityItalic |
messageEntityCode |
messageEntityPre |
messageEntityTextLink |
messageEntityTextMention;
interface MessageEntityBase {
type: string;
offset: number;
length: number;
}
export interface messageEntityMention extends MessageEntityBase {
type: "mention";
}
export interface messageEntityHashtag extends MessageEntityBase {
type: "hashtag";
}
export interface messageEntityBotCommand extends MessageEntityBase {
type: "bot_command";
}
export interface messageEntityUrl extends MessageEntityBase {
type: "url";
}
export interface messageEntityEmail extends MessageEntityBase {
type: "email";
}
export interface messageEntityBold extends MessageEntityBase {
type: "bold";
}
export interface messageEntityItalic extends MessageEntityBase {
type: "italic";
}
export interface messageEntityCode extends MessageEntityBase {
type: "code";
}
export interface messageEntityPre extends MessageEntityBase {
type: "pre";
}
export interface messageEntityTextLink extends MessageEntityBase {
type: "text_link";
url: string;
}
export interface messageEntityTextMention extends MessageEntityBase {
type: "text_mention";
user: User;
}
// Other types
export interface Image {
file: File;
width: number;
height: number;
}
export interface Location {
longitude: number;
latitude: number;
}
export interface File {
id: string;
size?: number;
mime?: string;
path?: string;
}
export interface Photo {
sizes: Image[];
image: Image;
}
export interface Animation {
file: File;
filename?: string;
thumbnail?: Image;
}
export interface GameHighScore {
position: number;
user: User;
score: number;
}
export interface ChatMember {
user: User,
status: "creator" | "administrator" | "member" | "restricted" | "left" | "kicked",
until?: Date;
editAllowed?: boolean;
privileges: ChatMemberPrivileges;
}
export type ChatMemberPrivileges = ChatMemberPermissions & ChatMemberRestrictions;
export interface ChatMemberPermissions {
changeInfo: boolean;
messagePost: boolean;
messageEdit: boolean;
messageDelete: boolean;
userInvite: boolean;
memberRestrict: boolean;
messagePin: boolean;
memberPromote: boolean;
}
export interface ChatMemberRestrictions {
messageSend: boolean;
messageSendMedia: boolean;
messageSendOther: boolean;
webPreviewAllow: boolean;
}
export type KeyboardButton = string | {
text: string;
request?: "contact" | "location";
};
export type KeyboardRow = KeyboardButton | KeyboardButton[];
export interface InlineKeyboardButton {
text: string;
url?: string;
callback_data?: string;
switch_inline_query?: string;
switch_inline_query_current_chat?: string;
callback_game?: {};
pay?: boolean;
}
// Stickers
export interface Sticker {
file: File;
width: number;
height: number;
emoji?: string;
setName?: string;
thumbnail?: Image;
maskPosition?: MaskPosition;
}
export interface StickerSet {
name: string;
title: string;
containsMasks: boolean;
stickers: Sticker[];
}
export interface MaskPosition {
point: "forehead" | "eyes" | "mouth" | "chin";
shift: { x: number; y: number; };
scale: number;
}
// Callback queries
export interface CallbackQuery {
id: string;
from: User;
message?: Message;
inlineMessageId?: string;
chatInstance?: string;
data?: string;
gameShortName?: string;
// extra fields added on facility
queued: boolean;
answer(options?: CallbackQueryAnswerOptions, callback?: (error: RequestError | null, result: true) => any): void;
}
export interface CallbackQueryAnswerOptions {
alert?: boolean;
text?: string;
url?: string;
cacheTime?: number;
}
// Inline queries
export interface InlineQuery {
id: string;
from: User;
location?: Location;
query: string;
offset: string;
}
export interface ChosenInlineResult {
id: string;
from: User;
location?: Location;
inlineMessageId?: string;
query: string;
}
// Functions! (resolvers / parsers / utilities)
export type FileLike = string | File;
export type StickerLike = FileLike | Sticker;
export type ChatLike = number | Chat;
export type MessageLike = number | Message;
export type StickerSetLike = string | StickerSet;
export type CallbackQueryLike = string | CallbackQuery;
export function resolveFile(x: FileLike): string;
export function resolveChat(x: ChatLike): number;
export function resolveMessage(x: MessageLike): number;
export function resolveSticker(x: StickerLike): string;
export function resolveStickerSet(x: StickerSetLike): string;
export type InputFile = FileLike | string /* URL */ | ReadableStream | Buffer;
export function resolveInputFile(file: InputFile): InputFile;
export function parsePhoto(photo: object, options: any): Photo;
export function parseCommand(msg: messageTextBase): messageCommand;
export function formatCommand(username: string | null | undefined | false, command: string, args?: string | string[]): string;
export function formatKeyboard(keys: KeyboardRow[]): object; | the_stack |
import type {Mutable, Class} from "@swim/util";
import {Affinity, Property, Animator} from "@swim/component";
import {AnyLength, Length, AnyR2Point, R2Point, R2Segment, R2Box, R2Circle, Transform} from "@swim/math";
import {AnyGeoPoint, GeoPoint, GeoBox} from "@swim/geo";
import {AnyColor, Color} from "@swim/style";
import {ThemeAnimator} from "@swim/theme";
import {ViewContextType, View} from "@swim/view";
import {
GraphicsView,
FillViewInit,
FillView,
StrokeViewInit,
StrokeView,
PaintingContext,
PaintingRenderer,
CanvasContext,
CanvasRenderer,
} from "@swim/graphics";
import {GeoViewInit, GeoView} from "../geo/GeoView";
import {GeoRippleOptions, GeoRippleView} from "../effect/GeoRippleView";
import type {GeoCircleViewObserver} from "./GeoCircleViewObserver";
/** @public */
export type AnyGeoCircleView = GeoCircleView | GeoCircleViewInit;
/** @public */
export interface GeoCircleViewInit extends GeoViewInit, FillViewInit, StrokeViewInit {
geoCenter?: AnyGeoPoint;
viewCenter?: AnyR2Point;
radius?: AnyLength;
hitRadius?: number;
}
/** @public */
export class GeoCircleView extends GeoView implements FillView, StrokeView {
constructor() {
super();
Object.defineProperty(this, "viewBounds", {
value: R2Box.undefined(),
writable: true,
enumerable: true,
configurable: true,
});
}
override readonly observerType?: Class<GeoCircleViewObserver>;
@Animator<GeoCircleView, GeoPoint | null, AnyGeoPoint | null>({
type: GeoPoint,
value: null,
didSetState(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.projectGeoCenter(newGeoCenter);
},
willSetValue(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.callObservers("viewWillSetGeoCenter", newGeoCenter, oldGeoCenter, this.owner);
},
didSetValue(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.setGeoBounds(newGeoCenter !== null ? newGeoCenter.bounds : GeoBox.undefined());
if (this.mounted) {
this.owner.projectCircle(this.owner.viewContext);
}
this.owner.callObservers("viewDidSetGeoCenter", newGeoCenter, oldGeoCenter, this.owner);
},
})
readonly geoCenter!: Animator<this, GeoPoint | null, AnyGeoPoint | null>;
@Animator<GeoCircleView, R2Point | null, AnyR2Point | null>({
type: R2Point,
value: R2Point.undefined(),
updateFlags: View.NeedsRender,
})
readonly viewCenter!: Animator<this, R2Point | null, AnyR2Point | null>;
@ThemeAnimator({type: Length, value: Length.zero(), updateFlags: View.NeedsRender})
readonly radius!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Color, value: null, inherits: true, updateFlags: View.NeedsRender})
readonly fill!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Color, value: null, inherits: true, updateFlags: View.NeedsRender})
readonly stroke!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Length, value: null, inherits: true, updateFlags: View.NeedsRender})
readonly strokeWidth!: ThemeAnimator<this, Length | null, AnyLength | null>;
@Property({type: Number})
readonly hitRadius!: Property<this, number | undefined>;
protected override onProject(viewContext: ViewContextType<this>): void {
super.onProject(viewContext);
this.projectCircle(viewContext);
}
protected projectGeoCenter(geoCenter: GeoPoint | null): void {
if (this.mounted) {
const viewContext = this.viewContext as ViewContextType<this>;
const viewCenter = geoCenter !== null && geoCenter.isDefined()
? viewContext.geoViewport.project(geoCenter)
: null;
this.viewCenter.setInterpolatedValue(this.viewCenter.value, viewCenter);
this.projectCircle(viewContext);
}
}
protected projectCircle(viewContext: ViewContextType<this>): void {
if (Affinity.Intrinsic >= (this.viewCenter.flags & Affinity.Mask)) { // this.viewCenter.hasAffinity(Affinity.Intrinsic)
const geoCenter = this.geoCenter.value;
const viewCenter = geoCenter !== null && geoCenter.isDefined()
? viewContext.geoViewport.project(geoCenter)
: null;
(this.viewCenter as Mutable<typeof this.viewCenter>).value = viewCenter; // this.viewCenter.setValue(viewCenter, Affinity.Intrinsic)
}
const viewFrame = viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const r = this.radius.getValue().pxValue(size);
const p0 = this.viewCenter.value;
const p1 = this.viewCenter.state;
if (p0 !== null && p1 !== null && (
viewFrame.intersectsCircle(new R2Circle(p0.x, p0.y, r)) ||
viewFrame.intersectsSegment(new R2Segment(p0.x, p0.y, p1.x, p1.y)))) {
this.setCulled(false);
} else {
this.setCulled(true);
}
}
protected override onRender(viewContext: ViewContextType<this>): void {
super.onRender(viewContext);
const renderer = viewContext.renderer;
if (renderer instanceof PaintingRenderer && !this.hidden && !this.culled) {
this.renderCircle(renderer.context, viewContext.viewFrame);
}
}
protected renderCircle(context: PaintingContext, frame: R2Box): void {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
// save
const contextFillStyle = context.fillStyle;
const contextLineWidth = context.lineWidth;
const contextStrokeStyle = context.strokeStyle;
const size = Math.min(frame.width, frame.height);
const radius = this.radius.getValue().pxValue(size);
context.beginPath();
context.arc(viewCenter.x, viewCenter.y, radius, 0, 2 * Math.PI);
const fill = this.fill.value;
if (fill !== null) {
context.fillStyle = fill.toString();
context.fill();
}
const stroke = this.stroke.value;
if (stroke !== null) {
const strokeWidth = this.strokeWidth.value;
if (strokeWidth !== null) {
context.lineWidth = strokeWidth.pxValue(size);
}
context.strokeStyle = stroke.toString();
context.stroke();
}
// restore
context.fillStyle = contextFillStyle;
context.lineWidth = contextLineWidth;
context.strokeStyle = contextStrokeStyle;
}
}
protected override renderGeoBounds(viewContext: ViewContextType<this>, outlineColor: Color, outlineWidth: number): void {
// nop
}
protected override updateGeoBounds(): void {
// nop
}
override readonly viewBounds!: R2Box;
override deriveViewBounds(): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const viewFrame = this.viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const radius = this.radius.getValue().pxValue(size);
return new R2Box(viewCenter.x - radius, viewCenter.y - radius,
viewCenter.x + radius, viewCenter.y + radius);
} else {
return R2Box.undefined();
}
}
override get popoverFrame(): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const viewFrame = this.viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const inversePageTransform = this.pageTransform.inverse();
const px = inversePageTransform.transformX(viewCenter.x, viewCenter.y);
const py = inversePageTransform.transformY(viewCenter.x, viewCenter.y);
const radius = this.radius.getValue().pxValue(size);
return new R2Box(px - radius, py - radius, px + radius, py + radius);
} else {
return this.pageBounds;
}
}
override get hitBounds(): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const viewFrame = this.viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const radius = this.radius.getValue().pxValue(size);
const hitRadius = Math.max(this.hitRadius.getValueOr(radius), radius);
return new R2Box(viewCenter.x - hitRadius, viewCenter.y - hitRadius,
viewCenter.x + hitRadius, viewCenter.y + hitRadius);
} else {
return this.viewBounds;
}
}
protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer) {
return this.hitTestCircle(x, y, renderer.context, viewContext.viewFrame, renderer.transform);
}
return null;
}
protected hitTestCircle(x: number, y: number, context: CanvasContext,
frame: R2Box, transform: Transform): GraphicsView | null {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const size = Math.min(frame.width, frame.height);
const radius = this.radius.getValue().pxValue(size);
if (this.fill.value !== null) {
const hitRadius = Math.max(this.hitRadius.getValueOr(radius), radius);
const dx = viewCenter.x - x;
const dy = viewCenter.y - y;
if (dx * dx + dy * dy < hitRadius * hitRadius) {
return this;
}
}
const strokeWidth = this.strokeWidth.value;
if (this.stroke.value !== null && strokeWidth !== null) {
// save
const contextLineWidth = context.lineWidth;
const p = transform.transform(x, y);
context.beginPath();
context.arc(viewCenter.x, viewCenter.y, radius, 0, 2 * Math.PI);
context.lineWidth = strokeWidth.pxValue(size);
const pointInStroke = context.isPointInStroke(p.x, p.y);
// restore
context.lineWidth = contextLineWidth;
if (pointInStroke) {
return this;
}
}
}
return null;
}
ripple(options?: GeoRippleOptions): GeoRippleView | null {
return GeoRippleView.ripple(this, options);
}
override init(init: GeoCircleViewInit): void {
super.init(init);
if (init.geoCenter !== void 0) {
this.geoCenter(init.geoCenter);
}
if (init.viewCenter !== void 0) {
this.viewCenter(init.viewCenter);
}
if (init.radius !== void 0) {
this.radius(init.radius);
}
if (init.hitRadius !== void 0) {
this.hitRadius(init.hitRadius);
}
if (init.fill !== void 0) {
this.fill(init.fill);
}
if (init.stroke !== void 0) {
this.stroke(init.stroke);
}
if (init.strokeWidth !== void 0) {
this.strokeWidth(init.strokeWidth);
}
}
} | the_stack |
import {
ActionBarAttributes,
ActionItemAttributes,
ActivityIndicatorAttributes,
ButtonAttributes,
ContentViewAttributes,
DatePickerAttributes,
FormattedStringAttributes,
SpanAttributes,
HtmlViewAttributes,
ImageAttributes,
LabelAttributes,
AbsoluteLayoutAttributes,
DockLayoutAttributes,
FlexboxLayoutAttributes,
GridLayoutAttributes,
StackLayoutAttributes,
WrapLayoutAttributes,
ListPickerAttributes,
ListViewAttributes,
NavigationButtonAttributes,
PlaceholderAttributes,
ProgressAttributes,
ScrollViewAttributes,
SearchBarAttributes,
SegmentedBarAttributes,
SegmentedBarItemAttributes,
SliderAttributes,
SwitchAttributes,
TabViewAttributes,
TabViewItemAttributes,
TextViewAttributes,
TextFieldAttributes,
TimePickerAttributes,
WebViewAttributes,
FrameAttributes,
PageAttributes,
TabsAttributes,
BottomNavigationAttributes,
TabStripAttributes,
TabStripItemAttributes,
TabContentItemAttributes,
ViewBaseAttributes,
ViewAttributes,
} from "./lib/react-nativescript-jsx";
import {
ActionBar,
ActionItem,
ActivityIndicator,
Button,
ContentView,
DatePicker,
HtmlView,
Label,
AbsoluteLayout,
DockLayout,
FlexboxLayout,
GridLayout,
StackLayout,
WrapLayout,
ListPicker,
ListView,
NavigationButton,
Placeholder,
Progress,
ScrollView,
SearchBar,
SegmentedBar,
Slider,
Switch,
TabView,
TabViewItem,
TextView,
TextField,
TimePicker,
Frame,
Page,
FormattedString,
SegmentedBarItem,
Span,
Image,
WebView,
View,
Application,
Tabs,
TabStrip,
TabStripItem,
BottomNavigation,
TabContentItem,
} from "@nativescript/core";
import { RNSStyle, NativeScriptAttributes, NativeScriptProps } from "./shared/NativeScriptJSXTypings";
export { RNSStyle, NativeScriptAttributes, NativeScriptProps };
import { __unstable__forwardNavOpts } from "./nativescript-vue-next/runtime/navigation";
export { __unstable__forwardNavOpts };
import * as ReactReconciler from "react-reconciler";
import * as React from "react";
import { ReactPortal, createElement, createRef } from "react";
import * as console from "./shared/Logger";
const { run, hasLaunched, getRootView } = Application;
import { reactReconcilerInst } from "./client/HostConfig";
import { Container } from "./shared/HostConfigTypes";
import { createPortal as _createPortal } from "./client/ReactPortal";
import {
NSVRoot,
NSVElement,
NSVNode,
NSVComment,
NSVText,
NSVNodeTypes,
NSVViewFlags,
} from "./nativescript-vue-next/runtime/nodes";
export { NSVRoot, NSVElement, NSVNode, NSVComment, NSVText, NSVNodeTypes, NSVViewFlags };
const { version: ReactNativeScriptVersion } = require("../package.json");
export {
ActionBarAttributes,
ActionItemAttributes,
ActivityIndicatorAttributes,
ButtonAttributes,
ContentViewAttributes,
DatePickerAttributes,
FormattedStringAttributes,
SpanAttributes,
HtmlViewAttributes,
ImageAttributes,
LabelAttributes,
AbsoluteLayoutAttributes,
DockLayoutAttributes,
FlexboxLayoutAttributes,
GridLayoutAttributes,
StackLayoutAttributes,
WrapLayoutAttributes,
ListPickerAttributes,
ListViewAttributes,
NavigationButtonAttributes,
PlaceholderAttributes,
ProgressAttributes,
ScrollViewAttributes,
SearchBarAttributes,
SegmentedBarAttributes,
SegmentedBarItemAttributes,
SliderAttributes,
SwitchAttributes,
TabViewAttributes,
TabViewItemAttributes,
TextViewAttributes,
TextFieldAttributes,
TimePickerAttributes,
WebViewAttributes,
FrameAttributes,
PageAttributes,
TabsAttributes,
BottomNavigationAttributes,
TabStripAttributes,
TabStripItemAttributes,
TabContentItemAttributes,
ViewBaseAttributes,
ViewAttributes,
};
export { registerElement } from "./nativescript-vue-next/runtime/registry";
export { ListView, CellViewContainer } from "./components/ListView";
export { StyleSheet } from "./client/StyleSheet";
// declare global {
// var __DEV__: boolean|undefined;
// }
// declare let __DEV__: boolean|undefined;
// https://blog.atulr.com/react-custom-renderer-1/
export function createPortal(
children: ReactReconciler.ReactNodeList,
// ReactFabric passes in a containerTag rather than a container; hope it can figure out how to re-use a root when the container is null :/
container: Container,
key: string | null = null
): ReactPortal {
// invariant(
// isValidContainer(container),
// 'Target container is not a DOM element.',
// );
// TODO (from Facebook): pass ReactDOM portal implementation as third argument
const portal = _createPortal(children, container, null, key);
// console.log(`Created portal:`, portal);
return portal;
}
type RootKey = Container | string | null;
const roots = new Map<RootKey, ReactReconciler.FiberRoot>();
/**
* React NativeScript can render into any container that extends View,
* but it makes sense to use the Frame > Page model if your whole app
* (rather than a portion of it) will be described using React NativeScript.
*
* @param reactElement - Your <App/> component.
* @param domElement - Your root component; typically Page, but can be any View. Accepts null for a detached tree.
* @param callback - A callback to run after the component (typically <App/>) is rendered.
* @param containerTag - A unique key by which to keep track of the root (useful when the domElement is null).
* 'roots' with reference to: https://github.com/facebook/react/blob/ef4ac42f8893afd0240d2679db7438f1b599bbd4/packages/react-native-renderer/src/ReactFabric.js#L119
* @returns a ref to the container.
*/
export function render(
reactElement: ReactReconciler.ReactNodeList,
domElement: Container | null,
callback: () => void | null | undefined = () => undefined,
containerTag: string | null = null
) {
const key: RootKey = containerTag || domElement;
let root: ReactReconciler.FiberRoot = roots.get(key);
if (!root) {
root = reactReconcilerInst.createContainer(domElement, false, false);
roots.set(key, root);
}
reactReconcilerInst.updateContainer(reactElement, root, null, callback);
return reactReconcilerInst.getPublicRootInstance(root);
}
// https://github.com/facebook/react/blob/61f62246c8cfb76a4a19d1661eeaa5822ec37b36/packages/react-native-renderer/src/ReactNativeRenderer.js#L139
/**
* Calls removeChildFromContainer() to make the container remove its immediate child.
* If said container is null (i.e. a detached tree), note that null.removeChild() doesn't exist, so it's a no-op.
* Either way, it'll delete our reference to the root and thus should remove the React association from it.
* @param containerTag - the key uniquely identifying this root (either the container itself, or a string).
*/
export function unmountComponentAtNode(containerTag: RootKey): void {
const root: ReactReconciler.FiberRoot = roots.get(containerTag);
if (!root) return;
// TODO (from FB): Is it safe to reset this now or should I wait since this unmount could be deferred?
reactReconcilerInst.updateContainer(null, root, null, () => {
roots.delete(containerTag);
});
}
/*
* https://github.com/reduxjs/react-redux/issues/1392
* https://github.com/facebook/react/blob/b15bf36750ca4c4a5a09f2de76c5315ded1258d0/packages/react-native-renderer/src/ReactNativeRenderer.js#L230
*/
export const unstable_batchedUpdates = reactReconcilerInst.batchedUpdates;
/**
* Convenience function to start your React NativeScript app.
* This should be placed as the final line of your app.ts file, as no
* code will run after it (at least on iOS).
*
* @param app - Your <App/> component.
*/
export function start(app: ReactReconciler.ReactNodeList): void {
const existingRootView: View | undefined = getRootView();
const _hasLaunched: boolean = hasLaunched();
console.log(
`[ReactNativeScript.ts] start(). hasLaunched(): ${_hasLaunched} existing rootView was: ${existingRootView}`
);
if (_hasLaunched || existingRootView) {
console.log(`[ReactNativeScript.ts] start() called again - hot reload, so shall no-op`);
/* As typings say, indeed reloadPage() doesn't exist. Maybe it's just a Vue thing. */
// if(existingRootView instanceof Frame){
// console.log(`[renderIntoRootView] hot reload: calling reloadPage() on root frame`);
// if(existingRootView.currentPage){
// (existingRootView as any).reloadPage();
// }
// }
return;
}
reactReconcilerInst.injectIntoDevTools({
bundleType: __DEV__ ? 1 : 0,
rendererPackageName: "react-nativescript",
version: ReactNativeScriptVersion,
});
run({
create: () => {
const root = new NSVRoot<View>();
render(app, root, () => console.log(`Container updated!`), "__APP_ROOT__");
return root.baseRef.nativeView;
},
});
}
declare global {
module JSX {
interface IntrinsicElements {
absoluteLayout: NativeScriptProps<AbsoluteLayoutAttributes, AbsoluteLayout>;
actionBar: NativeScriptProps<ActionBarAttributes, ActionBar>;
actionItem: NativeScriptProps<ActionItemAttributes, ActionItem>;
activityIndicator: NativeScriptProps<ActivityIndicatorAttributes, ActivityIndicator>;
button: NativeScriptProps<ButtonAttributes, Button>;
bottomNavigation: NativeScriptProps<BottomNavigationAttributes, BottomNavigation>;
contentView: NativeScriptProps<ContentViewAttributes, ContentView>;
datePicker: NativeScriptProps<DatePickerAttributes, DatePicker>;
dockLayout: NativeScriptProps<DockLayoutAttributes, DockLayout>;
flexboxLayout: NativeScriptProps<FlexboxLayoutAttributes, FlexboxLayout>;
formattedString: NativeScriptProps<FormattedStringAttributes, FormattedString>;
frame: NativeScriptProps<FrameAttributes, Frame>;
gridLayout: NativeScriptProps<GridLayoutAttributes, GridLayout>;
htmlView: NativeScriptProps<HtmlViewAttributes, HtmlView>;
image: NativeScriptProps<ImageAttributes, Image>;
label: NativeScriptProps<LabelAttributes, Label>;
listPicker: NativeScriptProps<ListPickerAttributes, ListPicker>;
listView: NativeScriptProps<ListViewAttributes, ListView>;
navigationButton: NativeScriptProps<NavigationButtonAttributes, NavigationButton>;
page: NativeScriptProps<PageAttributes, Page>;
placeholder: NativeScriptProps<PlaceholderAttributes, Placeholder>;
progress: NativeScriptProps<ProgressAttributes, Progress>;
scrollView: NativeScriptProps<ScrollViewAttributes, ScrollView>;
searchBar: NativeScriptProps<SearchBarAttributes, SearchBar>;
segmentedBar: NativeScriptProps<SegmentedBarAttributes, SegmentedBar>;
segmentedBarItem: NativeScriptProps<SegmentedBarItemAttributes, SegmentedBarItem>;
slider: NativeScriptProps<SliderAttributes, Slider>;
span: NativeScriptProps<SpanAttributes, Span>;
stackLayout: NativeScriptProps<StackLayoutAttributes, StackLayout>;
switch: NativeScriptProps<SwitchAttributes, Switch>;
tabs: NativeScriptProps<TabsAttributes, Tabs>;
tabStrip: NativeScriptProps<TabStripAttributes, TabStrip>;
tabStripItem: NativeScriptProps<TabStripItemAttributes, TabStripItem>;
tabContentItem: NativeScriptProps<TabContentItemAttributes, TabContentItem>;
tabView: NativeScriptProps<TabViewAttributes, TabView>;
tabViewItem: NativeScriptProps<TabViewItemAttributes, TabViewItem>;
textField: NativeScriptProps<TextFieldAttributes, TextField>;
textView: NativeScriptProps<TextViewAttributes, TextView>;
timePicker: NativeScriptProps<TimePickerAttributes, TimePicker>;
webView: NativeScriptProps<WebViewAttributes, WebView>;
wrapLayout: NativeScriptProps<WrapLayoutAttributes, WrapLayout>;
}
interface ElementChildrenAttribute {
children: {};
}
}
} | the_stack |
import { inject, optional } from 'inversify';
import { VNode } from "snabbdom/vnode";
import { isCtrlOrCmd } from "../../utils/browser";
import { matchesKeystroke } from "../../utils/keyboard";
import { toArray } from '../../utils/iterable';
import { SChildElement, SModelElement, SModelRoot, SParentElement } from '../../base/model/smodel';
import { findParentByFeature } from "../../base/model/smodel-utils";
import { Action } from "../../base/actions/action";
import { Command, CommandExecutionContext } from "../../base/commands/command";
import { MouseListener } from "../../base/views/mouse-tool";
import { KeyListener } from "../../base/views/key-tool";
import { setClass } from "../../base/views/vnode-utils";
import { ButtonHandlerRegistry } from '../button/button-handler';
import { SButton } from '../button/model';
import { isRoutable, SRoutingHandle } from '../edit/model';
import { SwitchEditModeAction } from '../edit/edit-routing';
import { isSelectable } from "./model";
/**
* Triggered when the user changes the selection, e.g. by clicking on a selectable element. The resulting
* SelectCommand changes the `selected` state accordingly, so the elements can be rendered differently.
* This action is also forwarded to the diagram server, if present, so it may react on the selection change.
* Furthermore, the server can send such an action to the client in order to change the selection programmatically.
*/
export class SelectAction implements Action {
kind = SelectCommand.KIND;
constructor(public readonly selectedElementsIDs: string[] = [],
public readonly deselectedElementsIDs: string[] = []) {
}
}
/**
* Programmatic action for selecting or deselecting all elements.
*/
export class SelectAllAction implements Action {
kind = SelectAllCommand.KIND;
/**
* If `select` is true, all elements are selected, othewise they are deselected.
*/
constructor(public readonly select: boolean = true) {
}
}
export type ElementSelection = {
element: SChildElement
parent: SParentElement
index: number
};
export class SelectCommand extends Command {
static readonly KIND = 'elementSelected';
protected selected: ElementSelection[] = [];
protected deselected: ElementSelection[] = [];
constructor(public action: SelectAction) {
super();
}
execute(context: CommandExecutionContext): SModelRoot {
const model = context.root;
this.action.selectedElementsIDs.forEach(id => {
const element = model.index.getById(id);
if (element instanceof SChildElement && isSelectable(element)) {
this.selected.push({
element,
parent: element.parent,
index: element.parent.children.indexOf(element)
});
}
});
this.action.deselectedElementsIDs.forEach(id => {
const element = model.index.getById(id);
if (element instanceof SChildElement && isSelectable(element)) {
this.deselected.push({
element,
parent: element.parent,
index: element.parent.children.indexOf(element)
});
}
});
return this.redo(context);
}
undo(context: CommandExecutionContext): SModelRoot {
for (let i = this.selected.length - 1; i >= 0; --i) {
const selection = this.selected[i];
const element = selection.element;
if (isSelectable(element))
element.selected = false;
selection.parent.move(element, selection.index);
}
this.deselected.reverse().forEach(selection => {
if (isSelectable(selection.element))
selection.element.selected = true;
});
return context.root;
}
redo(context: CommandExecutionContext): SModelRoot {
for (let i = 0; i < this.selected.length; ++i) {
const selection = this.selected[i];
const element = selection.element;
const childrenLength = selection.parent.children.length;
selection.parent.move(element, childrenLength - 1);
}
this.deselected.forEach(selection => {
if (isSelectable(selection.element))
selection.element.selected = false;
});
this.selected.forEach(selection => {
if (isSelectable(selection.element))
selection.element.selected = true;
});
return context.root;
}
}
export class SelectAllCommand extends Command {
static readonly KIND = 'allSelected';
protected previousSelection: Record<string, boolean> = {};
constructor(public action: SelectAllAction) {
super();
}
execute(context: CommandExecutionContext): SModelRoot {
this.selectAll(context.root, this.action.select);
return context.root;
}
protected selectAll(element: SParentElement, newState: boolean): void {
if (isSelectable(element)) {
this.previousSelection[element.id] = element.selected;
element.selected = newState;
}
for (const child of element.children) {
this.selectAll(child, newState);
}
}
undo(context: CommandExecutionContext): SModelRoot {
const index = context.root.index;
for (const id in this.previousSelection) {
if (this.previousSelection.hasOwnProperty(id)) {
const element = index.getById(id);
if (element !== undefined && isSelectable(element))
element.selected = this.previousSelection[id];
}
}
return context.root;
}
redo(context: CommandExecutionContext): SModelRoot {
this.selectAll(context.root, this.action.select);
return context.root;
}
}
export class SelectMouseListener extends MouseListener {
constructor(@inject(ButtonHandlerRegistry)@optional() protected buttonHandlerRegistry: ButtonHandlerRegistry) {
super();
}
wasSelected = false;
hasDragged = false;
mouseDown(target: SModelElement, event: MouseEvent): Action[] {
const result: Action[] = [];
if (event.button === 0) {
if (this.buttonHandlerRegistry !== undefined && target instanceof SButton && target.enabled) {
const buttonHandler = this.buttonHandlerRegistry.get(target.type);
if (buttonHandler !== undefined)
return buttonHandler.buttonPressed(target);
}
const selectableTarget = findParentByFeature(target, isSelectable);
if (selectableTarget !== undefined || target instanceof SModelRoot) {
this.hasDragged = false;
let deselect: SModelElement[] = [];
// multi-selection?
if (!isCtrlOrCmd(event)) {
deselect = toArray(target.root.index.all()
.filter(element => isSelectable(element) && element.selected
&& !(selectableTarget instanceof SRoutingHandle && element === selectableTarget.parent as SModelElement)));
}
if (selectableTarget !== undefined) {
if (!selectableTarget.selected) {
this.wasSelected = false;
result.push(new SelectAction([selectableTarget.id], deselect.map(e => e.id)));
const routableDeselect = deselect.filter(e => isRoutable(e)).map(e => e.id);
if (isRoutable(selectableTarget))
result.push(new SwitchEditModeAction([selectableTarget.id], routableDeselect));
else if (routableDeselect.length > 0)
result.push(new SwitchEditModeAction([], routableDeselect));
} else if (isCtrlOrCmd(event)) {
this.wasSelected = false;
result.push(new SelectAction([], [selectableTarget.id]));
if (isRoutable(selectableTarget))
result.push(new SwitchEditModeAction([], [selectableTarget.id]));
} else {
this.wasSelected = true;
}
} else {
result.push(new SelectAction([], deselect.map(e => e.id)));
const routableDeselect = deselect.filter(e => isRoutable(e)).map(e => e.id);
if (routableDeselect.length > 0)
result.push(new SwitchEditModeAction([], routableDeselect));
}
}
}
return result;
}
mouseMove(target: SModelElement, event: MouseEvent): Action[] {
this.hasDragged = true;
return [];
}
mouseUp(target: SModelElement, event: MouseEvent): Action[] {
if (event.button === 0) {
if (!this.hasDragged) {
const selectableTarget = findParentByFeature(target, isSelectable);
if (selectableTarget !== undefined && this.wasSelected) {
return [new SelectAction([selectableTarget.id], [])];
}
}
}
this.hasDragged = false;
return [];
}
decorate(vnode: VNode, element: SModelElement): VNode {
const selectableTarget = findParentByFeature(element, isSelectable);
if (selectableTarget !== undefined)
setClass(vnode, 'selected', selectableTarget.selected);
return vnode;
}
}
export class SelectKeyboardListener extends KeyListener {
keyDown(element: SModelElement, event: KeyboardEvent): Action[] {
if (matchesKeystroke(event, 'KeyA', 'ctrlCmd')) {
const selected = toArray(element.root.index.all().filter(e => isSelectable(e)).map(e => e.id));
return [new SelectAction(selected, [])];
}
return [];
}
} | the_stack |
import { Loki } from "../../src/loki";
import { Collection } from "../../src/collection";
describe("cloning behavior", () => {
interface User {
name: string;
owner: string;
maker: string;
}
let db: Loki;
let items: Collection<User>;
beforeEach(() => {
db = new Loki("cloningDisabled");
items = db.addCollection<User>("items");
items.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
items.insert({name: "gungnir", owner: "odin", maker: "elves"});
items.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
items.insert({name: "draupnir", owner: "odin", maker: "elves"});
});
describe("cloning disabled", () => {
it("works", () => {
const mj = items.findOne({name: "mjolnir"});
// you are modifying the actual object instance so this is worst case
// where you modify that object and dont even call update().
// this is not recommended, you should definately call update after modifying an object.
mj.maker = "the dwarves";
const mj2 = items.findOne({name: "mjolnir"});
expect(mj2.maker).toBe("the dwarves");
});
});
describe("cloning inserts are immutable", () => {
it("works", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<User>("items", {clone: true});
const oldObject = {name: "mjolnir", owner: "thor", maker: "dwarves"};
const insObject = citems.insert(oldObject);
// cant' have either of these polluting our collection
oldObject.name = "mewmew";
insObject.name = "mewmew";
const result = citems.findOne({"owner": "thor"});
expect(result.name).toBe("mjolnir");
});
});
describe("cloning Date and Arrays", () => {
it("deep", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<{ some: Date, other: (number | string | Date)[] }>("items", {
clone: true,
cloneMethod: "deep",
defaultLokiOperatorPackage : "loki"
});
const oldObject = {
some: new Date("July 21, 1983 01:14:00"),
other: [1, "2", 3, "4", new Date("July 21, 1983 01:15:00"), new Date("July 21, 1983 01:16:00")]
};
const insObject = citems.insert(oldObject);
oldObject.some = new Date("July 21, 1982 01:15:00");
oldObject.other = ["2", 1, "3", new Date("July 22, 1983 01:15:00"), "4"];
insObject.some = new Date("July 21, 1981 01:15:00");
insObject.other = ["3", 4, "7", new Date("July 20, 1983 01:15:00"), 5];
const result = citems.findOne({"some": {$eq: new Date("July 21, 1983 01:14:00")}});
expect(result.other).not.toEqual(oldObject.other);
expect(result.other).not.toEqual(insObject.other);
});
it("shallow-recursive", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<{ some: Date, other: (number | string | Date)[] }>("items", {
clone: true,
cloneMethod: "shallow-recurse",
defaultLokiOperatorPackage : "loki"
});
const oldObject = {
some: new Date("July 21, 1983 01:14:00"),
other: [1, "2", 3, "4", new Date("July 21, 1983 01:15:00"), new Date("July 21, 1983 01:16:00")]
};
const insObject = citems.insert(oldObject);
oldObject.some = new Date("July 21, 1982 01:15:00");
oldObject.other = ["2", 1, "3", new Date("July 22, 1983 01:15:00"), "4"];
insObject.some = new Date("July 21, 1981 01:15:00");
insObject.other = ["3", 4, "7", new Date("July 20, 1983 01:15:00"), 5];
const result = citems.findOne({"some": {$eq: new Date("July 21, 1983 01:14:00")}});
expect(result.other).not.toEqual(oldObject.other);
expect(result.other).not.toEqual(insObject.other);
});
it("parse-stringify", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<{ some: Date | string, other: (number | string | Date)[] }>("items", {
clone: true,
cloneMethod: "parse-stringify",
defaultLokiOperatorPackage : "loki"
});
const oldObject = {
some: new Date("July 21, 1983 01:14:00"),
other: [1, "2", 3, "4", new Date("July 21, 1983 01:15:00"), new Date("July 21, 1983 01:16:00")]
};
const insObject = citems.insert(oldObject);
oldObject.some = new Date("July 21, 1982 01:15:00");
oldObject.other = ["2", 1, "3", new Date("July 22, 1983 01:15:00"), "4"];
insObject.some = new Date("July 21, 1981 01:15:00");
insObject.other = ["3", 4, "7", new Date("July 20, 1983 01:15:00"), 5];
const result = citems.findOne({ "some": (new Date("July 21, 1983 01:14:00")).toISOString() });
expect(result.other).not.toEqual(oldObject.other);
expect(result.other).not.toEqual(insObject.other);
});
});
describe("cloning insert events emit cloned object", function () {
it("works", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<User & { count: number }>("items", {clone: true});
citems.on("insert", (obj: User) => {
/// attempt to tamper with name
obj.name = "zzz";
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves", count: 0});
citems.insert({name: "gungnir", owner: "odin", maker: "elves", count: 0});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves", count: 0});
citems.insert({name: "draupnir", owner: "odin", maker: "elves", count: 0});
const results = citems.find();
expect(results.length).toEqual(4);
results.forEach((obj) => {
expect(obj.name === "zzz").toEqual(false);
});
});
});
describe("cloning updates are immutable", () => {
it("works", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<User>("items", {clone: true});
const oldObject = {name: "mjolnir", owner: "thor", maker: "dwarves"};
citems.insert(oldObject);
const rObject = citems.findOne({"owner": "thor"});
// after all that, just do this to ensure internal ref is different
citems.update(rObject);
// can't have this polluting our collection
rObject.name = "mewmew";
const result = citems.findOne({"owner": "thor"});
expect(result.name).toBe("mjolnir");
});
});
describe("cloning updates events emit cloned object", function () {
it("works", () => {
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<User & { count: number }>("items", {clone: true});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves", count: 0});
citems.insert({name: "gungnir", owner: "odin", maker: "elves", count: 0});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves", count: 0});
citems.insert({name: "draupnir", owner: "odin", maker: "elves", count: 0});
citems.on("update", (obj: User & { count: number }) => {
/// attempt to tamper with name
obj.name = "zzz";
});
citems.findAndUpdate({name: "mjolnir"}, function (o) {
// make an approved modification
o.count++;
});
const results = citems.find();
expect(results.length).toEqual(4);
results.forEach((obj) => {
expect(obj.name === "zzz").toEqual(false);
});
const mj = citems.findOne({name: "mjolnir"});
expect(mj.count).toEqual(1);
});
});
describe("cloning method \"shallow\" save prototype", function () {
it("works", () => {
class Item {
public name: string;
public owner: string;
public maker: string;
constructor(name: string, owner: string, maker: string) {
this.name = name;
this.owner = owner;
this.maker = maker;
}
}
const cdb = new Loki("clonetest");
const citems = cdb.addCollection<User>("items", {clone: true, cloneMethod: "shallow"});
const oldObject = new Item("mjolnir", "thor", "dwarves");
const insObject = citems.insert(oldObject);
// cant' have either of these polluting our collection
oldObject.name = "mewmew";
insObject.name = "mewmew";
const result = citems.findOne({"owner": "thor"});
expect(result instanceof Item).toBe(true);
expect(result.name).toBe("mjolnir");
});
});
describe("collection find() cloning works", () => {
it("works", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
citems.insert({name: "gungnir", owner: "odin", maker: "elves"});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
citems.insert({name: "draupnir", owner: "odin", maker: "elves"});
// just to prove that ResultSet.data() is not giving the user the actual object reference we keep internally
// we will modify the object and see if future requests for that object show the change
const mj = citems.find({name: "mjolnir"})[0];
mj.maker = "the dwarves";
const mj2 = citems.find({name: "mjolnir"})[0];
expect(mj2.maker).toBe("dwarves");
});
it("works with stringify", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true,
cloneMethod: "parse-stringify"
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
citems.insert({name: "gungnir", owner: "odin", maker: "elves"});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
citems.insert({name: "draupnir", owner: "odin", maker: "elves"});
// just to prove that ResultSet.data() is not giving the user the actual object reference we keep internally
// we will modify the object and see if future requests for that object show the change
const mj = citems.find({name: "mjolnir"})[0];
mj.maker = "the dwarves";
const mj2 = citems.find({name: "mjolnir"})[0];
expect(mj2.maker).toBe("dwarves");
});
});
describe("collection findOne() cloning works", () => {
it("works", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
citems.insert({name: "gungnir", owner: "odin", maker: "elves"});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
citems.insert({name: "draupnir", owner: "odin", maker: "elves"});
// just to prove that ResultSet.data() is not giving the user the actual object reference we keep internally
// we will modify the object and see if future requests for that object show the change
const mj = citems.findOne({name: "mjolnir"});
mj.maker = "the dwarves";
const mj2 = citems.findOne({name: "mjolnir"});
expect(mj2.maker).toBe("dwarves");
});
});
describe("collection where() cloning works", () => {
it("works", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
citems.insert({name: "gungnir", owner: "odin", maker: "elves"});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
citems.insert({name: "draupnir", owner: "odin", maker: "elves"});
// just to prove that ResultSet.data() is not giving the user the actual object reference we keep internally
// we will modify the object and see if future requests for that object show the change
const mj = citems.where((obj: User) => obj.name === "mjolnir")[0];
mj.maker = "the dwarves";
const mj2 = citems.where((obj: User) => obj.name === "mjolnir")[0];
expect(mj2.maker).toBe("dwarves");
});
});
describe("collection by() cloning works", () => {
it("works", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true,
unique: ["name"]
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
citems.insert({name: "gungnir", owner: "odin", maker: "elves"});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
citems.insert({name: "draupnir", owner: "odin", maker: "elves"});
// just to prove that ResultSet.data() is not giving the user the actual object reference we keep internally
// we will modify the object and see if future requests for that object show the change
const mj = citems.by("name", "mjolnir");
mj.maker = "the dwarves";
const mj2 = citems.by("name", "mjolnir");
expect(mj2.maker).toBe("dwarves");
});
});
describe("collection by() cloning works with no data", () => {
it("works", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true,
unique: ["name"]
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
// we dont have any items so this should return null
let result = citems.by("name", "gungnir");
expect(result).toEqual(null);
result = citems.by("name", "mjolnir");
expect(result.owner).toEqual("thor");
});
});
describe("ResultSet data cloning works", () => {
it("works", () => {
const cdb = new Loki("cloningEnabled");
const citems = cdb.addCollection<User>("items", {
clone: true
});
citems.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
citems.insert({name: "gungnir", owner: "odin", maker: "elves"});
citems.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
citems.insert({name: "draupnir", owner: "odin", maker: "elves"});
// just to prove that ResultSet.data() is not giving the user the actual object reference we keep internally
// we will modify the object and see if future requests for that object show the change
const mj = citems.chain().find({name: "mjolnir"}).data()[0];
mj.maker = "the dwarves";
const mj2 = citems.findOne({name: "mjolnir"});
expect(mj2.maker).toBe("dwarves");
});
});
describe("ResultSet data forced cloning works", () => {
it("works", () => {
// although our collection does not define cloning, we can choose to clone results
// within ResultSet.data() options
const mj = items.chain().find({name: "mjolnir"}).data({
forceClones: true
})[0];
mj.maker = "the dwarves";
const mj2 = items.findOne({name: "mjolnir"});
expect(mj2.maker).toBe("dwarves");
});
});
}); | the_stack |
import * as vscode from "vscode";
import { Context, Direction, Lines, NotASelectionError, Positions, SelectionBehavior, Shift } from ".";
import { execRange, splitRange } from "../utils/regexp";
/**
* Sets the selections of the given editor.
*
* @param editor A `vscode.TextEditor` whose selections will be updated, or
* `undefined` to update the selections of the active text editor.
*
* ### Example
*
* ```js
* const start = new vscode.Position(0, 6),
* end = new vscode.Position(0, 11);
*
* setSelections([new vscode.Selection(start, end)]);
* ```
*
* Before:
* ```
* hello world
* ^ 0
* ```
*
* After:
* ```
* hello world
* ^^^^^ 0
* ```
*
* ### Example
* ```js
* assert.throws(() => setSelections([]), EmptySelectionsError);
* assert.throws(() => setSelections([1 as any]), NotASelectionError);
* ```
*/
export function setSelections(selections: readonly vscode.Selection[], context = Context.current) {
NotASelectionError.throwIfNotASelectionArray(selections);
context.selections = selections;
Selections.reveal(selections[0], context);
return selections;
}
/**
* Removes selections that do not match the given predicate.
*
* @param selections The `vscode.Selection` array to filter from, or `undefined`
* to filter the selections of the active text editor.
*
* ### Example
*
* ```js
* const atChar = (character: number) => new vscode.Position(0, character);
*
* assert.deepStrictEqual(
* filterSelections((text) => !isNaN(+text)),
* [new vscode.Selection(atChar(4), atChar(7))],
* );
* ```
*
* With:
* ```
* foo 123
* ^^^ 0
* ^^^ 1
* ```
*/
export function filterSelections(
predicate: filterSelections.Predicate<boolean>,
selections?: readonly vscode.Selection[],
): vscode.Selection[];
/**
* Removes selections that do not match the given async predicate.
*
* @param selections The `vscode.Selection` array to filter from, or `undefined`
* to filter the selections of the active text editor.
*
* ### Example
*
* ```js
* const atChar = (character: number) => new vscode.Position(0, character);
*
* assert.deepStrictEqual(
* await filterSelections(async (text) => !isNaN(+text)),
* [new vscode.Selection(atChar(4), atChar(7))],
* );
* ```
*
* With:
* ```
* foo 123
* ^^^ 0
* ^^^ 1
* ```
*/
export function filterSelections(
predicate: filterSelections.Predicate<Thenable<boolean>>,
selections?: readonly vscode.Selection[],
): Thenable<vscode.Selection[]>;
export function filterSelections(
predicate: filterSelections.Predicate<boolean> | filterSelections.Predicate<Thenable<boolean>>,
selections?: readonly vscode.Selection[],
) {
return filterSelections.byIndex(
(i, selection, document) => predicate(document.getText(selection), selection, i) as any,
selections,
) as any;
}
export namespace filterSelections {
/**
* A predicate passed to `filterSelections`.
*/
export interface Predicate<T extends boolean | Thenable<boolean>> {
(text: string, selection: vscode.Selection, index: number): T;
}
/**
* A predicate passed to `filterSelections.byIndex`.
*/
export interface ByIndexPredicate<T extends boolean | Thenable<boolean>> {
(index: number, selection: vscode.Selection, document: vscode.TextDocument): T;
}
/**
* Removes selections that do not match the given predicate.
*
* @param selections The `vscode.Selection` array to filter from, or
* `undefined` to filter the selections of the active text editor.
*/
export function byIndex(
predicate: ByIndexPredicate<boolean>,
selections?: readonly vscode.Selection[],
): vscode.Selection[];
/**
* Removes selections that do not match the given async predicate.
*
* @param selections The `vscode.Selection` array to filter from, or
* `undefined` to filter the selections of the active text editor.
*/
export function byIndex(
predicate: ByIndexPredicate<Thenable<boolean>>,
selections?: readonly vscode.Selection[],
): Thenable<vscode.Selection[]>;
export function byIndex(
predicate: ByIndexPredicate<boolean> | ByIndexPredicate<Thenable<boolean>>,
selections?: readonly vscode.Selection[],
) {
const context = Context.current,
document = context.document;
if (selections === undefined) {
selections = context.selections;
}
const firstSelection = selections[0],
firstResult = predicate(0, firstSelection, document);
if (typeof firstResult === "boolean") {
if (selections.length === 1) {
return firstResult ? [firstResult] : [];
}
const resultingSelections = firstResult ? [firstSelection] : [];
for (let i = 1; i < selections.length; i++) {
const selection = selections[i];
if (predicate(i, selection, document) as boolean) {
resultingSelections.push(selection);
}
}
return resultingSelections;
} else {
if (selections.length === 1) {
return context.then(firstResult, (value) => value ? [firstSelection] : []);
}
const promises = [firstResult];
for (let i = 1; i < selections.length; i++) {
const selection = selections[i];
promises.push(predicate(i, selection, document) as Thenable<boolean>);
}
const savedSelections = selections.slice(); // In case the original
// selections are mutated.
return context.then(Promise.all(promises), (results) => {
const resultingSelections = [];
for (let i = 0; i < results.length; i++) {
if (results[i]) {
resultingSelections.push(savedSelections[i]);
}
}
return resultingSelections;
});
}
}
}
/**
* Applies a function to all the given selections, and returns the array of all
* of its non-`undefined` results.
*
* @param selections The `vscode.Selection` array to map from, or `undefined`
* to map the selections of the active text editor.
*
* ### Example
*
* ```js
* assert.deepStrictEqual(
* mapSelections((text) => isNaN(+text) ? undefined : +text),
* [123],
* );
* ```
*
* With:
* ```
* foo 123
* ^^^ 0
* ^^^ 1
* ```
*/
export function mapSelections<T>(
f: mapSelections.Mapper<T | undefined>,
selections?: readonly vscode.Selection[],
): T[];
/**
* Applies an async function to all the given selections, and returns the array
* of all of its non-`undefined` results.
*
* @param selections The `vscode.Selection` array to map from, or `undefined`
* to map the selections of the active text editor.
*
* ### Example
*
* ```js
* assert.deepStrictEqual(
* await mapSelections(async (text) => isNaN(+text) ? undefined : +text),
* [123],
* );
* ```
*
* With:
* ```
* foo 123
* ^^^ 0
* ^^^ 1
* ```
*/
export function mapSelections<T>(
f: mapSelections.Mapper<Thenable<T | undefined>>,
selections?: readonly vscode.Selection[],
): Thenable<T[]>;
export function mapSelections<T>(
f: mapSelections.Mapper<T | undefined> | mapSelections.Mapper<Thenable<T | undefined>>,
selections?: readonly vscode.Selection[],
) {
return mapSelections.byIndex(
(i, selection, document) => f(document.getText(selection), selection, i),
selections,
) as any;
}
export namespace mapSelections {
/**
* A mapper function passed to `mapSelections`.
*/
export interface Mapper<T> {
(text: string, selection: vscode.Selection, index: number): T;
}
/**
* A mapper function passed to `mapSelections.byIndex`.
*/
export interface ByIndexMapper<T> {
(index: number, selection: vscode.Selection, document: vscode.TextDocument): T | undefined;
}
/**
* Applies a function to all the given selections, and returns the array of
* all of its non-`undefined` results.
*
* @param selections The `vscode.Selection` array to map from, or `undefined`
* to map the selections of the active text editor.
*/
export function byIndex<T>(
f: ByIndexMapper<T | undefined>,
selections?: readonly vscode.Selection[],
): T[];
/**
* Applies an async function to all the given selections, and returns the
* array of all of its non-`undefined` results.
*
* @param selections The `vscode.Selection` array to map from, or `undefined`
* to map the selections of the active text editor.
*/
export function byIndex<T>(
f: ByIndexMapper<Thenable<T | undefined>>,
selections?: readonly vscode.Selection[],
): Thenable<T[]>;
export function byIndex<T>(
f: ByIndexMapper<T | undefined> | ByIndexMapper<Thenable<T | undefined>>,
selections?: readonly vscode.Selection[],
) {
const context = Context.current,
document = context.document;
if (selections === undefined) {
selections = context.selections;
}
const firstSelection = selections[0],
firstResult = f(0, firstSelection, document);
if (firstResult === undefined || typeof (firstResult as Thenable<T>)?.then !== "function") {
const results = firstResult !== undefined ? [firstResult as T] : [];
for (let i = 1; i < selections.length; i++) {
const selection = selections[i],
value = f(i, selection, document) as T | undefined;
if (value !== undefined) {
results.push(value);
}
}
return results;
} else {
if (selections.length === 1) {
return context.then(firstResult as Thenable<T | undefined>, (result) => {
return result !== undefined ? [result] : [];
});
}
const promises = [firstResult as Thenable<T | undefined>];
for (let i = 1; i < selections.length; i++) {
const selection = selections[i],
promise = f(i, selection, document) as Thenable<T | undefined>;
promises.push(promise);
}
return context.then(Promise.all(promises), (results) => {
const filteredResults = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result !== undefined) {
filteredResults.push(result);
}
}
return filteredResults;
});
}
}
}
/**
* Sets the selections of the current editor after transforming them according
* to the given function.
*
* ### Example
*
* ```js
* const reverseUnlessNumber = (text: string, sel: vscode.Selection) =>
* isNaN(+text) ? new vscode.Selection(sel.active, sel.anchor) : undefined;
*
* updateSelections(reverseUnlessNumber);
* ```
*
* Before:
* ```
* foo 123
* ^^^ 0
* ^^^ 1
* ```
*
* After:
* ```
* foo 123
* |^^ 0
* ```
*
* ### Example
*
* ```js
* assert.throws(() => updateSelections(() => undefined), EmptySelectionsError);
* ```
*
* With:
* ```
* foo 123
* ^^^ 0
* ```
*/
export function updateSelections(
f: mapSelections.Mapper<vscode.Selection | undefined>,
context?: Context,
): vscode.Selection[];
/**
* Sets the selections of the current editor after transforming them according
* to the given async function.
*
* ### Example
*
* ```js
* const reverseIfNumber = async (text: string, sel: vscode.Selection) =>
* !isNaN(+text) ? new vscode.Selection(sel.active, sel.anchor) : undefined;
*
* await updateSelections(reverseIfNumber);
* ```
*
* Before:
* ```
* foo 123
* ^^^ 0
* ^^^ 1
* ```
*
* After:
* ```
* foo 123
* |^^ 0
* ```
*/
export function updateSelections(
f: mapSelections.Mapper<Thenable<vscode.Selection | undefined>>,
context?: Context,
): Thenable<vscode.Selection[]>;
export function updateSelections(
f: mapSelections.Mapper<vscode.Selection | undefined>
| mapSelections.Mapper<Thenable<vscode.Selection | undefined>>,
context?: Context,
): any {
const selections = mapSelections(f as any, context?.selections);
if (Array.isArray(selections)) {
return setSelections(selections, context);
}
return (selections as Thenable<vscode.Selection[]>).then((xs) => setSelections(xs, context));
}
function mapFallbackSelections(values: (vscode.Selection | readonly [vscode.Selection])[]) {
let selectionsCount = 0,
fallbackSelectionsCount = 0;
for (const value of values) {
if (Array.isArray(value)) {
fallbackSelectionsCount++;
} else if (value !== undefined) {
selectionsCount++;
}
}
if (selectionsCount > 0) {
const selections: vscode.Selection[] = [];
for (const value of values) {
if (value !== undefined && !Array.isArray(value)) {
selections.push(value as vscode.Selection);
}
}
return selections;
}
if (fallbackSelectionsCount > 0) {
const selections: vscode.Selection[] = [];
for (const value of values) {
if (Array.isArray(value)) {
selections.push(value[0]);
}
}
return selections;
}
return [];
}
export namespace updateSelections {
/**
* Sets the selections of the current editor after transforming them according
* to the given function.
*/
export function byIndex(
f: mapSelections.ByIndexMapper<vscode.Selection | undefined>,
context?: Context,
): vscode.Selection[];
/**
* Sets the selections of the current editor after transforming them according
* to the given async function.
*/
export function byIndex(
f: mapSelections.ByIndexMapper<Thenable<vscode.Selection | undefined>>,
context?: Context,
): Thenable<vscode.Selection[]>;
export function byIndex(
f: mapSelections.ByIndexMapper<vscode.Selection | undefined>
| mapSelections.ByIndexMapper<Thenable<vscode.Selection | undefined>>,
context?: Context,
): any {
const selections = mapSelections.byIndex(f as any, context?.selections);
if (Array.isArray(selections)) {
return setSelections(selections, context);
}
return (selections as Thenable<vscode.Selection[]>).then((xs) => setSelections(xs, context));
}
/**
* A possible return value for a function passed to `withFallback`. An
* array with a single selection corresponds to a fallback selection.
*/
export type SelectionOrFallback = vscode.Selection | readonly [vscode.Selection] | undefined;
/**
* Same as `updateSelections`, but additionally lets `f` return a fallback
* selection. If no selection remains after the end of the update, fallback
* selections will be used instead.
*/
export function withFallback<T extends SelectionOrFallback | Thenable<SelectionOrFallback>>(
f: mapSelections.Mapper<T>,
): T extends Thenable<SelectionOrFallback> ? Thenable<vscode.Selection[]> : vscode.Selection[] {
const selections = mapSelections(f as any);
if (Array.isArray(selections)) {
return setSelections(mapFallbackSelections(selections)) as any;
}
return (selections as Thenable<(vscode.Selection | readonly [vscode.Selection])[]>)
.then((values) => setSelections(mapFallbackSelections(values))) as any;
}
export namespace withFallback {
/**
* Same as `withFallback`, but does not pass the text of each selection.
*/
export function byIndex<T extends SelectionOrFallback | Thenable<SelectionOrFallback>>(
f: mapSelections.ByIndexMapper<T>,
): T extends Thenable<SelectionOrFallback> ? Thenable<vscode.Selection[]> : vscode.Selection[] {
const selections = mapSelections.byIndex(f as any);
if (Array.isArray(selections)) {
return setSelections(mapFallbackSelections(selections)) as any;
}
return (selections as Thenable<(vscode.Selection | readonly [vscode.Selection])[]>)
.then((values) => setSelections(mapFallbackSelections(values))) as any;
}
}
}
/**
* Rotates selections in the given direction.
*
* ### Example
*
* ```js
* setSelections(rotateSelections(1));
* ```
*
* Before:
* ```
* foo bar baz
* ^^^ 0 ^^^ 2
* ^^^ 1
* ```
*
* After:
* ```
* foo bar baz
* ^^^ 1 ^^^ 0
* ^^^ 2
* ```
*
* ### Example
*
* ```js
* setSelections(rotateSelections(-1));
* ```
*
* Before:
* ```
* foo bar baz
* ^^^ 0 ^^^ 2
* ^^^ 1
* ```
*
* After:
* ```
* foo bar baz
* ^^^ 2 ^^^ 1
* ^^^ 0
* ```
*/
export function rotateSelections(
by: Direction | number,
selections: readonly vscode.Selection[] = Context.current.selections,
) {
const len = selections.length;
// Handle negative values for `by`:
by = (by % len) + len;
if (by === len) {
return selections.slice();
}
const newSelections = new Array<vscode.Selection>(selections.length);
for (let i = 0; i < len; i++) {
newSelections[(i + by) % len] = selections[i];
}
return newSelections;
}
/**
* Returns an array containing all the unique lines included in the given or
* active selections. Though the resulting array is not sorted, it is likely
* that consecutive lines will be consecutive in the array as well.
*
* ### Example
*
* ```js
* expect(selectionsLines(), "to only contain", 0, 1, 3, 4, 5, 6);
* ```
*
* With:
* ```
* ab
* ^^ 0
* cd
* ^ 1
* ef
* gh
* ^ 2
* ^ 3
* ij
* ^ 3
* kl
* | 4
* mn
* ^^ 5
* op
* ```
*/
export function selectionsLines(
selections: readonly vscode.Selection[] = Context.current.selections,
) {
const lines: number[] = [];
for (const selection of selections) {
const startLine = selection.start.line,
endLine = Selections.endLine(selection);
// The first and last lines of the selection may contain other selections,
// so we check for duplicates with them. However, the intermediate
// lines are known to belong to one selection only, so there's no need
// for that with them.
if (lines.indexOf(startLine) === -1) {
lines.push(startLine);
}
for (let i = startLine + 1; i < endLine; i++) {
lines.push(i);
}
if (endLine !== startLine && lines.indexOf(endLine) === -1) {
lines.push(endLine);
}
}
return lines;
}
/**
* Returns the selections obtained by splitting the contents of all the given
* selections using the given RegExp.
*/
export function splitSelections(re: RegExp, selections = Context.current.selections) {
const document = Context.current.document;
return Selections.map((text, selection) => {
const offset = document.offsetAt(selection.start);
return splitRange(text, re).map(([start, end]) =>
Selections.fromStartEnd(offset + start, offset + end, selection.isReversed),
);
}, selections).flat();
}
/**
* Returns the selections obtained by finding all the matches within the given
* selections using the given RegExp.
*
* ### Example
*
* ```ts
* expect(Selections.selectWithin(/\d/).map<string>(text), "to equal", [
* "1",
* "2",
* "6",
* "7",
* "8",
* ]);
* ```
*
* With:
* ```
* a1b2c3d4
* ^^^^^ 0
* e5f6g7h8
* ^^^^^^ 1
* ```
*/
export function selectWithinSelections(re: RegExp, selections = Context.current.selections) {
const document = Context.current.document;
return Selections.map((text, selection) => {
const offset = document.offsetAt(selection.start);
return execRange(text, re).map(([start, end]) =>
Selections.fromStartEnd(offset + start, offset + end, selection.isReversed),
);
}, selections).flat();
}
/**
* Reveals selections in the current editor.
*/
export function revealSelections(selection?: vscode.Selection, context = Context.current) {
const editor = context.editor,
active = (selection ?? (editor as vscode.TextEditor).selection).active;
editor.revealRange(new vscode.Range(active, active));
}
/**
* Given an array of selections, returns an array of selections where all
* overlapping selections have been merged.
*
* ### Example
*
* Equal selections.
*
* ```ts
* expect(mergeOverlappingSelections(Selections.current), "to equal", [Selections.current[0]]);
* ```
*
* With:
* ```
* abcd
* ^^ 0
* ^^ 1
* ```
*
* ### Example
*
* Equal empty selections.
*
* ```ts
* expect(mergeOverlappingSelections(Selections.current), "to equal", [Selections.current[0]]);
* ```
*
* With:
* ```
* abcd
* | 0
* | 1
* ```
*
* ### Example
*
* Overlapping selections.
*
* ```ts
* expect(mergeOverlappingSelections(Selections.current), "to satisfy", [
* expect.it("to start at coords", 0, 0).and("to end at coords", 0, 4),
* ]);
* ```
*
* With:
* ```
* abcd
* ^^^ 0
* ^^^ 1
* ```
*
* ### Example
*
* Consecutive selections.
*
* ```ts
* expect(Selections.mergeOverlapping(Selections.current), "to equal", Selections.current);
*
* expect(Selections.mergeConsecutive(Selections.current), "to satisfy", [
* expect.it("to start at coords", 0, 0).and("to end at coords", 0, 4),
* ]);
* ```
*
* With:
* ```
* abcd
* ^^ 0
* ^^ 1
* ```
*
* ### Example
*
* Consecutive selections (reversed).
*
* ```ts
* expect(Selections.mergeOverlapping(Selections.current), "to equal", Selections.current);
*
* expect(Selections.mergeConsecutive(Selections.current), "to satisfy", [
* expect.it("to start at coords", 0, 0).and("to end at coords", 0, 4),
* ]);
* ```
*
* With:
* ```
* abcd
* ^^ 1
* ^^ 0
* ```
*/
export function mergeOverlappingSelections(
selections: readonly vscode.Selection[],
alsoMergeConsecutiveSelections = false,
) {
const len = selections.length,
ignoreSelections = new Uint8Array(selections.length);
let newSelections: vscode.Selection[] | undefined;
for (let i = 0; i < len; i++) {
if (ignoreSelections[i] === 1) {
continue;
}
const a = selections[i];
let aStart = a.start,
aEnd = a.end,
aIsEmpty = aStart.isEqual(aEnd),
changed = false;
for (let j = i + 1; j < len; j++) {
if (ignoreSelections[j] === 1) {
continue;
}
const b = selections[j],
bStart = b.start,
bEnd = b.end;
if (aIsEmpty) {
if (bStart.isEqual(bEnd)) {
if (bStart.isEqual(aStart)) {
// A and B are two equal empty selections, and we can keep A.
ignoreSelections[j] = 1;
changed = true;
} else {
// A and B are two different empty selections, we don't change
// anything.
}
continue;
}
if (bStart.isBeforeOrEqual(aStart) && bEnd.isAfterOrEqual(bStart)) {
// The empty selection A is included in B.
aStart = bStart;
aEnd = bEnd;
aIsEmpty = false;
changed = true;
ignoreSelections[j] = 1;
continue;
}
// The empty selection A is strictly before or after B.
continue;
}
if (aStart.isAfterOrEqual(bStart)
&& (aStart.isBefore(bEnd) || (alsoMergeConsecutiveSelections && aStart.isEqual(bEnd)))) {
// Selection A starts within selection B...
if (aEnd.isBeforeOrEqual(bEnd)) {
// ... and ends within selection B (it is included in selection B).
aStart = b.start;
aEnd = b.end;
} else {
// ... and ends after selection B.
if (aStart.isEqual(bStart)) {
// B is included in A: avoid creating a new selection needlessly.
ignoreSelections[j] = 1;
newSelections ??= selections.slice(0, i);
continue;
}
aStart = bStart;
}
} else if ((aEnd.isAfter(bStart) || (alsoMergeConsecutiveSelections && aEnd.isEqual(bStart)))
&& aEnd.isBeforeOrEqual(bEnd)) {
// Selection A ends within selection B. Furthermore, we know that
// selection A does not start within selection B, so it starts before
// selection B.
aEnd = bEnd;
} else {
// Selection A neither starts nor ends in selection B, so there is no
// overlap.
continue;
}
// B is NOT included in A; we must look at selections we previously saw
// again since they may now overlap with the new selection we will create.
changed = true;
ignoreSelections[j] = 1;
j = i; // `j++` above will set `j` to `i + 1`.
}
if (changed) {
// Selections have changed: make sure the `newSelections` are initialized
// and push the new selection.
if (newSelections === undefined) {
newSelections = selections.slice(0, i);
}
newSelections.push(Selections.fromStartEnd(aStart, aEnd, a.isReversed));
} else if (newSelections !== undefined) {
// Selection did not change, but a previous selection did; push existing
// selection to new array.
newSelections.push(a);
} else {
// Selections have not changed. Just keep going.
}
}
return newSelections !== undefined ? newSelections : selections;
}
/**
* Operations on `vscode.Selection`s.
*/
export namespace Selections {
export const filter = filterSelections,
lines = selectionsLines,
map = mapSelections,
reveal = revealSelections,
rotate = rotateSelections,
selectWithin = selectWithinSelections,
set = setSelections,
split = splitSelections,
update = updateSelections,
mergeOverlapping = mergeOverlappingSelections,
mergeConsecutive = (selections: readonly vscode.Selection[]) =>
mergeOverlappingSelections(selections, /* alsoMergeConsecutiveSelections= */ true);
export declare const current: readonly vscode.Selection[];
Object.defineProperty(Selections, "current", {
get() {
return Context.current.selections;
},
});
/**
* Returns a selection spanning the entire buffer.
*/
export function wholeBuffer(document = Context.current.document) {
return new vscode.Selection(Positions.zero, Positions.last(document));
}
/**
* Returns the active position (or cursor) of a selection.
*/
export function active(selection: vscode.Selection) {
return selection.active;
}
/**
* Returns the anchor position of a selection.
*/
export function anchor(selection: vscode.Selection) {
return selection.anchor;
}
/**
* Returns the start position of a selection.
*/
export function start(selection: vscode.Range) {
return selection.start;
}
/**
* Returns the end position of a selection.
*/
export function end(selection: vscode.Range) {
return selection.end;
}
/**
* Returns the given selection if it faces forward (`active >= anchor`), or
* the reverse of the given selection otherwise.
*/
export function forward(selection: vscode.Selection) {
const active = selection.active,
anchor = selection.anchor;
return active.isAfterOrEqual(anchor) ? selection : new vscode.Selection(active, anchor);
}
/**
* Returns the given selection if it faces backward (`active <= anchor`), or
* the reverse of the given selection otherwise.
*/
export function backward(selection: vscode.Selection) {
const active = selection.active,
anchor = selection.anchor;
return active.isBeforeOrEqual(anchor) ? selection : new vscode.Selection(active, anchor);
}
/**
* Returns a new empty selection starting and ending at the given position.
*/
export function empty(position: vscode.Position): vscode.Selection;
/**
* Returns a new empty selection starting and ending at the given line and
* character.
*/
export function empty(line: number, character: number): vscode.Selection;
export function empty(positionOrLine: vscode.Position | number, character?: number) {
if (typeof positionOrLine === "number") {
positionOrLine = new vscode.Position(positionOrLine, character!);
}
return new vscode.Selection(positionOrLine, positionOrLine);
}
/**
* Returns whether the two given ranges overlap.
*/
export function overlap(a: vscode.Range, b: vscode.Range) {
const aStart = a.start,
aEnd = a.end,
bStart = b.start,
bEnd = b.end;
return !(aEnd.line < bStart.line
|| (aEnd.line === bEnd.line && aEnd.character < bStart.character))
&& !(bEnd.line < aStart.line
|| (bEnd.line === aEnd.line && bEnd.character < aStart.character));
}
/**
* Returns the line of the end of the given selection. If the selection ends
* at the first character of a line and is not empty, this is equal to
* `end.line - 1`. Otherwise, this is `end.line`.
*/
export function endLine(selection: vscode.Selection | vscode.Range) {
const startLine = selection.start.line,
end = selection.end,
endLine = end.line,
endCharacter = end.character;
if (startLine !== endLine && endCharacter === 0) {
// If the selection ends after a line break, do not consider the next line
// selected. This is because a selection has to end on the very first
// caret position of the next line in order to select the last line break.
// For example, `vscode.TextLine.rangeIncludingLineBreak` does this:
// https://github.com/microsoft/vscode/blob/c8b27b9db6afc26cf82cf07a9653c89cdd930f6a/src/vs/workbench/api/common/extHostDocumentData.ts#L273
return endLine - 1;
}
return endLine;
}
/**
* Returns the character of the end of the given selection. If the selection
* ends at the first character of a line and is not empty, this is equal to
* the length of the previous line plus one. Otherwise, this is
* `end.character`.
*
* @see endLine
*/
export function endCharacter(
selection: vscode.Selection | vscode.Range,
document?: vscode.TextDocument,
) {
const startLine = selection.start.line,
end = selection.end,
endLine = end.line,
endCharacter = end.character;
if (startLine !== endLine && endCharacter === 0) {
return (document ?? Context.current.document).lineAt(endLine - 1).text.length + 1;
}
return endCharacter;
}
/**
* Returns the end position of the given selection. If the selection ends at
* the first character of a line and is not empty, this is equal to the
* position at the end of the previous line. Otherwise, this is `end`.
*/
export function endPosition(
selection: vscode.Selection | vscode.Range,
document?: vscode.TextDocument,
) {
const line = endLine(selection);
if (line !== selection.end.line) {
return new vscode.Position(
line,
(document ?? Context.current.document).lineAt(line).text.length,
);
}
return selection.end;
}
/**
* Returns the line of the active position of the given selection. If the
* selection faces forward (the active position is the end of the selection),
* returns `endLine(selection)`. Otherwise, returns `active.line`.
*/
export function activeLine(selection: vscode.Selection) {
if (selection.isReversed) {
return selection.active.line;
}
return endLine(selection);
}
/**
* Returns the character of the active position of the given selection.
*
* @see activeLine
*/
export function activeCharacter(selection: vscode.Selection, document?: vscode.TextDocument) {
if (selection.isReversed) {
return selection.active.character;
}
return endCharacter(selection, document);
}
/**
* Returns the position of the active position of the given selection.
*/
export function activePosition(selection: vscode.Selection, document?: vscode.TextDocument) {
if (selection.isReversed) {
return selection.active;
}
return endPosition(selection, document);
}
/**
* Returns whether the selection spans a single line. This differs from
* `selection.isSingleLine` because it also handles cases where the selection
* wraps an entire line (its end position is on the first character of the
* next line).
*/
export function isSingleLine(selection: vscode.Selection) {
return selection.start.line === endLine(selection);
}
/**
* Returns whether the given selection has length `1`.
*/
export function isSingleCharacter(
selection: vscode.Selection | vscode.Range,
document = Context.current.document,
) {
const start = selection.start,
end = selection.end;
if (start.line === end.line) {
return start.character === end.character - 1;
}
if (start.line === end.line - 1) {
return end.character === 0 && document.lineAt(start.line).text.length === start.character;
}
return false;
}
/**
* Returns whether the given selection has length `1` and corresponds to an
* empty selection extended by one character by `fromCharacterMode`.
*/
export function isNonDirectional(selection: vscode.Selection, context = Context.current) {
return context.selectionBehavior === SelectionBehavior.Character
&& !selection.isReversed
&& isSingleCharacter(selection, context.document);
}
/**
* The position from which a seek operation should start. This is equivalent
* to `selection.active` except when the selection is non-directional, in
* which case this is whatever position is **furthest** from the given
* direction (in order to include the current character in the search).
*
* A position other than active (typically, the `anchor`) can be specified to
* seek from that position.
*/
export function seekFrom(
selection: vscode.Selection,
direction: Direction,
position = selection.active,
context = Context.current,
) {
if (context.selectionBehavior === SelectionBehavior.Character) {
const doc = context.document;
return direction === Direction.Forward
? (position === selection.start ? position : Positions.previous(position, doc) ?? position)
: (position === selection.end ? position : Positions.next(position, doc) ?? position);
}
return position;
}
/**
* Returns the start position of the active character of the selection.
*
* If the current character behavior is `Caret`, this is `selection.active`.
*/
export function activeStart(selection: vscode.Selection, context = Context.current) {
const active = selection.active;
if (context.selectionBehavior !== SelectionBehavior.Character) {
return active;
}
const start = selection.start;
if (isSingleCharacter(selection, context.document)) {
return start;
}
return active === start ? start : Positions.previous(active, context.document)!;
}
/**
* Returns the end position of the active character of the selection.
*
* If the current character behavior is `Caret`, this is `selection.active`.
*/
export function activeEnd(selection: vscode.Selection, context = Context.current) {
const active = selection.active;
if (context.selectionBehavior !== SelectionBehavior.Character) {
return active;
}
const end = selection.end;
if (isSingleCharacter(selection, context.document)) {
return end;
}
return active === end ? end : Positions.next(active, context.document)!;
}
/**
* Returns `activeStart(selection)` if `direction === Backward`, and
* `activeEnd(selection)` otherwise.
*/
export function activeTowards(
selection: vscode.Selection,
direction: Direction,
context = Context.current,
) {
return direction === Direction.Backward
? activeStart(selection, context)
: activeEnd(selection, context);
}
/**
* Shifts the given selection to the given position using the specified
* `Shift` behavior:
* - If `Shift.Jump`, `result.active == result.anchor == position`.
* - If `Shift.Select`, `result.active == position`, `result.anchor == selection.active`.
* - If `Shift.Extend`, `result.active == position`, `result.anchor == selection.anchor`.
*
* ### Example
*
* ```js
* const s1 = Selections.empty(0, 0),
* shifted1 = Selections.shift(s1, Positions.at(0, 4), Select);
*
* expect(shifted1, "to have anchor at coords", 0, 0).and("to have cursor at coords", 0, 4);
* ```
*
* With
*
* ```
* line with 23 characters
* ```
*
* ### Example
*
* ```js
* setSelectionBehavior(SelectionBehavior.Character);
* ```
*/
export function shift(
selection: vscode.Selection,
position: vscode.Position,
shift: Shift,
context = Context.current,
) {
let anchor = shift === Shift.Jump
? position
: shift === Shift.Select
? selection.active
: selection.anchor;
if (context.selectionBehavior === SelectionBehavior.Character && shift !== Shift.Jump) {
const direction = anchor.isAfter(position) ? Direction.Backward : Direction.Forward;
anchor = seekFrom(selection, direction, anchor, context);
}
return new vscode.Selection(anchor, position);
}
/**
* Same as `shift`, but also extends the active character towards the given
* direction in character selection mode. If `direction === Forward`, the
* active character will be selected such that
* `activeEnd(selection) === active`. If `direction === Backward`, the
* active character will be selected such that
* `activeStart(selection) === active`.
*/
export function shiftTowards(
selection: vscode.Selection,
position: vscode.Position,
shift: Shift,
direction: Direction,
context = Context.current,
) {
if (context.selectionBehavior === SelectionBehavior.Character
&& direction === Direction.Backward) {
position = Positions.next(position) ?? position;
}
return Selections.shift(selection, position, shift, context);
}
/**
* Returns whether the given selection spans an entire line.
*
* ### Example
*
* ```js
* expect(Selections.isEntireLine(Selections.current[0]), "to be true");
* expect(Selections.isEntireLine(Selections.current[1]), "to be false");
* ```
*
* With:
* ```
* abc
* ^^^^ 0
*
* def
* ^^^ 1
* ```
*
* ### Example
* Use `isEntireLines` for multi-line selections.
*
* ```js
* expect(Selections.isEntireLine(Selections.current[0]), "to be false");
* ```
*
* With:
* ```
* abc
* ^^^^ 0
* def
* ^^^^ 0
*
* ```
*/
export function isEntireLine(selection: vscode.Selection | vscode.Range) {
const start = selection.start,
end = selection.end;
return start.character === 0 && end.character === 0 && start.line === end.line - 1;
}
/**
* Returns whether the given selection spans one or more entire lines.
*
* ### Example
*
* ```js
* expect(Selections.isEntireLines(Selections.current[0]), "to be true");
* expect(Selections.isEntireLines(Selections.current[1]), "to be true");
* expect(Selections.isEntireLines(Selections.current[2]), "to be false");
* ```
*
* With:
* ```
* abc
* ^^^^ 0
* def
* ^^^^ 0
* ghi
* ^^^^ 1
* jkl
* ^^^^ 2
* mno
* ^^^ 2
* ```
*/
export function isEntireLines(selection: vscode.Selection | vscode.Range) {
const start = selection.start,
end = selection.end;
return start.character === 0 && end.character === 0 && start.line !== end.line;
}
export function startsWithEntireLine(selection: vscode.Selection | vscode.Range) {
const start = selection.start;
return start.character === 0 && start.line !== selection.end.line;
}
export function endsWithEntireLine(selection: vscode.Selection | vscode.Range) {
const end = selection.end;
return end.character === 0 && selection.start.line !== end.line;
}
export function activeLineIsFullySelected(selection: vscode.Selection) {
return selection.active === selection.start
? startsWithEntireLine(selection)
: endsWithEntireLine(selection);
}
export function isMovingTowardsAnchor(selection: vscode.Selection, direction: Direction) {
return direction === Direction.Backward
? selection.active === selection.end
: selection.active === selection.start;
}
/**
* Returns the text contents of the given selection.
*
* ### Example
*
* ```js
* expect(Selections.text(Selections.current[0]), "to be", "abc\ndef");
* expect(Selections.text(Selections.current[1]), "to be", "g");
* expect(Selections.text(Selections.current[2]), "to be", "");
* ```
*
* With:
* ```
* abc
* ^^^^ 0
* def
* ^^^ 0
* ghi
* ^ 1
* | 2
* ```
*/
export function text(
selection: vscode.Selection | vscode.Range,
document = Context.current.document,
) {
return document.getText(selection);
}
/**
* Returns the length of the given selection.
*
* ### Example
*
* ```js
* expect(Selections.length(Selections.current[0]), "to be", 7);
* expect(Selections.length(Selections.current[1]), "to be", 1);
* expect(Selections.length(Selections.current[2]), "to be", 0);
* ```
*
* With:
* ```
* abc
* ^^^^ 0
* def
* ^^^ 0
* ghi
* ^ 1
* | 2
* ```
*/
export function length(
selection: vscode.Selection | vscode.Range,
document = Context.current.document,
) {
const start = selection.start,
end = selection.end;
if (start.line === end.line) {
return end.character - start.character;
}
return document.offsetAt(end) - document.offsetAt(start);
}
/**
* Returns a selection starting at the given position or offset and with the
* specified length.
*/
export function fromLength(
start: number | vscode.Position,
length: number,
reversed = false,
document = Context.current.document,
) {
let startOffset: number,
startPosition: vscode.Position;
if (length === 0) {
if (typeof start === "number") {
startPosition = document.positionAt(start);
} else {
startPosition = start;
}
return new vscode.Selection(startPosition, startPosition);
}
if (typeof start === "number") {
startOffset = start;
startPosition = document.positionAt(start);
} else {
startOffset = document.offsetAt(start);
startPosition = start;
}
const endPosition = document.positionAt(startOffset + length);
return reversed
? new vscode.Selection(endPosition, startPosition)
: new vscode.Selection(startPosition, endPosition);
}
/**
* Returns a new selection given its start and end positions. If `reversed` is
* false, the returned solution will be such that `start === anchor` and
* `end === active`. Otherwise, the returned solution will be such that
* `start === active` and `end === anchor`.
*
* ### Example
*
* ```js
* const p0 = new vscode.Position(0, 0),
* p1 = new vscode.Position(0, 1);
*
* expect(Selections.fromStartEnd(p0, p1, false), "to satisfy", {
* start: p0,
* end: p1,
* anchor: p0,
* active: p1,
* isReversed: false,
* });
*
* expect(Selections.fromStartEnd(p0, p1, true), "to satisfy", {
* start: p0,
* end: p1,
* anchor: p1,
* active: p0,
* isReversed: true,
* });
* ```
*/
export function fromStartEnd(
start: vscode.Position | number,
end: vscode.Position | number,
reversed: boolean,
document?: vscode.TextDocument,
) {
if (typeof start === "number") {
if (document === undefined) {
document = Context.current.document;
}
start = document.positionAt(start);
}
if (typeof end === "number") {
if (document === undefined) {
document = Context.current.document;
}
end = document.positionAt(end);
}
return reversed ? new vscode.Selection(end, start) : new vscode.Selection(start, end);
}
/**
* Returns the selection with the given anchor and active positions.
*/
export function fromAnchorActive(
anchor: vscode.Position,
active: vscode.Position,
): vscode.Selection;
/**
* Returns the selection with the given anchor and active positions.
*/
export function fromAnchorActive(
anchorLine: number,
anchorCharacter: number,
active: vscode.Position,
): vscode.Selection;
/**
* Returns the selection with the given anchor and active positions.
*/
export function fromAnchorActive(
anchor: vscode.Position,
activeLine: number,
activeCharacter: number,
): vscode.Selection;
/**
* Returns the selection with the given anchor and active position
* coordinates.
*/
export function fromAnchorActive(
anchorLine: number,
anchorCharacter: number,
activeLine: number,
activeCharacter: number,
): vscode.Selection;
export function fromAnchorActive(
anchorOrAnchorLine: number | vscode.Position,
activeOrAnchorCharacterOrActiveLine: number | vscode.Position,
activeOrActiveLineOrActiveCharacter?: number | vscode.Position,
activeCharacter?: number,
) {
if (activeCharacter !== undefined) {
// Four arguments: this is the last overload.
const anchorLine = anchorOrAnchorLine as number,
anchorCharacter = activeOrAnchorCharacterOrActiveLine as number,
activeLine = activeOrActiveLineOrActiveCharacter as number;
return new vscode.Selection(anchorLine, anchorCharacter, activeLine, activeCharacter);
}
if (activeOrActiveLineOrActiveCharacter === undefined) {
// Two arguments: this is the first overload.
const anchor = anchorOrAnchorLine as vscode.Position,
active = activeOrAnchorCharacterOrActiveLine as vscode.Position;
return new vscode.Selection(anchor, active);
}
if (typeof activeOrActiveLineOrActiveCharacter === "number") {
// Third argument is a number: this is the third overload.
const anchor = anchorOrAnchorLine as vscode.Position,
activeLine = activeOrAnchorCharacterOrActiveLine as number,
activeCharacter = activeOrActiveLineOrActiveCharacter as number;
return new vscode.Selection(anchor, new vscode.Position(activeLine, activeCharacter));
}
// Third argument is a position: this is the second overload.
const anchorLine = anchorOrAnchorLine as number,
anchorCharacter = activeOrAnchorCharacterOrActiveLine as number,
active = activeOrActiveLineOrActiveCharacter as vscode.Position;
return new vscode.Selection(new vscode.Position(anchorLine, anchorCharacter), active);
}
/**
* Shorthand for `fromAnchorActive`.
*/
export const from = fromAnchorActive;
/**
* Sorts selections in the given direction. If `Forward`, selections will be
* sorted from top to bottom. Otherwise, they will be sorted from bottom to
* top.
*/
export function sort(direction: Direction, selections: vscode.Selection[] = current.slice()) {
return selections.sort(direction === Direction.Forward ? sortTopToBottom : sortBottomToTop);
}
/**
* Sorts selections from top to bottom.
*/
export function topToBottom(selections: vscode.Selection[] = current.slice()) {
return selections.sort(sortTopToBottom);
}
/**
* Sorts selections from bottom to top.
*/
export function bottomToTop(selections: vscode.Selection[] = current.slice()) {
return selections.sort(sortBottomToTop);
}
/**
* Shifts empty selections by one character to the left.
*/
export function shiftEmptyLeft(
selections: vscode.Selection[],
document?: vscode.TextDocument,
) {
for (let i = 0; i < selections.length; i++) {
const selection = selections[i];
if (selection.isEmpty) {
if (document === undefined) {
document = Context.current.document;
}
const newPosition = Positions.previous(selection.active, document);
if (newPosition !== undefined) {
selections[i] = Selections.empty(newPosition);
}
}
}
}
/**
* Transforms a list of caret-mode selections (that is, regular selections as
* manipulated internally) into a list of character-mode selections (that is,
* selections modified to include a block character in them).
*
* This function should be used before setting the selections of a
* `vscode.TextEditor` if the selection behavior is `Character`.
*
* ### Example
* Forward-facing, non-empty selections are reduced by one character.
*
* ```js
* // One-character selection becomes empty.
* expect(Selections.toCharacterMode([Selections.fromAnchorActive(0, 0, 0, 1)]), "to satisfy", [
* expect.it("to be empty at coords", 0, 0),
* ]);
*
* // One-character selection becomes empty (at line break).
* expect(Selections.toCharacterMode([Selections.fromAnchorActive(0, 1, 1, 0)]), "to satisfy", [
* expect.it("to be empty at coords", 0, 1),
* ]);
*
* // Forward-facing selection becomes shorter.
* expect(Selections.toCharacterMode([Selections.fromAnchorActive(0, 0, 1, 1)]), "to satisfy", [
* expect.it("to have anchor at coords", 0, 0).and("to have cursor at coords", 1, 0),
* ]);
*
* // One-character selection becomes empty (reversed).
* expect(Selections.toCharacterMode([Selections.fromAnchorActive(0, 1, 0, 0)]), "to satisfy", [
* expect.it("to be empty at coords", 0, 0),
* ]);
*
* // One-character selection becomes empty (reversed, at line break).
* expect(Selections.toCharacterMode([Selections.fromAnchorActive(1, 0, 0, 1)]), "to satisfy", [
* expect.it("to be empty at coords", 0, 1),
* ]);
*
* // Reversed selection stays as-is.
* expect(Selections.toCharacterMode([Selections.fromAnchorActive(1, 1, 0, 0)]), "to satisfy", [
* expect.it("to have anchor at coords", 1, 1).and("to have cursor at coords", 0, 0),
* ]);
*
* // Empty selection stays as-is.
* expect(Selections.toCharacterMode([Selections.empty(1, 1)]), "to satisfy", [
* expect.it("to be empty at coords", 1, 1),
* ]);
* ```
*
* With:
* ```
* a
* b
* ```
*/
export function toCharacterMode(
selections: readonly vscode.Selection[],
document?: vscode.TextDocument,
) {
const characterModeSelections = [] as vscode.Selection[];
for (const selection of selections) {
const selectionActive = selection.active,
selectionActiveLine = selectionActive.line,
selectionActiveCharacter = selectionActive.character,
selectionAnchor = selection.anchor,
selectionAnchorLine = selectionAnchor.line,
selectionAnchorCharacter = selectionAnchor.character;
let active = selectionActive,
anchor = selectionAnchor,
changed = false;
if (selectionAnchorLine === selectionActiveLine) {
if (selectionAnchorCharacter + 1 === selectionActiveCharacter) {
// Selection is one-character long: make it empty.
active = selectionAnchor;
changed = true;
} else if (selectionAnchorCharacter - 1 === selectionActiveCharacter) {
// Selection is reversed and one-character long: make it empty.
anchor = selectionActive;
changed = true;
} else if (selectionAnchorCharacter < selectionActiveCharacter) {
// Selection is strictly forward-facing: make it shorter.
active = new vscode.Position(selectionActiveLine, selectionActiveCharacter - 1);
changed = true;
} else {
// Selection is reversed or empty: do nothing.
}
} else if (selectionAnchorLine < selectionActiveLine) {
// Selection is strictly forward-facing: make it shorter.
if (selectionActiveCharacter > 0) {
active = new vscode.Position(selectionActiveLine, selectionActiveCharacter - 1);
changed = true;
} else {
// The active character is the first one, so we have to get some
// information from the document.
if (document === undefined) {
document = Context.current.document;
}
const activePrevLine = selectionActiveLine - 1,
activePrevLineLength = document.lineAt(activePrevLine).text.length;
active = new vscode.Position(activePrevLine, activePrevLineLength);
changed = true;
}
} else if (selectionAnchorLine === selectionActiveLine + 1
&& selectionAnchorCharacter === 0
&& selectionActiveCharacter === Lines.length(selectionActiveLine, document)) {
// Selection is reversed and one-character long: make it empty.
anchor = selectionActive;
changed = true;
} else {
// Selection is reversed: do nothing.
}
characterModeSelections.push(changed ? new vscode.Selection(anchor, active) : selection);
}
return characterModeSelections;
}
/**
* Reverses the changes made by `toCharacterMode` by increasing by one the
* length of every empty or forward-facing selection.
*
* This function should be used on the selections of a `vscode.TextEditor` if
* the selection behavior is `Character`.
*
* ### Example
* Selections remain empty in empty documents.
*
* ```js
* expect(Selections.fromCharacterMode([Selections.empty(0, 0)]), "to satisfy", [
* expect.it("to be empty at coords", 0, 0),
* ]);
* ```
*
* With:
* ```
* ```
*
* ### Example
* Empty selections automatically become 1-character selections.
*
* ```js
* expect(Selections.fromCharacterMode([Selections.empty(0, 0)]), "to satisfy", [
* expect.it("to have anchor at coords", 0, 0).and("to have cursor at coords", 0, 1),
* ]);
*
* // At the end of the line, it selects the line ending:
* expect(Selections.fromCharacterMode([Selections.empty(0, 1)]), "to satisfy", [
* expect.it("to have anchor at coords", 0, 1).and("to have cursor at coords", 1, 0),
* ]);
*
* // But it does nothing at the end of the document:
* expect(Selections.fromCharacterMode([Selections.empty(2, 0)]), "to satisfy", [
* expect.it("to be empty at coords", 2, 0),
* ]);
* ```
*
* With:
* ```
* a
* b
*
* ```
*/
export function fromCharacterMode(
selections: readonly vscode.Selection[],
document?: vscode.TextDocument,
) {
const caretModeSelections = [] as vscode.Selection[];
for (const selection of selections) {
const selectionActive = selection.active,
selectionActiveLine = selectionActive.line,
selectionActiveCharacter = selectionActive.character,
selectionAnchor = selection.anchor,
selectionAnchorLine = selectionAnchor.line,
selectionAnchorCharacter = selectionAnchor.character;
let active = selectionActive,
changed = false;
const isEmptyOrForwardFacing = selectionAnchorLine < selectionActiveLine
|| (selectionAnchorLine === selectionActiveLine
&& selectionAnchorCharacter <= selectionActiveCharacter);
if (isEmptyOrForwardFacing) {
// Selection is empty or forward-facing: extend it if possible.
if (document === undefined) {
document = Context.current.document;
}
const lineLength = document.lineAt(selectionActiveLine).text.length;
if (selectionActiveCharacter === lineLength) {
// Character is at the end of the line.
if (selectionActiveLine + 1 < document.lineCount) {
// This is not the last line: we can extend the selection.
active = new vscode.Position(selectionActiveLine + 1, 0);
changed = true;
} else {
// This is the last line: we cannot do anything.
}
} else {
// Character is not at the end of the line: we can extend the selection.
active = new vscode.Position(selectionActiveLine, selectionActiveCharacter + 1);
changed = true;
}
}
caretModeSelections.push(changed ? new vscode.Selection(selectionAnchor, active) : selection);
}
return caretModeSelections;
}
}
function sortTopToBottom(a: vscode.Selection, b: vscode.Selection) {
return a.start.compareTo(b.start);
}
function sortBottomToTop(a: vscode.Selection, b: vscode.Selection) {
return b.start.compareTo(a.start);
} | the_stack |
import EventDispatcher from "../../patchwork/core/EventDispatcher";
import Module from "../../patchwork/core/Module";
import IPoint from "../data/interface/IPoint";
import ModuleCategories from "../../patchwork/enum/ModuleCategories";
import ModuleTypes from "../../patchwork/enum/ModuleTypes";
import VisualModuleEvent from "../event/VisualModuleEvent";
import ModuleEvent from "../../patchwork/event/ModuleEvent";
import AttributeTypes from "../../patchwork/enum/AttributeTypes";
import IAbstractModuleDefinitionAttribute from "../../patchwork/config/IAbstractModuleDefinitionAttribute";
declare var $:any;
class VisualModule extends EventDispatcher
{
public module:Module;
public viewOffset:IPoint;
public inputsByAttributeId:any = {};
public $element:any;
public $header:any;
public $title:any;
public $main:any;
public $info:any;
public $inputs:any;
public $outputs:any;
public headerMouseDownListener:any;
public documentMouseMoveListener:any;
public documentMouseUpListener:any;
public removeButtonClickHandler:any;
public attributeChangedHandler:any;
public position:IPoint;
constructor(module:Module, viewOffset:IPoint)
{
super();
this.module = module;
this.viewOffset = viewOffset;
// create module element
this.$element = $('<div>', {class: 'module noselect'});
// header
this.$header = $('<div>', {class: 'header'});
this.$title = $('<span>');
// different color for proxy modules
if(this.module.definition.category === ModuleCategories.PROXY)
{
this.$header.addClass('proxy');
}
var $remove = $('<a>', {class: 'remove', href: '#', text: 'X'});
this.$header.append(this.$title);
this.$header.append($remove);
// main area
this.$main = $('<div>', {class: 'main'});
switch(this.module.definition.category)
{
case ModuleCategories.NATIVE:
{
this.$info = $('<div>', {class: 'info'});
this.$info.text(
'id: ' + this.module.id +
', mode: ' + this.module.audioNode.channelCountMode +
', interpr: ' + this.module.audioNode.channelInterpretation +
', chcount: ' + this.module.audioNode.channelCount);
this.$main.append(this.$info);
this.createAttributes();
break;
}
case ModuleCategories.PROXY:
{
switch(this.module.definition.type)
{
case ModuleTypes.SUBPATCH:
{
this.$info = $('<div>', {class: 'info'});
this.$info.text('id: ' + this.module.id);
this.$main.append(this.$info);
var $openSubpatchButton = $('<button>', {text: 'Open subpatch'}).on('click', function()
{
this.dispatchEvent(VisualModuleEvent.OPEN_SUBPATCH, {module: this.module});
}.bind(this));
this.$main.append($openSubpatchButton);
break;
}
case ModuleTypes.OUTPUT:
{
if(!this.module.parentPatch.parentModule)
{
var text = 'This output is in the root of the patch and will act as the context\'s destination.';
this.$main.append($('<div>', {text: text, class: 'info'}));
}
break;
}
case ModuleTypes.INPUT:
{
if(!this.module.parentPatch.parentModule)
{
var text = 'An input in the root of the patch has no function, but will be useful if this patch is later used as subpatch.';
this.$main.append($('<div>', {text: text, class: 'info'}));
}
break;
}
}
break;
}
default:
{
console.warn('Unhandled module category: ' + this.module.definition.category);
}
}
// add all
this.$element.append(this.$inputs);
this.$element.append(this.$header);
this.$element.append(this.$main);
this.$element.append(this.$outputs);
// define listeners
this.headerMouseDownListener = this.handleHeaderMouseDown.bind(this);
this.documentMouseMoveListener = this.handleDocumentMouseMove.bind(this);
this.documentMouseUpListener = this.handleDocumentMouseUp.bind(this);
this.removeButtonClickHandler = this.handleRemoveButtonClick.bind(this);
// add mouse listeners
this.$header.on('mousedown', this.headerMouseDownListener);
$remove.on('click', this.removeButtonClickHandler);
// set the id in the element & title
this.$element.attr('data-id', this.module.id);
this.$title.text(this.module.definition.label);// + ' [' + this.module.id + ']');
// create transputs
var lastInY = this.createTransputs('in');
var lastOutY = this.createTransputs('out');
// set minheight of main to highest (either inputs or outputs)
this.$main.css({minHeight: Math.max(lastInY, lastOutY) + 15});
// isten to update values
this.attributeChangedHandler = this.handleAttributeChanged.bind(this);
module.addEventListener(ModuleEvent.ATTRIBUTE_CHANGED, this.attributeChangedHandler)
}
public handleAttributeChanged(type, data):void
{
this.updateAttribute(data.attribute);
}
public handleRemoveButtonClick(event):void
{
this.dispatchEvent(VisualModuleEvent.REMOVE, {moduleId: this.module.id});
}
public createAttributes():void
{
if(!this.module.definition.attributes) return;
for(var i = 0; i < this.module.definition.attributes.length; i++)
{
var attribute:IAbstractModuleDefinitionAttribute = this.module.definition.attributes[i];
switch(attribute.type)
{
case AttributeTypes.BUFFER:
case AttributeTypes.STREAM:
case AttributeTypes.FLOAT_ARRAY:
case AttributeTypes.READ_ONLY:
{
// TODO
console.warn('No input selector for: ' + attribute.type);
return;
}
case AttributeTypes.AUDIO_PARAM:
{
this.$main.append(this.$createInputForAttribute(attribute, true));
break;
}
case AttributeTypes.BOOLEAN:
case AttributeTypes.FLOAT:
{
this.$main.append(this.$createInputForAttribute(attribute, true));
break;
}
case AttributeTypes.OPTION_LIST:
{
this.$main.append(this.$createOptionListForAttribute(attribute));
break;
}
default:
{
console.error('Unknown attribute type: ' + attribute.type)
}
}
}
this.$main.append($('<div>', {class: 'clear'}));
}
public updateAttribute(attribute):void
{
switch(attribute.type)
{
case AttributeTypes.AUDIO_PARAM:
case AttributeTypes.OPTION_LIST:
{
var $input = this.inputsByAttributeId[attribute.id];
$input.val(this.module.getAttributeValue(attribute.id));
break;
}
case AttributeTypes.BUFFER:
case AttributeTypes.STREAM:
case AttributeTypes.FLOAT_ARRAY:
case AttributeTypes.BOOLEAN:
case AttributeTypes.FLOAT:
case AttributeTypes.READ_ONLY:
default:
{
console.error('Unknown attribute type: ' + attribute.type)
}
}
}
public $createOptionListForAttribute(attribute):any
{
var $container = this.createAttributeRow(attribute, true);
var $select = $('<select>');
var currentValue = this.module.getAttributeValue(attribute.id);
for(var i = 0; i < attribute.options.length; i++)
{
var optionValue = attribute.options[i];
var $option = $('<option>', {text: optionValue});
$select.append($option);
if(optionValue === currentValue) $option.prop('selected', true);
}
$container.append($select);
$select.on('change', function(event) {
var value = event.target.value;
// get the id of the attribute
var $parent = $(event.target.parentNode);
var attributeId = $parent.attr('data-id');
// set the value on the audionode
this.module.setAttributeValue(attributeId, value);
}.bind(this));
// story the input element by attribute id
this.inputsByAttributeId[attribute.id] = $select;
return $container;
}
public createAttributeRow(attribute, addLabel):any
{
var $container = $('<div>', {class: 'attribute' , 'data-id': attribute.id});
if(addLabel)
{
var $label = $('<div>', {class: 'label', text: attribute.label_short});
$container.append($label);
}
return $container;
}
public $createInputForAttribute(attribute, isEditable):any
{
if(typeof this.module.audioNode[attribute.id] === 'undefined')
{
console.warn('AudioNode ' + this.module.definition.type + ' doesn\'t have attribute ' + attribute.id);
return;
}
var $container = this.createAttributeRow(attribute, true);
var currentValue = this.module.getAttributeValue(attribute.id);
// var $value = $('<div>', {class: 'value', text: currentValue});
if(attribute.type === AttributeTypes.BOOLEAN)
{
// selectbox
var $input = $('<input>', {class: 'float'}).attr('type', 'checkbox');
}
else
{
// textfield input
var $input = $('<input>', {class: 'float'});
}
if(!isEditable)
{
$input.prop('disabled', true);
$container.find('.label').css('color', '#bbb');
}
$container.append($input);
$input.on('change', function(event) {
var value = event.target.value;
// set in value-field
var $parent = $(event.target.parentNode);
$parent.find('.value').text(value);
// get the id of the attribute
var attributeId = $parent.attr('data-id');
// set the value on the correct audioparam of the audionode
this.module.setAttributeValue(attributeId, value);
}.bind(this));
// set the current value
$input.val(currentValue);
// story the input element by attribute id
this.inputsByAttributeId[attribute.id] = $input;
return $container;
}
public createTransputs(type:string):number
{
var numberOfInputs = this.module.getNumberOfInputs();
var numberOfOutputs = this.module.getNumberOfOutputs();
let cssClass:string;
let numberOfTransputs:number;
let audioParams:Array<any>;
// set correct variables
if(type === 'in')
{
// inputs
cssClass = 'input';
//$containerElement = this.$inputs;
numberOfTransputs = numberOfInputs;
audioParams = this.module.getAudioParams();
}
else
{
// outputs
cssClass = 'output';
//$containerElement = this.$outputs;
numberOfTransputs = numberOfOutputs;
// audioparams are never outputs
audioParams = [];
}
var transputY = 0;
var transputYMultiply = 30;
var transputYOffset = 6;
var numberOfNodeInputs = this.module.getNumberOfNodeInputs();
for(var i = 0; i < numberOfTransputs; i++)
{
var $transput = $('<div>', {class: cssClass});
transputY = transputYOffset + i * transputYMultiply;
$transput.css({'top': transputY});
$transput.attr('data-index', i);
if(i < numberOfTransputs - audioParams.length)
{
// in our output
$transput.text(type + '-' + (i + 1));
}
else
{
// audio params (always inputs)
var audioParam = audioParams[i - numberOfNodeInputs];
$transput.addClass('audioparam');
$transput.attr('data-audioparam', audioParam.id);
$transput.text(audioParam.label_short);
}
// set horizontal position
if(type === 'in')
{
$transput.css('left', 0);
}
else
{
$transput.css('right', 0);
}
this.$main.append($transput);
}
// return the latest y-value of the created transput, so the module knows what height to set
return transputY;
}
public handleHeaderMouseDown(event):void
{
$(document).on('mousemove', this.documentMouseMoveListener);
$(document).on('mouseup', this.documentMouseUpListener);
}
public handleDocumentMouseUp(event):void
{
$(document).off('mousemove', this.documentMouseMoveListener);
$(document).off('mouseup', this.documentMouseUpListener);
}
handleDocumentMouseMove(event):void
{
var moveX = event.originalEvent.movementX || event.originalEvent.mozMovementX || 0;
var moveY = event.originalEvent.movementY || event.originalEvent.mozMovementY || 0;
this.setPosition(this.position.x + moveX, this.position.y + moveY);
this.dispatchEvent(VisualModuleEvent.MOVE);
}
public setPosition(x, y):void
{
this.position = {x: x, y: y};
// we also need to set this on the module itself, since the module has
// no reference to the visual module (and we need to store the position when saving)
this.module.position = {x: x, y: y};
this.moveToPosition();
}
public moveToPosition():void
{
this.$element.css({
left: this.position.x - this.viewOffset.x,
top: this.position.y - this.viewOffset.y
});
}
public destruct():void
{
this.removeAllEventListeners();
this.$title = null;
this.$element = null;
this.position = null;
this.viewOffset = null;
if(this.$header)
{
this.$header.off('mousedown', this.headerMouseDownListener);
//this.titleMouseDownListener = null;
this.$header = null;
}
$(document).off('mousemove', this.documentMouseMoveListener);
$(document).off('mouseup', this.documentMouseUpListener);
this.documentMouseMoveListener = null;
this.documentMouseUpListener = null;
this.module = null;
}
}
export default VisualModule; | the_stack |
// Generated by: https://github.com/david-driscoll/atom-typescript-generator
// Generation tool by david-driscoll <https://github.com/david-driscoll/>
declare module Linter {
/**
* Commands
* This class was not documented by atomdoc, assume it is private. Use with caution.
*/
class Commands {
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
linter: Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
constructor(linter? : Linter);
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
togglePanel() : Atom.Panel;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
toggleLinter() : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
setBubbleTransparent() : void;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
setBubbleOpaque() : void;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
expandMultilineMessages() : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
collapseMultilineMessages() : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
lint() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getMessage(index? : any) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
nextError() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
previousError() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
dispose() : void;
}
/**
* EditorRegistry
* This class was not documented by atomdoc, assume it is private. Use with caution.
*/
class EditorRegistry {
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
constructor();
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
create(textEditor? : Atom.TextEditor) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
forEach(callback? : any) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
ofPath(path? : string) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
ofTextEditor(editor? : any) : Atom.TextEditor;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
ofActiveTextEditor() : Atom.TextEditor;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
observe(callback : (any: any) => void) : EventKit.Disposable;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
dispose() : void;
}
/**
* LinterRegistry
* This class was not documented by atomdoc, assume it is private. Use with caution.
*/
class LinterRegistry {
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
constructor();
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getLinters() : Linter[];
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
hasLinter(linter? : Linter) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
addLinter(linter? : Linter) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
deleteLinter(linter? : Linter) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
lint({ onChange, editorLinter } : { onChange? : any; editorLinter? : Linter }) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
triggerLinter(linter? : Linter, editor? : any, scopes? : any) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
onDidUpdateMessages(callback : Function /* needs to be defined */) : EventKit.Disposable;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
dispose() : void;
}
/**
* LinterViews
* This class was not documented by atomdoc, assume it is private. Use with caution.
*/
class LinterViews {
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
linter: Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
constructor(linter? : Linter);
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
render({ added, removed, messages } : { added? : any; removed? : any; messages? : string }) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
notifyEditors({ added, removed } : { added? : any; removed? : any }) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
notifyEditor(editorLinter? : Linter) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
renderLineMessages(render? : any) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
classifyMessages(messages? : string) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
classifyMessagesByLine(messages? : string) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
renderBubble() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
renderBubbleContent(message? : string) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
renderCount() : number;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
attachBottom(statusBar? : any) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
removeBubble() : void;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
dispose() : void;
}
/**
* Linter
* This class was not documented by atomdoc, assume it is private. Use with caution.
*/
class Linter {
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
state: any /* default */;
/**
* State is an object by default; never null or undefined
* This field or method was marked private by atomdoc. Use with caution.
*/
constructor(state? : any);
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
addLinter(linter? : Linter) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
deleteLinter(linter? : Linter) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
hasLinter(linter? : Linter) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getLinters() : Linter[];
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
setMessages(linter? : Linter, messages? : string) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
deleteMessages(linter? : Linter) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getMessages() : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
onDidUpdateMessages(callback : Function /* needs to be defined */) : EventKit.Disposable;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getActiveEditorLinter() : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getEditorLinter(editor? : any) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getEditorLinterByPath(path? : string) : string;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
eachEditorLinter(callback? : any) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
observeEditorLinters(callback : (any: any) => void) : EventKit.Disposable;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
createEditorLinter(editor? : any) : Linter;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
deactivate() : void;
}
/**
* BottomContainer
* This class was not documented by atomdoc, assume it is private. Use with caution.
*/
class BottomContainer /*extends HTMLElement*/ {
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
prepare(state? : any) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
createdCallback() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
attachedCallback() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
detachedCallback() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
setVisibility(value? : any) : void;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getVisibility() : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
getTab(name? : string) : any;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
onDidChangeTab(callback : Function /* needs to be defined */) : EventKit.Disposable;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
onShouldTogglePanel(callback? : any) : Atom.Panel;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
setCount({ Project, File, Line } : { Project? : Atom.Project; File? : Pathwatcher.File; Line? : number }) : number;
/**
* This field or method was not documented by atomdoc, assume it is private. Use with caution.
*/
updateTabs() : void;
}
}
declare module "linter" {
export = Linter.Linter;
} | the_stack |
module Fayde.Controls {
export class ComboBox extends Primitives.Selector {
DropDownOpened = new nullstone.Event();
DropDownClosed = new nullstone.Event();
static IsDropDownOpenProperty = DependencyProperty.Register("IsDropDownOpen", () => Boolean, ComboBox, false, (d, args) => (<ComboBox>d)._IsDropDownOpenChanged(args));
static ItemContainerStyleProperty = DependencyProperty.Register("ItemContainerStyle", () => Style, ComboBox, undefined, (d, args) => (<ListBox>d).OnItemContainerStyleChanged(args));
static MaxDropDownHeightProperty = DependencyProperty.Register("MaxDropDownHeight", () => Number, ComboBox, Number.POSITIVE_INFINITY, (d, args) => (<ComboBox>d)._MaxDropDownHeightChanged(args));
static IsSelectionActiveProperty = Primitives.Selector.IsSelectionActiveProperty;
static WatermarkProperty = DependencyProperty.Register("Watermark", () => String, ComboBox, "");
IsDropDownOpen: boolean;
ItemContainerStyle: Style;
MaxDropDownHeight: number;
Watermark: String;
private $ContentPresenter: ContentPresenter;
private $Popup: Primitives.Popup;
private $DropDownToggle: Primitives.ToggleButton;
private $DisplayedItem: ComboBoxItem = null;
private $SelectionBoxItem: any = null;
private $SelectionBoxItemTemplate: DataTemplate = null;
private $WatermarkElement: FrameworkElement;
private _NullSelFallback: any;
private _FocusedIndex: number = -1;
constructor() {
super();
this.DefaultStyleKey = ComboBox;
}
private _IsDropDownOpenChanged(args: IDependencyPropertyChangedEventArgs) {
var open = args.NewValue;
if (this.$Popup != null)
this.$Popup.IsOpen = open;
if (this.$DropDownToggle != null)
this.$DropDownToggle.IsChecked = open;
if (open) {
this._FocusedIndex = this.Items.Count > 0 ? Math.max(this.SelectedIndex, 0) : -1;
if (this._FocusedIndex > -1) {
var focusedItem = this.ItemContainersManager.ContainerFromIndex(this._FocusedIndex);
if (focusedItem instanceof ComboBoxItem)
(<ComboBoxItem>focusedItem).Focus();
}
this.LayoutUpdated.on(this._UpdatePopupSizeAndPosition, this);
this.DropDownOpened.raise(this, null);
} else {
this.Focus();
this.LayoutUpdated.off(this._UpdatePopupSizeAndPosition, this);
this.DropDownClosed.raise(this, null);
}
var selectedItem = this.SelectedItem;
this._UpdateDisplayedItem(open && selectedItem instanceof Fayde.UIElement ? null : selectedItem);
this.UpdateVisualState(true);
this._CheckWatermarkVisibility();
}
private _MaxDropDownHeightChanged(args: IDependencyPropertyChangedEventArgs) {
this._UpdatePopupMaxHeight(args.NewValue);
}
private _GetChildOfType(name: string, type: Function): any {
var temp = this.GetTemplateChild(name);
if (temp instanceof type)
return temp;
}
OnApplyTemplate() {
super.OnApplyTemplate();
this.UpdateVisualState(false);
this.$ContentPresenter = this._GetChildOfType("ContentPresenter", ContentPresenter);
this.$Popup = this._GetChildOfType("Popup", Primitives.Popup);
this.$DropDownToggle = this._GetChildOfType("DropDownToggle", Primitives.ToggleButton);
this.$WatermarkElement = <FrameworkElement>this.GetTemplateChild("WatermarkElement", FrameworkElement);
if (this.$ContentPresenter != null)
this._NullSelFallback = this.$ContentPresenter.Content;
if (this.$Popup != null) {
this._UpdatePopupMaxHeight(this.MaxDropDownHeight);
this.$Popup.WatchOutsideClick(this._PopupClickedOutside, this);
var child = this.$Popup.Child;
if (child != null) {
child.KeyDown.on(this._OnChildKeyDown, this);
(<FrameworkElement>child).SizeChanged.on(this._UpdatePopupSizeAndPosition, this);
}
}
if (this.$DropDownToggle != null) {
this.$DropDownToggle.Checked.on(this._OnToggleChecked, this);
this.$DropDownToggle.Unchecked.on(this._OnToggleUnchecked, this);
}
this.UpdateVisualState(false);
this._UpdateDisplayedItem(this.SelectedItem);
}
OnItemContainerStyleChanged(args: IDependencyPropertyChangedEventArgs) {
var newStyle = <Style>args.NewValue;
var enumerator = this.ItemContainersManager.GetEnumerator();
while (enumerator.moveNext()) {
var container = <FrameworkElement>enumerator.current;
if (container && container !== enumerator.CurrentItem)
container.Style = newStyle;
}
}
IsItemItsOwnContainer(item: any): boolean {
return item instanceof ComboBoxItem;
}
GetContainerForItem(): UIElement {
return new ComboBoxItem();
}
PrepareContainerForItem(container: UIElement, item: any) {
super.PrepareContainerForItem(container, item);
var cbi = <ComboBoxItem>container;
if (cbi !== item) {
var ics = this.ItemContainerStyle;
if (!cbi.Style && ics)
cbi.Style = ics;
}
}
GoToStateFocus(gotoFunc: (state: string) => boolean): boolean {
var isEnabled = this.IsEnabled;
if (this.IsDropDownOpen && isEnabled)
return gotoFunc("FocusedDropDown");
else if (this.IsFocused && isEnabled)
return gotoFunc("Focused");
return gotoFunc("Unfocused");
}
OnIsEnabledChanged(e: IDependencyPropertyChangedEventArgs) {
super.OnIsEnabledChanged(e);
if (!this.IsEnabled)
this.IsDropDownOpen = false;
}
OnMouseLeftButtonDown(e: Input.MouseButtonEventArgs) {
super.OnMouseLeftButtonDown(e);
if (!e.Handled) {
e.Handled = true;
this.SetValueInternal(ComboBox.IsSelectionActiveProperty, true);
this.IsDropDownOpen = !this.IsDropDownOpen;
}
}
OnMouseEnter(e: Input.MouseEventArgs) {
super.OnMouseEnter(e);
this.UpdateVisualState(true);
}
OnMouseLeave(e: Input.MouseEventArgs) {
super.OnMouseLeave(e);
this.UpdateVisualState(true);
}
OnTouchMove(e: Input.TouchEventArgs) {
super.OnTouchMove(e);
this.UpdateVisualState(true);
}
OnTouchDown(e: Input.TouchEventArgs) {
super.OnTouchDown(e);
if (!e.Handled) {
e.Handled = true;
this.SetValueInternal(ComboBox.IsSelectionActiveProperty, true);
this.IsDropDownOpen = !this.IsDropDownOpen;
}
}
OnTouchLeave(e: Input.TouchEventArgs) {
super.OnTouchLeave(e);
this.UpdateVisualState(true);
}
OnKeyDown(e: Input.KeyEventArgs) {
super.OnKeyDown(e);
if (e.Handled)
return;
e.Handled = true;
var key = e.Key;
if (this.FlowDirection === FlowDirection.RightToLeft) {
if (key === Input.Key.Left)
key = Input.Key.Right;
else if (key === Input.Key.Right)
key = Input.Key.Left;
}
switch (key) {
case Input.Key.Escape:
this.IsDropDownOpen = false;
break;
case Input.Key.Enter:
case Input.Key.Space:
if (this.IsDropDownOpen && this._FocusedIndex !== this.SelectedIndex) {
this.SelectedIndex = this._FocusedIndex;
this.IsDropDownOpen = false;
} else {
this.IsDropDownOpen = true;
}
break;
case Input.Key.Right:
case Input.Key.Down:
if (this.IsDropDownOpen) {
if (this._FocusedIndex < (this.Items.Count - 1)) {
this._FocusedIndex++;
(<UIElement>this.ItemContainersManager.ContainerFromIndex(this._FocusedIndex)).Focus();
}
} else {
this.SelectedIndex = Math.min(this.SelectedIndex + 1, this.Items.Count - 1);
}
break;
case Input.Key.Left:
case Input.Key.Up:
if (this.IsDropDownOpen) {
if (this._FocusedIndex > 0) {
this._FocusedIndex--;
(<UIElement>this.ItemContainersManager.ContainerFromIndex(this._FocusedIndex)).Focus();
}
} else {
this.SelectedIndex = Math.max(this.SelectedIndex - 1, 0);
}
break;
default:
e.Handled = false;
break;
}
}
private _CheckWatermarkVisibility() {
if (this.Watermark.length > 0 && this.$WatermarkElement)
this.$WatermarkElement.Visibility = this.$SelectionBoxItem != null ? Visibility.Collapsed : Visibility.Visible;
}
OnGotFocus(e: RoutedEventArgs) {
super.OnGotFocus(e);
this.UpdateVisualState(true);
}
OnLostFocus(e: RoutedEventArgs) {
super.OnLostFocus(e);
this.SetValueInternal(ComboBox.IsSelectionActiveProperty, this.$Popup == null ? false : this.$Popup.IsOpen);
this.UpdateVisualState(true);
}
private _OnChildKeyDown(sender, e: Input.KeyEventArgs) {
this.OnKeyDown(e);
}
OnSelectionChanged(e: Primitives.SelectionChangedEventArgs) {
if (!this.IsDropDownOpen)
this._UpdateDisplayedItem(this.SelectedItem);
this._CheckWatermarkVisibility();
}
private _OnToggleChecked(sender, e) { this.IsDropDownOpen = true; }
private _OnToggleUnchecked(sender, e) { this.IsDropDownOpen = false; }
private _PopupClickedOutside() {
this.IsDropDownOpen = false;
}
private _UpdateDisplayedItem(selectedItem: any) {
if (!this.$ContentPresenter)
return;
if (this.$DisplayedItem != null) {
this.$DisplayedItem.Content = this.$ContentPresenter.Content;
this.$DisplayedItem = null;
}
this.$ContentPresenter.Content = null;
if (selectedItem == null) {
this.$ContentPresenter.Content = this._NullSelFallback;
this.$ContentPresenter.ContentTemplate = null;
this.$SelectionBoxItem = null;
this.$SelectionBoxItemTemplate = null;
return;
}
var content = selectedItem;
if (content instanceof ComboBoxItem)
content = content.Content;
var icm = this.ItemContainersManager;
var selectedIndex = this.SelectedIndex;
var temp = icm.ContainerFromIndex(selectedIndex);
if (temp instanceof ComboBoxItem) this.$DisplayedItem = <ComboBoxItem>temp;
this.$SelectionBoxItem = content;
this.$SelectionBoxItemTemplate = this.ItemTemplate;
if (this.$DisplayedItem != null) {
this.$SelectionBoxItemTemplate = this.$DisplayedItem.ContentTemplate;
if (content instanceof Fayde.UIElement)
this.$DisplayedItem.Content = null;
else
this.$DisplayedItem = null;
} else {
temp = icm.ContainerFromIndex(selectedIndex);
var container: ComboBoxItem;
if (temp instanceof ComboBoxItem) container = <ComboBoxItem>temp;
if (!container) {
var generator = icm.CreateGenerator(selectedIndex, 1);
if (generator.Generate() && generator.Current instanceof ComboBoxItem) {
container = <ComboBoxItem>generator.Current;
this.PrepareContainerForItem(container, generator.CurrentItem);
}
}
if (container)
this.$SelectionBoxItemTemplate = container.ContentTemplate;
}
this.$ContentPresenter.Content = this.$SelectionBoxItem;
this.$ContentPresenter.ContentTemplate = this.$SelectionBoxItemTemplate;
}
private _UpdatePopupSizeAndPosition(sender, e: nullstone.IEventArgs) {
var popup = this.$Popup;
if (!popup)
return;
var child = <FrameworkElement>popup.Child;
if (!(child instanceof FrameworkElement))
return;
child.MinWidth = this.ActualWidth;
var root = <FrameworkElement>VisualTreeHelper.GetRoot(this);
if (!root)
return;
try {
var xform = this.TransformToVisual(null);
} catch (err) {
//Ignore ComboBox being detached
return;
}
var offset = new Point(0, this.ActualHeight);
var bottomRight = new Point(offset.x + child.ActualWidth, offset.y + child.ActualHeight);
var topLeft = xform.Transform(offset);
bottomRight = xform.Transform(bottomRight);
var isRightToLeft = (this.FlowDirection === FlowDirection.RightToLeft);
if (isRightToLeft) {
var left = bottomRight.x;
bottomRight.x = topLeft.x;
topLeft.x = left;
}
var finalOffset = new Point();
var raw = root.ActualWidth;
if (bottomRight.x > raw) {
finalOffset.x = raw - bottomRight.x;
} else if (topLeft.x < 0) {
finalOffset.x = offset.x - topLeft.x;
} else {
finalOffset.x = offset.x;
}
if (isRightToLeft)
finalOffset.x = -finalOffset.x;
var rah = root.ActualHeight;
if (bottomRight.y > rah) {
finalOffset.y = -child.ActualHeight;
} else {
finalOffset.y = this.RenderSize.height;
}
popup.HorizontalOffset = finalOffset.x;
popup.VerticalOffset = finalOffset.y;
this._UpdatePopupMaxHeight(this.MaxDropDownHeight);
}
private _UpdatePopupMaxHeight(height: number) {
var child: FrameworkElement;
if (this.$Popup && (child = <FrameworkElement>this.$Popup.Child) && child instanceof FrameworkElement) {
if (height === Number.POSITIVE_INFINITY) {
var surface = this.XamlNode.LayoutUpdater.tree.surface;
if (surface)
height = surface.height / 2.0;
}
child.MaxHeight = height;
}
}
}
Fayde.CoreLibrary.add(ComboBox);
TemplateParts(ComboBox,
{ Name: "ContentPresenter", Type: ContentPresenter },
{ Name: "Popup", Type: Primitives.Popup },
{ Name: "ContentPresenterBorder", Type: FrameworkElement },
{ Name: "DropDownToggle", Type: Primitives.ToggleButton },
{ Name: "ScrollViewer", Type: ScrollViewer },
{ Name: "WatermarkElement", Type: FrameworkElement });
TemplateVisualStates(ComboBox,
{ GroupName: "CommonStates", Name: "Normal" },
{ GroupName: "CommonStates", Name: "MouseOver" },
{ GroupName: "CommonStates", Name: "Disabled" },
{ GroupName: "FocusStates", Name: "Unfocused" },
{ GroupName: "FocusStates", Name: "Focused" },
{ GroupName: "FocusStates", Name: "FocusedDropDown" },
{ GroupName: "ValidationStates", Name: "Valid" },
{ GroupName: "ValidationStates", Name: "InvalidUnfocused" },
{ GroupName: "ValidationStates", Name: "InvalidFocused" });
} | the_stack |
import { IgniteUIForAngularTemplate } from "@igniteui/angular-templates";
import { App, GoogleAnalytics, PackageManager, ProjectConfig, TypeScriptFileUpdate, TypeScriptUtils, Util } from "@igniteui/cli-core";
import * as path from "path";
import * as ts from "typescript";
import { default as addCmd } from "../../packages/cli/lib/commands/add";
import { PromptSession } from "../../packages/cli/lib/PromptSession";
import { AngularTemplate } from "../../packages/cli/lib/templates/AngularTemplate";
import { resetSpy } from "../helpers/utils";
describe("Unit - Add command", () => {
beforeEach(() => {
spyOn(GoogleAnalytics, "post");
});
it("Should start prompt session with missing arg", async done => {
spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);
spyOn(ProjectConfig, "getConfig").and.returnValue({ project: {
framework: "angular",
theme: "infragistics"}});
const mockProjLib = {};
addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {
getFrameworkById: {},
getProjectLibrary: mockProjLib
});
const promptSession = PromptSession.prototype;
spyOn(promptSession, "chooseActionLoop");
await addCmd.execute({});
expect(promptSession.chooseActionLoop).toHaveBeenCalledWith(mockProjLib);
done();
});
it("Should validate and trim name", async done => {
spyOn(ProjectConfig, "getConfig").and.returnValue({ project: {
framework: "angular",
theme: "infragistics"}});
spyOn(Util, "error");
spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(false));
spyOn(process, "cwd").and.returnValue("Mock directory");
const mockTemplate = jasmine.createSpyObj("Template", ["generateConfig", "templatePath", "registerInProject"]);
const mockConfig = { test: "test" };
mockTemplate.generateConfig.and.returnValue(mockConfig);
mockTemplate.templatePaths = ["test"];
const mockDelimiters = { mockDelimiter: { start: "test", end: "test" }};
mockTemplate.delimiters = mockDelimiters;
const errorCombos = [
{ name: "name.ts", inError: "name.ts" }, // file extension test
{ name: "1 is not valid", inError: "1 is not valid" },
{ name: " 1 is not valid \t ", inError: "1 is not valid" },
{ name: "name!", inError: "name!" },
{ name: "bits~and*bobs()", inError: "bits~and*bobs()" }
];
for (const item of errorCombos) {
resetSpy(Util.error);
await addCmd.addTemplate(item.name, mockTemplate);
expect(Util.error).toHaveBeenCalledWith(`Name '${item.inError}' is not valid. `
+ "Name should start with a letter and can also contain numbers, dashes and spaces.", "red");
}
const validCombos = [
{ name: " valid name \t ", valid: "valid name" },
{ name: "th1s is valid", valid: "th1s is valid" },
{ name: "b1ts-and bobs ", valid: "b1ts-and bobs" },
{ name: "../editors", valid: "../editors" },
{ name: "template/editors", valid: "template/editors" },
{ name: "a name", valid: "a name" },
{ name: "a", valid: "a" } // single letter name test
];
for (const item of validCombos) {
await addCmd.addTemplate(item.name, mockTemplate);
expect(mockTemplate.generateConfig).toHaveBeenCalledWith(item.valid, {});
expect(Util.processTemplates).toHaveBeenCalledWith("test", "Mock directory", mockConfig, mockDelimiters);
}
done();
});
it("Should queue package dependencies and wait for install", async done => {
spyOn(ProjectConfig, "getConfig").and.returnValue({ project: {
framework: "angular",
theme: "infragistics"}});
spyOn(Util, "log");
spyOn(PackageManager, "queuePackage");
spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));
const mockTemplate = jasmine.createSpyObj("Template", ["generateConfig", "registerInProject"]);
mockTemplate.templatePaths = ["test"];
mockTemplate.packages = ["tslib" , "test-pack"];
addCmd.templateManager = jasmine.createSpyObj("TemplateManager", ["updateProjectConfiguration"]);
await addCmd.addTemplate("template with packages", mockTemplate);
expect(mockTemplate.generateConfig).toHaveBeenCalled();
expect(mockTemplate.registerInProject).toHaveBeenCalled();
expect(Util.processTemplates).toHaveBeenCalledTimes(1);
expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalled();
expect(PackageManager.queuePackage).toHaveBeenCalledTimes(2);
expect(PackageManager.queuePackage).toHaveBeenCalledWith("tslib");
expect(PackageManager.queuePackage).toHaveBeenCalledWith("test-pack");
spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);
addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {
getFrameworkById: {},
getProjectLibrary: jasmine.createSpyObj("ProjectLibrary", {
getTemplateById: {},
hasTemplate: true
})
});
spyOn(addCmd, "addTemplate");
spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());
spyOn(PackageManager, "ensureIgniteUISource");
await addCmd.execute({name: "template with packages", template: "test-id"});
expect(addCmd.addTemplate).toHaveBeenCalledWith("template with packages", {}, jasmine.any(Object));
expect(PackageManager.flushQueue).toHaveBeenCalled();
done();
});
it("Should properly accept module args when passed - IgniteUI for Angular", async done => {
const mockProjectConfig = {project: {
framework: "angular",
theme: "infragistics"
}};
spyOn(TypeScriptUtils, "getFileSource").and.returnValue(
ts.createSourceFile("test-file-name", ``, ts.ScriptTarget.Latest, true)
);
const routeSpy = spyOn(TypeScriptFileUpdate.prototype, "addRoute");
const declarationSpy = spyOn(TypeScriptFileUpdate.prototype, "addDeclaration").and.callThrough();
const ngMetaSpy = spyOn(TypeScriptFileUpdate.prototype, "addNgModuleMeta");
const finalizeSpy = spyOn(TypeScriptFileUpdate.prototype, "finalize");
const mockTemplate = new IgniteUIForAngularTemplate("test");
mockTemplate.packages = [];
mockTemplate.dependencies = [];
const directoryPath = path.join("My/Example/Path");
spyOn(process, "cwd").and.returnValue(directoryPath);
spyOn(mockTemplate, "generateConfig");
spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));
spyOn(mockTemplate, "registerInProject").and.callThrough();
// const sourceFilesSpy = spyOn<any>(mockTemplate, "ensureSourceFiles");
const mockLibrary = jasmine.createSpyObj("frameworkLibrary", ["hasTemplate", "getTemplateById"]);
mockLibrary.hasTemplate.and.returnValue(true);
mockLibrary.getTemplateById.and.returnValue(mockTemplate);
addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {
getFrameworkById: {},
getProjectLibrary: mockLibrary,
updateProjectConfiguration: () => {}
});
spyOn(ProjectConfig, "getConfig").and.returnValue(mockProjectConfig);
spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);
spyOn(addCmd, "addTemplate").and.callThrough();
spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());
spyOn(PackageManager, "ensureIgniteUISource");
spyOn(Util, "directoryExists").and.returnValue(true);
const mockVirtFs = {
fileExists: () => {}
};
spyOn(App.container, "get").and.returnValue(mockVirtFs);
spyOn(mockVirtFs, "fileExists").and.callFake(file => {
if (file === "src/app/app-routing.module.ts") {
return true;
}
});
await addCmd.execute({
name: "test-file-name", template: "CustomTemplate",
// tslint:disable-next-line:object-literal-sort-keys
module: "myCustomModule/my-custom-module.module.ts"
});
expect(addCmd.addTemplate).toHaveBeenCalledWith(
"test-file-name", mockTemplate,
jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })
);
expect(PackageManager.flushQueue).toHaveBeenCalled();
expect(mockTemplate.generateConfig).toHaveBeenCalledTimes(1);
expect(mockTemplate.generateConfig).toHaveBeenCalledWith(
"test-file-name",
jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })
);
expect(mockTemplate.registerInProject).toHaveBeenCalledTimes(1);
expect(mockTemplate.registerInProject).toHaveBeenCalledWith(
directoryPath, "test-file-name",
jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })
);
// expect(sourceFilesSpy).toHaveBeenCalledTimes(1);
expect(routeSpy).toHaveBeenCalledTimes(1);
expect(declarationSpy).toHaveBeenCalledTimes(1);
expect(declarationSpy).toHaveBeenCalledWith(
path.join(directoryPath, `src/app/test-file-name/test-file-name.component.ts`),
true);
expect(ngMetaSpy).toHaveBeenCalledTimes(1);
expect(ngMetaSpy).toHaveBeenCalledWith({
declare: null,
from: "../test-file-name/test-file-name.component",
// tslint:disable-next-line:object-literal-sort-keys
export: null
});
expect(finalizeSpy).toHaveBeenCalledTimes(1);
expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalledTimes(1);
done();
});
it("Should properly accept module args when passed - Angular Wrappers", async done => {
const mockProjectConfig = {project: {
framework: "angular",
theme: "infragistics"
}};
spyOn(TypeScriptUtils, "getFileSource").and.returnValue(
ts.createSourceFile("test-file-name", ``, ts.ScriptTarget.Latest, true)
);
const routeSpy = spyOn(TypeScriptFileUpdate.prototype, "addRoute");
const declarationSpy = spyOn(TypeScriptFileUpdate.prototype, "addDeclaration").and.callThrough();
const ngMetaSpy = spyOn(TypeScriptFileUpdate.prototype, "addNgModuleMeta");
const finalizeSpy = spyOn(TypeScriptFileUpdate.prototype, "finalize");
const mockTemplate = new AngularTemplate("test");
mockTemplate.packages = [];
mockTemplate.dependencies = [];
const directoryPath = path.join("My/Example/Path");
spyOn(process, "cwd").and.returnValue(directoryPath);
spyOn(mockTemplate, "generateConfig");
spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));
spyOn(mockTemplate, "registerInProject").and.callThrough();
spyOn(Util, "directoryExists").and.returnValue(true);
// const sourceFilesSpy = spyOn<any>(mockTemplate, "ensureSourceFiles");
const mockLibrary = jasmine.createSpyObj("frameworkLibrary", ["hasTemplate", "getTemplateById"]);
mockLibrary.hasTemplate.and.returnValue(true);
mockLibrary.getTemplateById.and.returnValue(mockTemplate);
addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {
getFrameworkById: {},
getProjectLibrary: mockLibrary,
updateProjectConfiguration: () => {}
});
spyOn(ProjectConfig, "getConfig").and.returnValue(mockProjectConfig);
spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);
spyOn(addCmd, "addTemplate").and.callThrough();
spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());
spyOn(PackageManager, "ensureIgniteUISource");
await addCmd.execute({
name: "test-file-name", template: "CustomTemplate",
// tslint:disable-next-line:object-literal-sort-keys
module: "myCustomModule/my-custom-module.module.ts"
});
expect(addCmd.addTemplate).toHaveBeenCalledWith(
"test-file-name", mockTemplate,
jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })
);
expect(PackageManager.flushQueue).toHaveBeenCalled();
expect(mockTemplate.generateConfig).toHaveBeenCalledTimes(1);
expect(mockTemplate.generateConfig).toHaveBeenCalledWith(
"test-file-name",
jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })
);
expect(mockTemplate.registerInProject).toHaveBeenCalledTimes(1);
expect(mockTemplate.registerInProject).toHaveBeenCalledWith(
directoryPath, "test-file-name",
jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" }));
// expect(sourceFilesSpy).toHaveBeenCalledTimes(1);
expect(routeSpy).toHaveBeenCalledTimes(1);
expect(declarationSpy).toHaveBeenCalledTimes(1);
expect(declarationSpy).toHaveBeenCalledWith(
path.join(directoryPath, `src/app/components/test-file-name/test-file-name.component.ts`),
true);
expect(ngMetaSpy).toHaveBeenCalledTimes(1);
expect(ngMetaSpy).toHaveBeenCalledWith({
declare: null,
from: "../components/test-file-name/test-file-name.component",
// tslint:disable-next-line:object-literal-sort-keys
export: null
});
expect(finalizeSpy).toHaveBeenCalledTimes(1);
expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalledTimes(1);
done();
});
it("Should properly accept skip-route args when passed", async done => {
const mockProjectConfig = {project: {
framework: "angular",
theme: "infragistics"
}};
spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);
spyOn(ProjectConfig, "getConfig").and.returnValue(mockProjectConfig);
const mockTemplate = jasmine.createSpyObj("Template", {
generateConfig: { test: "test" }, registerInProject: null
});
mockTemplate.templatePaths = ["test"];
mockTemplate.packages = [];
const mockLibrary = jasmine.createSpyObj("frameworkLibrary", {
getTemplateById: mockTemplate, hasTemplate: true
});
addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {
getFrameworkById: {},
getProjectLibrary: mockLibrary,
updateProjectConfiguration: () => {}
});
const directoryPath = path.join("My/Example/Path");
spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));
spyOn(process, "cwd").and.returnValue(directoryPath);
spyOn(addCmd, "addTemplate").and.callThrough();
spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());
spyOn(PackageManager, "ensureIgniteUISource");
await addCmd.execute({
name: "test-file-name", template: "CustomTemplate",
// tslint:disable-next-line:object-literal-sort-keys
skipRoute: true
});
expect(addCmd.addTemplate).toHaveBeenCalledWith(
"test-file-name", mockTemplate,
jasmine.objectContaining({ skipRoute: true })
);
expect(Util.processTemplates).toHaveBeenCalledTimes(1);
expect(PackageManager.flushQueue).toHaveBeenCalled();
expect(mockTemplate.generateConfig).toHaveBeenCalledTimes(1);
expect(mockTemplate.generateConfig).toHaveBeenCalledWith(
"test-file-name",
jasmine.objectContaining({ skipRoute: true })
);
expect(mockTemplate.registerInProject).toHaveBeenCalledTimes(1);
expect(mockTemplate.registerInProject).toHaveBeenCalledWith(
directoryPath, "test-file-name",
jasmine.objectContaining({ skipRoute: true })
);
expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalledWith(mockTemplate);
done();
});
it("Should not add component and should log error if wrong path is passed to module", async done => {
spyOn(Util, "fileExists").and.returnValue(false);
spyOn(Util, "error");
const wrongPath = "myCustomModule/my-custom-module.module.ts";
addCmd.addTemplate("test-file-name", new AngularTemplate(__dirname), { modulePath: wrongPath });
expect(Util.fileExists).toHaveBeenCalledTimes(1);
expect(Util.error).toHaveBeenCalledTimes(1);
expect(Util.error).toHaveBeenCalledWith(`Wrong module path provided: ${wrongPath}. No components were added!`);
done();
});
}); | the_stack |
import {RequestOptions} from "http";
import {Readable} from "stream";
export = hbase;
/**
* Calling the hbase method return an initialized client object.
* https://hbase.js.org/api/client/#grab-an-instance-of-hbaseclient
* @param config
*/
declare function hbase(config: hbase.ClientConfig): hbase.Client;
/**
* HBase client for Node.js using REST
* https://hbase.js.org/
*/
declare namespace hbase {
type CallbackType<T = any> = (err: Error, data: T, response?) => void;
/**
* krb5 options
* https://hbase.js.org/api/client/#creating-a-new-client
*/
interface KerberosOptions {
principal: string;
password?: string;
keytab?: string;
service_principal: string;
}
/**
* A new instance of "HBase" may be instantiated with an object containing the following properties
* https://hbase.js.org/api/client/#creating-a-new-client
*/
interface ClientConfig extends RequestOptions {
krb5?: KerberosOptions | any;
encoding?: string;
}
/**
* Client: server information and API entry point
* https://hbase.js.org/api/client/#client-server-information-and-api-entry-point
*/
class Client {
options: ClientConfig;
connection: Connection;
/**
* Constructor
* https://hbase.js.org/api/client/#creating-a-new-client
* @param options
*/
constructor(options: ClientConfig);
/**
* Query the storage cluster status.
* https://hbase.js.org/api/client/#api-clientstatus_cluster
* @param callback
*/
status_cluster(callback: CallbackType): void;
/**
* Return a new instance of "hbase.Table"
* https://hbase.js.org/api/client/#api-clienttable
* @param name
*/
table(name: string): Table;
/**
* List of all non-system tables.
* https://hbase.js.org/api/client/#api-clienttables
* @param callback
*/
tables(callback: CallbackType): void;
/**
* Query Software Version.
* https://hbase.js.org/api/client/#api-version
* @param callback
*/
version(callback: CallbackType): void;
/**
* Query the storage cluster version.
* https://hbase.js.org/api/client/#api-version_cluster
* @param callback
*/
version_cluster(callback: CallbackType): void;
}
/**
* Connection: HTTP REST requests for HBase
* https://hbase.js.org/api/connection/#connection-http-rest-requests-for-hbase
*/
class Connection {
client: Client;
options: any;
/**
* Pass client to get new Connection
* https://hbase.js.org/api/connection/#creating-a-new-connection
* @param client
*/
constructor(client: Client);
/**
* Execute an HTTP Delete request.
* The callback contains 3 arguments:
* the error object if any,
* the decoded response body,
* the Node http.ClientResponse object.
* @param command
* @param callback
*/
delete(command: string, callback: CallbackType): void;
/**
* https://hbase.js.org/api/connection/#http-get-requests
* Execute an HTTP Get request to hbase rest server.
* The callback contains 3 arguments:
* the error object if any,
* the decoded response body,
* the Node http.ClientResponse object.
* @param command
* @param callback
*/
get(command: string, callback: CallbackType): void;
/**
* Private method used to process JSON
* @param response
* @param body
*/
handleJson(response: any, body: any): void;
/**
* Internal method used to make API calls to hbase rest
* @param method
* @param command
* @param data
* @param callback
*/
makeRequest(method: string, command: string, data: any, callback: CallbackType): void;
/**
* Execute an HTTP POST request to hbase rest server.
* The callback contains 3 arguments:
* the error object if any,
* the decoded response body,
* the Node http.ClientResponse object.
* @param command
* @param data
* @param callback
*/
post(command: string, data: any, callback: CallbackType): void;
/**
* Execute an HTTP PUT request to hbase rest server.
* The callback contains 3 arguments:
* the error object if any,
* the decoded response body,
* the Node http.ClientResponse object.
* @param command
* @param data
* @param callback
*/
put(command: string, data: any, callback: CallbackType): void;
}
/**
* Row: CRUD operations on rows and columns
* Row objects provide access and manipulation on colunns and rows.
* Single and multiple operations are available and are documented below.
* https://hbase.js.org/api/row/
*/
class Row {
client: Client;
/**
* @description correspond to Table.name
*/
table: string;
key: string;
/**
* Grab an instance of Row
* https://hbase.js.org/api/row/#grab-an-instance-of-row
* @param client
* @param table
* @param key
*/
constructor(client: Client, table: Table, key: string);
/**
* Delete one or multiple rows or columns.
* Column is optional and corresponds to a column family
* optionally followed by a column name separated with a column (":").
* Callback is required and receive two arguments,
* an error object if any and
* a boolean indicating whether the column exists or not.
* https://hbase.js.org/api/row/#api-rowdelete
* @param column
* @param callback
*/
delete(column: string, callback: CallbackType): void;
delete(callback: CallbackType): void;
/**
* Test if a row or a column exists.
* The column argument is optional and corresponds to a column family optionally followed by a column name separated with a colon character (":").
* The callback argument is required and receives two arguments,
* an error object if any
* and a boolean value indicating whether the column exists or not.
* https://hbase.js.org/api/row/#api-rowexists
* @param column
* @param callback
*/
exists(column: string, callback: CallbackType): void;
exists(callback: CallbackType): void;
/**
* Retrieve values from one or multiple rows.
* Values from multiple rows is achieved by appending a suffix glob on the row key.
* Note the new "key" property present in the returned objects.
* https://hbase.js.org/api/row/#api-rowget
* @param column
* @param callback
*/
get(column: string, callback: CallbackType): void;
/**
* Insert and update one or multiple column values.
* Column is required and corresponds to a column family optionally followed by a column name separated with a column (":").
* Callback is optional and receive two arguments,
* an error object if any and
* a boolean indicating whether the column was inserted/updated or not.
* https://hbase.js.org/api/row/#api-rowput
* @param columns
* @param values
* @param callback
*/
put(columns: any, values: any, callback: CallbackType): void;
}
/**
* Scanner options
* https://hbase.js.org/api/scanner/#options
*/
interface ScannerConfig {
table: string;
startRow?: number;
endRow?: number;
columns?: string;
batch?: number;
maxVersions?: number;
startTime?: string | Date;
endTime?: string | Date;
filter?: any;
encoding?: string;
}
/**
* Scanner and filter operations:
* Scanner are the most efficient way to retrieve multiple rows and columns from HBase.
* For scalability reasons, this module implements internally the native Node.js Stream Readable API.
* https://hbase.js.org/api/scanner/
*/
class Scanner extends Readable {
client: Client;
options: ScannerConfig;
/**
* Grab an instance of "Scanner"
* https://hbase.js.org/api/scanner/#grab-an-instance-of-scanner
* @param client
* @param options
*/
constructor(client: Client, options: ScannerConfig);
/**
* Internal method to unregister the scanner from the HBase server.
* The callback is optional and receives two arguments,
* an error object if any and
* a boolean indicating whether the scanner was removed or not.
* https://hbase.js.org/api/scanner/#api-scannerdelete
* @param callback
*/
delete(callback: CallbackType<boolean>): void;
/**
* Internal method to retrieve a batch of records.
* The method is expected to be called multiple time to get the next cells from HBase.
* The callback is required and receive two arguments,
* an error object if any and
* a array of cells or null if the scanner is exhausted.
* https://hbase.js.org/api/scanner/#api-scannerget
* @param callback
*/
get(callback: CallbackType): void;
/**
* Internal method to create a new scanner and retrieve its ID.
* https://hbase.js.org/api/scanner/#options
* @param callback
*/
init(callback: CallbackType): any;
/**
* Implementation of the stream.Readable API.
* https://hbase.js.org/api/scanner/#api-scanner_readsize
* @param size
*/
_read(size: number);
}
/**
* Table operations: create, modify and delete HBase tables
* https://hbase.js.org/api/table/
*/
class Table {
client: Client;
name: string;
/**
* Grab an instance of "hbase.Table"
* https://hbase.js.org/api/table/#grab-an-instance-of-hbasetable
* @param client
* @param name
*/
constructor(client: Client, name: string);
/**
* Create a new table in HBase.
* Callback is optional and receive two arguments,
* an error object if any and
* a boolean indicating whether the table was created or not.
*
* The simplest way is to grab a table object and call its create function with the schema as argument.
* https://hbase.js.org/api/table/#api-tablecreate
* @param schema
* @param callback
*/
create(schema?: any, callback?: CallbackType<boolean>): void;
// create(schema: any, callback?: CallbackType<boolean>): void;
// create(schema: any, callback: CallbackType<boolean>): void;
/**
* Drop an existing table.
* The callback argument is optional and receives two arguments,
* an error object if any and
* a boolean value indicating whether the table was removed/disabled or not.
* https://hbase.js.org/api/table/#api-tabledelete
* @param callback
*/
delete(callback: CallbackType<boolean>): void;
/**
* Check if a table is created.
* https://hbase.js.org/api/table/#api-tableexists
* @param callback
*/
exists(callback: CallbackType<boolean>): void;
/**
* Retrieves the table region metadata
* https://hbase.js.org/api/table/#api-tableregions
* @param callback
*/
regions(callback: CallbackType): void;
/**
* Return a new row instance.
* https://hbase.js.org/api/table/#api-tablerow
* @param key
*/
row(key: string): Row;
/**
* Return a new scanner instance.
* https://hbase.js.org/api/table/#api-tablescan
* @param options
* @param callback
*/
scan(options?: Omit<ScannerConfig, 'table'>, callback?: CallbackType): Scanner;
/**
* Retrieves the table schema.
* https://hbase.js.org/api/table/#api-tableschema
* @param callback
*/
schema(callback: CallbackType): void;
/**
* Update an existing table
* https://hbase.js.org/api/table/#update-an-existing-table
* @param schema
* @param callback
*/
update(schema: string, callback: CallbackType): void;
}
/**
* Utility functions for internal use of library
*/
namespace utils {
function merge(...args: any[]): any;
namespace base64 {
// tslint:disable-next-line:variable-name
function decode(data: Buffer | string, from_encoding: string): string;
// tslint:disable-next-line:variable-name
function encode(data: Buffer | string, to_encoding: string): string;
}
namespace url {
function encode(args: {
table: string;
key: string;
columns: [] | { key: any } | string;
start: string;
end: string;
params: { key: any };
}): string;
}
}
} | the_stack |
import { jsx, css } from "@emotion/core";
import * as React from "react";
import color from "color";
import PropTypes from "prop-types";
import { alpha, lighten } from "./Theme/colors";
import { Spinner } from "./Spinner";
import { useTheme } from "./Theme/Providers";
import { Theme } from "./Theme";
import { IconWrapper } from "./IconWrapper";
import { useTouchable, OnPressFunction } from "touchable-hook";
import cx from "classnames";
import { safeBind } from "./Hooks/compose-bind";
export type ButtonSize = "xs" | "sm" | "md" | "lg" | "xl";
const getTextColor = (background: string, theme: Theme) => {
return color(background).isDark() ? "white" : theme.modes.light.text.default;
};
export const getHeight = (size: ButtonSize) => {
if (size === "xs") return "25px";
if (size === "sm") return "30px";
if (size === "lg") return "48px";
if (size === "xl") return "60px";
return "40px";
};
const getPadding = (size: ButtonSize) => {
if (size === "xs") return "0 0.5rem";
if (size === "sm") return "0 0.8rem";
if (size === "lg") return "0 1.5rem";
if (size === "xl") return "0 2.2rem";
return "0 1rem";
};
const getFontSize = (size: ButtonSize, theme: Theme) => {
if (size === "xs") return theme.fontSizes[0];
if (size === "lg") return theme.fontSizes[2];
if (size === "sm") return theme.fontSizes[0];
if (size === "xl") return theme.fontSizes[3];
return theme.fontSizes[1];
};
const getDisplay = (block?: boolean) => (block ? "flex" : "inline-flex");
function gradient(start: string, end: string) {
return `linear-gradient(to top, ${start}, ${end})`;
}
function insetShadow(from: string, to: string) {
return `inset 0 0 0 1px ${from}, inset 0 -1px 1px 0 ${to}`;
}
export function focusShadow(first: string, second: string, third: string) {
return `0 0 0 3px ${first}, inset 0 0 0 1px ${second}, inset 0 -1px 1px 0 ${third}`;
}
export const buttonReset = css({
textDecoration: "none",
background: "none",
whiteSpace: "nowrap",
WebkitAppearance: "none",
boxSizing: "border-box",
textAlign: "center",
WebkitFontSmoothing: "antialiased",
border: "none",
textRendering: "optimizeLegibility",
userSelect: "none",
WebkitTapHighlightColor: "transparent",
cursor: "pointer",
boxShadow: "none"
});
/**
* Intent describes the intention of the button
* -- eg., does it indicate danger?
*/
const getIntentStyles = (
theme: Theme,
intent: ButtonIntent,
_hover: boolean,
active: boolean
) => {
const dark = theme.colors.mode === "dark";
const { palette } = theme.colors;
const activeShadow = dark
? insetShadow(alpha(palette.gray.dark, 1), alpha(palette.gray.dark, 0.9))
: insetShadow(alpha(palette.gray.dark, 0.5), alpha(palette.gray.dark, 0.5));
switch (intent) {
case "none": {
if (dark)
return css([
{
backgroundColor: theme.colors.scales.gray[5],
color: getTextColor(theme.colors.intent.none.base, theme),
background: gradient(
theme.colors.intent.none.base,
lighten(theme.colors.intent.none.base, 0.6)
),
boxShadow: insetShadow(
alpha(theme.colors.palette.gray.dark, 0.9),
alpha(theme.colors.palette.gray.dark, 0.8)
),
'&[aria-expanded="true"]': {
background: "none",
backgroundColor: theme.colors.intent.none.base,
boxShadow: insetShadow(
alpha(palette.gray.base, 1),
alpha(palette.gray.base, 0.9)
)
}
},
active && {
background: "none",
backgroundColor: theme.colors.intent.none.base,
boxShadow: insetShadow(
alpha(theme.colors.palette.gray.dark, 1),
alpha(theme.colors.palette.gray.dark, 0.9)
)
}
]);
return css([
{
backgroundColor: "white",
color: getTextColor(theme.colors.intent.none.lightest, theme),
background: gradient(theme.colors.intent.none.lightest, "white"),
boxShadow: insetShadow(
alpha(theme.colors.palette.gray.dark, 0.2),
alpha(theme.colors.palette.gray.dark, 0.1)
),
'&[aria-expanded="true"]': {
background: "none",
backgroundColor: theme.colors.intent.none.lightest,
boxShadow: insetShadow(
alpha(palette.gray.dark, 0.3),
alpha(palette.gray.dark, 0.15)
)
}
},
active && {
background: "none",
backgroundColor: theme.colors.intent.none.lightest,
boxShadow: insetShadow(
alpha(palette.gray.dark, 0.3),
alpha(palette.gray.dark, 0.15)
)
}
]);
}
case "primary":
return css([
{
backgroundColor: theme.colors.intent.primary.base,
color: getTextColor(theme.colors.intent.primary.base, theme),
backgroundImage: gradient(
theme.colors.intent.primary.base,
color(theme.colors.intent.primary.base)
.lighten(0.4)
.toString()
),
boxShadow: dark
? insetShadow(
theme.colors.palette.gray.dark,
theme.colors.palette.gray.dark
)
: insetShadow(
alpha(palette.gray.dark, 0.2),
alpha(palette.gray.dark, 0.2)
),
'&[aria-expanded="true"]': {
boxShadow: activeShadow,
backgroundImage: gradient(
theme.colors.intent.primary.dark,
theme.colors.intent.primary.base
)
}
},
active && {
boxShadow: activeShadow,
backgroundImage: gradient(
theme.colors.intent.primary.dark,
theme.colors.intent.primary.base
)
}
]);
case "success":
return css([
{
backgroundColor: theme.colors.intent.success.base,
color: getTextColor(theme.colors.intent.success.base, theme),
backgroundImage: gradient(
theme.colors.intent.success.base,
color(theme.colors.intent.success.base)
.lighten(0.5)
.toString()
),
boxShadow: dark
? insetShadow(
theme.colors.palette.gray.dark,
theme.colors.palette.gray.dark
)
: insetShadow(
alpha(palette.gray.dark, 0.2),
alpha(palette.gray.dark, 0.2)
),
'&[aria-expanded="true"]': {
boxShadow: activeShadow,
backgroundImage: gradient(
color(theme.colors.intent.success.base)
.darken(0.2)
.toString(),
theme.colors.intent.success.base
)
}
},
active && {
boxShadow: activeShadow,
backgroundImage: gradient(
color(theme.colors.intent.success.base)
.darken(0.2)
.toString(),
theme.colors.intent.success.base
)
}
]);
case "danger":
return css([
{
backgroundColor: theme.colors.intent.danger.base,
color: getTextColor(theme.colors.intent.danger.base, theme),
backgroundImage: gradient(
theme.colors.intent.danger.base,
color(theme.colors.intent.danger.base)
.lighten(0.3)
.toString()
),
boxShadow: dark
? insetShadow(
theme.colors.palette.gray.dark,
theme.colors.palette.gray.dark
)
: insetShadow(
alpha(palette.gray.dark, 0.2),
alpha(palette.gray.dark, 0.2)
),
'&[aria-expanded="true"]': {
boxShadow: activeShadow,
backgroundImage: gradient(
color(theme.colors.intent.danger.base)
.darken(0.2)
.toString(),
theme.colors.intent.danger.base
)
}
},
active && {
boxShadow: activeShadow,
backgroundImage: gradient(
color(theme.colors.intent.danger.base)
.darken(0.2)
.toString(),
theme.colors.intent.danger.base
)
}
]);
case "warning":
return css([
{
backgroundColor: theme.colors.intent.warning.base,
color: getTextColor(theme.colors.intent.warning.base, theme),
backgroundImage: gradient(
theme.colors.intent.warning.base,
color(theme.colors.intent.warning.base)
.lighten(0.4)
.toString()
),
boxShadow: dark
? insetShadow(
theme.colors.palette.gray.dark,
theme.colors.palette.gray.dark
)
: insetShadow(
alpha(palette.gray.dark, 0.2),
alpha(palette.gray.dark, 0.2)
),
'&[aria-expanded="true"]': {
boxShadow: activeShadow,
backgroundImage: gradient(
color(theme.colors.intent.warning.base)
.darken(0.2)
.toString(),
theme.colors.intent.warning.base
)
}
},
active && {
boxShadow: activeShadow,
backgroundImage: gradient(
color(theme.colors.intent.warning.base)
.darken(0.2)
.toString(),
theme.colors.intent.warning.base
)
}
]);
}
};
export type ButtonIntent =
| "none"
| "warning"
| "primary"
| "success"
| "danger";
// variations to the ghost buttons based on intent
const ghostIntents = (
theme: Theme,
intent: ButtonIntent,
hover: boolean,
active: boolean
) => {
const none = intent === "none";
const dark = theme.colors.mode === "dark";
let base = none
? theme.colors.text.default
: theme.colors.intent[intent].base;
if (dark && !none) {
base = theme.colors.intent[intent].light;
}
return css([
{
color: none ? theme.colors.text.muted : base,
opacity: 1,
background: "transparent",
boxShadow: "none",
transition:
"box-shadow 0.07s cubic-bezier(0.35,0,0.25,1), background 0.07s cubic-bezier(0.35,0,0.25,1), opacity 0.35s cubic-bezier(0.35,0,0.25,1)",
'&[aria-expanded="true"]': {
background: alpha(base, 0.15),
boxShadow: "none",
opacity: 1
}
},
hover && {
background: alpha(base, 0.07)
},
active && {
background: alpha(base, 0.15),
boxShadow: "none",
opacity: 1
}
]);
};
// variations to the outline buttons based on intent
const outlineIntents = (
theme: Theme,
intent: ButtonIntent,
hover: boolean,
active: boolean
) => {
const none = intent === "none";
const dark = theme.colors.mode === "dark";
let base = none
? theme.colors.text.default
: theme.colors.intent[intent].base;
if (dark && !none) {
base = theme.colors.intent[intent].light;
}
return css([
{
color: base,
borderColor: alpha(base, 0.2),
boxShadow: "none",
transition:
"box-shadow 0.07s cubic-bezier(0.35,0,0.25,1), background 0.07s cubic-bezier(0.35,0,0.25,1)",
'&[aria-expanded="true"]': {
background: alpha(base, 0.15)
}
},
hover && {
background: alpha(base, 0.05)
},
active && {
background: alpha(base, 0.15)
}
]);
};
const variants = {
default: css({}),
ghost: css({
background: "transparent",
boxShadow: "none"
}),
outline: css({
border: `1px solid`,
background: "none"
})
};
const iconSpaceForSize = (theme: Theme) => ({
xs: `calc(${theme.iconSizes.xs} + 0.6rem)`,
sm: `calc(${theme.iconSizes.sm} + 0.6rem)`,
md: `calc(${theme.iconSizes.md} + 0.6rem)`,
lg: `calc(${theme.iconSizes.lg} + 0.6rem)`,
xl: `calc(${theme.iconSizes.xl} + 0.6rem)`
});
export type ButtonVariant = keyof typeof variants;
export interface ButtonStyleProps {
/** Use onPress instead of onClick to handle both touch and click events */
onPress?: OnPressFunction;
/** Controls the basic button style. */
variant?: ButtonVariant;
/** Controls the colour of the button. */
intent?: ButtonIntent;
/** If true, the button will be displayed as a block element instead of inline. */
block?: boolean;
/** The size of the button. */
size?: ButtonSize;
/** Show a loading indicator */
loading?: boolean;
disabled?: boolean;
/** The name of the icon to appear to the left of the button text*/
iconBefore?: React.ReactNode;
/** The name of the icon to appear to the right of the button text */
iconAfter?: React.ReactNode;
/** By default, a button element will only highlight after a short
* delay to prevent unintended highlights when scrolling. You can set this to
* 0 if the element is not in a scrollable container */
pressDelay?: number;
/**
* By default, a touchable element will have an expanded press area of 20px
* on touch devices. This will only effect touch devices.
*/
pressExpandPx?: number;
}
export interface ButtonProps
extends ButtonStyleProps,
React.ButtonHTMLAttributes<HTMLButtonElement> {
children: React.ReactNode;
ref?: React.Ref<HTMLButtonElement>;
component?: React.ReactType<any>;
[key: string]: any; // bad hack to permit component injection
}
/**
* Your standard Button element
*/
export const Button: React.RefForwardingComponent<
React.Ref<HTMLButtonElement>,
ButtonProps
> = React.forwardRef(
(
{
size = "md",
block,
variant = "default",
intent = "none",
className = "",
disabled = false,
loading = false,
component: Component = "div",
iconBefore,
iconAfter,
children,
pressDelay = 0,
pressExpandPx,
onPress,
...other
}: ButtonProps,
ref: React.Ref<any>
) => {
const theme = useTheme();
const isLink = other.to || other.href;
const { bind, hover, active } = useTouchable({
onPress,
delay: pressDelay,
pressExpandPx,
disabled,
behavior: isLink ? "link" : "button"
});
// how necessary is this?
const intentStyle = React.useMemo(
() => getIntent(variant, intent, theme, hover, active),
[variant, intent, theme, hover, active]
);
if (other.type === "submit" && Component === "div") {
Component = "button";
}
return (
<Component
className={cx("Button", "Touchable", className, {
"Touchable--hover": hover,
"Touchable--active": active
})}
role={isLink ? "link" : "button"}
tabIndex={0}
css={[
buttonReset,
{
width: block ? "100%" : undefined,
fontWeight: 500,
position: "relative",
fontFamily: theme.fonts.base,
borderRadius: theme.radii.sm,
fontSize: getFontSize(size, theme),
padding: getPadding(size),
height: getHeight(size),
display: getDisplay(block),
alignItems: "center",
justifyContent: "center",
":focus": {
outline: theme.outline
},
":focus:not([data-focus-visible-added])": {
outline: other.autoFocus ? "theme.outline" : "none"
}
},
variants[variant],
intentStyle,
disabled && {
opacity: 0.6,
pointerEvents: "none"
},
loading && {
"& > :not(.Spinner)": {
opacity: 0,
transition: "opacity 0.1s ease"
}
},
(iconBefore || (block && iconAfter)) && {
paddingLeft: "0.65rem"
},
(iconAfter || (block && iconBefore)) && {
paddingRight: "0.65rem"
}
]}
{...safeBind(bind, { ref }, other)}
>
{loading && (
<div
className="Spinner"
css={{
position: "absolute",
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)"
}}
>
<Spinner delay={1} size={size} />
</div>
)}
{iconBefore && (
<IconWrapper
css={{ marginRight: theme.spaces.sm }}
size={size}
color="currentColor"
aria-hidden
>
{iconBefore}
</IconWrapper>
)}
{typeof children === "string" ? (
<span
css={{
flex: 1,
// kinda lame hack to center our text in block
// mode with icons before and after
marginRight:
block && iconBefore && !iconAfter
? iconSpaceForSize(theme)[size]
: 0,
marginLeft:
block && iconAfter && !iconBefore
? iconSpaceForSize(theme)[size]
: 0
}}
aria-hidden={loading}
>
{children}
</span>
) : (
children
)}
{iconAfter && (
<IconWrapper
color="currentColor"
css={{ marginLeft: theme.spaces.sm }}
size={size}
>
{iconAfter}
</IconWrapper>
)}
</Component>
);
}
);
Button.displayName = "Button";
Button.propTypes = {
variant: PropTypes.oneOf(["default", "ghost", "outline"] as ButtonVariant[]),
size: PropTypes.oneOf(["xs", "sm", "md", "lg", "xl"] as ButtonSize[]),
block: PropTypes.bool,
intent: PropTypes.oneOf([
"none",
"primary",
"success",
"warning",
"danger"
] as ButtonIntent[]),
iconBefore: PropTypes.node,
iconAfter: PropTypes.node
};
function getIntent(
variant: ButtonVariant,
intent: ButtonIntent,
theme: Theme,
hover: boolean,
active: boolean
) {
switch (variant) {
case "default":
return getIntentStyles(theme, intent, hover, active);
case "ghost":
return ghostIntents(theme, intent, hover, active);
case "outline":
return outlineIntents(theme, intent, hover, active);
}
} | the_stack |
module BABYLON {
export interface ICommand {
canExecute(parameter: any): boolean;
execute(parameter: any): void;
canExecuteChanged: Observable<void>;
}
export class Command implements ICommand {
constructor(execute: (p) => void, canExecute: (p) => boolean) {
if (!execute) {
throw Error("At least an execute lambda must be given at Command creation time");
}
this._canExecuteChanged = null;
this._lastCanExecuteResult = null;
this.execute = execute;
this.canExecute = canExecute;
}
canExecute(parameter): boolean {
let res = true;
if (this._canExecute) {
res = this._canExecute(parameter);
}
if (res !== this._lastCanExecuteResult) {
if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
this._canExecuteChanged.notifyObservers(null);
}
this._lastCanExecuteResult = res;
}
return res;
}
execute(parameter): void {
this._execute(parameter);
}
get canExecuteChanged(): Observable<void> {
if (!this._canExecuteChanged) {
this._canExecuteChanged = new Observable<void>();
}
return this._canExecuteChanged;
}
private _lastCanExecuteResult: boolean;
private _execute: (p) => void;
private _canExecute: (p) => boolean;
private _canExecuteChanged: Observable<void>;
}
export abstract class UIElement extends SmartPropertyBase {
static get enabledState(): string {
return UIElement._enableState;
}
static get disabledState(): string {
return UIElement._disabledState;
}
static get mouseOverState(): string {
return UIElement._mouseOverState;
}
static UIELEMENT_PROPCOUNT: number = 16;
static parentProperty : Prim2DPropInfo;
static widthProperty : Prim2DPropInfo;
static heightProperty : Prim2DPropInfo;
static minWidthProperty : Prim2DPropInfo;
static minHeightProperty : Prim2DPropInfo;
static maxWidthProperty : Prim2DPropInfo;
static maxHeightProperty : Prim2DPropInfo;
static actualWidthProperty : Prim2DPropInfo;
static actualHeightProperty : Prim2DPropInfo;
static marginProperty : Prim2DPropInfo;
static paddingProperty : Prim2DPropInfo;
static marginAlignmentProperty : Prim2DPropInfo;
static paddingAlignmentProperty: Prim2DPropInfo;
static isEnabledProperty : Prim2DPropInfo;
static isFocusedProperty : Prim2DPropInfo;
static isMouseOverProperty : Prim2DPropInfo;
constructor(settings: {
id ?: string,
parent ?: UIElement,
templateName ?: string,
styleName ?: string,
minWidth ?: number,
minHeight ?: number,
maxWidth ?: number,
maxHeight ?: number,
width ?: number,
height ?: number,
marginTop ?: number | string,
marginLeft ?: number | string,
marginRight ?: number | string,
marginBottom ?: number | string,
margin ?: number | string,
marginHAlignment ?: number,
marginVAlignment ?: number,
marginAlignment ?: string,
paddingTop ?: number | string,
paddingLeft ?: number | string,
paddingRight ?: number | string,
paddingBottom ?: number | string,
padding ?: string,
paddingHAlignment?: number,
paddingVAlignment?: number,
paddingAlignment ?: string,
}) {
super();
if (!settings) {
throw Error("A settings object must be passed with at least either a parent or owner parameter");
}
let type = Tools.getFullClassName(this);
this._ownerWindow = null;
this._parent = null;
this._visualPlaceholder = null;
this._visualTemplateRoot = null;
this._visualChildrenPlaceholder = null;
this._hierarchyDepth = 0;
this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
this._style = (settings.styleName!=null) ? GUIManager.getStyle(type, settings.styleName) : null;
this._flags = 0;
this._id = (settings.id!=null) ? settings.id : null;
this._uid = null;
this._width = (settings.width != null) ? settings.width : null;
this._height = (settings.height != null) ? settings.height : null;
this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
this._margin = null;
this._padding = null;
this._marginAlignment = null;
this._setFlags(UIElement.flagIsVisible|UIElement.flagIsEnabled);
// Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
//this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
//this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
// Set the layout/margin stuffs
if (settings.marginTop) {
this.margin.setTop(settings.marginTop);
}
if (settings.marginLeft) {
this.margin.setLeft(settings.marginLeft);
}
if (settings.marginRight) {
this.margin.setRight(settings.marginRight);
}
if (settings.marginBottom) {
this.margin.setBottom(settings.marginBottom);
}
if (settings.margin) {
if (typeof settings.margin === "string") {
this.margin.fromString(<string>settings.margin);
} else {
this.margin.fromUniformPixels(<number>settings.margin);
}
}
if (settings.marginHAlignment) {
this.marginAlignment.horizontal = settings.marginHAlignment;
}
if (settings.marginVAlignment) {
this.marginAlignment.vertical = settings.marginVAlignment;
}
if (settings.marginAlignment) {
this.marginAlignment.fromString(settings.marginAlignment);
}
if (settings.paddingTop) {
this.padding.setTop(settings.paddingTop);
}
if (settings.paddingLeft) {
this.padding.setLeft(settings.paddingLeft);
}
if (settings.paddingRight) {
this.padding.setRight(settings.paddingRight);
}
if (settings.paddingBottom) {
this.padding.setBottom(settings.paddingBottom);
}
if (settings.padding) {
this.padding.fromString(settings.padding);
}
if (settings.paddingHAlignment) {
this.paddingAlignment.horizontal = settings.paddingHAlignment;
}
if (settings.paddingVAlignment) {
this.paddingAlignment.vertical = settings.paddingVAlignment;
}
if (settings.paddingAlignment) {
this.paddingAlignment.fromString(settings.paddingAlignment);
}
if (settings.parent != null) {
this._parent = settings.parent;
this._hierarchyDepth = this._parent._hierarchyDepth + 1;
}
}
public dispose(): boolean {
if (this.isDisposed) {
return false;
}
if (this._renderingTemplate) {
this._renderingTemplate.detach();
this._renderingTemplate = null;
}
super.dispose();
// Don't set to null, it may upset somebody...
this.animations.splice(0);
return true;
}
/**
* Animation array, more info: http://doc.babylonjs.com/tutorials/Animations
*/
public animations: Animation[];
/**
* Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
* Look at Sprite2D for more information
*/
public getAnimatables(): IAnimatable[] {
return new Array<IAnimatable>();
}
// TODO
// PROPERTIES
// Style
// Id
// Parent/Children
// ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
// Alignment/Margin
// Visibility, IsVisible
// IsEnabled (is false, control is disabled, no interaction and a specific render state)
// CacheMode of Visual Elements
// Focusable/IsFocused
// IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
// ContextMenu
// Cursor
// DesiredSize
// IsInputEnable ?
// Opacity, OpacityMask ?
// SnapToDevicePixels
// Tag
// ToolTip
// METHODS
// BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
// Capture/ReleaseCapture (mouse, touch, stylus)
// Focus
// PointFrom/ToScreen to translate coordinates
// EVENTS
// ContextMenuOpening/Closing/Changed
// DragEnter/LeaveOver, Drop
// Got/LostFocus
// IsEnabledChanged
// IsPointerOver/DirectlyOverChanged
// IsVisibleChanged
// KeyDown/Up
// LayoutUpdated ?
// Pointer related events
// SizeChanged
// ToolTipOpening/Closing
public findById(id: string): UIElement {
if (this._id === id) {
return this;
}
let children = this._getChildren();
for (let child of children) {
let r = child.findById(id);
if (r != null) {
return r;
}
}
}
public get ownerWindow(): Window {
return this._ownerWindow;
}
public get style(): string {
if (!this.style) {
return GUIManager.DefaultStyleName;
}
return this._style.name;
}
public set style(value: string) {
if (this._style && (this._style.name === value)) {
return;
}
let newStyle: UIElementStyle = null;
if (value) {
newStyle = GUIManager.getStyle(Tools.getFullClassName(this), value);
if (!newStyle) {
throw Error(`Couldn't find Style ${value} for UIElement ${Tools.getFullClassName(this)}`);
}
}
if (this._style) {
this._style.removeStyle(this);
}
if (newStyle) {
newStyle.applyStyle(this);
}
this._style = newStyle;
}
/**
* A string that identifies the UIElement.
* The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
*/
public get id(): string {
return this._id;
}
public set id(value: string) {
if (this._id === value) {
return;
}
this._id = value;
}
/**
* Return a unique id automatically generated.
* This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
*/
public get uid(): string {
if (!this._uid) {
this._uid = Tools.RandomId();
}
return this._uid;
}
public get hierarchyDepth(): number {
return this._hierarchyDepth;
}
@dependencyProperty(0, pi => UIElement.parentProperty = pi)
public get parent(): UIElement {
return this._parent;
}
public set parent(value: UIElement) {
this._parent = value;
}
@dependencyProperty(1, pi => UIElement.widthProperty = pi)
public get width(): number {
return this._width;
}
public set width(value: number) {
this._width = value;
}
@dependencyProperty(2, pi => UIElement.heightProperty = pi)
public get height(): number {
return this._height;
}
public set height(value: number) {
this._height = value;
}
@dependencyProperty(3, pi => UIElement.minWidthProperty = pi)
public get minWidth(): number {
return this._minWidth;
}
public set minWidth(value: number) {
this._minWidth = value;
}
@dependencyProperty(4, pi => UIElement.minHeightProperty = pi)
public get minHheight(): number {
return this._minHeight;
}
public set minHeight(value: number) {
this._minHeight = value;
}
@dependencyProperty(5, pi => UIElement.maxWidthProperty = pi)
public get maxWidth(): number {
return this._maxWidth;
}
public set maxWidth(value: number) {
this._maxWidth = value;
}
@dependencyProperty(6, pi => UIElement.maxHeightProperty = pi)
public get maxHeight(): number {
return this._maxHeight;
}
public set maxHeight(value: number) {
this._maxHeight = value;
}
@dependencyProperty(7, pi => UIElement.actualWidthProperty = pi)
public get actualWidth(): number {
return this._actualWidth;
}
public set actualWidth(value: number) {
this._actualWidth = value;
}
@dependencyProperty(8, pi => UIElement.actualHeightProperty = pi)
public get actualHeight(): number {
return this._actualHeight;
}
public set actualHeight(value: number) {
this._actualHeight = value;
}
@dynamicLevelProperty(9, pi => UIElement.marginProperty = pi)
/**
* You can get/set a margin on the primitive through this property
* @returns the margin object, if there was none, a default one is created and returned
*/
public get margin(): PrimitiveThickness {
if (!this._margin) {
this._margin = new PrimitiveThickness(() => {
if (!this.parent) {
return null;
}
return this.parent.margin;
});
}
return this._margin;
}
public set margin(value: PrimitiveThickness) {
this.margin.copyFrom(value);
}
public get _hasMargin(): boolean {
return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
}
@dynamicLevelProperty(10, pi => UIElement.paddingProperty = pi)
/**
* You can get/set a margin on the primitive through this property
* @returns the margin object, if there was none, a default one is created and returned
*/
public get padding(): PrimitiveThickness {
if (!this._padding) {
this._padding = new PrimitiveThickness(() => {
if (!this.parent) {
return null;
}
return this.parent.padding;
});
}
return this._padding;
}
public set padding(value: PrimitiveThickness) {
this.padding.copyFrom(value);
}
private get _hasPadding(): boolean {
return this._padding !== null && !this._padding.isDefault;
}
@dynamicLevelProperty(11, pi => UIElement.marginAlignmentProperty = pi)
/**
* You can get/set the margin alignment through this property
*/
public get marginAlignment(): PrimitiveAlignment {
if (!this._marginAlignment) {
this._marginAlignment = new PrimitiveAlignment();
}
return this._marginAlignment;
}
public set marginAlignment(value: PrimitiveAlignment) {
this.marginAlignment.copyFrom(value);
}
/**
* Check if there a marginAlignment specified (non null and not default)
*/
public get _hasMarginAlignment(): boolean {
return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
}
@dynamicLevelProperty(12, pi => UIElement.paddingAlignmentProperty = pi)
/**
* You can get/set the margin alignment through this property
*/
public get paddingAlignment(): PrimitiveAlignment {
if (!this._paddingAlignment) {
this._paddingAlignment = new PrimitiveAlignment();
}
return this._paddingAlignment;
}
public set paddingAlignment(value: PrimitiveAlignment) {
this.paddingAlignment.copyFrom(value);
}
/**
* Check if there a marginAlignment specified (non null and not default)
*/
public get _hasPaddingAlignment(): boolean {
return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
}
public get isVisible(): boolean {
return this._isFlagSet(UIElement.flagIsVisible);
}
public set isVisible(value: boolean) {
if (this.isVisible === value) {
return;
}
this._visualPlaceholder.levelVisible = value;
this._changeFlags(UIElement.flagIsVisible, value);
}
@dynamicLevelProperty(13, pi => UIElement.isEnabledProperty = pi)
/**
* True if the UIElement is enabled, false if it's disabled.
* User interaction is not possible if the UIElement is not enabled
*/
public get isEnabled(): boolean {
return this._isFlagSet(UIElement.flagIsEnabled);
}
public set isEnabled(value: boolean) {
this._changeFlags(UIElement.flagIsEnabled, value);
}
@dynamicLevelProperty(14, pi => UIElement.isFocusedProperty = pi)
/**
* True if the UIElement has the focus, false if it doesn't
*/
public get isFocused(): boolean {
return this._isFlagSet(UIElement.flagIsFocus);
}
public set isFocused(value: boolean) {
// If the UIElement doesn't accept focus, set it on its parent
if (!this.isFocusable) {
let p = this.parent;
if (!p) {
return;
}
p.isFocused = value;
}
// If the focus is being set, notify the Focus Manager
if (value) {
this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
}
this._changeFlags(UIElement.flagIsFocus, value);
}
@dynamicLevelProperty(15, pi => UIElement.isMouseOverProperty = pi)
/**
* True if the UIElement has the mouse over it
*/
public get isMouseOver(): boolean {
return this._isFlagSet(UIElement.flagIsMouseOver);
}
public set isMouseOver(value: boolean) {
this._changeFlags(UIElement.flagIsMouseOver, value);
}
public get isFocusScope(): boolean {
return this._isFlagSet(UIElement.flagIsFocusScope);
}
public set isFocusScope(value: boolean) {
this._changeFlags(UIElement.flagIsFocusScope, value);
}
public get isFocusable(): boolean {
return this._isFlagSet(UIElement.flagIsFocusable);
}
public set isFocusable(value: boolean) {
this._changeFlags(UIElement.flagIsFocusable, value);
}
// Look for the nearest parent which is the focus scope. Should always return something as the Window UIElement which is the root of all UI Tree is focus scope (unless the user disable it)
protected getFocusScope(): UIElement {
if (this.isFocusScope) {
return this;
}
let p = this.parent;
if (!p) {
return null;
}
return p.getFocusScope();
}
/**
* Check if a given flag is set
* @param flag the flag value
* @return true if set, false otherwise
*/
public _isFlagSet(flag: number): boolean {
return (this._flags & flag) !== 0;
}
/**
* Check if all given flags are set
* @param flags the flags ORed
* @return true if all the flags are set, false otherwise
*/
public _areAllFlagsSet(flags: number): boolean {
return (this._flags & flags) === flags;
}
/**
* Check if at least one flag of the given flags is set
* @param flags the flags ORed
* @return true if at least one flag is set, false otherwise
*/
public _areSomeFlagsSet(flags: number): boolean {
return (this._flags & flags) !== 0;
}
/**
* Clear the given flags
* @param flags the flags to clear
*/
public _clearFlags(flags: number) {
this._flags &= ~flags;
}
/**
* Set the given flags to true state
* @param flags the flags ORed to set
* @return the flags state before this call
*/
public _setFlags(flags: number): number {
let cur = this._flags;
this._flags |= flags;
return cur;
}
/**
* Change the state of the given flags
* @param flags the flags ORed to change
* @param state true to set them, false to clear them
*/
public _changeFlags(flags: number, state: boolean) {
if (state) {
this._flags |= flags;
} else {
this._flags &= ~flags;
}
}
private _assignTemplate(templateName: string) {
if (!templateName) {
templateName = GUIManager.DefaultTemplateName;
}
let className = Tools.getFullClassName(this);
if (!className) {
throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
}
let factory = GUIManager.getRenderingTemplate(className, templateName);
if (!factory) {
throw Error(`Couldn't get the renderingTemplate ${templateName} of class ${className}`);
}
this._renderingTemplateName = templateName;
this._renderingTemplate = factory();
this._renderingTemplate.attach(this);
}
public _createVisualTree() {
let parentPrim: Prim2DBase = this.ownerWindow.canvas;
if (this.parent) {
parentPrim = this.parent.visualChildrenPlaceholder;
}
if (!this._renderingTemplate) {
this._assignTemplate(this._renderingTemplateName);
}
this._visualPlaceholder = new Group2D({ parent: parentPrim, id: `GUI ${Tools.GetClassName(this)} RootGroup of ${this.id}`});
let p = this._visualPlaceholder;
p.addExternalData<UIElement>("_GUIOwnerElement_", this);
p.dataSource = this;
p.createSimpleDataBinding(Prim2DBase.widthProperty , "width" , DataBinding.MODE_ONEWAY);
p.createSimpleDataBinding(Prim2DBase.heightProperty , "height" , DataBinding.MODE_ONEWAY);
p.createSimpleDataBinding(Prim2DBase.actualWidthProperty , "actualWidth" , DataBinding.MODE_ONEWAYTOSOURCE);
p.createSimpleDataBinding(Prim2DBase.actualHeightProperty , "actualHeight" , DataBinding.MODE_ONEWAYTOSOURCE);
p.createSimpleDataBinding(Prim2DBase.marginProperty , "margin" , DataBinding.MODE_ONEWAY);
p.createSimpleDataBinding(Prim2DBase.marginAlignmentProperty, "marginAlignment", DataBinding.MODE_ONEWAY);
this.createVisualTree();
}
public _patchUIElement(ownerWindow: Window, parent: UIElement) {
if (ownerWindow) {
if (!this._ownerWindow) {
ownerWindow._registerVisualToBuild(this);
}
this._ownerWindow = ownerWindow;
}
this._parent = parent;
if (parent) {
this._hierarchyDepth = parent.hierarchyDepth + 1;
}
let children = this._getChildren();
if (children) {
for (let curChild of children) {
curChild._patchUIElement(ownerWindow, this);
}
}
}
// Overload the SmartPropertyBase's method to provide the additional logic of returning the parent's dataSource if there's no dataSource specified at this level.
protected _getDataSource(): IPropertyChanged {
let levelDS = super._getDataSource();
if (levelDS != null) {
return levelDS;
}
let p = this.parent;
if (p != null) {
return p.dataSource;
}
return null;
}
protected createVisualTree() {
let res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
this._visualTemplateRoot = res.root;
this._visualChildrenPlaceholder = res.contentPlaceholder;
}
protected get visualPlaceholder(): Prim2DBase {
return this._visualPlaceholder;
}
protected get visualTemplateRoot(): Prim2DBase {
return this._visualTemplateRoot;
}
protected get visualChildrenPlaceholder(): Prim2DBase {
return this._visualChildrenPlaceholder;
}
protected get _position(): Vector2 { return null; } // TODO use abstract keyword when TS 2.0 will be approved
protected abstract _getChildren(): Array<UIElement>;
public static flagVisualToBuild = 0x0000001;
public static flagIsVisible = 0x0000002;
public static flagIsFocus = 0x0000004;
public static flagIsFocusScope = 0x0000008;
public static flagIsFocusable = 0x0000010;
public static flagIsEnabled = 0x0000020;
public static flagIsMouseOver = 0x0000040;
protected _visualPlaceholder: Group2D;
protected _visualTemplateRoot: Prim2DBase;
protected _visualChildrenPlaceholder: Prim2DBase;
private _renderingTemplateName: string;
protected _renderingTemplate: UIElementRenderingTemplateBase;
private _parent: UIElement;
private _hierarchyDepth: number;
private _flags: number;
private _style: UIElementStyle;
private _ownerWindow: Window;
private _id: string;
private _uid: string;
private _actualWidth: number;
private _actualHeight: number;
private _minWidth: number;
private _minHeight: number;
private _maxWidth: number;
private _maxHeight: number;
private _width: number;
private _height: number;
private _margin: PrimitiveThickness;
private _padding: PrimitiveThickness;
private _marginAlignment: PrimitiveAlignment;
private _paddingAlignment: PrimitiveAlignment;
private static _enableState = "Enabled";
private static _disabledState = "Disabled";
private static _mouseOverState = "MouseOver";
}
export abstract class UIElementStyle {
abstract removeStyle(uiel: UIElement);
abstract applyStyle(uiel: UIElement);
get name(): string { return null; } // TODO use abstract keyword when TS 2.0 will be approved
}
export class GUIManager {
/////////////////////////////////////////////////////////////////////////////////////////////////////
// DATA TEMPLATE MANAGER
static registerDataTemplate(className: string, factory: (parent: UIElement, dataObject: any) => UIElement) {
}
// DATA TEMPLATE MANAGER
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
// STYLE MANAGER
static getStyle(uiElType: string, styleName: string): UIElementStyle {
let styles = GUIManager.stylesByUIElement.get(uiElType);
if (!styles) {
throw Error(`The type ${uiElType} is unknown, no style were registered for it.`);
}
let style = styles.get(styleName);
if (!style) {
throw Error(`Couldn't find Template ${styleName} of UIElement type ${uiElType}`);
}
return style;
}
static registerStyle(uiElType: string, templateName: string, style: UIElementStyle) {
let templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, () => new StringDictionary<UIElementStyle>());
if (templates.contains(templateName)) {
templates[templateName] = style;
} else {
templates.add(templateName, style);
}
}
static stylesByUIElement: StringDictionary<StringDictionary<UIElementStyle>> = new StringDictionary<StringDictionary<UIElementStyle>>();
public static get DefaultStyleName(): string {
return GUIManager._defaultStyleName;
}
public static set DefaultStyleName(value: string) {
GUIManager._defaultStyleName = value;
}
// STYLE MANAGER
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
// RENDERING TEMPLATE MANAGER
static getRenderingTemplate(uiElType: string, templateName: string): () => UIElementRenderingTemplateBase {
let templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
if (!templates) {
throw Error(`The type ${uiElType} is unknown, no Rendering Template were registered for it.`);
}
let templateFactory = templates.get(templateName);
if (!templateFactory) {
throw Error(`Couldn't find Template ${templateName} of UI Element type ${uiElType}`);
}
return templateFactory;
}
static registerRenderingTemplate(uiElType: string, templateName: string, factory: () => UIElementRenderingTemplateBase) {
let templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, () => new StringDictionary<() => UIElementRenderingTemplateBase>());
if (templates.contains(templateName)) {
templates[templateName] = factory;
} else {
templates.add(templateName, factory);
}
}
static renderingTemplatesByUIElement: StringDictionary<StringDictionary<() => UIElementRenderingTemplateBase>> = new StringDictionary<StringDictionary<() => UIElementRenderingTemplateBase>>();
public static get DefaultTemplateName(): string {
return GUIManager._defaultTemplateName;
}
public static set DefaultTemplateName(value: string) {
GUIManager._defaultTemplateName = value;
}
// RENDERING TEMPLATE MANAGER
/////////////////////////////////////////////////////////////////////////////////////////////////////
private static _defaultTemplateName = "Default";
private static _defaultStyleName = "Default";
}
export abstract class UIElementRenderingTemplateBase {
attach(owner: UIElement) {
this._owner = owner;
}
detach() {
}
public get owner(): UIElement {
return this._owner;
}
abstract createVisualTree(owner: UIElement, visualPlaceholder: Group2D): { root: Prim2DBase, contentPlaceholder: Prim2DBase };
private _owner: UIElement;
}
export function registerWindowRenderingTemplate(uiElType: string, templateName: string, factory: () => UIElementRenderingTemplateBase): (target: Object) => void {
return () => {
GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
}
}
} | the_stack |
import { mount, shallow } from 'enzyme';
import Mask from './Mask';
import React from 'react';
import { unmaskValue } from './maskHelpers';
// Some tests are generated. When a new mask is added, add it here:
const masks = ['currency', 'ssn', 'zip', 'phone'];
function render(customProps = {}, inputProps = {}, deep = false) {
const component = (
<Mask {...customProps}>
<input name="foo" type="text" {...inputProps} />
</Mask>
);
return {
props: customProps,
wrapper: deep ? mount(component) : shallow(component),
};
}
describe('Mask', function () {
masks.forEach((mask) => {
describe(`${mask} fallbacks`, () => {
it('renders a blank controlled field when value is empty', () => {
const data = render({ mask: mask }, { value: '' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('');
});
it('renders a blank controlled field when value is null', () => {
const data = render({ mask: mask }, { value: null });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('');
});
it('renders a blank controlled field when value is undefined', () => {
const data = render({ mask: mask });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('');
});
});
});
it('renders mask', () => {
const data = render({
mask: 'ssn',
});
expect(data.wrapper).toMatchSnapshot();
});
it('renders mask overlay', () => {
const data = render({
mask: 'currency',
});
expect(data.wrapper).toMatchSnapshot();
});
it('calls onBlur when the value is the same', () => {
const onBlur = jest.fn();
const wrapper = render({ mask: 'currency' }, { value: '123', onBlur: onBlur }).wrapper;
const input = wrapper.find('input');
input.simulate('blur', { target: { value: '123' }, persist: jest.fn() });
expect(onBlur.mock.calls.length).toBe(1);
});
it('calls onBlur when the value changes', () => {
const onBlur = jest.fn();
const wrapper = render({ mask: 'currency' }, { value: '123', onBlur: onBlur }).wrapper;
// The wrapper is actually the input element that it renders
wrapper
.find('input')
.props()
.onBlur({ target: { value: '1234' }, persist: jest.fn() });
expect(onBlur.mock.calls.length).toBe(1);
});
it('calls onChange', () => {
const onChange = jest.fn();
const wrapper = render({ mask: 'currency' }, { value: '123', onChange: onChange }).wrapper;
const input = wrapper.find('input');
input.simulate('change', { target: { value: '123' } });
expect(onChange.mock.calls.length).toBe(1);
});
it('changes to a controlled field using defaultValue', () => {
const data = render({ mask: 'currency' }, { defaultValue: '1234' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('1,234');
});
describe('Controlled component behavior', () => {
it('will not cause masking until blur when value prop still matches unmasked input', () => {
const onChange = (event) => {
// Simulate the change bubbling up to the controlling component and the
// controlling component then updating the value prop.
this.setProps({
children: (
<input name="foo" type="text" value={unmaskValue(event.target.value, 'currency')} />
),
});
};
const { wrapper } = render({ mask: 'currency', onChange }, { value: '1000' });
const input = () => wrapper.find('input');
expect(input().prop('value')).toBe('1,000');
input()
.props()
.onChange({ target: { value: '1,0000' } });
expect(input().prop('value')).toBe('1,0000');
input()
.props()
.onBlur({ target: { value: '1,0000' }, persist: jest.fn() });
expect(input().prop('value')).toBe('10,000');
});
it('will change the value of the input when value prop changes (beyond unmasked/masked differences)', () => {
const { wrapper } = render({ mask: 'currency' }, { value: '1000' });
const input = () => wrapper.find('input');
expect(input().prop('value')).toBe('1,000');
// Make sure we can change the value
wrapper.setProps({
children: <input name="foo" type="text" value="2000" />,
});
expect(input().prop('value')).toBe('2,000');
});
});
describe('Currency', () => {
// testComponent tests the entire <Mask mask="currency"> component
// others will simply test the formatting function, toCurrency
const testComponent = (value, expected) => {
const data = render({ mask: 'currency' }, { value });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe(expected);
};
it('does not mask if value is empty string', () => testComponent('', ''));
it('does not mask if value does not contain at least one digit', () =>
testComponent('abcABC!@#', 'abcABC!@#'));
it('will mask value as long as there is at least one digit', () => testComponent('a1!', '1'));
});
describe('Phone', () => {
it('accepts partial phone #', () => {
const data = render({ mask: 'phone' }, { value: '123' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123');
});
it('accepts unexpectedly long value', () => {
const data = render({ mask: 'phone' }, { value: '123456789000' });
const input = data.wrapper.find('input');
// Yes, this is invalid, but it should be up to to the app
// to surface an error in these cases. The mask shouldn't
// be changing the raw value a user has entered.
expect(input.prop('value')).toBe('123-456-789000');
});
it('accepts masked phone #', () => {
const data = render({ mask: 'phone' }, { value: '123-456-7890' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-456-7890');
});
it('masks phone #', () => {
const data = render({ mask: 'phone' }, { value: '1234567890' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-456-7890');
});
});
describe('SSN', () => {
it('accepts partial ssn', () => {
const data = render({ mask: 'ssn' }, { value: '123' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123');
});
it('accepts unexpectedly long value', () => {
const data = render({ mask: 'ssn' }, { value: '1234567890' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-45-67890');
});
it('accepts masked ssn', () => {
const data = render({ mask: 'ssn' }, { value: '123-45-6789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-45-6789');
});
it('accepts ssn masked with different characters', () => {
const data = render({ mask: 'ssn' }, { value: '123 45 6789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-45-6789');
});
it('accepts obfuscated ssns', () => {
const data = render({ mask: 'ssn' }, { value: '*****6789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('***-**-6789');
});
it('accepts masked, obfuscated ssns', () => {
const data = render({ mask: 'ssn' }, { value: '***-**-6789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('***-**-6789');
});
it('masks full ssn', () => {
const data = render({ mask: 'ssn' }, { value: '123456789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-45-6789');
});
it('masks partial (5) ssn', () => {
const data = render({ mask: 'ssn' }, { value: '12345' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-45');
});
it('masks partial (7) ssn', () => {
const data = render({ mask: 'ssn' }, { value: '1234567' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123-45-67');
});
});
describe('Zip code', () => {
it('accepts partial zip code', () => {
const data = render({ mask: 'zip' }, { value: '123' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('123');
});
it('accepts unexpectedly long value', () => {
const data = render({ mask: 'zip' }, { value: '1234567890' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345-67890');
});
it('accepts five-digit zip code', () => {
const data = render({ mask: 'zip' }, { value: '12345' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345');
});
it('accepts five-digits with bad extra chars', () => {
const data = render({ mask: 'zip' }, { value: '1234-5' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345');
});
it('accepts nine-digits with bad extra chars', () => {
const data = render({ mask: 'zip' }, { value: '1234-5-67-89' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345-6789');
});
it('accepts nine-digit zip code', () => {
const data = render({ mask: 'zip' }, { value: '123456789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345-6789');
});
it('accepts partial +4 zip code', () => {
const data = render({ mask: 'zip' }, { value: '1234567' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345-67');
});
it('accepts masked nine-digit zip code', () => {
const data = render({ mask: 'zip' }, { value: '12345-6789' });
const input = data.wrapper.find('input');
expect(input.prop('value')).toBe('12345-6789');
});
});
}); | the_stack |
import {
ColorLike,
NumericAttribValue,
PolyDictionary,
Vector2Like,
Vector3Like,
Vector4Like,
} from '../../types/GlobalTypes';
import {Vector3} from 'three/src/math/Vector3';
import {Int32BufferAttribute} from 'three/src/core/BufferAttribute';
import {Float32BufferAttribute} from 'three/src/core/BufferAttribute';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {Box3} from 'three/src/math/Box3';
import {CorePoint} from './Point';
import {CoreFace} from './Face';
import {ObjectType, AttribType, AttribSize} from './Constant';
import {CoreAttribute} from './Attribute';
import {CoreAttributeData} from './AttributeData';
import {CoreGeometryBuilderPoints} from './builders/Points';
import {CoreGeometryBuilderMerge} from './builders/Merge';
import {CoreGeometryBuilderMesh} from './builders/Mesh';
import {CoreGeometryBuilderLineSegments} from './builders/LineSegments';
import {TypeAssert} from '../../engine/poly/Assert';
import {CoreType} from '../Type';
import {ArrayUtils} from '../ArrayUtils';
import {ObjectUtils} from '../ObjectUtils';
import {CoreString} from '../String';
import {GroupString} from './Group';
const IS_INSTANCE_KEY = 'isInstance';
export class CoreGeometry {
_bounding_box: Box3 | undefined;
constructor(private _geometry: BufferGeometry) {}
geometry() {
return this._geometry;
}
uuid() {
return this._geometry.uuid;
}
boundingBox() {
return (this._bounding_box = this._bounding_box || this._create_bounding_box());
}
private _create_bounding_box() {
this._geometry.computeBoundingBox();
if (this._geometry.boundingBox) {
return this._geometry.boundingBox;
}
}
markAsInstance() {
this._geometry.userData[IS_INSTANCE_KEY] = true;
}
static markedAsInstance(geometry: BufferGeometry): boolean {
return geometry.userData[IS_INSTANCE_KEY] === true;
}
markedAsInstance(): boolean {
return CoreGeometry.markedAsInstance(this._geometry);
}
positionAttribName() {
let name = 'position';
if (this.markedAsInstance()) {
name = 'instancePosition';
}
return name;
}
computeVertexNormals() {
this._geometry.computeVertexNormals();
}
userDataAttribs() {
const key = 'indexed_attrib_values';
return (this._geometry.userData[key] = this._geometry.userData[key] || {});
}
indexedAttributeNames() {
return Object.keys(this.userDataAttribs() || {});
}
userDataAttrib(name: string) {
name = CoreAttribute.remapName(name);
return this.userDataAttribs()[name];
}
isAttribIndexed(name: string): boolean {
name = CoreAttribute.remapName(name);
return this.userDataAttrib(name) != null;
}
hasAttrib(name: string): boolean {
if (name === 'ptnum') {
return true;
}
name = CoreAttribute.remapName(name);
return this._geometry.attributes[name] != null;
}
attribType(name: string) {
if (this.isAttribIndexed(name)) {
return AttribType.STRING;
} else {
return AttribType.NUMERIC;
}
}
static attribNames(geometry: BufferGeometry): string[] {
return Object.keys(geometry.attributes);
}
attribNames(): string[] {
return CoreGeometry.attribNames(this._geometry);
}
static attribNamesMatchingMask(geometry: BufferGeometry, masks_string: GroupString) {
const masks = CoreString.attribNames(masks_string);
const matching_attrib_names: string[] = [];
for (let attrib_name of this.attribNames(geometry)) {
for (let mask of masks) {
if (CoreString.matchMask(attrib_name, mask)) {
matching_attrib_names.push(attrib_name);
}
}
}
return ArrayUtils.uniq(matching_attrib_names);
}
attribSizes() {
const h: PolyDictionary<AttribSize> = {};
for (let attrib_name of this.attribNames()) {
h[attrib_name] = this._geometry.attributes[attrib_name].itemSize;
}
return h;
}
attribSize(name: string): number {
let attrib;
name = CoreAttribute.remapName(name);
if ((attrib = this._geometry.attributes[name]) != null) {
return attrib.itemSize;
} else {
if (name === 'ptnum') {
// to ensure attrib copy with ptnum as source works
return 1;
} else {
return 0;
}
}
}
setIndexedAttributeValues(name: string, values: string[]) {
this.userDataAttribs()[name] = values;
}
setIndexedAttribute(name: string, values: string[], indices: number[]) {
this.setIndexedAttributeValues(name, values);
this._geometry.setAttribute(name, new Int32BufferAttribute(indices, 1));
}
addNumericAttrib(name: string, size: number = 1, default_value: NumericAttribValue = 0) {
const values = [];
let attribute_added = false;
if (CoreType.isNumber(default_value)) {
// adding number
for (let i = 0; i < this.pointsCount(); i++) {
for (let j = 0; j < size; j++) {
values.push(default_value);
}
}
attribute_added = true;
} else {
if (size > 1) {
if (CoreType.isArray(default_value)) {
// adding array
for (let i = 0; i < this.pointsCount(); i++) {
for (let j = 0; j < size; j++) {
values.push(default_value[j]);
}
}
attribute_added = true;
} else {
// adding Vector2
const vec2 = default_value as Vector2Like;
if (size == 2 && vec2.x != null && vec2.y != null) {
for (let i = 0; i < this.pointsCount(); i++) {
values.push(vec2.x);
values.push(vec2.y);
}
attribute_added = true;
}
// adding Vector3
const vec3 = default_value as Vector3Like;
if (size == 3 && vec3.x != null && vec3.y != null && vec3.z != null) {
for (let i = 0; i < this.pointsCount(); i++) {
values.push(vec3.x);
values.push(vec3.y);
values.push(vec3.z);
}
attribute_added = true;
}
// adding Color
const col = default_value as ColorLike;
if (size == 3 && col.r != null && col.g != null && col.b != null) {
for (let i = 0; i < this.pointsCount(); i++) {
values.push(col.r);
values.push(col.g);
values.push(col.b);
}
attribute_added = true;
}
// adding Vector4
const vec4 = default_value as Vector4Like;
if (size == 4 && vec4.x != null && vec4.y != null && vec4.z != null && vec4.w != null) {
for (let i = 0; i < this.pointsCount(); i++) {
values.push(vec4.x);
values.push(vec4.y);
values.push(vec4.z);
values.push(vec4.w);
}
attribute_added = true;
}
}
}
}
if (attribute_added) {
this._geometry.setAttribute(name.trim(), new Float32BufferAttribute(values, size));
} else {
console.warn(default_value);
throw `CoreGeometry.add_numeric_attrib error: no other default value allowed for now in add_numeric_attrib (default given: ${default_value})`;
}
}
initPositionAttribute(points_count: number, default_value?: Vector3) {
const values = [];
if (default_value == null) {
default_value = new Vector3();
}
for (let i = 0; i < points_count; i++) {
values.push(default_value.x);
values.push(default_value.y);
values.push(default_value.z);
}
return this._geometry.setAttribute('position', new Float32BufferAttribute(values, 3));
}
addAttribute(name: string, attrib_data: CoreAttributeData) {
switch (attrib_data.type()) {
case AttribType.STRING:
return console.log('TODO: to implement');
case AttribType.NUMERIC:
return this.addNumericAttrib(name, attrib_data.size());
}
}
renameAttrib(old_name: string, new_name: string) {
if (this.isAttribIndexed(old_name)) {
this.userDataAttribs()[new_name] = ObjectUtils.clone(this.userDataAttribs()[old_name]);
delete this.userDataAttribs()[old_name];
}
const old_attrib = this._geometry.getAttribute(old_name);
this._geometry.setAttribute(new_name.trim(), new Float32BufferAttribute(old_attrib.array, old_attrib.itemSize));
return this._geometry.deleteAttribute(old_name);
}
deleteAttribute(name: string) {
if (this.isAttribIndexed(name)) {
delete this.userDataAttribs()[name];
}
return this._geometry.deleteAttribute(name);
}
clone(): BufferGeometry {
return CoreGeometry.clone(this._geometry);
}
static clone(src_geometry: BufferGeometry): BufferGeometry {
let src_userData;
// monkey path
// for (let attribute_name of Object.keys(src_geometry.attributes)) {
// const attribute = src_geometry.getAttribute(attribute_name);
// if (attribute.constructor.name == InterleavedBufferAttribute.name) {
// MonkeyPatcher.patch(attribute as InterleavedBufferAttribute);
// }
// }
const new_geometry = src_geometry.clone();
if ((src_userData = src_geometry.userData) != null) {
new_geometry.userData = ObjectUtils.cloneDeep(src_userData);
}
return new_geometry;
}
pointsCount(): number {
return CoreGeometry.pointsCount(this._geometry);
}
static pointsCount(geometry: BufferGeometry): number {
let position;
let count = 0;
const core_geometry = new this(geometry);
let position_attrib_name = 'position';
if (core_geometry.markedAsInstance()) {
position_attrib_name = 'instancePosition';
}
if ((position = geometry.getAttribute(position_attrib_name)) != null) {
let array;
if ((array = position.array) != null) {
count = array.length / 3;
}
}
return count;
}
points(): CorePoint[] {
// do not cache, as this gives unexpected results
// when the points are updated internaly
return this.pointsFromGeometry();
}
pointsFromGeometry(): CorePoint[] {
const points = [];
const positionAttrib = this._geometry.getAttribute(this.positionAttribName());
if (positionAttrib != null) {
const count = positionAttrib.array.length / 3;
for (let i = 0; i < count; i++) {
const point = new CorePoint(this, i);
points.push(point);
}
}
return points;
}
private static _mesh_builder = new CoreGeometryBuilderMesh();
private static _points_builder = new CoreGeometryBuilderPoints();
private static _lines_segment_builder = new CoreGeometryBuilderLineSegments();
static geometryFromPoints(points: CorePoint[], object_type: ObjectType) {
switch (object_type) {
case ObjectType.MESH:
return this._mesh_builder.from_points(points);
case ObjectType.POINTS:
return this._points_builder.from_points(points);
case ObjectType.LINE_SEGMENTS:
return this._lines_segment_builder.from_points(points);
case ObjectType.OBJECT3D:
return null;
case ObjectType.LOD:
return null;
}
TypeAssert.unreachable(object_type);
}
static mergeGeometries(geometries: BufferGeometry[]) {
return CoreGeometryBuilderMerge.merge(geometries);
}
// legacy helper
static merge_geometries(geometries: BufferGeometry[]) {
return CoreGeometryBuilderMerge.merge(geometries);
}
segments() {
const index: Array<number> = (this.geometry().index?.array || []) as Array<number>;
return ArrayUtils.chunk(index, 2);
}
faces(): CoreFace[] {
return this.facesFromGeometry();
}
facesFromGeometry(): CoreFace[] {
const index_array = this.geometry().index?.array || [];
const faces_count = index_array.length / 3;
return ArrayUtils.range(faces_count).map((i) => new CoreFace(this, i));
}
} | the_stack |
import { Chart } from "chart.js";
export interface Complex {
Real: number;
Imag: number;
Magnitude: number;
Phase: number;
};
export interface DisplayableState {
n_qubits: number;
div_id: string;
amplitudes: Complex[] | null;
};
export type PlotStyle = "amplitude-phase" | "amplitude-squared" | "real-imag";
export function updateChart(plotStyle: PlotStyle, chart: Chart, state: DisplayableState) {
fitChart(chart, state);
switch (plotStyle) {
case "amplitude-phase":
updateWithAmplitudePhaseData(chart, state);
break;
case "amplitude-squared":
updateWithAmplitudeSquaredData(chart, state);
break;
case "real-imag":
updateWithRealImagData(chart, state);
break;
}
}
function fitChart(chart: Chart, state: DisplayableState) {
let chartWidth = state.amplitudes.length * 100;
chart.canvas.parentElement.style.width = `${chartWidth}px`;
}
function updateWithAmplitudePhaseData(chart: Chart, state: DisplayableState) {
let amps = state.amplitudes;
let nBasisStates = amps.length;
let nBitLength = Math.ceil(Math.log2(nBasisStates));
chart.data = {
labels: Array.from(Array(nBasisStates), (_, idx) => {
let bitstring = (idx >>> 0).toString(2).padStart(nBitLength, "0");
return `|${bitstring}⟩`;
}), //basis state labels
datasets: [
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Magnitude);
}),
backgroundColor: "#4c4cff",
borderColor: "#4c4cff",
label: "Amplitude"
},
{
data: Array.from(Array(nBasisStates), (_, idx) =>{
return (amps[idx].Phase);
}),
backgroundColor: "#4c4cff",
borderColor: "#4c4cff",
label: "Phase"
}
],
};
chart.options.legend = {
display: false,
};
chart.options.scales = {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Basis States'
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Amplitude and Phase'
},
ticks: {
beginAtZero: true
}
}]
};
chart.update();
}
function updateWithAmplitudeSquaredData(chart: Chart, state: DisplayableState) {
let amps = state.amplitudes;
let nBasisStates = amps.length;
let nBitLength = Math.ceil(Math.log2(nBasisStates));
chart.data = {
labels: Array.from(Array(nBasisStates), (_, idx) => {
let bitstring = (idx >>> 0).toString(2).padStart(nBitLength, "0");
return `|${bitstring}⟩`;
}), //basis state labels
datasets: [
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Magnitude ** 2);
}),
backgroundColor: "#5390d9",
borderColor: "#5390d9",
}
],
};
chart.options.legend = {
display: false,
};
chart.options.scales = {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Basis States'
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Measurement Probability'
},
ticks: {
beginAtZero: true,
suggestedMax: 1,
suggestedMin: 0
}
}]
};
chart.update();
}
function updateWithRealImagData(chart: Chart, state: DisplayableState) {
let amps = state.amplitudes;
let nBasisStates = amps.length;
let nBitLength = Math.ceil(Math.log2(nBasisStates));
chart.data = {
labels: Array.from(Array(nBasisStates), (_, idx) => {
let bitstring = (idx >>> 0).toString(2).padStart(nBitLength, "0");
return `|${bitstring}⟩`;
}), //basis state labels
datasets: [
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Real);
}),
backgroundColor: "#5390d9",
borderColor: "#5390d9",
label: "Real"
},
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Imag);
}),
backgroundColor: "#48bfe3",
borderColor: "#48bfe3",
label: "Imaginary"
}
],
};
chart.options.legend = {
display: false,
};
chart.options.scales = {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Basis States'
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Real and Imaginary'
},
ticks: {
beginAtZero: true,
suggestedMax: 1,
suggestedMin: -1
}
}]
};
chart.update();
}
export function createNewCanvas(
parentNode: HTMLElement, initialState?: DisplayableState | null
): { chart: Chart } {
let canvas = document.createElement("canvas");
canvas.style.width = "100%"
let measurementHistogram = new Chart(canvas, {
type: 'bar',
options: {
responsive: true,
maintainAspectRatio: false
}
});
if (initialState !== null && initialState !== undefined) {
updateWithAmplitudeSquaredData(measurementHistogram, initialState);
}
parentNode.appendChild(canvas);
return { chart: measurementHistogram };
}
export function addToolbarButton(container: HTMLElement, label: string, onClick: EventListener) {
let toolbarButton = document.createElement("button");
toolbarButton.appendChild(document.createTextNode(label));
container.appendChild(toolbarButton);
toolbarButton.addEventListener("click", onClick);
toolbarButton.className = "btn btn-default btn-sm"
toolbarButton.style.marginRight = "10px";
}
export function createToolbarContainer(toolbarName: string) {
let toolbarContainer = document.createElement("div");
toolbarContainer.style.marginTop = "10px";
toolbarContainer.style.marginBottom = "10px";
let toolbarTitle = document.createElement("span");
toolbarTitle.appendChild(document.createTextNode(toolbarName))
toolbarTitle.style.marginRight = "10px";
toolbarTitle.style.fontWeight = "bold";
toolbarContainer.appendChild(toolbarTitle);
return toolbarContainer;
}
export function attachDumpMachineToolbar(chart: Chart, state: DisplayableState) {
// Create toolbar container and insert at the beginning of the state div
let stateDiv = document.getElementById(state.div_id);
let toolbarContainer = createToolbarContainer("Chart options:");
stateDiv.insertBefore(toolbarContainer, stateDiv.firstChild);
// Create buttons to change plot style
addToolbarButton(toolbarContainer, "Measurement Probability", event => updateWithAmplitudeSquaredData(chart, state));
addToolbarButton(toolbarContainer, "Amplitude and Phase", event => updateWithAmplitudePhaseData(chart, state));
addToolbarButton(toolbarContainer, "Real and Imaginary", event => updateWithRealImagData(chart, state));
// Add horizontal rule above toolbar
stateDiv.insertBefore(document.createElement("hr"), stateDiv.firstChild);
};
export function createBarChart(element: HTMLCanvasElement, state: DisplayableState) {
let amps = state.amplitudes;
let nBasisStates = amps.length;
let nBitLength = Math.ceil(Math.log2(nBasisStates));
const measurementHistogram = new Chart(element, {
type: 'bar',
data: {
labels: Array.from(Array(nBasisStates), (_, idx) => {
let bitstring = (idx >>> 0).toString(2).padStart(nBitLength, "0");
return `|${bitstring}⟩`;
}), //basis state labels
datasets: [
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Magnitude ** 2);
}),
backgroundColor: "#5390d9",
borderColor: "#5390d9",
}
],
},
options: {
responsive: true,
legend: {
display: false,
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Basis States'
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Measurement Probability'
},
ticks: {
beginAtZero: true,
suggestedMax: 1,
suggestedMin: 0
}
}]
}
}
});
};
export function createBarChartRealImagOption(element: HTMLCanvasElement, state: DisplayableState) {
let amps = state.amplitudes;
let nBasisStates = amps.length;
let nBitLength = Math.ceil(Math.log2(nBasisStates));
const measurementHistogram = new Chart(element, {
type: 'bar',
data: {
labels: Array.from(Array(nBasisStates), (_, idx) => {
let bitstring = (idx >>> 0).toString(2).padStart(nBitLength, "0");
return `|${bitstring}⟩`;
}), //basis state labels
datasets: [
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Real);
}),
backgroundColor: "#5390d9",
borderColor: "#5390d9",
label: "Real"
},
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Imag);
}),
backgroundColor: "#48bfe3",
borderColor: "#48bfe3",
label: "Imaginary"
}
],
},
options: {
responsive: true,
legend: {
display: true,
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Basis States'
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Real and Imaginary'
},
ticks: {
suggestedMax: 1,
suggestedMin: -1
}
}]
}
}
});
};
export function createBarChartAmplitudePhaseOption(element: HTMLCanvasElement, state: DisplayableState) {
let amps = state.amplitudes;
let nBasisStates = amps.length;
let nBitLength = Math.ceil(Math.log2(nBasisStates));
const measurementHistogram = new Chart(element, {
type: 'bar',
data: {
labels: Array.from(Array(nBasisStates), (_, idx) => {
let bitstring = (idx >>> 0).toString(2).padStart(nBitLength, "0");
return `|${bitstring}⟩`;
}), //basis state labels
datasets: [
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Magnitude);
}),
backgroundColor: "#4c4cff",
borderColor: "#4c4cff",
label: "Amplitude"
},
{
data: Array.from(Array(nBasisStates), (_, idx) => {
return (amps[idx].Phase);
}),
backgroundColor: "#4c4cff",
borderColor: "#4c4cff",
label: "Phase"
}
],
},
options: {
responsive: true,
legend: {
display: false,
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Basis States'
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Amplitude and Phase'
},
ticks: {
beginAtZero: true,
}
}]
}
}
});
}; | the_stack |
import * as vs from 'vscode';
import {FileInfo} from './FileInfo';
import * as minimatch from 'minimatch';
import PathConfiguration from './PathConfiguration';
// node modules
import * as fs from 'fs';
import * as path from 'path';
var configuration = new PathConfiguration();
// load the initial configurations
configuration.update();
export class PathAutocomplete implements vs.CompletionItemProvider {
currentFile: string;
currentLine: string;
currentPosition: number;
insideString: boolean;
namePrefix: string;
provideCompletionItems(document: vs.TextDocument, position: vs.Position, token: vs.CancellationToken): Thenable<vs.CompletionItem[]> {
var currentLine = document.getText(document.lineAt(position).range);
var self = this;
configuration.update(document.uri);
this.currentFile = document.fileName;
this.currentLine = currentLine;
this.currentPosition = position.character;
this.namePrefix = this.getNamePrefix();
if (!this.shouldProvide()) {
return Promise.resolve([]);
}
var foldersPath = this.getFoldersPath(document.fileName, currentLine, position.character);
if (foldersPath.length == 0) {
return Promise.resolve([]);
}
var folderItems = this.getFolderItems(foldersPath).then((items: FileInfo[]) => {
// build the list of the completion items
var result = items.filter(self.filter, self).map((file) => {
var completion = new vs.CompletionItem(file.getName());
completion.insertText = this.getInsertText(file);
// show folders before files
if (file.isDirectory()) {
if (configuration.data.useBackslash) {
completion.label += '\\';
} else {
completion.label += '/';
}
if (configuration.data.enableFolderTrailingSlash) {
var commandText = '/';
if (configuration.data.useBackslash) {
commandText = this.isInsideQuotes() ? '\\\\' : '\\';
}
completion.command = {
command: 'default:type',
title: 'triggerSuggest',
arguments: [{
text: commandText
}]
};
}
completion.sortText = 'd';
completion.kind = vs.CompletionItemKind.Folder;
} else {
completion.sortText = 'f';
completion.kind = vs.CompletionItemKind.File;
}
// this is deprecated but still needed for the completion to work
// in json files
completion.textEdit = new vs.TextEdit(new vs.Range(position, position), completion.insertText);
return completion;
});
// add the `up one folder` item
if (!configuration.data.disableUpOneFolder) {
result.unshift(new vs.CompletionItem('..'))
}
return Promise.resolve(result);
});
return folderItems;
}
/**
* Gets the name prefix for the completion item.
* This is used when the path that the user user typed so far
* contains part of the file/folder name
* Examples:
* /folder/Fi
* /folder/subfo
*/
getNamePrefix(): string {
var userPath = this.getUserPath(this.currentLine, this.currentPosition);
if (userPath.endsWith("/") || userPath.endsWith("\\")) {
return "";
}
return path.basename(userPath);
}
/**
* Detemines if the file extension should be included in the selected options when
* the selection is made.
*/
isExtensionEnabled(): boolean {
if (this.currentLine.match(/require|import/)) {
return configuration.data.withExtensionOnImport;
}
return configuration.data.withExtension;
}
getInsertText(file: FileInfo): string {
var insertText = '';
if (this.isExtensionEnabled() || file.isDirectory()) {
insertText = path.basename(file.getName());
} else {
// remove the extension
insertText = path.basename(file.getName(), path.extname(file.getName()));
}
if (configuration.data.useBackslash && this.isInsideQuotes()) {
// determine if we should insert an additional backslash
if (this.currentLine[this.currentPosition - 2] != '\\') {
insertText = '\\' + insertText;
}
}
// apply the transformations
configuration.data.transformations.forEach((transform) => {
var fileNameRegex = transform.when && transform.when.fileName && new RegExp(transform.when.fileName);
if (fileNameRegex && !file.getName().match(fileNameRegex)) {
return;
}
var parameters = transform.parameters || [];
if (transform.type == 'replace' && parameters[0]) {
insertText = String.prototype.replace.call(insertText, new RegExp(parameters[0]), parameters[1]);
}
});
if (this.namePrefix) {
insertText = insertText.substr(this.namePrefix.length);
}
return insertText;
}
/**
* Builds a list of the available files and folders from the provided path.
*/
getFolderItems(foldersPath: string[]) {
var results = foldersPath.map(folderPath => {
return new Promise(function(resolve, reject) {
fs.readdir(folderPath, function(err, items) {
if (err) {
return reject(err);
}
var fileResults = [];
items.forEach(item => {
try {
fileResults.push(new FileInfo(path.join(folderPath, item)));
} catch (err) {
// silently ignore permissions errors
}
});
resolve(fileResults);
});
});
});
return Promise.all(results).then(allResults => {
return allResults.reduce((all: string[], currentResults: string[]) => {
return all.concat(currentResults);
}, []);
});
}
/**
* Builds the current folder path based on the current file and the path from
* the current line.
*
*/
getFoldersPath(fileName: string, currentLine: string, currentPosition: number): string[] {
var userPath = this.getUserPath(currentLine, currentPosition);
var mappingResult = this.applyMapping(userPath);
return mappingResult.items.map((item) => {
var insertedPath = item.insertedPath;
var currentDir = item.currentDir || this.getCurrentDirectory(fileName, insertedPath);
// relative to the disk
if (insertedPath.match(/^[a-z]:/i)) {
var resolved = path.resolve(insertedPath);
// restore trailing slashes if they were removed
if (resolved.slice(-1) != insertedPath.slice(-1)) {
resolved += insertedPath.substr(-1);
}
return [resolved];
}
// user folder
if (insertedPath.startsWith('~')) {
return [path.join(configuration.data.homeDirectory, insertedPath.substring(1))];
}
// npm package
if (this.isNodePackage(insertedPath, currentLine)) {
return [path.join(this.getNodeModulesPath(currentDir), insertedPath), path.join(currentDir, insertedPath)];
}
return [path.join(currentDir, insertedPath)];
})
// merge the resulted path
.reduce((flat, toFlatten) => {
return flat.concat(toFlatten);
}, [])
// keep only folders
.map((folderPath: string) => {
if (folderPath.endsWith("/") || folderPath.endsWith("\\")) {
return folderPath;
}
return path.dirname(folderPath);
})
// keep only valid paths
.filter(folderPath => {
if (!fs.existsSync(folderPath) || !fs.lstatSync(folderPath).isDirectory()) {
return false;
}
return true;
});
}
/**
* Retrieves the path inserted by the user. This is taken based on the last quote or last white space character.
*
* @param currentLine The current line of the cursor.
* @param currentPosition The current position of the cursor.
*/
getUserPath(currentLine: string, currentPosition: number): string {
var lastQuote = -1;
var lastSeparator = -1;
var pathSepartors = configuration.data.pathSeparators.split('');
for (var i = 0; i < currentPosition; i++) {
var c = currentLine[i];
// skip next character if escaped
if (c == "\\") {
i++;
continue;
}
// handle separators for support outside strings
if (pathSepartors.indexOf(c) > -1) {
lastSeparator = i;
continue;
}
// handle quotes
if (c == "'" || c == '"' || c == "`") {
lastQuote = i;
}
}
var startPosition = (lastQuote != -1) ? lastQuote : lastSeparator;
return currentLine.substring(startPosition + 1, currentPosition);
}
/**
* Searches for the node_modules folder in the parent folders of the current directory.
*
* @param currentDir The current directory
*/
getNodeModulesPath(currentDir: string): string {
var rootPath = configuration.data.workspaceFolderPath;
while (currentDir != path.dirname(currentDir)) {
var candidatePath = path.join(currentDir, 'node_modules');
if (fs.existsSync(candidatePath)) {
return candidatePath;
}
currentDir = path.dirname(currentDir);
}
return path.join(rootPath, 'node_modules');
}
/**
* Returns the current working directory
*/
getCurrentDirectory(fileName: string, insertedPath: string): string {
var currentDir = path.parse(fileName).dir || '/';
var workspacePath = configuration.data.workspaceFolderPath;
// based on the project root
if (insertedPath.startsWith('/') && workspacePath) {
currentDir = workspacePath;
}
return path.resolve(currentDir);
}
/**
* Applies the folder mappings based on the user configurations
*/
applyMapping(insertedPath: string): { items } {
var currentDir = '';
var workspaceFolderPath = configuration.data.workspaceFolderPath;
var workspaceRootPath = configuration.data.workspaceRootPath;
var items = [];
Object.keys(configuration.data.pathMappings || {})
// if insertedPath is '@view/'
// and mappings is [{key: '@', ...}, {key: '@view', ...}]
// and it will match '@' and return wrong items { currentDir: 'xxx', insertedPath: 'view/'}
// solution : Sort keys by matching longest prefix, and it will match key(@view) first
.sort((key1, key2) => {
const f1 = insertedPath.startsWith(key1) ? key1.length : 0;
const f2 = insertedPath.startsWith(key2) ? key2.length : 0;
return f2 - f1;
})
.map((key) => {
var candidatePaths = configuration.data.pathMappings[key];
if (typeof candidatePaths == 'string') {
candidatePaths = [candidatePaths];
}
return candidatePaths.map(candidatePath => {
if (workspaceRootPath) {
candidatePath = candidatePath.replace('${workspace}', workspaceRootPath);
}
if (workspaceFolderPath) {
candidatePath = candidatePath.replace('${folder}', workspaceFolderPath);
}
candidatePath = candidatePath.replace('${home}', configuration.data.homeDirectory);
return {
key: key,
path: candidatePath
};
});
})
.some((mappings) => {
var found = false;
mappings.forEach(mapping => {
if (insertedPath.startsWith(mapping.key) || (mapping.key === '$root' && !insertedPath.startsWith('.'))) {
items.push({
currentDir: mapping.path,
insertedPath: insertedPath.replace(mapping.key, '')
});
found = true;
}
});
// stop after the first mapping found
return found;
});
// no mapping was found, use the raw path inserted by the user
if (items.length === 0) {
items.push({
currentDir: '',
insertedPath
});
}
return { items };
}
/**
* Determine if the current path matches the pattern for a node module
*/
isNodePackage(insertedPath: string, currentLine: string) {
if (!currentLine.match(/require|import/)) {
return false;
}
if (!insertedPath.match(/^[a-z]/i)) {
return false;
}
return true;
}
/**
* Determine if we should provide path completion.
*/
shouldProvide() {
if (configuration.data.ignoredFilesPattern && minimatch(this.currentFile, configuration.data.ignoredFilesPattern)) {
return false;
}
if (this.isIgnoredPrefix()) {
return false;
}
if (configuration.data.triggerOutsideStrings) {
return true;
}
return this.isInsideQuotes();
}
/**
* Determines if the prefix of the path is in the ignored list
*/
isIgnoredPrefix() {
var igoredPrefixes = configuration.data.ignoredPrefixes;
if (!igoredPrefixes || igoredPrefixes.length == 0) {
return false;
}
return igoredPrefixes.some((prefix) => {
var currentLine = this.currentLine;
var position = this.currentPosition;
if (prefix.length > currentLine.length) {
return false;
}
var candidate = currentLine.substring(position - prefix.length, position);
if (prefix == candidate) {
return true;
}
return false;
});
}
/**
* Determines if the cursor is inside quotes.
*/
isInsideQuotes(): boolean {
var currentLine = this.currentLine;
var position = this.currentPosition;
var quotes = {
single: 0,
double: 0,
backtick: 0
};
// check if we are inside quotes
for (var i = 0; i < position; i++) {
if (currentLine.charAt(i) == "'" && currentLine.charAt(i-1) != '\\') {
quotes.single += quotes.single > 0 ? -1 : 1;
}
if (currentLine.charAt(i) == '"' && currentLine.charAt(i-1) != '\\') {
quotes.double += quotes.double > 0 ? -1 : 1;
}
if (currentLine.charAt(i) == '`' && currentLine.charAt(i-1) != '\\') {
quotes.backtick += quotes.backtick > 0 ? -1 : 1;
}
}
return !!(quotes.single || quotes.double || quotes.backtick);
}
/**
* Filter for the suggested items
*/
filter(suggestionFile: FileInfo) {
// no options configured
if (!configuration.data.excludedItems || typeof configuration.data.excludedItems != 'object') {
return true;
}
// keep only the records that match the name prefix inserted by the user
if (this.namePrefix && (suggestionFile.getName().indexOf(this.namePrefix) != 0)) {
return false;
}
var currentFile = this.currentFile;
var currentLine = this.currentLine;
var valid = true;
Object.keys(configuration.data.excludedItems).forEach(function(item) {
var exclusion = configuration.data.excludedItems[item];
// check the local file name pattern
if (!minimatch(currentFile, exclusion.when)) {
return;
}
if (!minimatch(suggestionFile.getPath(), item)) {
return;
}
// check the local line context
if (exclusion.context) {
var contextRegex = new RegExp(exclusion.context);
if (!contextRegex.test(currentLine)) {
return;
}
}
// exclude folders from the results
if (exclusion.isDir && !suggestionFile.isDirectory()) {
return;
}
valid = false;
});
return valid;
}
} | the_stack |
import {
deriveWalletKeys,
deriveAccount,
getStxAddress,
deriveLegacyConfigPrivateKey,
DerivationType,
selectStxDerivation,
fetchUsernameForAccountByDerivationType,
} from '../src';
// https://github.com/paulmillr/scure-bip39
// Secure, audited & minimal implementation of BIP39 mnemonic phrases.
import { mnemonicToSeed } from '@scure/bip39';
import { BIP32Interface, fromBase58 } from 'bip32';
import { HDKey } from '@scure/bip32';
import { TransactionVersion } from '@stacks/transactions';
import { StacksMainnet } from '@stacks/network';
import fetchMock from 'jest-fetch-mock';
import { bytesToHex } from '@stacks/common';
const SECRET_KEY =
'sound idle panel often situate develop unit text design antenna ' +
'vendor screen opinion balcony share trigger accuse scatter visa uniform brass ' +
'update opinion media';
const WALLET_ADDRESS = 'SP384CVPNDTYA0E92TKJZQTYXQHNZSWGCAG7SAPVB';
const DATA_ADDRESS = 'SP30RZ44NTH2D95M1HSWVMM8VVHSAFY71VF3XQZ0K';
test('keys are serialized, and can be deserialized properly using wallet private key for stx', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode1 = HDKey.fromMasterSeed(rootPrivateKey);
const derived = await deriveWalletKeys(rootNode1);
const rootNode = HDKey.fromExtendedKey(derived.rootKey);
const account = deriveAccount({
rootNode,
index: 0,
salt: derived.salt,
stxDerivationType: DerivationType.Wallet,
});
expect(getStxAddress({ account, transactionVersion: TransactionVersion.Mainnet })).toEqual(
WALLET_ADDRESS
);
});
test('keys are serialized, and can be deserialized properly using data private key for stx', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode1 = HDKey.fromMasterSeed(rootPrivateKey);
const derived = await deriveWalletKeys(rootNode1);
const rootNode = HDKey.fromExtendedKey(derived.rootKey);
const account = deriveAccount({
rootNode,
index: 0,
salt: derived.salt,
stxDerivationType: DerivationType.Data,
});
expect(getStxAddress({ account, transactionVersion: TransactionVersion.Mainnet })).toEqual(
DATA_ADDRESS
);
});
test('backwards compatible legacy config private key derivation', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const legacyKey = deriveLegacyConfigPrivateKey(rootNode);
expect(legacyKey).toEqual('767b51d866d068b02ce126afe3737896f4d0c486263d9b932f2822109565a3c6');
});
test('derive derivation path without username', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const network = new StacksMainnet();
const { username, stxDerivationType } = await selectStxDerivation({
username: undefined,
rootNode,
index: 0,
network,
});
expect(username).toEqual(undefined);
expect(stxDerivationType).toEqual(DerivationType.Wallet);
});
test('derive derivation path with username owned by address of stx derivation path', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const network = new StacksMainnet();
fetchMock.once(JSON.stringify({ address: DATA_ADDRESS }));
const { username, stxDerivationType } = await selectStxDerivation({
username: 'public_profile_for_testing.id.blockstack',
rootNode,
index: 0,
network,
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
expect(stxDerivationType).toEqual(DerivationType.Data);
});
test('derive derivation path with username owned by address of unknown derivation path', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const network = new StacksMainnet();
fetchMock.once(JSON.stringify({ address: 'SP000000000000000000002Q6VF78' }));
const { username, stxDerivationType } = await selectStxDerivation({
username: 'public_profile_for_testing.id.blockstack',
rootNode,
index: 0,
network,
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
expect(stxDerivationType).toEqual(DerivationType.Unknown);
});
test('derive derivation path with username owned by address of data derivation path', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const network = new StacksMainnet();
fetchMock.once(JSON.stringify({ address: 'SP30RZ44NTH2D95M1HSWVMM8VVHSAFY71VF3XQZ0K' }));
const { username, stxDerivationType } = await selectStxDerivation({
username: 'public_profile_for_testing.id.blockstack',
rootNode,
index: 0,
network,
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
expect(stxDerivationType).toEqual(DerivationType.Data);
});
test('derive derivation path with new username owned by address of stx derivation path', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const network = new StacksMainnet();
fetchMock.once(JSON.stringify({ names: ['public_profile_for_testing.id.blockstack'] }));
const { username, stxDerivationType } = await selectStxDerivation({
username: undefined,
rootNode,
index: 0,
network,
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
expect(stxDerivationType).toEqual(DerivationType.Wallet);
expect(fetchMock.mock.calls[0][0]).toEqual(
`https://stacks-node-api.mainnet.stacks.co/v1/addresses/stacks/${WALLET_ADDRESS}`
);
});
test('derive derivation path with new username owned by address of data derivation path', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const network = new StacksMainnet();
fetchMock
.once(JSON.stringify({ names: [] })) // no names on stx derivation path
.once(JSON.stringify({ names: ['public_profile_for_testing.id.blockstack'] }));
const { username, stxDerivationType } = await selectStxDerivation({
username: undefined,
rootNode,
index: 0,
network,
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
expect(stxDerivationType).toEqual(DerivationType.Data);
expect(fetchMock.mock.calls[0][0]).toEqual(
`https://stacks-node-api.mainnet.stacks.co/v1/addresses/stacks/${WALLET_ADDRESS}`
);
expect(fetchMock.mock.calls[1][0]).toEqual(
`https://stacks-node-api.mainnet.stacks.co/v1/addresses/stacks/${DATA_ADDRESS}`
);
});
test('derive derivation path with username and without network', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const { username, stxDerivationType } = await selectStxDerivation({
username: 'public_profile_for_testing.id.blockstack',
rootNode,
index: 0,
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
expect(stxDerivationType).toEqual(DerivationType.Unknown);
});
test('derive derivation path without username and without network', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
const { username, stxDerivationType } = await selectStxDerivation({
username: undefined,
rootNode,
index: 0,
});
expect(username).toEqual(undefined);
expect(stxDerivationType).toEqual(DerivationType.Wallet);
});
test('fetch username owned by derivation type', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
fetchMock.once(JSON.stringify({ names: ['public_profile_for_testing.id.blockstack'] }));
const { username } = await fetchUsernameForAccountByDerivationType({
rootNode,
index: 0,
derivationType: DerivationType.Wallet,
network: new StacksMainnet(),
});
expect(username).toEqual('public_profile_for_testing.id.blockstack');
});
test('fetch username owned by different derivation type', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
fetchMock.once(JSON.stringify({ names: [] }));
const { username } = await fetchUsernameForAccountByDerivationType({
rootNode,
index: 0,
derivationType: DerivationType.Wallet,
network: new StacksMainnet(),
});
expect(username).toEqual(undefined);
});
test('fetch username defaults to mainnet', async () => {
const rootPrivateKey = await mnemonicToSeed(SECRET_KEY);
const rootNode = HDKey.fromMasterSeed(rootPrivateKey);
fetchMock.once(JSON.stringify({ names: ['public_profile_for_testing.id.blockstack'] }));
await fetchUsernameForAccountByDerivationType({
rootNode,
index: 0,
derivationType: DerivationType.Wallet,
});
expect(fetchMock.mock.calls[0][0]).toContain('stacks-node-api.mainnet');
});
test('Verify compatibility between @scure/bip32 and bip32 dependency', () => {
// Consider a root key in base58 format
const root =
'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi';
const bip32Node: BIP32Interface = fromBase58(root);
// Use same root key to create node using @scure/bip32
const keychainNode = HDKey.fromExtendedKey(root);
if (bip32Node.privateKey && keychainNode.privateKey) {
expect(bip32Node.privateKey.toString('hex')).toEqual(bytesToHex(keychainNode.privateKey));
} else {
// Reject test case
fail(
'No private keys: failed to verify compatibility between @scure/bip32 and bip32 dependency'
);
}
const derivationPath = 'm/0/0';
// Derive a child from bip32Node at given derivation path
const childBip32Node: BIP32Interface = bip32Node.derivePath(derivationPath);
// Derive a child from keychainNode at given derivation path
const childKeychainNode = keychainNode.derive(derivationPath);
if (childBip32Node.privateKey && childKeychainNode.privateKey) {
expect(childBip32Node.privateKey.toString('hex')).toEqual(
bytesToHex(childKeychainNode.privateKey)
);
} else {
// Reject test case
fail(
'No private keys: failed to verify compatibility between @scure/bip32 and bip32 dependency'
);
}
}); | the_stack |
import { Vector4 } from '../math/Vector4'
import { Vector3 } from '../math/Vector3'
import { Vector2 } from '../math/Vector2'
import { Color } from '../math/Color'
import { fillUint32ArrayWithValues, fillFloat32ArrayWithValues } from './TypedArrayUtils'
class UpdateRange {
offset: f32
count: f32
}
export enum ArrayType {
Int8,
Uint8,
Uint8Clamped,
Int16,
Uint16,
Int32,
Uint32,
Float32,
Float64,
}
function getArrayTypeName(arrayType: ArrayType): string {
// prettier-ignore
switch (arrayType) {
case ArrayType.Int8: return 'Int8'
case ArrayType.Uint8: return 'Uint8'
case ArrayType.Uint8Clamped: return 'Uint8Clamped'
case ArrayType.Int16: return 'Int16'
case ArrayType.Uint16: return 'Uint16'
case ArrayType.Int32: return 'Int32'
case ArrayType.Uint32: return 'Uint32'
case ArrayType.Float32: return 'Float32'
case ArrayType.Float64: return 'Float64'
default: throw new TypeError('Invalid value for arrayType.')
}
}
class TypedArrays {
Int8: Int8Array = new Int8Array(0)
Uint8: Uint8Array = new Uint8Array(0)
Uint8Clamped: Uint8ClampedArray = new Uint8ClampedArray(0)
Int16: Int16Array = new Int16Array(0)
Uint16: Uint16Array = new Uint16Array(0)
Int32: Int32Array = new Int32Array(0)
Uint32: Uint32Array = new Uint32Array(0)
Float32: Float32Array = new Float32Array(0)
Float64: Float64Array = new Float64Array(0)
}
/**
* @see <a href="https://github.com/mrdoob/three.js/blob/master/src/core/BufferAttribute.js">src/core/BufferAttribute.js</a>
*/
export class BufferAttribute {
name: string = ''
arrays: TypedArrays = new TypedArrays()
dynamic: boolean = false
updateRange: UpdateRange = { offset: 0, count: -1 }
version: i32 = 0
isBufferAttribute: true = true
onUploadCallback: () => void = () => {}
constructor(
public arrayType: ArrayType,
public count: i32,
public itemSize: i32,
public normalized: boolean = true
) {
this.__makeInitialArray()
}
private __makeInitialArray(): void {
const size = this.count * this.itemSize
// prettier-ignore
switch (this.arrayType) {
case ArrayType.Int8: this.arrays.Int8 = new Int8Array(size); break
case ArrayType.Uint8: this.arrays.Uint8 = new Uint8Array(size); break
case ArrayType.Uint8Clamped: this.arrays.Uint8Clamped = new Uint8ClampedArray(size); break
case ArrayType.Int16: this.arrays.Int16 = new Int16Array(size); break
case ArrayType.Uint16: this.arrays.Uint16 = new Uint16Array(size); break
case ArrayType.Int32: this.arrays.Int32 = new Int32Array(size); break
case ArrayType.Uint32: this.arrays.Uint32 = new Uint32Array(size); break
case ArrayType.Float32: this.arrays.Float32 = new Float32Array(size); break
case ArrayType.Float64: this.arrays.Float64 = new Float64Array(size); break
default: throw new TypeError('This should never happen.')
}
}
set needsUpdate(value: boolean) {
if (value === true) this.version++
}
// setArray(array: TypedArray<f32>): this {
// this.count = array !== undefined ? array.length / this.itemSize : 0;
// this.array = array;
// return this;
// }
// setDynamic(dynamic: boolean): this {
// this.dynamic = dynamic;
// return this;
// }
// clone(): BufferAttribute {
// return new BufferAttribute( this.array, this.itemSize ).copy( this );
// }
// copy(source: BufferAttribute): this {
// this.array = new Float32Array( source.array.length );
// for (let i = 0, l = source.array.length; i < l; i++) {
// this.array[i] = source.array[i]
// }
// this.itemSize = source.itemSize;
// this.count = source.count;
// this.normalized = source.normalized;
// this.dynamic = source.dynamic;
// return this;
// }
// copyAt(index1: f32, attribute: BufferAttribute, index2: f32): this {
// index1 *= this.itemSize;
// index2 *= attribute.itemSize;
// for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
// this.array[ index1 + i ] = attribute.array[ index2 + i ];
// }
// return this;
// }
copyArray<A extends ArrayLike<number>>(array: A): this {
if (array instanceof Int8Array) this.copyInt8Array(array)
else if (array instanceof Uint8Array) this.copyUint8Array(array)
else if (array instanceof Uint8ClampedArray) this.copyUint8ClampedArray(array)
else if (array instanceof Int16Array) this.copyInt16Array(array)
else if (array instanceof Uint16Array) this.copyUint16Array(array)
else if (array instanceof Int32Array) this.copyInt32Array(array)
else if (array instanceof Uint32Array) this.copyUint32Array(array)
else if (array instanceof Float32Array) this.copyFloat32Array(array)
else if (array instanceof Float64Array) this.copyFloat64Array(array)
else throw new TypeError('Wrong type for array.')
return this
}
copyInt8Array(array: Int8Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Int8)
const thisArray = this.arrays.Int8
if (array.length > thisArray.length)
throw new Error('copyInt8Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyUint8Array(array: Uint8Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Uint8)
const thisArray = this.arrays.Uint8
if (array.length > thisArray.length)
throw new Error('copyUint8Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyUint8ClampedArray(array: Uint8ClampedArray): this {
this.__checkArrayTypeMatch(array, ArrayType.Uint8Clamped)
const thisArray = this.arrays.Uint8Clamped
if (array.length > thisArray.length)
throw new Error('copyUint8ClampedArray: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyInt16Array(array: Int16Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Int16)
const thisArray = this.arrays.Int16
if (array.length > thisArray.length)
throw new Error('copyInt16Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyUint16Array(array: Uint16Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Uint16)
const thisArray = this.arrays.Uint16
if (array.length > thisArray.length)
throw new Error('copyUint16Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyInt32Array(array: Int32Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Int32)
const thisArray = this.arrays.Int32
if (array.length > thisArray.length)
throw new Error('copyInt32Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyUint32Array(array: Uint32Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Uint32)
const thisArray = this.arrays.Uint32
if (array.length > thisArray.length)
throw new Error('copyUint32Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyFloat32Array(array: Float32Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Float32)
const thisArray = this.arrays.Float32
if (array.length > thisArray.length)
throw new Error('copyFloat32Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
copyFloat64Array(array: Float64Array): this {
this.__checkArrayTypeMatch(array, ArrayType.Float64)
const thisArray = this.arrays.Float64
if (array.length > thisArray.length)
throw new Error('copyFloat64Array: Source array is bigger than the target array.')
for (let i = 0, l = array.length; i < l; i++) thisArray[i] = array[i]
return this
}
private __checkArrayTypeMatch<T>(array: T, arrayType: ArrayType): void {
if (
(arrayType == ArrayType.Int8 && !(array instanceof Int8Array)) ||
(arrayType == ArrayType.Uint8 && !(array instanceof Uint8Array)) ||
(arrayType == ArrayType.Uint8Clamped && !(array instanceof Uint8ClampedArray)) ||
(arrayType == ArrayType.Int16 && !(array instanceof Int16Array)) ||
(arrayType == ArrayType.Uint16 && !(array instanceof Uint16Array)) ||
(arrayType == ArrayType.Int32 && !(array instanceof Int32Array)) ||
(arrayType == ArrayType.Uint32 && !(array instanceof Uint32Array)) ||
(arrayType == ArrayType.Float32 && !(array instanceof Float32Array)) ||
(arrayType == ArrayType.Float64 && !(array instanceof Float64Array))
) {
throw new Error(
'Wrong array type provided. Expected it to be an array of ' + getArrayTypeName(arrayType) + '.'
)
// TODO Also tell the user which type of array the user provided.
}
}
copyColorsArray(colors: Color[]): this {
if (this.itemSize !== 3) throw new TypeError('copyColorsArray can only be used when itemSize is 3.')
if (colors.length > this.count)
throw new RangeError('copyColorsArray was called with more colors than fit into array.')
if (!(this.arrayType == ArrayType.Float32 || this.arrayType == ArrayType.Float64))
throw new TypeError('copyColorsArray only works with Float32BufferAttribute or Float64BufferAttribute.')
let offset = 0
for (let i = 0, l = colors.length; i < l; i++) {
const color = colors[i]
// undefined does not exist in AS
// if (color === undefined) {
// //console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
// color = new Color()
// }
if (this.arrayType == ArrayType.Float32) {
this.arrays.Float32[offset++] = color.r
this.arrays.Float32[offset++] = color.g
this.arrays.Float32[offset++] = color.b
} else if (this.arrayType == ArrayType.Float64) {
this.arrays.Float64[offset++] = color.r
this.arrays.Float64[offset++] = color.g
this.arrays.Float64[offset++] = color.b
}
}
return this
}
copyVector2sArray(vectors: Vector2[]): this {
if (this.itemSize !== 2) throw new TypeError('copyVector2sArray can only be used when itemSize is 2.')
if (vectors.length > this.count)
throw new RangeError('copyVector2sArray was called with more vectors than fit into array.')
if (!(this.arrayType == ArrayType.Float32 || this.arrayType == ArrayType.Float64))
throw new TypeError('copyVector2sArray only works with Float32BufferAttribute or Float64BufferAttribute.')
let offset = 0
for (let i = 0, l = vectors.length; i < l; i++) {
const vector = vectors[i]
// undefined does not exist in AS
// if (vector === undefined) {
// //console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
// vector = new Vector2()
// }
if (this.arrayType == ArrayType.Float32) {
this.arrays.Float32[offset++] = vector.x
this.arrays.Float32[offset++] = vector.y
} else if (this.arrayType == ArrayType.Float64) {
this.arrays.Float64[offset++] = vector.x
this.arrays.Float64[offset++] = vector.y
}
}
return this
}
copyVector3sArray(vectors: Vector3[]): this {
if (this.itemSize !== 3) throw new TypeError('copyVector3sArray can only be used when itemSize is 3.')
if (vectors.length > this.count)
throw new RangeError('copyVector3sArray was called with more vectors than fit into array.')
if (!(this.arrayType == ArrayType.Float32 || this.arrayType == ArrayType.Float64))
throw new TypeError('copyVector3sArray only works with Float32BufferAttribute or Float64BufferAttribute.')
let offset: i32 = 0
for (let i = 0, l = vectors.length; i < l; i++) {
const vector = vectors[i]
// undefined does not exist in AS
// if (vector === undefined) {
// //console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
// vector = new Vector3()
// }
if (this.arrayType == ArrayType.Float32) {
this.arrays.Float32[offset++] = vector.x
this.arrays.Float32[offset++] = vector.y
this.arrays.Float32[offset++] = vector.z
} else if (this.arrayType == ArrayType.Float64) {
this.arrays.Float64[offset++] = vector.x
this.arrays.Float64[offset++] = vector.y
this.arrays.Float64[offset++] = vector.z
}
}
return this
}
// copyVector4sArray(vectors: {x: f32; y: f32; z: f32; w: f32}[]): this {
// var array = this.array, offset = 0;
// for ( var i = 0, l = vectors.length; i < l; i ++ ) {
// var vector = vectors[ i ];
// if ( vector === undefined ) {
// //console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
// vector = new Vector4();
// }
// array[ offset ++ ] = vector.x;
// array[ offset ++ ] = vector.y;
// array[ offset ++ ] = vector.z;
// array[ offset ++ ] = vector.w;
// }
// return this;
// }
// set(value: T, offset?: f32): this {
// if ( offset === undefined ) offset = 0;
// this.copyArray(value.subarray(offset))
// // this.array.set( value, offset );
// return this;
// }
// getX(index: f32): f32 {
// return this.array[ index * this.itemSize ];
// }
// setX(index: f32, x: f32): this {
// this.array[ index * this.itemSize ] = x;
// return this;
// }
// getY(index: f32): f32 {
// return this.array[ index * this.itemSize + 1 ];
// }
// setY(index: f32, y: f32): this {
// this.array[ index * this.itemSize + 1 ] = y;
// return this;
// }
// getZ(index: f32): f32 {
// return this.array[ index * this.itemSize + 2 ];
// }
// setZ(index: f32, z: f32): this {
// this.array[ index * this.itemSize + 2 ] = z;
// return this;
// }
// getW(index: f32): f32 {
// return this.array[ index * this.itemSize + 3 ];
// }
// setW(index: f32, w: f32): this {
// this.array[ index * this.itemSize + 3 ] = w;
// return this;
// }
// setXY(index: f32, x: f32, y: f32): this {
// index *= this.itemSize;
// this.array[ index + 0 ] = x;
// this.array[ index + 1 ] = y;
// return this;
// }
// setXYZ(index: f32, x: f32, y: f32, z: f32): this {
// index *= this.itemSize;
// this.array[ index + 0 ] = x;
// this.array[ index + 1 ] = y;
// this.array[ index + 2 ] = z;
// return this;
// }
// setXYZW(index: f32, x: f32, y: f32, z: f32, w: f32): this {
// index *= this.itemSize;
// this.array[ index + 0 ] = x;
// this.array[ index + 1 ] = y;
// this.array[ index + 2 ] = z;
// this.array[ index + 3 ] = w;
// return this;
// }
onUpload(callback: () => void): this {
this.onUploadCallback = callback
return this
}
// toJSON(): any {
// return {
// itemSize: this.itemSize,
// // type: this.array.constructor.name,
// // array: Array.prototype.slice.call( this.array ),
// array: this.array,
// normalized: this.normalized
// };
// }
// TODO Make more of the following static from* methods as needed...
static fromArrayOfUint32(array: u32[], itemSize: i32, normalized: boolean = false): Uint32BufferAttribute {
if (array.length % itemSize != 0) throw new Error('itemSize does not fit into the array length')
const attr = new Uint32BufferAttribute(array.length / itemSize, itemSize, normalized)
attr.copyArray(fillUint32ArrayWithValues(array))
return attr
}
static fromArrayOfFloat32(array: f32[], itemSize: i32, normalized: boolean = false): Float32BufferAttribute {
if (array.length % itemSize != 0) throw new Error('itemSize does not fit into the array length')
const attr = new Float32BufferAttribute(array.length / itemSize, itemSize, normalized)
attr.copyArray(fillFloat32ArrayWithValues(array))
return attr
}
}
export class Int8BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Int8, count, itemSize, normalized)
}
}
export class Uint8BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Uint8, count, itemSize, normalized)
}
}
export class Uint8ClampedBufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Uint8Clamped, count, itemSize, normalized)
}
}
export class Int16BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Int16, count, itemSize, normalized)
}
}
export class Uint16BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Uint16, count, itemSize, normalized)
}
}
export class Int32BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Int32, count, itemSize, normalized)
}
}
export class Uint32BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Uint32, count, itemSize, normalized)
}
}
export class Float32BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Float32, count, itemSize, normalized)
}
}
export class Float64BufferAttribute extends BufferAttribute {
constructor(count: i32, itemSize: i32, normalized: boolean = false) {
super(ArrayType.Float64, count, itemSize, normalized)
}
} | the_stack |
import {Time, Moment, WeekTime, TimeWeekDay} from "./time.types";
import {CommonUtils} from "../core/utils/common-utils";
declare const moment: any;
/**
* 时间粒度值
*/
export enum TimeGr {
second, minute, hour, date, week, month, time, time_hour_minute, time_minute_second, time_hour
}
/**
* 周起始日期
*/
export enum TimeWeekStart {
sun, mon, tue, wed, thu, fri, sat
}
/**
* 关于时间宏:
*
* 它通过一些数字,以及语义化的单词作为单位来表示一个时刻,时间宏是一个普通的字符串。
* 例如`"now"`这个宏表示当前时刻,`JigsawDateTimePicker`将会将其换算为其被初始化的时刻。
*
* 此外,时间宏还支持加减运算。例如`"now-1d"`的意思是昨天的这个时候,相应的,明天则是`"now+1d"`,上个月是`"now-1M"`等。
* 时间宏目前可以支持的时刻是`"now"`,支持的所有单位在这个枚举类型中全部列出了。(注意大小写)
*
* 时间宏的换算是由Jigsaw自动完成的,如果你需要获得一个时间宏的值,请调用`TimeService.getFormatDate()`方法。
*
* `TimeService`提供了许多有用的时间换算、格式化工具,当你有需要对时间进行运算时,可以参考它的api说。
*/
export enum TimeUnit {
s, m, h, d, w, M, y
}
/**
* 常用时间格式,`TimeService.format`可以支持任何格式,我们做这个枚举只是他们太常用了,使用这个枚举+IDE提示,你可以少敲很多次键盘。
*/
export enum TimeFormatters {
yyyy_mm_dd_hh_mm_ss, yyyy_mm_dd_hh_mm, yyyy_mm_dd_hh, yyyy_mm_dd, yyyy_mm, hh_mm_ss, hh_mm, mm_ss
}
/**
* 提供了日期运算、格式化、转换等一系列常用的方法,当你需要对时间做任何操作时,它都可以帮到你。
*/
// @dynamic
export class TimeService {
/**
* 将一个时刻转成符合改粒度的值,例如
*
* ```
* TimeService.convertValue("now", TimeGr.date); // -> 2018/3/23 00:00:00
* ```
*
* `"now"`的时分秒被切去。
*
* @param value 待转换的时刻,支持时间宏,请参考这里`TimeUnit`的说明。
* @param gr 目标粒度
* @return 符合粒度格式的时刻
*/
public static convertValue(value: WeekTime, gr: TimeGr): string {
if (this.isWeekDate(value)) {
value = this._handleWeekDateToDate(value, gr);
} else {
value = this.getFormatDate(<Time>value, gr);
}
return <string>value;
}
public static getDateByGr(date: WeekTime, gr: TimeGr): string | TimeWeekDay {
date = this.convertValue(date, gr);
return gr == TimeGr.week ? this.getWeekDate(date) : date;
}
public static isWeekDate(date: WeekTime) {
return date && !!date['week'] && !!date['year'];
}
private static _handleWeekDateToDate(date: WeekTime, gr: TimeGr) {
if (!date || typeof date['week'] != 'number') {
return this.getFormatDate(<Time>date, gr);
}
date = this.getDateFromYearAndWeek(date["year"], date["week"]);
let [dateWeekNum, weekStartNum] = [new Date(date).getDay(), this.getWeekStart()];
let dateIndex = dateWeekNum - weekStartNum >= 0 ? dateWeekNum - weekStartNum : dateWeekNum - weekStartNum + 7;
let [weekStartDate, weekEndDate] = [this.addDate(date, -dateIndex, TimeUnit.d),
this.addDate(date, 6 - dateIndex, TimeUnit.d)];
let [weekStartMonth, weekEndMonth] = [this.getMonth(weekStartDate), this.getMonth(weekEndDate)];
if (weekStartMonth == weekEndMonth) {
return this.getFormatDate(weekStartDate, gr);
} else {
return this.getFormatDate(`${this.getYear(weekEndDate)}-${weekEndMonth}-01`, gr);
}
}
private static _timeFormatterConvert(formatter: TimeFormatters): string {
switch (formatter) {
case TimeFormatters.yyyy_mm_dd_hh_mm_ss :
return "YYYY-MM-DD HH:mm:ss";
case TimeFormatters.yyyy_mm_dd_hh_mm :
return "YYYY-MM-DD HH:mm";
case TimeFormatters.yyyy_mm_dd_hh :
return "YYYY-MM-DD HH";
case TimeFormatters.yyyy_mm_dd :
return "YYYY-MM-DD";
case TimeFormatters.yyyy_mm :
return "YYYY-MM";
case TimeFormatters.hh_mm_ss :
return "HH:mm:ss";
case TimeFormatters.hh_mm :
return "HH:mm";
case TimeFormatters.mm_ss :
return "mm:ss";
}
}
private static _timeFormatMap = new Map([
[TimeGr.second, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd_hh_mm_ss)],
[TimeGr.minute, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd_hh_mm)],
[TimeGr.hour, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd_hh)],
[TimeGr.date, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd)],
[TimeGr.week, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd)],
[TimeGr.month, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm)],
[TimeGr.time, TimeService._timeFormatterConvert(TimeFormatters.hh_mm_ss)],
[TimeGr.time_hour_minute, TimeService._timeFormatterConvert(TimeFormatters.hh_mm)],
[TimeGr.time_minute_second, TimeService._timeFormatterConvert(TimeFormatters.mm_ss)],
]);
/**
* 时间单位枚举值转对应字符串
*
* @param unit 时间单位枚举值
* @return 返回对应的字符串
*/
public static timeUnitConvert(unit: TimeUnit): string {
return TimeUnit[unit];
}
private static _timeUnitMap = new Map([
[TimeUnit.s, 'seconds'],
[TimeUnit.m, 'minutes'],
[TimeUnit.h, "hours"],
[TimeUnit.d, 'days'],
[TimeUnit.w, 'weeks'],
[TimeUnit.M, 'months'],
[TimeUnit.y, 'years']
]);
private static _initMoment() {
try {
moment.suppressDeprecationWarnings = 1;
} catch (e) {
}
}
/**
* 仅仅是为了初始化moment对象
*
*/
private static init = TimeService._initMoment();
/**
* 判断给定的时刻值是否是时间宏字符串
*
* @param time 给定的时刻值
* @returns 如果给定的值非字符串,则必然返回false。
*/
public static isMacro(time: Time): boolean {
if (typeof time === 'string') {
return !!time.match(/^\s*(now|today|yestoday|tomorrow)\s*([+-]\s*\d+\s*\w+)?\s*$/i);
}
return false;
}
/**
* 特殊时间宏的转换
* @param timeMacro
*
*/
private static _convertBasicMacro(timeMacro: string): Date | string {
let date;
switch (timeMacro) {
case 'now':
date = new Date();
break;
default:
date = timeMacro;
break;
}
return date;
}
/**
* 时间加减法
*
* @param date 时间
* @param num 数量,为负数即为减法
* @param unit 单位
*/
public static addDate(date: Time, num: string | number, unit: TimeUnit): Moment {
return moment(date).add(num, TimeService._timeUnitMap.get(unit));
}
/**
* 根据粒度获取格式化字符串
*
* @param gr
*
*/
public static getFormatter(gr: TimeGr): string {
return TimeService._timeFormatMap.has(gr) ? TimeService._timeFormatMap.get(gr) : 'YYYY-MM-DD';
}
/**
* 时间格式化
*
* @param date
* @param formatter
*/
public static format(date: Time, formatter: string | TimeFormatters): string {
if (typeof formatter === "number") formatter = TimeService._timeFormatterConvert(formatter);
return moment(date).format(formatter);
}
/**
* 根据粒度格式化时间
*
* @param date
* @param gr
*/
public static formatWithGr(date: Time, gr: TimeGr): string {
let format = TimeService.getFormatter(gr);
return moment(date).format(format);
}
/**
* 设置默认周开始,设置之后会影响之后的所有计算结果
* https://momentjs.com/docs/#/customization/dow-doy/
* @param weekStart
*/
public static setWeekStart(weekStart: TimeWeekStart = TimeWeekStart.sun): void {
let locale = moment.locale();
let weekSet = moment.localeData()._week;
let janX = 7 + weekSet.dow - weekSet.doy;
moment.updateLocale(locale, {
week: {
dow: weekStart,
doy: 7 + weekStart - janX
}
});
}
/**
* 设置一年的第一周要包含一月几号
* https://momentjs.com/docs/#/customization/dow-doy/
* @param janX
*/
public static setFirstWeekOfYear(janX: number): void {
let locale = moment.locale();
let weekSet = moment.localeData()._week;
moment.updateLocale(locale, {
week: {
dow: weekSet.dow,
doy: 7 + weekSet.dow - janX
}
});
}
public static getWeekStart() {
return moment.localeData().firstDayOfWeek()
}
public static getWeekdaysMin() {
return moment.weekdaysMin();
}
public static getWeekdaysShort() {
return moment.weekdaysShort();
}
public static getMonthShort() {
return moment.localeData().monthsShort();
}
/**
* 获取周数对应的年份
*
* @param date
*
*/
public static getWeekYear(date: Time): number {
return moment(date).weekYear();
}
/**
* 获取给定时间在当年的周数
*
* @param date
*
*/
public static getWeekOfYear(date: Time): number {
return moment(date).week();
}
public static getWeekDate(date: Time) {
return {year: this.getWeekYear(date), week: this.getWeekOfYear(date)};
}
/**
* 获取给定时间的年数值
*
* @param date
*
*/
public static getYear(date: Time): number {
return moment(date).year();
}
/**
* 获取给定时间的月数值
*
* @param date
*
*/
public static getMonth(date: Time): number {
return moment(date).month() + 1;
}
/**
* 获取给定时间的天数值
*
* @param date
*
*/
public static getDay(date: Time): number {
return moment(date).date();
}
public static getDateFromYearAndWeek(year: number, week: number): Date {
return moment().weekYear(year).week(week)
}
public static getDate(str: Time, gr: TimeGr): Moment {
return moment(str, TimeService.getFormatter(gr));
}
public static getFirstDateOfMonth(year: number, month: number): Moment {
return this.getRealDateOfMonth(year, month, 1);
}
public static getLastDateOfMonth(year: number, month: number): Moment {
return this.getRealDateOfMonth(year, month, 31);
}
public static getRealDateOfMonth(year: number, month: number, day: number): Moment {
return moment([year, 0, day]).month(month - 1);
}
/**
* 根据字符串获取真实时间
*
* @param time
* @param gr
*
*/
public static getFormatDate(time: Time, gr?: TimeGr): Time {
let result = time;
if (TimeService.isMacro(time)) {
time = (<string>time).replace(/\s+/g, "");
let fullPara = /([a-z]+)(\+|\-)?([\d]+)([a-z]+)?/i;
let timeMacroArr = fullPara.exec(time);
if (timeMacroArr && CommonUtils.isDefined(timeMacroArr[2])) { //有加减 now-2d
result = TimeService.addDate(
TimeService._convertBasicMacro(timeMacroArr[1]),
"" + timeMacroArr[2] + timeMacroArr[3],
TimeUnit[timeMacroArr[4]]);
} else { //无加减 now
result = TimeService._convertBasicMacro(time);
}
}
if (typeof result === 'string') {
result = TimeService.format(result, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd_hh_mm_ss));
result = new Date(moment(result, TimeService._timeFormatterConvert(TimeFormatters.yyyy_mm_dd_hh_mm_ss)));
result = isNaN(result.valueOf()) ? new Date() : result;
}
if (result && (gr || (!gr && gr == 0)) || result instanceof Date || result instanceof moment) {
if (result instanceof moment) {
result = TimeService.formatWithGr(result, gr);
} else {
result = TimeService.formatWithGr(moment(result, TimeService.getFormatter(gr)), gr);
}
}
return result;
}
public static deFineZhLocale() {
moment.defineLocale('zh', {
months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'YYYY年MMMD日',
LL: 'YYYY年MMMD日',
LLL: 'YYYY年MMMD日Ah点mm分',
LLLL: 'YYYY年MMMD日ddddAh点mm分',
l: 'YYYY年MMMD日',
ll: 'YYYY年MMMD日',
lll: 'YYYY年MMMD日 HH:mm',
llll: 'YYYY年MMMD日dddd HH:mm'
},
meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
meridiemHour: function (hour, meridiem) {
if (hour === 12) {
hour = 0;
}
if (meridiem === '凌晨' || meridiem === '早上' ||
meridiem === '上午') {
return hour;
} else if (meridiem === '下午' || meridiem === '晚上') {
return hour + 12;
} else {
// '中午'
return hour >= 11 ? hour : hour + 12;
}
},
meridiem: function (hour, minute, isLower) {
let hm = hour * 100 + minute;
if (hm < 600) {
return '凌晨';
} else if (hm < 900) {
return '早上';
} else if (hm < 1130) {
return '上午';
} else if (hm < 1230) {
return '中午';
} else if (hm < 1800) {
return '下午';
} else {
return '晚上';
}
},
calendar: {
sameDay: '[今天]LT',
nextDay: '[明天]LT',
nextWeek: '[下]ddddLT',
lastDay: '[昨天]LT',
lastWeek: '[上]ddddLT',
sameElse: 'L'
},
dayOfMonthOrdinalParse: /\d{1,2}([日月周])/,
ordinal: function (number, period) {
switch (period) {
case 'd':
case 'D':
case 'DDD':
return number + '日';
case 'M':
return number + '月';
case 'w':
case 'W':
return number + '周';
default:
return number;
}
},
relativeTime: {
future: '%s内',
past: '%s前',
s: '几秒',
m: '1 分钟',
mm: '%d 分钟',
h: '1 小时',
hh: '%d 小时',
d: '1 天',
dd: '%d 天',
M: '1 个月',
MM: '%d 个月',
y: '1 年',
yy: '%d 年'
},
week: {
// GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
dow: 1, // Monday is the first day of the week.
doy: 4 // The week that contains Jan 4th is the first week of the year.
}
});
}
public static setLocale(lang: string) {
moment.locale(lang);
}
} | the_stack |
import {
createConnection,
TextDocuments,
Diagnostic,
DiagnosticSeverity,
ProposedFeatures,
InitializeParams,
DidChangeConfigurationNotification,
CompletionItem,
CompletionItemKind,
TextDocumentPositionParams,
TextDocumentSyncKind,
InitializeResult,
Hover,
HoverParams,
MarkupContent,
DefinitionParams,
DocumentFormattingParams,
Position,
TextEdit,
} from 'vscode-languageserver';
import { TextDocument } from 'vscode-languageserver-textdocument';
import * as wasm from '../pkg/';
import { standardPrelude, controlOperators } from './keywords';
// import { WorkDoneProgress } from 'vscode-languageserver/lib/progress';
// Create a connection for the server. The connection uses Node's IPC as a transport.
// Also include all preview / proposed LSP features.
let connection = createConnection(ProposedFeatures.all);
// Create a simple text document manager. The text document manager
// supports full document sync only
let documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
let hasConfigurationCapability: boolean = false;
let hasWorkspaceFolderCapability: boolean = false;
// let hasDiagnosticRelatedInformationCapability: boolean = false;
let cddl: any;
connection.onInitialize((params: InitializeParams) => {
let capabilities = params.capabilities;
// Does the client support the `workspace/configuration` request?
// If not, we will fall back using global settings
hasConfigurationCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
// hasDiagnosticRelatedInformationCapability = !!(
// capabilities.textDocument &&
// capabilities.textDocument.publishDiagnostics &&
// capabilities.textDocument.publishDiagnostics.relatedInformation
// );
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
// Tell the client that the server supports code completion
completionProvider: {
resolveProvider: true,
triggerCharacters: ['.'],
},
hoverProvider: true,
definitionProvider: true,
documentFormattingProvider: true,
},
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true,
},
};
}
return result;
});
connection.onInitialized(() => {
if (hasConfigurationCapability) {
// Register for all configuration changes.
connection.client.register(
DidChangeConfigurationNotification.type,
undefined
);
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders((_event) => {
connection.console.log('Workspace folder change event received.');
});
}
});
// The example settings
interface ExampleSettings {
maxNumberOfProblems: number;
}
// The global settings, used when the `workspace/configuration` request is not supported by the client.
// Please note that this is not the case when using this server with the client provided in this example
// but could happen with other clients.
const defaultSettings: ExampleSettings = { maxNumberOfProblems: 1000 };
let globalSettings: ExampleSettings = defaultSettings;
// Cache the settings of all open documents
let documentSettings: Map<string, Thenable<ExampleSettings>> = new Map();
connection.onDidChangeConfiguration((change) => {
if (hasConfigurationCapability) {
// Reset all cached document settings
documentSettings.clear();
} else {
globalSettings = <ExampleSettings>(
(change.settings.cddllsp || defaultSettings)
);
}
// Revalidate all open text documents
documents.all().forEach(validateTextDocument);
});
function getDocumentSettings(resource: string): Thenable<ExampleSettings> {
if (!hasConfigurationCapability) {
return Promise.resolve(globalSettings);
}
let result = documentSettings.get(resource);
if (!result) {
result = connection.workspace.getConfiguration({
scopeUri: resource,
section: 'cddllsp',
});
documentSettings.set(resource, result);
}
return result;
}
// Only keep settings for open documents
documents.onDidClose((e) => {
documentSettings.delete(e.document.uri);
});
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent((change) => {
validateTextDocument(change.document);
});
async function validateTextDocument(textDocument: TextDocument): Promise<void> {
// In this simple example we get the settings for every validate run.
let settings = await getDocumentSettings(textDocument.uri);
// The validator creates diagnostics for all uppercase words length 2 and more
let text = textDocument.getText();
let errors: any[] = [];
try {
cddl = wasm.cddl_from_str(text);
} catch (e) {
errors = e;
}
let diagnostics: Diagnostic[] = [];
while (errors.length < settings.maxNumberOfProblems) {
for (const error of errors) {
let diagnostic: Diagnostic = {
severity: DiagnosticSeverity.Error,
range: {
start: textDocument.positionAt(error.position.range[0]),
end: textDocument.positionAt(error.position.range[1]),
},
message: error.msg.short,
source: 'cddl',
};
// if (hasDiagnosticRelatedInformationCapability) {
// diagnostic.relatedInformation = [
// {
// location: {
// uri: textDocument.uri,
// range: Object.assign({}, diagnostic.range)
// },
// message: 'Spelling matters'
// },
// {
// location: {
// uri: textDocument.uri,
// range: Object.assign({}, diagnostic.range)
// },
// message: 'Particularly for names'
// }
// ];
// }
diagnostics.push(diagnostic);
}
break;
}
// Send the computed diagnostics to VSCode.
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
connection.onDidChangeWatchedFiles((_change) => {
// Monitored files have change in VSCode
connection.console.log('We received an file change event');
});
let triggeredOnControl = false;
let triggeredOnPlug = false;
// This handler provides the initial list of the completion items.
connection.onCompletion(
(textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => {
let completionItems: CompletionItem[] = [];
// Get first two characters at current position
let chars = documents.get(textDocumentPosition.textDocument.uri)?.getText({
start: {
character: textDocumentPosition.position.character - 1,
line: textDocumentPosition.position.line,
},
end: {
character: textDocumentPosition.position.character + 1,
line: textDocumentPosition.position.line
}
});
// If character is leading '.', then only emit controls
if (chars && chars[0] === '.') {
triggeredOnControl = true;
for (let index = 0; index < controlOperators.length; index++) {
completionItems[index] = {
label: controlOperators[index].label,
kind: CompletionItemKind.Keyword,
data: index,
documentation: controlOperators[index].documentation,
};
}
return completionItems;
}
for (let index = 0; index < standardPrelude.length; index++) {
completionItems[index] = {
label: standardPrelude[index].label,
kind: CompletionItemKind.Keyword,
data: index,
documentation: standardPrelude[index].documentation,
};
}
if (cddl) {
let groupPlugs: any[] = [];
let typePlugs: any[] = [];
let nonPlugRules: any[] = [];
for (let rule of cddl.rules) {
if (rule.Group) {
if (rule.Group.rule.name.socket === "GROUP") {
groupPlugs.push(rule.Group.rule.name.ident);
} else {
nonPlugRules.push(rule.Group.rule.name.ident);
}
}
if (rule.Type) {
if (rule.Type.rule.name.socket == "TYPE") {
typePlugs.push(rule.Type.rule.name.ident)
} else {
nonPlugRules.push(rule.Type.rule.name.ident);
}
}
}
if (chars === '$$') {
triggeredOnPlug = true;
for (let groupPlug of groupPlugs) {
let label = "$$" + groupPlug;
completionItems.push({
label,
kind: CompletionItemKind.Variable
});
}
return completionItems;
}
if (chars === '$') {
triggeredOnPlug = true;
for (let typePlug of typePlugs) {
let label = "$" + typePlug;
completionItems.push({
label,
kind: CompletionItemKind.Variable
});
}
return completionItems;
}
for (let label of nonPlugRules) {
completionItems.push({
label,
kind: CompletionItemKind.Variable
});
}
return completionItems;
}
return completionItems;
}
);
// This handler resolves additional information for the item selected in
// the completion list.
connection.onCompletionResolve(
(item: CompletionItem): CompletionItem => {
if (triggeredOnControl) {
for (let index = 0; index < controlOperators.length; index++) {
if (item.data === index) {
item.insertText = item.label.substring(1);
return item;
}
}
}
if (triggeredOnPlug) {
if (item.label.startsWith("$$")) {
item.insertText = item.label.substring(2);
} else if (item.label.startsWith("$")) {
item.insertText = item.label.substring(1);
}
return item;
}
for (let index = 0; index < standardPrelude.length; index++) {
if (item.data === index) {
item.detail = standardPrelude[index].detail;
break;
}
}
return item;
}
);
connection.onHover((params: HoverParams): Hover | undefined => {
// TODO: If identifier is a single character followed immediately by some
// delimiter without any space in between, this sometimes gets tripped up
let identifier = getIdentifierAtPosition(params);
if (identifier === undefined) {
return undefined;
}
for (const itemDetail of standardPrelude) {
if (identifier === itemDetail.label) {
return {
contents: itemDetail.detail,
};
}
}
for (const itemDetail of controlOperators) {
if (identifier == itemDetail.label) {
return {
contents: itemDetail.documentation
? (itemDetail.documentation as MarkupContent)
: itemDetail.detail,
};
}
}
});
connection.onDefinition((params: DefinitionParams) => {
let ident = getIdentifierAtPosition(params);
let document = documents.get(params.textDocument.uri);
if (document === undefined) {
return undefined;
}
if (ident) {
for (const rule of cddl.rules) {
if (rule.Type) {
if (rule.Type.rule.name.ident === ident) {
let start_position = document.positionAt(rule.Type.rule.name.span[0]);
let end_position = document.positionAt(rule.Type.rule.name.span[1]);
return {
uri: params.textDocument.uri,
range: {
start: {
character: start_position.character,
line: start_position.line,
},
end: {
character: end_position.character,
line: end_position.line,
},
},
};
}
if (rule.Type.rule.generic_param) {
for (const gp of rule.Type.rule.generic_param.params) {
if (gp.ident === ident) {
let start_position = document.positionAt(gp.span[0]);
let end_position = document.positionAt(gp.span[1]);
return {
uri: params.textDocument.uri,
range: {
start: {
character: start_position.character,
line: start_position.line,
},
end: {
character: end_position.character,
line: end_position.line,
},
},
};
}
}
}
}
if (rule.Group && rule.Group.rule.name.ident === ident) {
let start_position = document.positionAt(rule.Group.rule.name.span[0]);
let end_position = document.positionAt(rule.Group.rule.name.span[1]);
return {
uri: params.textDocument.uri,
range: {
start: {
character: start_position.character,
line: start_position.line,
},
end: {
character: end_position.character,
line: end_position.line,
},
},
};
}
}
}
return undefined;
});
connection.onDocumentFormatting((params: DocumentFormattingParams):
| TextEdit[]
| undefined => {
let document = documents.get(params.textDocument.uri);
if (document === undefined) {
return undefined;
}
let formatted_text = '';
try {
formatted_text = wasm.format_cddl_from_str(document.getText());
} catch (e) {
console.error(e);
return undefined;
}
return [
TextEdit.replace(
{
start: Position.create(0, 0),
end: document.positionAt(document.getText().length),
},
formatted_text
),
];
});
function getIdentifierAtPosition(
docParams: TextDocumentPositionParams
): string | undefined {
let document = documents.get(docParams.textDocument.uri);
if (document === undefined) {
return undefined;
}
let documentText = document.getText();
let offset = document.offsetAt(docParams.position);
if (offset === undefined) {
return undefined;
}
let start = offset;
let end = offset;
if (
documentText &&
(documentText.length < offset || documentText[offset] === ' ')
) {
return undefined;
}
let re = /\s|,|:|=|\*|\?|\+|<|>|{|}|\[|\]|\(|\)/;
while (!re.test(documentText[start]) && start > 0) {
start--;
}
while (!re.test(documentText[end]) && end < documentText.length) {
end++;
}
return documentText?.substring(start == 0 ? 0 : start + 1, end);
}
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
// Listen on the connection
connection.listen(); | the_stack |
import * as cdk from '@aws-cdk/core';
import * as cw from '@aws-cdk/aws-cloudwatch';
import { IBLEAFrontend } from './blea-frontend-interface';
interface BLEADashboardStackProps extends cdk.StackProps {
dashboardName: string;
webFront: IBLEAFrontend;
ecsClusterName: string;
ecsServiceName: string;
appTargetGroupName: string;
dbClusterName: string;
albTgUnHealthyHostCountAlarm: cw.Alarm;
ecsTargetUtilizationPercent: number;
ecsScaleOnRequestCount: number;
canaryDurationAlarm: cw.Alarm;
canaryFailedAlarm: cw.Alarm;
}
export class BLEADashboardStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: BLEADashboardStackProps) {
super(scope, id, props);
/*
*
* Metrics definition
* Note: These definitions do not create any resource. Just dashboard widget refer to these metrics.
*
*/
// CloudFront
// Available metrics: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/programming-cloudwatch-metrics.html
const cfRequests = new cw.Metric({
namespace: 'AWS/CloudFront',
metricName: 'Requests',
dimensions: {
Region: 'Global',
DistributionId: props.webFront.cfDistribution.distributionId,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.NONE,
region: 'us-east-1', // cloudfront defined on us-east-1
});
const cf5xxErrorRate = new cw.Metric({
namespace: 'AWS/CloudFront',
metricName: '5xxErrorRate',
dimensions: {
Region: 'Global',
DistributionId: props.webFront.cfDistribution.distributionId,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
region: 'us-east-1', // cloudfront defined on us-east-1
});
const cf4xxErrorRate = new cw.Metric({
namespace: 'AWS/CloudFront',
metricName: '4xxErrorRate',
dimensions: {
Region: 'Global',
DistributionId: props.webFront.cfDistribution.distributionId,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
region: 'us-east-1', // cloudfront defined on us-east-1
});
const cfTotalErrorRate = new cw.Metric({
namespace: 'AWS/CloudFront',
metricName: 'TotalErrorRate',
dimensions: {
Region: 'Global',
DistributionId: props.webFront.cfDistribution.distributionId,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
region: 'us-east-1', // cloudfront defined on us-east-1
});
// Application Load Balancing
// Available metrics: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html
const albRequests = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'RequestCount',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albNewConnectionCount = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'NewConnectionCount',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albRejectedConnectionCount = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'RejectedConnectionCount',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albTLSNegotiationErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'ClientTLSNegotiationErrorCount',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const alb5xxErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'HTTPCode_ELB_5XX_Count',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const alb4xxErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'HTTPCode_ELB_4XX_Count',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
// Target Group
// Available metrics: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html
const albTgRequests = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'HTTPCode_Target_2XX_Count',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albTg5xxErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'HTTPCode_Target_5XX_Count',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albTg4xxErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'HTTPCode_Target_4XX_Count',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albTgConnectionErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'TargetConnectionErrorCount',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albTgTLSNegotiationErrors = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'TargetConnectionErrorCount',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const albTgResponseTime = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'TargetResponseTime',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.SECONDS,
});
const albTgRequestCountPerTarget = new cw.Metric({
namespace: 'AWS/ApplicationELB',
metricName: 'RequestCountPerTarget',
dimensions: {
LoadBalancer: props.webFront.appAlb.loadBalancerFullName,
TargetGroup: props.appTargetGroupName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
// ECS
// Available metrics:
// - https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cloudwatch-metrics.html
// - https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-metrics-ECS.html
const ecsCPUUtilization = new cw.Metric({
namespace: 'AWS/ECS',
metricName: 'CPUUtilization',
dimensions: {
ClusterName: props.ecsClusterName,
ServiceName: props.ecsServiceName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
});
const ecsMemoryUtilization = new cw.Metric({
namespace: 'AWS/ECS',
metricName: 'MemoryUtilization',
dimensions: {
ClusterName: props.ecsClusterName,
ServiceName: props.ecsServiceName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
});
const ecsDesiredTaskCount = new cw.Metric({
namespace: 'ECS/ContainerInsights',
metricName: 'DesiredTaskCount',
dimensions: {
ClusterName: props.ecsClusterName,
ServiceName: props.ecsServiceName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const ecsRunningTaskCount = new cw.Metric({
namespace: 'ECS/ContainerInsights',
metricName: 'RunningTaskCount',
dimensions: {
ClusterName: props.ecsClusterName,
ServiceName: props.ecsServiceName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const ecsPendingTaskCount = new cw.Metric({
namespace: 'ECS/ContainerInsights',
metricName: 'PendingTaskCount',
dimensions: {
ClusterName: props.ecsClusterName,
ServiceName: props.ecsServiceName,
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
// Aurora
// Available metrics: https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraMySQL.Monitoring.Metrics.html
// for Writer & Reader
const dbWriterDatabaseConnections = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'DatabaseConnections',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "Writer: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const dbReaderDatabaseConnections = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'DatabaseConnections',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.SUM,
label: "Reader: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.COUNT,
});
const dbWriterCPUUtilization = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'CPUUtilization',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "Writer: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
});
const dbReaderCPUUtilization = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'CPUUtilization',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "Reader: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.PERCENT,
});
const dbWriterFreeableMemory = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'FreeableMemory',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "Writer: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MEGABITS,
});
const dbReaderFreeableMemory = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'FreeableMemory',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "Reader: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MEGABITS,
});
const dbWriterFreeLocalStorage = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'FreeLocalStorage',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "Writer: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MEGABITS,
});
const dbReaderFreeLocalStorage = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'FreeLocalStorage',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "Reader: ${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MEGABITS,
});
// for Writer
const dbWriterInsertLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'InsertLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterSelectLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'SelectLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterUpdateLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'UpdateLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterCommitLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'CommitLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterDDLLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'DDLLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterDeleteLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'DeleteLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterDMLLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'DeleteLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbWriterReadLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'ReadLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.SECONDS,
});
const dbWriterWriteLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'WriteLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'WRITER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.SECONDS,
});
// for Reader
const dbReaderSelectLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'SelectLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.MILLISECONDS,
});
const dbReaderReadLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'ReadLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.SECONDS,
});
const dbReaderWriteLatency = new cw.Metric({
namespace: 'AWS/RDS',
metricName: 'WriteLatency',
dimensions: {
DBClusterIdentifier: props.dbClusterName,
Role: 'READER',
},
period: cdk.Duration.minutes(1),
statistic: cw.Statistic.AVERAGE,
label: "${PROP('MetricName')} /${PROP('Period')}sec",
unit: cw.Unit.SECONDS,
});
/*
*
* Dashboard definition
*
* Note:
* - This sample summarize widgets in metrics group such as Requests, ResponseTime, Errors, Resources.
* We added header text widget on top of each metrics group.
* - If you use the name CloudWatch-Default, the dashboard appears on the overview on the CloudWatch home page.
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create_dashboard.html
*
* - Widget Array Structure (height, width, x, y)
* width=24 means Full screen width. This sample is define widget height as 6.
* You can just add widgets in array, x and y axis are defined well by CDK.
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Dashboard-Body-Structure.html#CloudWatch-Dashboard-Properties-Widgets-Structure
*
* - "stacked: true," means stack(add) each metrics.
*
* - Label for each metrics is defined on metrics object and you can use "Dynamic Label".
* We usually use "${PROP('MetricName')} /${PROP('Period')}sec" so we can see period of the metrics.
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/graph-dynamic-labels.html
*
*/
const dashboard = new cw.Dashboard(this, 'Dashboard', {
dashboardName: props.dashboardName,
});
dashboard.addWidgets(
// Canary
new cw.TextWidget({
markdown: '# Canary',
height: 1,
width: 24,
}),
new cw.AlarmWidget({
title: 'Canary response time',
width: 12,
height: 6,
alarm: props.canaryDurationAlarm,
}),
new cw.AlarmWidget({
title: 'Canary request failed',
width: 12,
height: 6,
alarm: props.canaryFailedAlarm,
}),
// Requests
new cw.TextWidget({
markdown: '# Requests',
height: 1,
width: 24,
}),
new cw.GraphWidget({
title: 'CloudFront Requests',
width: 6,
height: 6,
stacked: false,
left: [cfRequests],
}),
new cw.GraphWidget({
title: 'ALB Requests',
width: 6,
height: 6,
stacked: false,
left: [albRequests, albNewConnectionCount, albRejectedConnectionCount],
}),
new cw.GraphWidget({
title: 'Target Group Requests',
width: 6,
height: 6,
stacked: false,
left: [albTgRequests],
}),
new cw.GraphWidget({
title: 'Aurora Connections',
width: 6,
height: 6,
stacked: false,
left: [dbWriterDatabaseConnections, dbReaderDatabaseConnections],
}),
// Response Time
new cw.TextWidget({
markdown: '# Response Time',
height: 1,
width: 24,
}),
new cw.GraphWidget({
title: 'Target Group Response Time',
width: 8,
height: 6,
stacked: false,
left: [albTgResponseTime],
}),
new cw.GraphWidget({
title: 'Aurora Operation Lantency (Writer)',
width: 8,
height: 6,
stacked: false,
left: [
dbWriterInsertLatency,
dbWriterSelectLatency,
dbWriterUpdateLatency,
dbWriterCommitLatency,
dbWriterDDLLatency,
dbWriterDeleteLatency,
dbWriterDMLLatency,
],
right: [dbWriterReadLatency, dbWriterWriteLatency],
}),
new cw.GraphWidget({
title: 'Aurora Operation Lantency (Reader)',
width: 8,
height: 6,
stacked: false,
left: [dbReaderSelectLatency],
right: [dbReaderReadLatency, dbReaderWriteLatency],
}),
// Errors
new cw.TextWidget({
markdown: '# Errors',
height: 1,
width: 24,
}),
new cw.GraphWidget({
title: 'CloudFront Error Rates',
width: 6,
height: 6,
// stacked: false,
// left: [cf5xxErrorRate, cf4xxErrorRate, cfTotalErrorRate],
stacked: true,
left: [cf5xxErrorRate, cf4xxErrorRate],
}),
new cw.GraphWidget({
title: 'ALB Errors',
width: 6,
height: 6,
stacked: false,
left: [albTLSNegotiationErrors, alb5xxErrors, alb4xxErrors],
}),
new cw.AlarmWidget({
title: 'Alarm for UnHealthy Host in Target Group',
width: 6,
height: 6,
alarm: props.albTgUnHealthyHostCountAlarm, // This alarm is defined on ECSApp Stack
}),
new cw.GraphWidget({
title: 'Target Group Errors',
width: 6,
height: 6,
// stacked: false,
stacked: true,
left: [albTg5xxErrors, albTg4xxErrors, albTgConnectionErrors, albTgTLSNegotiationErrors],
}),
// Resources
new cw.TextWidget({
markdown: '# Resources',
height: 1,
width: 24,
}),
new cw.GraphWidget({
title: 'ECS CPU Utilization',
width: 6,
height: 6,
stacked: false,
left: [ecsCPUUtilization],
}),
new cw.GraphWidget({
title: 'ECS Memory Utilization',
width: 6,
height: 6,
stacked: false,
left: [ecsMemoryUtilization],
}),
new cw.GraphWidget({
title: 'ECS Desired Task Count',
width: 6,
height: 6,
stacked: false,
left: [ecsDesiredTaskCount],
}),
new cw.GraphWidget({
title: 'ECS Task Count',
width: 6,
height: 6,
stacked: true,
left: [ecsRunningTaskCount, ecsPendingTaskCount],
}),
new cw.GraphWidget({
title: 'ECS Auto Scaling with Requests per tasks',
width: 12,
height: 6,
stacked: false,
left: [albTgRequestCountPerTarget],
leftAnnotations: [
{
value: props.ecsScaleOnRequestCount, // Defined on ECSApp Stack
label: 'Threshold: Requests per tasks',
color: '#aec7e8',
fill: cw.Shading.BELOW,
},
],
right: [ecsRunningTaskCount, ecsPendingTaskCount],
}),
new cw.GraphWidget({
title: 'ECS Auto Scaling with CPU Utilization',
width: 12,
height: 6,
stacked: false,
left: [ecsCPUUtilization],
leftAnnotations: [
{
value: props.ecsTargetUtilizationPercent, // Defined on ECSApp Stack
label: 'Threshold: CPU Utilization',
color: '#aec7e8',
fill: cw.Shading.BELOW,
},
],
right: [ecsRunningTaskCount, ecsPendingTaskCount],
}),
new cw.GraphWidget({
title: 'Aurora CPU Utilization',
width: 6,
height: 6,
stacked: false,
left: [dbWriterCPUUtilization, dbReaderCPUUtilization],
}),
new cw.GraphWidget({
title: 'Aurora Free Memory',
width: 6,
height: 6,
stacked: false,
left: [dbWriterFreeableMemory, dbReaderFreeableMemory],
}),
new cw.GraphWidget({
title: 'Aurora Free Local Storage',
width: 6,
height: 6,
stacked: false,
left: [dbWriterFreeLocalStorage, dbReaderFreeLocalStorage],
}),
);
}
} | the_stack |
import type { Root } from "../../core/Root";
import type { DataItem } from "../../core/render/Component";
import type { HierarchyNode } from "./HierarchyNode";
import type { Bullet } from "../../core/render/Bullet";
import type { Series } from "../../core/render/Series";
import { Partition, IPartitionPrivate, IPartitionSettings, IPartitionDataItem } from "./Partition";
import { Template } from "../../core/util/Template";
import { ListTemplate } from "../../core/util/List";
import { Slice } from "../../core/render/Slice";
import { RadialLabel } from "../../core/render/RadialLabel";
import { Percent, p100, p50 } from "../../core/util/Percent";
import * as $array from "../../core/util/Array";
import * as d3hierarchy from "d3-hierarchy";
import * as $utils from "../../core/util/Utils";
import * as $type from "../../core/util/Type";
import * as $math from "../../core/util/Math";
/**
* @ignore
*/
export interface ISunburstDataObject {
name?: string,
value?: number,
children?: ISunburstDataObject[],
dataItem?: DataItem<ISunburstDataItem>
};
export interface ISunburstDataItem extends IPartitionDataItem {
/**
* Data items of child nodes.
*/
children: Array<DataItem<ISunburstDataItem>>;
/**
* Data item of a parent node.
*/
parent: DataItem<ISunburstDataItem>;
/**
* @ignore
*/
d3PartitionNode: d3hierarchy.HierarchyRectangularNode<ISunburstDataObject>;
/**
* A [[Slice]] element of the node.
*/
slice: Slice;
}
export interface ISunburstSettings extends IPartitionSettings {
/**
* Start angle of the series.
*
* @default -90
*/
startAngle?: number;
/**
* End angle of the series.
*
* @default 270
*/
endAngle?: number;
/**
* Inner radius of the suburst pie.
*
* Setting to negative number will mean pixels from outer radius.
*
* @default 0
*/
innerRadius?: number | Percent;
/**
* Outer radius of the sunburst pie.
*
* @default 100%
*/
radius?: number | Percent;
}
export interface ISunburstPrivate extends IPartitionPrivate {
/**
* @ignore
*/
dr: number;
/**
* @ignore
*/
dx: number;
/**
* @ignore
*/
innerRadius: number;
/**
* @ignore
*/
hierarchySize?: number;
}
/**
* Builds a sunburst diagram.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/sunburst/} for more info
* @important
*/
export class Sunburst extends Partition {
declare public _settings: ISunburstSettings;
declare public _privateSettings: ISunburstPrivate;
declare public _dataItemSettings: ISunburstDataItem;
protected _tag: string = "sunburst";
public static className: string = "Sunburst";
public static classNames: Array<string> = Partition.classNames.concat([Sunburst.className]);
public _partitionLayout = d3hierarchy.partition();
declare public _rootNode: d3hierarchy.HierarchyRectangularNode<ISunburstDataObject> | undefined;
/**
* A list of node slice elements in a [[Sunburst]] chart.
*
* @default new ListTemplate<Slice>
*/
public readonly slices: ListTemplate<Slice> = new ListTemplate(
Template.new({}),
() => Slice._new(this._root, {
themeTags: $utils.mergeTags(this.slices.template.get("themeTags", []), [this._tag, "hierarchy", "node", "shape"])
}, [this.slices.template])
);
/**
* A list of label elements in a [[Hierarchy]] chart.
*
* @default new ListTemplate<RadialLabel>
*/
public readonly labels: ListTemplate<RadialLabel> = new ListTemplate(
Template.new({}),
() => RadialLabel._new(this._root, {
themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), [this._tag])
}, [this.labels.template])
);
protected _afterNew() {
super._afterNew();
this.nodesContainer.setAll({ x: p50, y: p50 });
this.setPrivateRaw("dx", 0);
this.setPrivateRaw("dr", 0);
}
public _prepareChildren() {
super._prepareChildren();
if (this.isPrivateDirty("dr") || this.isPrivateDirty("dx")) {
if (this._rootNode) {
this._updateNodesScale(this._rootNode);
}
}
}
protected _updateVisuals() {
if (this._rootNode) {
const partitionLayout = this._partitionLayout;
let bounds = $math.getArcBounds(0, 0, this.get("startAngle", 0), this.get("endAngle", 360), 1);
let w = this.innerWidth();
let h = this.innerHeight();
const wr = w / (bounds.right - bounds.left);
const hr = h / (bounds.bottom - bounds.top);
let s = Math.min(wr, hr);
let r = $utils.relativeToValue(this.get("radius", p100), s);
let ir = $utils.relativeToValue(this.get("innerRadius", 0), r);
if (ir < 0) {
ir = r + ir;
}
s = r - ir;
this.setPrivateRaw("innerRadius", ir);
this.setPrivateRaw("hierarchySize", s);
partitionLayout.size([s, s]);
this.nodesContainer.setAll({
dy: -r * (bounds.bottom + bounds.top) / 2, dx: -r * (bounds.right + bounds.left) / 2
})
const nodePadding = this.get("nodePadding");
if ($type.isNumber(nodePadding)) {
partitionLayout.padding(nodePadding);
}
partitionLayout(this._rootNode);
this._updateNodes(this._rootNode);
}
}
protected _updateNode(dataItem: DataItem<this["_dataItemSettings"]>) {
super._updateNode(dataItem);
const hierarchyNode = dataItem.get("d3HierarchyNode");
const node = dataItem.get("node");
node.setAll({ x: 0, y: 0 });
const duration = this.get("animationDuration", 0);
const easing = this.get("animationEasing");
const scaleX = this.getPrivate("scaleX", 1);
const scaleY = this.getPrivate("scaleY", 1);
const dr = this.getPrivate("dr", 0);
const dx = this.getPrivate("dx", 0);
const x0 = hierarchyNode.x0 * scaleX + dx;
const x1 = hierarchyNode.x1 * scaleX + dx;
const y0 = hierarchyNode.y0 * scaleY;
const y1 = hierarchyNode.y1 * scaleY;
const ir = this.getPrivate("innerRadius");
const hs = this.getPrivate("hierarchySize", 0);
const slice = dataItem.get("slice");
if (slice) {
const startAngle = this.get("startAngle", -90);
const endAngle = this.get("endAngle", 270);
const sliceStartAngle = startAngle + x0 / hs * (endAngle - startAngle);
const arc = startAngle + x1 / hs * (endAngle - startAngle) - sliceStartAngle;
let sliceInnerRadius = ir + y0;
let sliceRadius = ir + y1;
sliceInnerRadius -= dr;
sliceRadius -= dr;
sliceRadius = Math.max(0, sliceRadius);
sliceInnerRadius = Math.max(0, sliceInnerRadius);
slice.animate({ key: "radius", to: sliceRadius, duration: duration, easing: easing })
slice.animate({ key: "innerRadius", to: sliceInnerRadius, duration: duration, easing: easing })
slice.animate({ key: "startAngle", to: sliceStartAngle, duration: duration, easing: easing })
slice.animate({ key: "arc", to: arc, duration: duration, easing: easing })
const fill = dataItem.get("fill");
slice._setDefault("fill", fill);
slice._setDefault("stroke", fill);
}
}
protected _updateNodesScale(hierarchyNode: d3hierarchy.HierarchyRectangularNode<ISunburstDataObject>) {
const dataItem = hierarchyNode.data.dataItem;
if (dataItem) {
const scaleX = this.getPrivate("scaleX", 1);
const scaleY = this.getPrivate("scaleY", 1);
const dr = this.getPrivate("dr", 0);
const dx = this.getPrivate("dx", 0);
const x0 = hierarchyNode.x0 * scaleX + dx;
const x1 = hierarchyNode.x1 * scaleX + dx;
const y0 = hierarchyNode.y0 * scaleY;
const y1 = hierarchyNode.y1 * scaleY;
const ir = this.getPrivate("innerRadius");
const hs = this.getPrivate("hierarchySize", 0);
const slice = dataItem.get("slice");
if (slice) {
const startAngle = this.get("startAngle", -90);
const endAngle = this.get("endAngle", 270);
const sliceStartAngle = startAngle + x0 / hs * (endAngle - startAngle);
const arc = startAngle + x1 / hs * (endAngle - startAngle) - sliceStartAngle;
let sliceInnerRadius = ir + y0;
let sliceRadius = ir + y1;
sliceInnerRadius -= dr;
sliceRadius -= dr;
sliceRadius = Math.max(0, sliceRadius);
sliceInnerRadius = Math.max(0, sliceInnerRadius);
slice.setAll({ radius: sliceRadius, innerRadius: sliceInnerRadius, startAngle: sliceStartAngle, arc: arc });
}
const hierarchyChildren = hierarchyNode.children;
if (hierarchyChildren) {
$array.each(hierarchyChildren, (hierarchyChild) => {
this._updateNodesScale(hierarchyChild)
})
}
}
}
protected _makeNode(dataItem: DataItem<this["_dataItemSettings"]>, node: HierarchyNode) {
const slice = node.children.moveValue(this.slices.make(), 0);
node.setPrivate("tooltipTarget", slice);
dataItem.setRaw("slice", slice);
slice._setDataItem(dataItem);
slice.on("arc", () => {
this._updateLabel(dataItem);
})
slice.on("innerRadius", () => {
this._updateLabel(dataItem);
})
slice.on("radius", () => {
this._updateLabel(dataItem);
})
}
protected _updateLabel(dataItem: DataItem<this["_dataItemSettings"]>) {
const slice = dataItem.get("slice");
const label = dataItem.get("label") as RadialLabel;
if (slice && label) {
let innerRadius = slice.get("innerRadius", 0);
let radius = slice.get("radius", 0);
let angle = slice.get("startAngle", 0);
let arc = Math.abs(slice.get("arc", 0));
let labelAngle = angle + arc / 2;
let maxWidth = radius - innerRadius;
let maxHeight = radius * arc * $math.RADIANS;
if (innerRadius == 0 && arc >= 360) {
radius = 1;
labelAngle = 0;
}
label.set("labelAngle", labelAngle);
label.setPrivate("radius", radius);
label.setPrivate("innerRadius", innerRadius);
if (arc >= 360) {
maxWidth *= 2;
maxHeight = maxWidth;
}
label.setAll({
maxHeight: maxHeight,
maxWidth: maxWidth
});
}
}
protected _zoom(dataItem: DataItem<this["_dataItemSettings"]>) {
let x0 = 0;
let x1 = 0;
let hs = this.getPrivate("hierarchySize", 0);
const hierarchyNode = dataItem.get("d3HierarchyNode");
let upDepth = this.get("upDepth", 0);
let topDepth = this.get("topDepth", 0);
let currentDepth = hierarchyNode.depth;
let maxDepth = this.getPrivate("maxDepth", 1);
let downDepth = this._currentDownDepth;
if (downDepth == null) {
downDepth = this.get("downDepth", 1);
}
const levelHeight = hs / (maxDepth + 1);
if (currentDepth < topDepth) {
currentDepth = topDepth;
}
if (currentDepth - upDepth < 0) {
upDepth = currentDepth;
}
x0 = hierarchyNode.x0;
x1 = hierarchyNode.x1;
let scaleDepth = (downDepth + upDepth + 1);
if (scaleDepth > maxDepth - topDepth + 1) {
scaleDepth = maxDepth - topDepth + 1;
}
let scaleX = hs / (x1 - x0);
let scaleY = hs / (levelHeight * scaleDepth);
let dr = Math.max(currentDepth - upDepth, topDepth) * levelHeight * scaleY;
const easing = this.get("animationEasing");
let duration = this.get("animationDuration", 0);
if (!this.inited) {
duration = 0;
}
let dx = -x0 * scaleX
this.animatePrivate({ key: "scaleX", to: scaleX, duration: duration, easing: easing });
this.animatePrivate({ key: "scaleY", to: scaleY, duration: duration, easing: easing });
this.animatePrivate({ key: "dr", to: dr, duration: duration, easing: easing });
this.animatePrivate({ key: "dx", to: dx, duration: duration, easing: easing });
}
protected _handleSingle(dataItem: DataItem<this["_dataItemSettings"]>) {
const parent = dataItem.get("parent");
if (parent) {
const children = parent.get("children");
if (children) {
$array.each(children, (child) => {
if (child != dataItem) {
this.disableDataItem(child);
child.get("node").hide();
}
})
}
this._handleSingle(parent);
}
}
public _positionBullet(bullet: Bullet) {
const sprite = bullet.get("sprite");
if (sprite) {
const dataItem = sprite.dataItem as DataItem<this["_dataItemSettings"]>;
const locationX = bullet.get("locationX", 0.5);
const locationY = bullet.get("locationY", 0.5);
const slice = dataItem.get("slice");
const arc = slice.get("arc", 0);
const angle = slice.get("startAngle", 0) + slice.get("arc", 0) * locationX;
const innerRadius = slice.get("innerRadius", 0);
const radius = innerRadius + (slice.get("radius", 0) - innerRadius) * locationY;
let x = $math.cos(angle) * radius;
let y = $math.sin(angle) * radius;
if ($math.round(arc, 5) === 360 && $math.round(innerRadius, 2) === 0) {
x = 0;
y = 0;
}
sprite.set("x", x);
sprite.set("y", y);
}
}
protected _makeBullet(dataItem: DataItem<this["_dataItemSettings"]>, bulletFunction: (root: Root, series: Series, dataItem: DataItem<this["_dataItemSettings"]>) => Bullet | undefined, index?: number) {
const bullet = super._makeBullet(dataItem, bulletFunction, index);
if (bullet) {
const sprite = bullet.get("sprite");
const slice = dataItem.get("slice");
if (sprite && slice) {
slice.on("arc", () => {
this._positionBullet(bullet);
})
slice.on("radius", () => {
this._positionBullet(bullet);
})
}
return bullet;
}
}
} | the_stack |
import * as expect from "expect";
import { Appservice, ProfileCache } from "../../src";
import { createTestClient } from "../MatrixClientTest";
import * as simple from "simple-mock";
import { testDelay } from "../TestUtils";
describe('ProfileCache', () => {
it('should request the profile if it is not cached', async () => {
const userId = "@test:example.org";
const roomId = "!room:example.org";
const roomProfile = {displayname: "Alice", avatar_url: "mxc://example.org/abc"};
const generalProfile = {displayname: "Bob", avatar_url: "mxc://example.org/123"};
const {client} = createTestClient();
const getStateEventSpy = simple.mock(client, "getRoomStateEvent").callFn((rid, type, stateKey) => {
expect(rid).toBe(roomId);
expect(type).toBe("m.room.member");
expect(stateKey).toBe(userId);
return Promise.resolve(roomProfile);
});
const getProfileSpy = simple.mock(client, "getUserProfile").callFn((uid) => {
expect(uid).toEqual(userId);
return Promise.resolve(generalProfile);
});
const cache = new ProfileCache(20, 30000, client);
let profile = await cache.getUserProfile(userId, roomId);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(roomProfile.displayname);
expect(profile.avatarUrl).toEqual(roomProfile.avatar_url);
expect(getStateEventSpy.callCount).toBe(1);
expect(getProfileSpy.callCount).toBe(0);
// Make sure it cached it
profile = await cache.getUserProfile(userId, roomId);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(roomProfile.displayname);
expect(profile.avatarUrl).toEqual(roomProfile.avatar_url);
expect(getStateEventSpy.callCount).toBe(1);
expect(getProfileSpy.callCount).toBe(0);
// Now check the general profile
profile = await cache.getUserProfile(userId, null);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(generalProfile.displayname);
expect(profile.avatarUrl).toEqual(generalProfile.avatar_url);
expect(getStateEventSpy.callCount).toBe(1);
expect(getProfileSpy.callCount).toBe(1);
// Make sure it cached it
profile = await cache.getUserProfile(userId, null);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(generalProfile.displayname);
expect(profile.avatarUrl).toEqual(generalProfile.avatar_url);
expect(getStateEventSpy.callCount).toBe(1);
expect(getProfileSpy.callCount).toBe(1);
});
it('should watch for membership updates with a MatrixClient', async () => {
const userId = "@test:example.org";
const roomId = "!room:example.org";
const roomProfile = {displayname: "Alice", avatar_url: "mxc://example.org/abc"};
let generalProfile = {displayname: "Bob", avatar_url: "mxc://example.org/123"};
const altRoomProfile = {displayname: "Charlie", avatar_url: "mxc://example.org/456"};
const membershipEvent = {state_key: userId, type: 'm.room.member', content: altRoomProfile};
const {client: client1} = createTestClient();
const {client: client2} = createTestClient();
const getStateEventSpy1 = simple.mock(client1, "getRoomStateEvent").callFn((rid, type, stateKey) => {
expect(rid).toBe(roomId);
expect(type).toBe("m.room.member");
expect(stateKey).toBe(userId);
return Promise.resolve(roomProfile);
});
const getProfileSpy1 = simple.mock(client1, "getUserProfile").callFn((uid) => {
expect(uid).toEqual(userId);
return Promise.resolve(generalProfile);
});
const getStateEventSpy2 = simple.mock(client2, "getRoomStateEvent").callFn((rid, type, stateKey) => {
expect(rid).toBe(roomId);
expect(type).toBe("m.room.member");
expect(stateKey).toBe(userId);
return Promise.resolve(roomProfile);
});
const getProfileSpy2 = simple.mock(client2, "getUserProfile").callFn((uid) => {
expect(uid).toEqual(userId);
return Promise.resolve(generalProfile);
});
const cache = new ProfileCache(20, 30000, client1);
// Watch for changes
cache.watchWithClient(client2);
// Ensure nothing changes when an update happens
client2.emit("room.event", roomId, membershipEvent);
expect(getStateEventSpy1.callCount).toBe(0);
expect(getProfileSpy1.callCount).toBe(0);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Get the profile once to cache it
let profile = await cache.getUserProfile(userId, roomId);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(roomProfile.displayname);
expect(profile.avatarUrl).toEqual(roomProfile.avatar_url);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(0);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Ensure it's updated from the right client (which should be none because it's a membership event)
client2.emit("room.event", roomId, membershipEvent);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(0);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Verify the profile got updated
profile = await cache.getUserProfile(userId, roomId);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(altRoomProfile.displayname);
expect(profile.avatarUrl).toEqual(altRoomProfile.avatar_url);
// Now check the general profile (cache it first)
profile = await cache.getUserProfile(userId, null);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(generalProfile.displayname);
expect(profile.avatarUrl).toEqual(generalProfile.avatar_url);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(1);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Change the profile slightly and expect it to update
generalProfile = {displayname: "Daniel", avatar_url: "mxc://example.org/def"};
client2.emit("room.event", roomId, membershipEvent);
await testDelay(100); // Let the promises settle.
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(1);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(1);
profile = await cache.getUserProfile(userId, null);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(generalProfile.displayname);
expect(profile.avatarUrl).toEqual(generalProfile.avatar_url);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(1);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(1);
});
it('should watch for membership updates with an appservice', async () => {
const userId = "@test:example.org";
const roomId = "!room:example.org";
const roomProfile = {displayname: "Alice", avatar_url: "mxc://example.org/abc"};
let generalProfile = {displayname: "Bob", avatar_url: "mxc://example.org/123"};
const altRoomProfile = {displayname: "Charlie", avatar_url: "mxc://example.org/456"};
const membershipEvent = {state_key: userId, type: 'm.room.member', content: altRoomProfile};
const {client: client1} = createTestClient();
const {client: client2} = createTestClient();
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
const getStateEventSpy1 = simple.mock(client1, "getRoomStateEvent").callFn((rid, type, stateKey) => {
expect(rid).toBe(roomId);
expect(type).toBe("m.room.member");
expect(stateKey).toBe(userId);
return Promise.resolve(roomProfile);
});
const getProfileSpy1 = simple.mock(client1, "getUserProfile").callFn((uid) => {
expect(uid).toEqual(userId);
return Promise.resolve(generalProfile);
});
const getStateEventSpy2 = simple.mock(client2, "getRoomStateEvent").callFn((rid, type, stateKey) => {
expect(rid).toBe(roomId);
expect(type).toBe("m.room.member");
expect(stateKey).toBe(userId);
return Promise.resolve(roomProfile);
});
const getProfileSpy2 = simple.mock(client2, "getUserProfile").callFn((uid) => {
expect(uid).toEqual(userId);
return Promise.resolve(generalProfile);
});
const cache = new ProfileCache(20, 30000, client1);
// Watch for changes
const clientFnSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
return client2;
});
cache.watchWithAppservice(appservice, clientFnSpy);
// Ensure nothing changes when an update happens
appservice.emit("room.event", roomId, membershipEvent);
expect(clientFnSpy.callCount).toBe(1);
expect(getStateEventSpy1.callCount).toBe(0);
expect(getProfileSpy1.callCount).toBe(0);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Get the profile once to cache it
let profile = await cache.getUserProfile(userId, roomId);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(roomProfile.displayname);
expect(profile.avatarUrl).toEqual(roomProfile.avatar_url);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(0);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Ensure it's updated from the right client (which should be none because it's a membership event)
appservice.emit("room.event", roomId, membershipEvent);
expect(clientFnSpy.callCount).toBe(2);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(0);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Verify the profile got updated
profile = await cache.getUserProfile(userId, roomId);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(altRoomProfile.displayname);
expect(profile.avatarUrl).toEqual(altRoomProfile.avatar_url);
// Now check the general profile (cache it first)
profile = await cache.getUserProfile(userId, null);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(generalProfile.displayname);
expect(profile.avatarUrl).toEqual(generalProfile.avatar_url);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(1);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(0);
// Change the profile slightly and expect it to update
generalProfile = {displayname: "Daniel", avatar_url: "mxc://example.org/def"};
appservice.emit("room.event", roomId, membershipEvent);
await testDelay(100); // Let the promises settle.
expect(clientFnSpy.callCount).toBe(3);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(1);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(1);
profile = await cache.getUserProfile(userId, null);
expect(profile).toBeDefined();
expect(profile.displayName).toEqual(generalProfile.displayname);
expect(profile.avatarUrl).toEqual(generalProfile.avatar_url);
expect(getStateEventSpy1.callCount).toBe(1);
expect(getProfileSpy1.callCount).toBe(1);
expect(getStateEventSpy2.callCount).toBe(0);
expect(getProfileSpy2.callCount).toBe(1);
});
}); | the_stack |
* @module OrbitGT
*/
//package orbitgt.system.runtime;
type int8 = number;
type int16 = number;
type int32 = number;
type float32 = number;
type float64 = number;
import { ASystem } from "./ASystem";
import { Numbers } from "./Numbers";
import { Strings } from "./Strings";
/**
* Class ALong defines a signed 64-bit integer using two (high and low) 64-bit floats.
*
* @version 1.0 February 2019
*/
/** @internal */
export class ALong {
/** The value of a 32 bit unit */
private static readonly _U32: float64 = 4294967296.0;
/** The value of a 31 bit unit */
private static readonly _U31: float64 = 2147483648.0;
/** The value of a 24 bit unit */
private static readonly _U24: float64 = 16777216.0;
/** The value of a 16 bit unit */
private static readonly _U16: float64 = 65536.0;
/** The value of a 8 bit unit */
private static readonly _U8: float64 = 256.0;
/** The integer value 0 */
public static ZERO: ALong = new ALong(0.0, 0.0);
/** The integer value 1 */
public static ONE: ALong = new ALong(0.0, 1.0);
/** The integer value 2 */
public static TWO: ALong = new ALong(0.0, 2.0);
/** The integer value 4 */
public static FOUR: ALong = new ALong(0.0, 4.0);
/** The integer value 10 */
public static TEN: ALong = new ALong(0.0, 10.0);
/** The integer value -1 */
public static MINUS_ONE: ALong = new ALong(ALong._U32 - 1.0, ALong._U32 - 1.0);
/** The maximum positive value of a signed_ 64-bit integer (9223372036854775807) */
public static MAX_VALUE: ALong = new ALong(ALong._U31 - 1.0, ALong._U32 - 1.0);
/** The minimum negative value of a signed 64-bit integer (-9223372036854775808) */
public static MIN_VALUE: ALong = new ALong(ALong._U31, 0.0);
/** The high value (unsigned integer [0..U32[ after normalization, negative i64 if >= U31) */
private _high: float64;
/** The low value (unsigned integer [0..U32[ after normalization) */
private _low: float64;
/**
* Create a new value.
* @param high the 32-bit high part.
* @param low the 32-bit low part.
*/
private constructor(high: float64, low: float64) {
this._high = high;
this._low = low;
}
/**
* Check if the number is zero.
* @return true if zero.
*/
public isZero(): boolean {
return (this._high == 0.0) && (this._low == 0.0);
}
/**
* Check if the number is not zero.
* @return true if zero.
*/
public isNonZero(): boolean {
return (this.isZero() == false);
}
/**
* Check if the number is one.
* @return true if one.
*/
public isOne(): boolean {
return (this._high == 0.0) && (this._low == 1.0);
}
/**
* Check if the number is positive.
* @return true if positive (false if zero).
*/
public isPositive(): boolean {
return this.isZero() ? false : (this._high < ALong._U31);
}
/**
* Check if the number is negative.
* @return true if negative (false if zero).
*/
public isNegative(): boolean {
return this.isZero() ? false : (this._high >= ALong._U31);
}
/**
* Normalize the number.
* @return this number for chaining operations.
*/
private static normalize2(high: float64, low: float64): ALong {
// normalize the low part
let overflowLow: float64 = Numbers.floor(low / ALong._U32);
low = (low - overflowLow * ALong._U32); // inside range [0..U32[
high += overflowLow;
// normalize the high part
let overflowHigh: float64 = Numbers.floor(high / ALong._U32);
high = (high - overflowHigh * ALong._U32); // inside range [0..U32[
// return the result
return new ALong(high, low);
}
/**
* Negate the number.
* @return the result.
*/
public negate(): ALong {
/* Zero? */
if (this.isZero()) {
/* Return this immutable instance */
return this;
}
/* Compute */
let resultHigh: float64 = (ALong._U32 - 1.0 - this._high);
let resultLow: float64 = (ALong._U32 - this._low);
/* Overflow? */
if (resultLow == ALong._U32) {
resultLow = 0.0;
resultHigh += 1.0; // in case we try to invert ALong.MIN_VALUE we get ALong.MIN_VALUE as a result again
}
/* Return the result */
return new ALong(resultHigh, resultLow);
}
/**
* Add a number.
* @param value the value to add.
* @return the result.
*/
public add(value: ALong): ALong {
/* Compute */
let resultHigh: float64 = (this._high + value._high);
let resultLow: float64 = (this._low + value._low);
/* Return the result */
return ALong.normalize2(resultHigh, resultLow);
}
/**
* Add a number.
* @param value the value to add.
* @return the result.
*/
public addInt(value: int32): ALong {
return this.add(ALong.fromInt(value));
}
/**
* Increase by one.
* @return the result.
*/
public increase(): ALong {
return this.addInt(1);
}
/**
* Subtract a number.
* @param value the value to subtract.
* @return the result.
*/
public sub(value: ALong): ALong {
return this.add(value.negate());
}
/**
* Subtract a number.
* @param value the value to subtract.
* @return the result.
*/
public subInt(value: int32): ALong {
return this.sub(ALong.fromInt(value));
}
/**
* Decrease by one.
* @return the result.
*/
public decrease(): ALong {
return this.subInt(1);
}
/**
* Multiply two unsigned 32-bit integer values.
* @param v1 the first value.
* @param v2 the second value.
* @param high0 the initial high value of the result.
* @return the unsigned 64-bit product.
*/
private static mul2(v1: ALong, v2: ALong): ALong {
/* Zero? */
if (v1.isZero()) return v1;
if (v2.isZero()) return v2;
/* Make the values unsigned */
let neg1: int32 = v1.isNegative() ? 1 : 0;
if (neg1 == 1) v1 = v1.negate();
let neg2: int32 = v2.isNegative() ? 1 : 0;
if (neg2 == 1) v2 = v2.negate();
/* Split first low into 16-bit parts */
let a1: float64 = Numbers.floor(v1._low / ALong._U16);;
let a2: float64 = (v1._low - a1 * ALong._U16);
/* Split second low into 16-bit parts */
let b1: float64 = Numbers.floor(v2._low / ALong._U16);;
let b2: float64 = (v2._low - b1 * ALong._U16);
/* Compute */
let resultHigh: float64 = (v1._high * v2._low + v1._low * v2._high) + (a1 * b1);
let resultLow: float64 = (a1 * b2 + a2 * b1) * ALong._U16 + (a2 * b2);
let result: ALong = ALong.normalize2(resultHigh, resultLow);
/* Return the result */
return (neg1 + neg2 == 1) ? result.negate() : result;
}
/**
* Multiply by a number.
* @param value the value to multiply.
* @return the result.
*/
public mul(value: ALong): ALong {
return ALong.mul2(this, value);
}
/**
* Multiply by a number.
* @param value the value to multiply.
* @return the result.
*/
public mulInt(value: int32): ALong {
return this.mul(ALong.fromInt(value));
}
/**
* Divide by a number.
* @param value the value to divide by.
* @return the result.
*/
public div(value: ALong): ALong {
/* Division by zero? */
ASystem.assertNot(value.isZero(), "ALong division by ALong zero");
/* Division by one? */
if (value.isOne()) return this;
/* Make the values unsigned */
let currentValue: ALong = this;
let neg1: boolean = currentValue.isNegative();
if (neg1) currentValue = currentValue.negate();
let value2: ALong = value;
let neg2: boolean = value2.isNegative();
if (neg2) value2.negate();
let neg: boolean = (neg1 && !neg2) || (!neg1 && neg2);
/* Loop until the remainder is smaller than the value */
let result: ALong = ALong.ZERO;
while (currentValue.isLargerThanOrEqualTo(value2)) {
/* Shift the value as much as possible */
let test: ALong = value2;
let times: ALong = ALong.ONE;
if (test.isSmallerThan(currentValue)) {
while (test.isSmallerThan(currentValue)) {
test = test.mulInt(2);
times = times.mulInt(2);
}
test = test.divInt(2);
times = times.divInt(2);
}
/* Subtract the shifted value */
currentValue = currentValue.sub(test);
result = result.add(times);
}
/* Return the result */
return (neg) ? result.negate() : result;
}
/**
* Divide by a number.
* @param value the value to divide by.
* @return the result.
*/
public divInt(value: int32): ALong {
/* Division by zero? */
ASystem.assertNot(value == 0, "ALong division by int zero");
/* Division by one? */
if (value == 1) return this;
/* Make the values unsigned */
let value1: ALong = this;
let neg1: boolean = value1.isNegative();
if (neg1) value1 = value1.negate();
let neg2: boolean = (value < 0);
if (neg2) value = -1 * value;
let neg: boolean = (neg1 && !neg2) || (!neg1 && neg2);
/* Compute */
let valueF: float64 = (0.0 + value);
let h1: float64 = Numbers.floor(value1._high / valueF);
let h2: float64 = (value1._high - valueF * h1);
let l1: float64 = Numbers.floor(value1._low / valueF);
let l2: float64 = (value1._low - valueF * l1);
let t: float64 = (h2 * ALong._U32 + l2);
let t1: float64 = Numbers.floor(t / valueF);
let t2: float64 = (t - valueF * t1); // remainder
let result: ALong = ALong.normalize2(h1, l1 + t1);
/* Return the result */
return (neg) ? result.negate() : result;
}
/**
* Modulate by a number.
* @param value the value to modulate by.
* @return the result.
*/
public mod(value: ALong): ALong {
/* Division by zero? */
ASystem.assertNot(value.isZero(), "ALong modulo by ALong zero");
/* Division by one? */
if (value.isOne()) return ALong.ZERO;
/* Compute */
let result: ALong = this.sub(this.div(value).mul(value));
/* Return the result */
return result;
}
/**
* Modulate by a number.
* @param value the value to modulate by.
* @return the modulo value.
*/
public modInt(value: int32): int32 {
/* Division by zero? */
ASystem.assertNot(value == 0, "ALong modulo by int zero");
/* Division by one? */
if (value == 1) return 0;
/* Make the values unsigned */
let value1: ALong = this;
let neg1: boolean = value1.isNegative();
if (neg1) value1 = value1.negate();
let neg2: boolean = (value < 0);
if (neg2) value = -1 * value;
let neg: boolean = (neg1 && !neg2) || (!neg1 && neg2);
/* Compute */
let valueF: float64 = (0.0 + value);
let h1: float64 = Numbers.floor(value1._high / valueF);
let h2: float64 = (value1._high - valueF * h1);
let l1: float64 = Numbers.floor(value1._low / valueF);
let l2: float64 = (value1._low - valueF * l1);
let t: float64 = (h2 * ALong._U32 + l2);
let t1: float64 = Numbers.floor(t / valueF);
let t2: float64 = (t - valueF * t1); // remainder
let result: int32 = Math.trunc(t2);
/* Return the result */
return result;
}
/**
* Create a new number.
* @param value the 64-bit float value.
* @return the new number.
*/
public static fromDouble(value: float64): ALong {
/* Make the value unsigned */
let neg: boolean = (value < 0.0);
if (neg) value = (-1.0 * value);
/* Compute */
value = Numbers.floor(value);
let high: float64 = Numbers.floor(value / ALong._U32);
let low: float64 = (value - high * ALong._U32);
let result: ALong = ALong.normalize2(high, low);
/* Return the result */
return (neg) ? result.negate() : result;
}
/**
* Get a double.
* @return the double value.
*/
public toDouble(): float64 {
/* Make the value unsigned */
let value: ALong = this;
let neg: boolean = value.isNegative();
if (neg) value = value.negate();
/* Compute */
let result: float64 = (value._high * ALong._U32) + value._low;
if (neg) result *= -1.0;
/* Return the result */
return result;
}
/**
* Create a new number.
* @param value the 32-bit integer value.
* @return the new number.
*/
public static fromInt(value: float64): ALong {
return (value < 0.0) ? new ALong(ALong._U32 - 1.0, ALong._U32 + value) : new ALong(0.0, value);
}
/**
* Get a 32-bit integer.
* @return the integer value.
*/
public toInt(): int32 {
/* Make the value unsigned */
let value: ALong = this;
let neg: boolean = value.isNegative();
if (neg) value = value.negate();
/* Compute */
let result: float64 = value._low;
if (neg) result *= -1.0;
/* Return the result */
return Numbers.doubleToInt(result);
}
/**
* Create a new number.
* @param i1 the 32-bit high part.
* @param i0 the 32-bit low part.
* @return the new number.
*/
public static fromHighLow(i1: float64, i0: float64): ALong {
if (i1 < 0.0) i1 += ALong._U32; // make unsigned
if (i0 < 0.0) i0 += ALong._U32;
return new ALong(i1, i0);
}
/**
* Get the high part.
* @return the integer value (0..4294967295)
*/
public getHigh(): float64 {
return this._high;
}
/**
* Get the low part.
* @return the integer value (0..4294967295)
*/
public getLow(): float64 {
return this._low;
}
/**
* Create a new number.
* @param b7 the most significant 8-bit byte of the high part (0..255).
* @param b6 the most third 8-bit byte of the high part (0..255).
* @param b5 the most second 8-bit byte of the high part (0..255).
* @param b4 the most least 8-bit byte of the high part (0..255).
* @param b3 the most significant 8-bit byte of the low part (0..255).
* @param b2 the most third 8-bit byte of the low part (0..255).
* @param b1 the most second 8-bit byte of the low part (0..255).
* @param b0 the most least 8-bit byte of the low part (0..255).
* @return the new number.
*/
public static fromBytes(b7: float64, b6: float64, b5: float64, b4: float64, b3: float64, b2: float64, b1: float64, b0: float64): ALong {
if (b7 < 0.0) b7 += ALong._U8; // make unsigned
if (b6 < 0.0) b6 += ALong._U8;
if (b5 < 0.0) b5 += ALong._U8;
if (b4 < 0.0) b4 += ALong._U8;
if (b3 < 0.0) b3 += ALong._U8;
if (b2 < 0.0) b2 += ALong._U8;
if (b1 < 0.0) b1 += ALong._U8;
if (b0 < 0.0) b0 += ALong._U8;
let high: float64 = (b7 * ALong._U24 + b6 * ALong._U16 + b5 * ALong._U8 + b4);
let low: float64 = (b3 * ALong._U24 + b2 * ALong._U16 + b1 * ALong._U8 + b0);
return ALong.fromHighLow(high, low);
}
/**
* Get a byte.
* @param index the index of the byte (0..7 where 0 is low).
* @return the byte value (0..255)
*/
public getByte(index: int32): int32 {
let value: float64 = (index < 4) ? this._low : this._high; // this should be unsigned
let position: int32 = (index < 4) ? index : (index - 4);
for (let i: number = 0; i < position; i++) value = Numbers.floor(value / 256.0);
return Math.trunc(value % 256);
}
/**
* Check if a number is equal.
* @param value the value to check.
* @return true if equal.
*/
public isEqualTo(value: ALong): boolean {
return (value._high == this._high) && (value._low == this._low);
}
/**
* Check if a number is not equal.
* @param value the value to check.
* @return true if equal.
*/
public isNotEqualTo(value: ALong): boolean {
return (this.isEqualTo(value) == false);
}
/**
* Check if a number is equal.
* @param value the value to check.
* @return true if equal.
*/
public same(value: ALong): boolean {
return this.isEqualTo(value);
}
/**
* Check if a number is equal.
* @param value the value to check.
* @return true if equal.
*/
public equals(value: ALong): boolean {
return this.isEqualTo(value);
}
/**
* Compare this long to another long.
* @param value the other long.
* @return zero if equal, positive if smaller, or negative if value is larger.
*/
public compareTo(value: ALong): int32 {
let diff: ALong = this.sub(value);
if (diff.isZero()) return 0;
return diff.isNegative() ? -1 : 1;
}
/**
* Check if a value is larger.
* @param value the value to check.
* @return true if this number is larger than the check value.
*/
public isLargerThan(value: ALong): boolean {
return (this.compareTo(value) > 0);
}
/**
* Check if a value is larger.
* @param value the value to check.
* @return true if this number is larger than the check value.
*/
public isLargerThanOrEqualTo(value: ALong): boolean {
return (this.compareTo(value) >= 0);
}
/**
* Check if a value is smaller.
* @param value the value to check.
* @return true if this number is smaller than the check value.
*/
public isSmallerThan(value: ALong): boolean {
return (this.compareTo(value) < 0);
}
/**
* Check if a value is smaller.
* @param value the value to check.
* @return true if this number is smaller than the check value.
*/
public isSmallerThanOrEqualTo(value: ALong): boolean {
return (this.compareTo(value) <= 0);
}
/**
* Get the maximum value.
* @param v1 the first value.
* @param v2 the second value.
* @return the maximum value.
*/
public static max(v1: ALong, v2: ALong): ALong {
return (v2.isLargerThan(v1)) ? v2 : v1;
}
/**
* Get the minimum value.
* @param v1 the first value.
* @param v2 the second value.
* @return the minimum value.
*/
public static min(v1: ALong, v2: ALong): ALong {
return (v2.isSmallerThan(v1)) ? v2 : v1;
}
/**
* Create a number from a string.
* @param svalue the string value.
* @param radix the radix (2 to 36).
* @return the number.
*/
public static fromRadixString(svalue: string, radix: int32): ALong {
/* Check the radix */
ASystem.assertNot((radix < 2) || (radix > 36), "Invalid radix: " + radix);
/* Common values? */
if (Strings.equals(svalue, "0")) return ALong.ZERO;
if (Strings.equals(svalue, "1")) return ALong.ONE;
/* Negative? */
let neg: boolean = Strings.startsWith(svalue, "-");
if (neg) svalue = Strings.substringFrom(svalue, 1);
/* Add all digits */
let result: ALong = ALong.ZERO;
let unit: ALong = ALong.ONE;
let radixHL: ALong = ALong.fromInt(radix);
let slength: int32 = Strings.getLength(svalue);
for (let i: number = 0; i < slength; i++) {
/* Add the next digit */
let charCode: int32 = Strings.charCodeAt(svalue, slength - 1 - i);
let digit: int32 = (charCode >= 65) ? (charCode - 65 + 10) : (charCode - 48);
if (digit > 0) result = result.add(unit.mulInt(digit));
unit = unit.mul(radixHL);
}
/* Return the result */
return (neg) ? result.negate() : result;
}
/**
* Create a number from a decimal string.
* @param value the string value.
* @return the number.
*/
public static fromString(value: string): ALong {
if (value == null) return null;
return ALong.fromRadixString(value, 10);
}
/**
* Create a number from a hexadecimal string.
* @param value the string value.
* @return the number.
*/
public static fromHexString(value: string): ALong {
if (value == null) return null;
return ALong.fromRadixString(value, 16);
}
/**
* Convert the number to a string.
* @param radix the radix (2 to 36).
* @return the string.
*/
public getRadixString(radix: int32): string {
/* Check the radix */
ASystem.assertNot((radix < 2) || (radix > 36), "Invalid radix: " + radix);
/* Common values? */
let value: ALong = this;
if (value.isZero()) return "0";
/* Make the value unsigned */
let neg: boolean = value.isNegative();
if (neg) value = value.negate();
/* Add all digits */
let result: string = "";
while (true) {
/* Add the next digit */
if (value.isZero()) break;
let digit: int32 = value.modInt(radix);
value = value.divInt(radix);
let sdigit: string = (digit < 10) ? Strings.charCodeToString(48 + digit) : Strings.charCodeToString(65 + digit - 10);
result = (sdigit + result);
/* Fail? */
ASystem.assertNot(Strings.getLength(result) > 20, "Failed to convert longHL to string (radix " + radix + "): " + this._high + ";" + this._low);
}
if (neg) result = ("-" + result);
/* Return the result */
return result;
}
/**
* Convert the number to a decimal string.
* @return the string.
*/
public getString(): string {
return this.getRadixString(10);
}
/**
* Convert the number to a hexadecimal string.
* @return the string.
*/
public getHexString(): string {
return this.getRadixString(16);
}
/**
* The standard toString method.
* @see Object#toString
*/
public toString(): string {
return this.getString();
}
} | the_stack |
import { readFileSync, readFile, mkdirpSync, writeFileSync, remove, copy, pathExistsSync } from 'fs-extra';
import { rootDir } from '../tool-utils';
import { pressCarouselItems } from './utils/pressCarousel';
import { getMarkdownIt, loadMustachePartials, markdownToPageHtml, renderMustache } from './utils/render';
import { AssetUrls, Env, PlanPageParams, Sponsors, TemplateParams } from './utils/types';
import { getPlans, loadStripeConfig } from '@joplin/lib/utils/joplinCloud';
import { stripOffFrontMatter } from './utils/frontMatter';
import { dirname, basename } from 'path';
const moment = require('moment');
const glob = require('glob');
const path = require('path');
const md5File = require('md5-file/promise');
const env = Env.Prod;
const docDir = `${dirname(dirname(dirname(dirname(__dirname))))}/joplin-website/docs`;
if (!pathExistsSync(docDir)) throw new Error(`Doc directory does not exist: ${docDir}`);
const websiteAssetDir = `${rootDir}/Assets/WebsiteAssets`;
const readmeDir = `${rootDir}/readme`;
const mainTemplateHtml = readFileSync(`${websiteAssetDir}/templates/main-new.mustache`, 'utf8');
const frontTemplateHtml = readFileSync(`${websiteAssetDir}/templates/front.mustache`, 'utf8');
const plansTemplateHtml = readFileSync(`${websiteAssetDir}/templates/plans.mustache`, 'utf8');
const stripeConfig = loadStripeConfig(env, `${rootDir}/packages/server/stripeConfig.json`);
const partialDir = `${websiteAssetDir}/templates/partials`;
const discussLink = 'https://discourse.joplinapp.org/c/news/9';
let tocMd_: string = null;
let tocHtml_: string = null;
const tocRegex_ = /<!-- TOC -->([^]*)<!-- TOC -->/;
function tocMd() {
if (tocMd_) return tocMd_;
const md = readFileSync(`${rootDir}/README.md`, 'utf8');
const toc = md.match(tocRegex_);
tocMd_ = toc[1];
return tocMd_;
}
const donateLinksRegex_ = /<!-- DONATELINKS -->([^]*)<!-- DONATELINKS -->/;
async function getDonateLinks() {
const md = await readFile(`${rootDir}/README.md`, 'utf8');
const matches = md.match(donateLinksRegex_);
if (!matches) throw new Error('Cannot fetch donate links');
return `<div class="donate-links">\n\n${matches[1].trim()}\n\n</div>`;
}
function replaceGitHubByWebsiteLinks(md: string) {
return md
.replace(/https:\/\/github.com\/laurent22\/joplin\/blob\/dev\/readme\/(.*?)\.md(#[^\s)]+|)/g, '/$1/$2')
.replace(/https:\/\/github.com\/laurent22\/joplin\/blob\/dev\/README\.md(#[^\s)]+|)/g, '/help/$1')
.replace(/https:\/\/raw.githubusercontent.com\/laurent22\/joplin\/dev\/Assets\/WebsiteAssets\/(.*?)/g, '/$1');
}
function tocHtml() {
if (tocHtml_) return tocHtml_;
const markdownIt = getMarkdownIt();
let md = tocMd();
md = md.replace(/# Table of contents/, '');
md = replaceGitHubByWebsiteLinks(md);
tocHtml_ = markdownIt.render(md);
tocHtml_ = `<div>${tocHtml_}</div>`;
return tocHtml_;
}
const baseUrl = '';
const cssBasePath = `${websiteAssetDir}/css`;
const cssBaseUrl = `${baseUrl}/css`;
const jsBasePath = `${websiteAssetDir}/js`;
const jsBaseUrl = `${baseUrl}/js`;
async function getAssetUrls(): Promise<AssetUrls> {
return {
css: {
fontawesome: `${cssBaseUrl}/fontawesome-all.min.css?h=${await md5File(`${cssBasePath}/fontawesome-all.min.css`)}`,
site: `${cssBaseUrl}/site.css?h=${await md5File(`${cssBasePath}/site.css`)}`,
},
js: {
script: `${jsBaseUrl}/script.js?h=${await md5File(`${jsBasePath}/script.js`)}`,
},
};
}
function defaultTemplateParams(assetUrls: AssetUrls): TemplateParams {
return {
env,
baseUrl,
imageBaseUrl: `${baseUrl}/images`,
cssBaseUrl,
jsBaseUrl,
tocHtml: tocHtml(),
yyyy: (new Date()).getFullYear().toString(),
templateHtml: mainTemplateHtml,
forumUrl: 'https://discourse.joplinapp.org/',
showToc: true,
showImproveThisDoc: true,
showJoplinCloudLinks: true,
navbar: {
isFrontPage: false,
},
assetUrls,
};
}
function renderPageToHtml(md: string, targetPath: string, templateParams: TemplateParams) {
// Remove the header because it's going to be added back as HTML
md = md.replace(/# Joplin\n/, '');
templateParams = {
...defaultTemplateParams(templateParams.assetUrls),
...templateParams,
};
templateParams.showBottomLinks = templateParams.showImproveThisDoc || !!templateParams.discussOnForumLink;
const title = [];
if (!templateParams.title) {
title.push('Joplin - an open source note taking and to-do application with synchronisation capabilities');
} else {
title.push(templateParams.title);
title.push('Joplin');
}
md = replaceGitHubByWebsiteLinks(md);
if (templateParams.donateLinksMd) {
md = `${templateParams.donateLinksMd}\n\n${md}`;
}
templateParams.pageTitle = title.join(' | ');
const html = templateParams.contentHtml ? renderMustache(templateParams.contentHtml, templateParams) : markdownToPageHtml(md, templateParams);
const folderPath = dirname(targetPath);
mkdirpSync(folderPath);
writeFileSync(targetPath, html);
}
async function readmeFileTitle(sourcePath: string) {
let md = await readFile(sourcePath, 'utf8');
md = stripOffFrontMatter(md).doc;
const r = md.match(/(^|\n)# (.*)/);
if (!r) {
throw new Error(`Could not determine title for Markdown file: ${sourcePath}`);
} else {
return r[2];
}
}
function renderFileToHtml(sourcePath: string, targetPath: string, templateParams: TemplateParams) {
let md = readFileSync(sourcePath, 'utf8');
md = stripOffFrontMatter(md).doc;
return renderPageToHtml(md, targetPath, templateParams);
}
function makeHomePageMd() {
let md = readFileSync(`${rootDir}/README.md`, 'utf8');
md = md.replace(tocRegex_, '');
// HACK: GitHub needs the \| or the inline code won't be displayed correctly inside the table,
// while MarkdownIt doesn't and will in fact display the \. So we remove it here.
md = md.replace(/\\\| bash/g, '| bash');
return md;
}
async function loadSponsors(): Promise<Sponsors> {
const sponsorsPath = `${rootDir}/packages/tools/sponsors.json`;
const output: Sponsors = JSON.parse(await readFile(sponsorsPath, 'utf8'));
output.orgs = output.orgs.map(o => {
if (o.urlWebsite) o.url = o.urlWebsite;
return o;
});
return output;
}
const makeNewsFrontPage = async (sourceFilePaths: string[], targetFilePath: string, templateParams: TemplateParams) => {
const maxNewsPerPage = 20;
const frontPageMd: string[] = [];
for (const mdFilePath of sourceFilePaths) {
let md = await readFile(mdFilePath, 'utf8');
const info = stripOffFrontMatter(md);
md = info.doc.trim();
const dateString = moment(info.created).format('D MMM YYYY');
md = md.replace(/^# (.*)/, `# [$1](https://github.com/laurent22/joplin/blob/dev/readme/news/${path.basename(mdFilePath)})\n\n*Published on **${dateString}***\n\n`);
md += `\n\n* * *\n\n[<i class="fab fa-discourse"></i> Discuss on the forum](${discussLink})`;
frontPageMd.push(md);
if (frontPageMd.length >= maxNewsPerPage) break;
}
renderPageToHtml(frontPageMd.join('\n\n* * *\n\n'), targetFilePath, templateParams);
};
const isNewsFile = (filePath: string): boolean => {
return filePath.includes('readme/news/');
};
async function main() {
await remove(`${docDir}`);
await copy(websiteAssetDir, `${docDir}`);
const sponsors = await loadSponsors();
const partials = await loadMustachePartials(partialDir);
const assetUrls = await getAssetUrls();
const readmeMd = makeHomePageMd();
// await updateDownloadPage(readmeMd);
// =============================================================
// HELP PAGE
// =============================================================
renderPageToHtml(readmeMd, `${docDir}/help/index.html`, { sourceMarkdownFile: 'README.md', partials, sponsors, assetUrls });
// =============================================================
// FRONT PAGE
// =============================================================
renderPageToHtml('', `${docDir}/index.html`, {
templateHtml: frontTemplateHtml,
partials,
pressCarouselRegular: {
id: 'carouselRegular',
items: pressCarouselItems(),
},
pressCarouselMobile: {
id: 'carouselMobile',
items: pressCarouselItems(),
},
sponsors,
navbar: {
isFrontPage: true,
},
showToc: false,
assetUrls,
});
// =============================================================
// PLANS PAGE
// =============================================================
const planPageFaqMd = await readFile(`${readmeDir}/faq_joplin_cloud.md`, 'utf8');
const planPageFaqHtml = getMarkdownIt().render(planPageFaqMd, {});
const planPageParams: PlanPageParams = {
...defaultTemplateParams(assetUrls),
partials,
templateHtml: plansTemplateHtml,
plans: getPlans(stripeConfig),
faqHtml: planPageFaqHtml,
stripeConfig,
};
const planPageContentHtml = renderMustache('', planPageParams);
renderPageToHtml('', `${docDir}/plans/index.html`, {
...defaultTemplateParams(assetUrls),
pageName: 'plans',
partials,
showToc: false,
showImproveThisDoc: false,
contentHtml: planPageContentHtml,
title: 'Joplin Cloud Plans',
});
// =============================================================
// All other pages are generated dynamically from the
// Markdown files under /readme
// =============================================================
const mdFiles = glob.sync(`${readmeDir}/**/*.md`).map((f: string) => f.substr(rootDir.length + 1));
const sources = [];
const donateLinksMd = await getDonateLinks();
const makeTargetFilePath = (input: string): string => {
if (isNewsFile(input)) {
const filenameNoExt = basename(input, '.md');
return `${docDir}/news/${filenameNoExt}/index.html`;
} else {
// Input is for example "readme/spec/interop_with_frontmatter.md",
// and we need to convert it to
// "docs/spec/interop_with_frontmatter/index.html" and prefix it
// with the website repo full path.
return `${docDir}/${input.replace(/\.md/, '/index.html').replace(/readme\//, '')}`;
}
};
const newsFilePaths: string[] = [];
for (const mdFile of mdFiles) {
const title = await readmeFileTitle(`${rootDir}/${mdFile}`);
const targetFilePath = makeTargetFilePath(mdFile);
const isNews = isNewsFile(mdFile);
if (isNews) newsFilePaths.push(mdFile);
sources.push([mdFile, targetFilePath, {
title: title,
donateLinksMd: mdFile === 'readme/donate.md' ? '' : donateLinksMd,
showToc: mdFile !== 'readme/download.md' && !isNews,
}]);
}
for (const source of sources) {
source[2].sourceMarkdownFile = source[0];
source[2].sourceMarkdownName = path.basename(source[0], path.extname(source[0]));
const sourceFilePath = `${rootDir}/${source[0]}`;
const targetFilePath = source[1];
const isNews = isNewsFile(sourceFilePath);
renderFileToHtml(sourceFilePath, targetFilePath, {
...source[2],
templateHtml: mainTemplateHtml,
pageName: isNews ? 'news-item' : '',
discussOnForumLink: isNews ? discussLink : '',
showImproveThisDoc: !isNews,
partials,
assetUrls,
});
}
newsFilePaths.sort((a, b) => {
return a.toLowerCase() > b.toLowerCase() ? -1 : +1;
});
await makeNewsFrontPage(newsFilePaths, `${docDir}/news/index.html`, {
...defaultTemplateParams(assetUrls),
pageName: 'news',
partials,
showToc: false,
showImproveThisDoc: false,
donateLinksMd,
});
}
main().catch((error) => {
console.error(error);
process.exit(1);
}); | the_stack |
import { Injectable, EventEmitter } from '@angular/core';
import { CoreFile } from '@services/file';
import { CoreFileHelper } from '@services/file-helper';
import { CoreFilepool } from '@services/filepool';
import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUrlUtils } from '@services/utils/url';
import { CoreUtils } from '@services/utils/utils';
import { CoreWSFile } from '@services/ws';
import { makeSingleton, Translate } from '@singletons';
import { CoreQuestion, CoreQuestionProvider, CoreQuestionQuestionParsed, CoreQuestionsAnswers } from './question';
import { CoreQuestionDelegate } from './question-delegate';
/**
* Service with some common functions to handle questions.
*/
@Injectable({ providedIn: 'root' })
export class CoreQuestionHelperProvider {
protected lastErrorShown = 0;
/**
* Add a behaviour button to the question's "behaviourButtons" property.
*
* @param question Question.
* @param button Behaviour button (DOM element).
*/
protected addBehaviourButton(question: CoreQuestionQuestion, button: HTMLInputElement): void {
if (!button || !question) {
return;
}
question.behaviourButtons = question.behaviourButtons || [];
// Extract the data we want.
question.behaviourButtons.push({
id: button.id,
name: button.name,
value: button.value,
disabled: button.disabled,
});
}
/**
* Clear questions temporary data after the data has been saved.
*
* @param questions The list of questions.
* @param component The component the question is related to.
* @param componentId Component ID.
* @return Promise resolved when done.
*/
async clearTmpData(questions: CoreQuestionQuestionParsed[], component: string, componentId: string | number): Promise<void> {
questions = questions || [];
await Promise.all(questions.map(async (question) => {
await CoreQuestionDelegate.clearTmpData(question, component, componentId);
}));
}
/**
* Delete files stored for a question.
*
* @param question Question.
* @param component The component the question is related to.
* @param componentId Component ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async deleteStoredQuestionFiles(
question: CoreQuestionQuestionParsed,
component: string,
componentId: string | number,
siteId?: string,
): Promise<void> {
const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId);
const folderPath = CoreQuestion.getQuestionFolder(question.type, component, questionComponentId, siteId);
// Ignore errors, maybe the folder doesn't exist.
await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath));
}
/**
* Extract question behaviour submit buttons from the question's HTML and add them to "behaviourButtons" property.
* The buttons aren't deleted from the content because all the im-controls block will be removed afterwards.
*
* @param question Question to treat.
* @param selector Selector to search the buttons. By default, '.im-controls input[type="submit"]'.
*/
extractQbehaviourButtons(question: CoreQuestionQuestionParsed, selector?: string): void {
if (CoreQuestionDelegate.getPreventSubmitMessage(question)) {
// The question is not fully supported, don't extract the buttons.
return;
}
selector = selector || '.im-controls input[type="submit"]';
const element = CoreDomUtils.convertToElement(question.html);
// Search the buttons.
const buttons = <HTMLInputElement[]> Array.from(element.querySelectorAll(selector));
buttons.forEach((button) => {
this.addBehaviourButton(question, button);
});
}
/**
* Check if the question has CBM and, if so, extract the certainty options and add them to a new
* "behaviourCertaintyOptions" property.
* The value of the selected option is stored in question.behaviourCertaintySelected.
* We don't remove them from HTML because the whole im-controls block will be removed afterwards.
*
* @param question Question to treat.
* @return Wether the certainty is found.
*/
extractQbehaviourCBM(question: CoreQuestionQuestion): boolean {
const element = CoreDomUtils.convertToElement(question.html);
const labels = Array.from(element.querySelectorAll('.im-controls .certaintychoices label[for*="certainty"]'));
question.behaviourCertaintyOptions = [];
labels.forEach((label) => {
// Search the radio button inside this certainty and add its data to the options array.
const input = <HTMLInputElement> label.querySelector('input[type="radio"]');
if (input) {
question.behaviourCertaintyOptions!.push({
id: input.id,
name: input.name,
value: input.value,
text: CoreTextUtils.cleanTags(label.innerHTML),
disabled: input.disabled,
});
if (input.checked) {
question.behaviourCertaintySelected = input.value;
}
}
});
// If we have a certainty value stored in local we'll use that one.
if (question.localAnswers && typeof question.localAnswers['-certainty'] != 'undefined') {
question.behaviourCertaintySelected = question.localAnswers['-certainty'];
}
return labels.length > 0;
}
/**
* Check if the question has a redo button and, if so, add it to "behaviourButtons" property
* and remove it from the HTML.
*
* @param question Question to treat.
*/
extractQbehaviourRedoButton(question: CoreQuestionQuestion): void {
// Create a fake div element so we can search using querySelector.
const redoSelector = 'input[type="submit"][name*=redoslot], input[type="submit"][name*=tryagain]';
// Search redo button in feedback.
if (!this.searchBehaviourButton(question, 'html', '.outcome ' + redoSelector)) {
// Not found in question HTML.
if (question.feedbackHtml) {
// We extracted the feedback already, search it in there.
if (this.searchBehaviourButton(question, 'feedbackHtml', redoSelector)) {
// Button found, stop.
return;
}
}
// Button still not found. Now search in the info box if it exists.
if (question.infoHtml) {
this.searchBehaviourButton(question, 'infoHtml', redoSelector);
}
}
}
/**
* Check if the question contains a "seen" input.
* If so, add the name and value to a "behaviourSeenInput" property and remove the input.
*
* @param question Question to treat.
* @return Whether the seen input is found.
*/
extractQbehaviourSeenInput(question: CoreQuestionQuestion): boolean {
const element = CoreDomUtils.convertToElement(question.html);
// Search the "seen" input.
const seenInput = <HTMLInputElement> element.querySelector('input[type="hidden"][name*=seen]');
if (!seenInput) {
return false;
}
// Get the data and remove the input.
question.behaviourSeenInput = {
name: seenInput.name,
value: seenInput.value,
};
seenInput.parentElement?.removeChild(seenInput);
question.html = element.innerHTML;
return true;
}
/**
* Removes the comment from the question HTML code and adds it in a new "commentHtml" property.
*
* @param question Question.
*/
extractQuestionComment(question: CoreQuestionQuestion): void {
this.extractQuestionLastElementNotInContent(question, '.comment', 'commentHtml');
}
/**
* Removes the feedback from the question HTML code and adds it in a new "feedbackHtml" property.
*
* @param question Question.
*/
extractQuestionFeedback(question: CoreQuestionQuestion): void {
this.extractQuestionLastElementNotInContent(question, '.outcome', 'feedbackHtml');
}
/**
* Extracts the info box from a question and add it to an "infoHtml" property.
*
* @param question Question.
* @param selector Selector to search the element.
*/
extractQuestionInfoBox(question: CoreQuestionQuestion, selector: string): void {
this.extractQuestionLastElementNotInContent(question, selector, 'infoHtml');
}
/**
* Searches the last occurrence of a certain element and check it's not in the question contents.
* If found, removes it from the question HTML and adds it to a new property inside question.
*
* @param question Question.
* @param selector Selector to search the element.
* @param attrName Name of the attribute to store the HTML in.
*/
protected extractQuestionLastElementNotInContent(question: CoreQuestionQuestion, selector: string, attrName: string): void {
const element = CoreDomUtils.convertToElement(question.html);
const matches = <HTMLElement[]> Array.from(element.querySelectorAll(selector));
// Get the last element and check it's not in the question contents.
let last = matches.pop();
while (last) {
if (!CoreDomUtils.closest(last, '.formulation')) {
// Not in question contents. Add it to a separate attribute and remove it from the HTML.
question[attrName] = last.innerHTML;
last.parentElement?.removeChild(last);
question.html = element.innerHTML;
return;
}
// It's inside the question content, treat next element.
last = matches.pop();
}
}
/**
* Removes the scripts from a question's HTML and adds it in a new 'scriptsCode' property.
* It will also search for init_question functions of the question type and add the object to an 'initObjects' property.
*
* @param question Question.
* @param usageId Usage ID.
*/
extractQuestionScripts(question: CoreQuestionQuestion, usageId?: number): void {
question.scriptsCode = '';
question.initObjects = undefined;
question.amdArgs = undefined;
// Search the scripts.
const matches = question.html?.match(/<script[^>]*>[\s\S]*?<\/script>/mg);
if (!matches) {
// No scripts, stop.
return;
}
matches.forEach((match: string) => {
// Add the script to scriptsCode and remove it from html.
question.scriptsCode += match;
question.html = question.html.replace(match, '');
// Search init_question functions for this type.
const initMatches = match.match(new RegExp('M.qtype_' + question.type + '.init_question\\(.*?}\\);', 'mg'));
if (initMatches) {
let initMatch = initMatches.pop()!;
// Remove start and end of the match, we only want the object.
initMatch = initMatch.replace('M.qtype_' + question.type + '.init_question(', '');
initMatch = initMatch.substr(0, initMatch.length - 2);
// Try to convert it to an object and add it to the question.
question.initObjects = CoreTextUtils.parseJSON(initMatch, null);
}
const amdRegExp = new RegExp('require\\(\\[["\']qtype_' + question.type + '/question["\']\\],[^f]*' +
'function\\(amd\\)[^\\{]*\\{[^a]*amd\\.init\\((["\'](q|question-' + usageId + '-)' + question.slot +
'["\'].*?)\\);', 'm');
const amdMatch = match.match(amdRegExp);
if (amdMatch) {
// Try to convert the arguments to an array and add them to the question.
question.amdArgs = CoreTextUtils.parseJSON('[' + amdMatch[1] + ']', null);
}
});
}
/**
* Get the names of all the inputs inside an HTML code.
* This function will return an object where the keys are the input names. The values will always be true.
* This is in order to make this function compatible with other functions like CoreQuestionProvider.getBasicAnswers.
*
* @param html HTML code.
* @return Object where the keys are the names.
*/
getAllInputNamesFromHtml(html: string): Record<string, boolean> {
const element = CoreDomUtils.convertToElement('<form>' + html + '</form>');
const form = <HTMLFormElement> element.children[0];
const answers: Record<string, boolean> = {};
// Search all input elements.
Array.from(form.elements).forEach((element: HTMLInputElement) => {
const name = element.name || '';
// Ignore flag and submit inputs.
if (!name || name.match(/_:flagged$/) || element.type == 'submit' || element.tagName == 'BUTTON') {
return;
}
answers[CoreQuestion.removeQuestionPrefix(name)] = true;
});
return answers;
}
/**
* Retrieve the answers entered in a form.
* We don't use ngModel because it doesn't detect changes done by JavaScript and some questions might do that.
*
* @param form Form.
* @return Object with the answers.
*/
getAnswersFromForm(form: HTMLFormElement): CoreQuestionsAnswers {
if (!form || !form.elements) {
return {};
}
const answers: CoreQuestionsAnswers = {};
const elements = Array.from(form.elements);
elements.forEach((element: HTMLInputElement) => {
const name = element.name || element.getAttribute('ng-reflect-name') || '';
// Ignore flag and submit inputs.
if (!name || name.match(/_:flagged$/) || element.type == 'submit' || element.tagName == 'BUTTON') {
return;
}
// Get the value.
if (element.type == 'checkbox') {
answers[name] = !!element.checked;
} else if (element.type == 'radio') {
if (element.checked) {
answers[name] = element.value;
}
} else {
answers[name] = element.value;
}
});
return answers;
}
/**
* Given an HTML code with list of attachments, returns the list of attached files (filename and fileurl).
* Please take into account that this function will treat all the anchors in the HTML, you should provide
* an HTML containing only the attachments anchors.
*
* @param html HTML code to search in.
* @return Attachments.
*/
getQuestionAttachmentsFromHtml(html: string): CoreWSFile[] {
const element = CoreDomUtils.convertToElement(html);
// Remove the filemanager (area to attach files to a question).
CoreDomUtils.removeElement(element, 'div[id*=filemanager]');
// Search the anchors.
const anchors = Array.from(element.querySelectorAll('a'));
const attachments: CoreWSFile[] = [];
anchors.forEach((anchor) => {
let content = anchor.innerHTML;
// Check anchor is valid.
if (anchor.href && content) {
content = CoreTextUtils.cleanTags(content, true).trim();
attachments.push({
filename: content,
fileurl: anchor.href,
});
}
});
return attachments;
}
/**
* Get the sequence check from a question HTML.
*
* @param html Question's HTML.
* @return Object with the sequencecheck name and value.
*/
getQuestionSequenceCheckFromHtml(html: string): { name: string; value: string } | undefined {
if (!html) {
return;
}
// Search the input holding the sequencecheck.
const element = CoreDomUtils.convertToElement(html);
const input = <HTMLInputElement> element.querySelector('input[name*=sequencecheck]');
if (!input || input.name === undefined || input.value === undefined) {
return;
}
return {
name: input.name,
value: input.value,
};
}
/**
* Get the CSS class for a question based on its state.
*
* @param name Question's state name.
* @return State class.
*/
getQuestionStateClass(name: string): string {
const state = CoreQuestion.getState(name);
return state ? state.class : '';
}
/**
* Return the files of a certain response file area.
*
* @param question Question.
* @param areaName Name of the area, e.g. 'attachments'.
* @return List of files.
*/
getResponseFileAreaFiles(question: CoreQuestionQuestion, areaName: string): CoreWSFile[] {
if (!question.responsefileareas) {
return [];
}
const area = question.responsefileareas.find((area) => area.area == areaName);
return area?.files || [];
}
/**
* Get files stored for a question.
*
* @param question Question.
* @param component The component the question is related to.
* @param componentId Component ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the files.
*/
getStoredQuestionFiles(
question: CoreQuestionQuestion,
component: string,
componentId: string | number,
siteId?: string,
): Promise<(FileEntry | DirectoryEntry)[]> {
const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId);
const folderPath = CoreQuestion.getQuestionFolder(question.type, component, questionComponentId, siteId);
return CoreFile.getDirectoryContents(folderPath);
}
/**
* Get the validation error message from a question HTML if it's there.
*
* @param html Question's HTML.
* @return Validation error message if present.
*/
getValidationErrorFromHtml(html: string): string | undefined {
const element = CoreDomUtils.convertToElement(html);
return CoreDomUtils.getContentsOfElement(element, '.validationerror');
}
/**
* Check if some HTML contains draft file URLs for the current site.
*
* @param html Question's HTML.
* @return Whether it contains draft files URLs.
*/
hasDraftFileUrls(html: string): boolean {
let url = CoreSites.getCurrentSite()?.getURL();
if (!url) {
return false;
}
if (url.slice(-1) != '/') {
url = url += '/';
}
url += 'draftfile.php';
return html.indexOf(url) != -1;
}
/**
* Load local answers of a question.
*
* @param question Question.
* @param component Component.
* @param attemptId Attempt ID.
* @return Promise resolved when done.
*/
async loadLocalAnswers(question: CoreQuestionQuestion, component: string, attemptId: number): Promise<void> {
const answers = await CoreUtils.ignoreErrors(
CoreQuestion.getQuestionAnswers(component, attemptId, question.slot),
);
if (answers) {
question.localAnswers = CoreQuestion.convertAnswersArrayToObject(answers, true);
} else {
question.localAnswers = {};
}
}
/**
* For each input element found in the HTML, search if there's a local answer stored and
* override the HTML's value with the local one.
*
* @param question Question.
*/
loadLocalAnswersInHtml(question: CoreQuestionQuestion): void {
const element = CoreDomUtils.convertToElement('<form>' + question.html + '</form>');
const form = <HTMLFormElement> element.children[0];
// Search all input elements.
Array.from(form.elements).forEach((element: HTMLInputElement | HTMLButtonElement) => {
let name = element.name || '';
// Ignore flag and submit inputs.
if (!name || name.match(/_:flagged$/) || element.type == 'submit' || element.tagName == 'BUTTON' ||
!question.localAnswers) {
return;
}
// Search if there's a local answer.
name = CoreQuestion.removeQuestionPrefix(name);
if (question.localAnswers[name] === undefined) {
if (Object.keys(question.localAnswers).length && element.type == 'radio') {
// No answer stored, but there is a sequencecheck or similar. This means the user cleared his choice.
element.removeAttribute('checked');
}
return;
}
if (element.tagName == 'TEXTAREA') {
// Just put the answer inside the textarea.
element.innerHTML = question.localAnswers[name];
} else if (element.tagName == 'SELECT') {
// Search the selected option and select it.
const selected = element.querySelector('option[value="' + question.localAnswers[name] + '"]');
if (selected) {
selected.setAttribute('selected', 'selected');
}
} else if (element.type == 'radio') {
// Check if this radio is selected.
if (element.value == question.localAnswers[name]) {
element.setAttribute('checked', 'checked');
} else {
element.removeAttribute('checked');
}
} else if (element.type == 'checkbox') {
// Check if this checkbox is checked.
if (CoreUtils.isTrueOrOne(question.localAnswers[name])) {
element.setAttribute('checked', 'checked');
} else {
element.removeAttribute('checked');
}
} else {
// Put the answer in the value.
element.setAttribute('value', question.localAnswers[name]);
}
});
// Update the question HTML.
question.html = form.innerHTML;
}
/**
* Prefetch the files in a question HTML.
*
* @param question Question.
* @param component The component to link the files to. If not defined, question component.
* @param componentId An ID to use in conjunction with the component. If not defined, question ID.
* @param siteId Site ID. If not defined, current site.
* @param usageId Usage ID. Required in Moodle 3.7+.
* @return Promise resolved when all the files have been downloaded.
*/
async prefetchQuestionFiles(
question: CoreQuestionQuestion,
component?: string,
componentId?: string | number,
siteId?: string,
usageId?: number,
): Promise<void> {
if (!component) {
component = CoreQuestionProvider.COMPONENT;
componentId = question.number;
}
const files = CoreQuestionDelegate.getAdditionalDownloadableFiles(question, usageId) || [];
files.push(...CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(question.html));
const site = await CoreSites.getSite(siteId);
const treated: Record<string, boolean> = {};
await Promise.all(files.map(async (file) => {
const timemodified = file.timemodified || 0;
const fileUrl = CoreFileHelper.getFileUrl(file);
if (treated[fileUrl]) {
return;
}
treated[fileUrl] = true;
if (!site.canDownloadFiles() && CoreUrlUtils.isPluginFileUrl(fileUrl)) {
return;
}
if (fileUrl.indexOf('theme/image.php') > -1 && fileUrl.indexOf('flagged') > -1) {
// Ignore flag images.
return;
}
await CoreFilepool.addToQueueByUrl(site.getId(), fileUrl, component, componentId, timemodified);
}));
}
/**
* Prepare and return the answers.
*
* @param questions The list of questions.
* @param answers The input data.
* @param offline True if data should be saved in offline.
* @param component The component the question is related to.
* @param componentId Component ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with answers to send to server.
*/
async prepareAnswers(
questions: CoreQuestionQuestion[],
answers: CoreQuestionsAnswers,
offline: boolean,
component: string,
componentId: string | number,
siteId?: string,
): Promise<CoreQuestionsAnswers> {
await CoreUtils.allPromises(questions.map(async (question) => {
await CoreQuestionDelegate.prepareAnswersForQuestion(
question,
answers,
offline,
component,
componentId,
siteId,
);
}));
return answers;
}
/**
* Replace Moodle's correct/incorrect classes with the Mobile ones.
*
* @param element DOM element.
*/
replaceCorrectnessClasses(element: HTMLElement): void {
CoreDomUtils.replaceClassesInElement(element, {
correct: 'core-question-answer-correct',
incorrect: 'core-question-answer-incorrect',
});
}
/**
* Replace Moodle's feedback classes with the Mobile ones.
*
* @param element DOM element.
*/
replaceFeedbackClasses(element: HTMLElement): void {
CoreDomUtils.replaceClassesInElement(element, {
outcome: 'core-question-feedback-container core-question-feedback-padding',
specificfeedback: 'core-question-feedback-container core-question-feedback-inline',
});
}
/**
* Search a behaviour button in a certain question property containing HTML.
*
* @param question Question.
* @param htmlProperty The name of the property containing the HTML to search.
* @param selector The selector to find the button.
* @return Whether the button is found.
*/
protected searchBehaviourButton(question: CoreQuestionQuestion, htmlProperty: string, selector: string): boolean {
const element = CoreDomUtils.convertToElement(question[htmlProperty]);
const button = <HTMLInputElement> element.querySelector(selector);
if (!button) {
return false;
}
// Add a behaviour button to the question's "behaviourButtons" property.
this.addBehaviourButton(question, button);
// Remove the button from the HTML.
button.parentElement?.removeChild(button);
// Update the question's html.
question[htmlProperty] = element.innerHTML;
return true;
}
/**
* Convenience function to show a parsing error and abort.
*
* @param onAbort If supplied, will emit an event.
* @param error Error to show.
*/
showComponentError(onAbort: EventEmitter<void>, error?: string): void {
// Prevent consecutive errors.
const now = Date.now();
if (now - this.lastErrorShown > 500) {
this.lastErrorShown = now;
CoreDomUtils.showErrorModalDefault(error || '', 'addon.mod_quiz.errorparsequestions', true);
}
onAbort?.emit();
}
/**
* Treat correctness icons, replacing them with local icons and setting click events to show the feedback if needed.
*
* @param element DOM element.
*/
treatCorrectnessIcons(element: HTMLElement): void {
const icons = <HTMLElement[]> Array.from(element.querySelectorAll('img.icon, img.questioncorrectnessicon, i.icon'));
icons.forEach((icon) => {
let correct = false;
if ('src' in icon) {
if ((icon as HTMLImageElement).src.indexOf('correct') >= 0) {
correct = true;
} else if ((icon as HTMLImageElement).src.indexOf('incorrect') < 0 ) {
return;
}
} else {
const classList = icon.classList.toString();
if (classList.indexOf('fa-check') >= 0) {
correct = true;
} else if (classList.indexOf('fa-remove') < 0) {
return;
}
}
// Replace the icon with the font version.
const newIcon: HTMLElement = document.createElement('ion-icon');
if (correct) {
newIcon.setAttribute('name', 'fas-check');
newIcon.setAttribute('src', 'assets/fonts/font-awesome/solid/check.svg');
newIcon.className = 'core-correct-icon ion-color ion-color-success questioncorrectnessicon';
} else {
newIcon.setAttribute('name', 'fas-times');
newIcon.setAttribute('src', 'assets/fonts/font-awesome/solid/times.svg');
newIcon.className = 'core-correct-icon ion-color ion-color-danger questioncorrectnessicon';
}
newIcon.title = icon.title;
newIcon.setAttribute('aria-label', icon.title);
icon.parentNode?.replaceChild(newIcon, icon);
});
const spans = Array.from(element.querySelectorAll('.feedbackspan.accesshide'));
spans.forEach((span) => {
// Search if there's a hidden feedback for this element.
const icon = <HTMLElement> span.previousSibling;
if (!icon || !icon.classList.contains('icon') && !icon.classList.contains('questioncorrectnessicon')) {
return;
}
icon.classList.add('questioncorrectnessicon');
if (span.innerHTML) {
// There's a hidden feedback. Mark the icon as tappable.
// The click listener is only added if treatCorrectnessIconsClicks is called.
icon.setAttribute('tappable', '');
}
});
}
/**
* Add click listeners to all tappable correctness icons.
*
* @param element DOM element.
* @param component The component to use when viewing the feedback.
* @param componentId An ID to use in conjunction with the component.
* @param contextLevel The context level.
* @param contextInstanceId Instance ID related to the context.
* @param courseId Course ID the text belongs to. It can be used to improve performance with filters.
*/
treatCorrectnessIconsClicks(
element: HTMLElement,
component?: string,
componentId?: number,
contextLevel?: string,
contextInstanceId?: number,
courseId?: number,
): void {
const icons = <HTMLElement[]> Array.from(element.querySelectorAll('ion-icon.questioncorrectnessicon[tappable]'));
const title = Translate.instant('core.question.feedback');
icons.forEach((icon) => {
// Search the feedback for the icon.
const span = <HTMLElement | undefined> icon.parentElement?.querySelector('.feedbackspan.accesshide');
if (!span) {
return;
}
// There's a hidden feedback, show it when the icon is clicked.
icon.addEventListener('click', () => {
CoreTextUtils.viewText(title, span.innerHTML, {
component: component,
componentId: componentId,
filter: true,
contextLevel: contextLevel,
instanceId: contextInstanceId,
courseId: courseId,
});
});
});
}
}
export const CoreQuestionHelper = makeSingleton(CoreQuestionHelperProvider);
/**
* Question with calculated data.
*/
export type CoreQuestionQuestion = CoreQuestionQuestionParsed & {
localAnswers?: Record<string, string>;
commentHtml?: string;
feedbackHtml?: string;
infoHtml?: string;
behaviourButtons?: CoreQuestionBehaviourButton[];
behaviourCertaintyOptions?: CoreQuestionBehaviourCertaintyOption[];
behaviourCertaintySelected?: string;
behaviourSeenInput?: { name: string; value: string };
scriptsCode?: string;
initObjects?: Record<string, unknown> | null;
amdArgs?: unknown[] | null;
};
/**
* Question behaviour button.
*/
export type CoreQuestionBehaviourButton = {
id: string;
name: string;
value: string;
disabled: boolean;
};
/**
* Question behaviour certainty option.
*/
export type CoreQuestionBehaviourCertaintyOption = CoreQuestionBehaviourButton & {
text: string;
}; | the_stack |
import {
Cell,
CellCollector,
HexString,
Indexer,
Script,
Tip,
Output,
utils,
Block,
} from "@ckb-lumos/base";
import { validators } from "ckb-js-toolkit";
import { RPC } from "@ckb-lumos/rpc";
import { request, requestBatch } from "./services";
import { CKBCellCollector } from "./collector";
import { EventEmitter } from "events";
import {
GetTransactionRPCResult,
CKBIndexerQueryOptions,
GetCellsResults,
GetLiveCellsResult,
GetTransactionsResult,
GetTransactionsResults,
IndexerEmitter,
Order,
OutputToVerify,
SearchKey,
SearchKeyFilter,
Terminator,
OtherQueryOptions,
} from "./type";
const DefaultTerminator: Terminator = () => {
return { stop: false, push: true };
};
function defaultLogger(level: string, message: string) {
console.log(`[${level}] ${message}`);
}
/** CkbIndexer.collector will not get cell with block_hash by default, please use OtherQueryOptions.withBlockHash and OtherQueryOptions.CKBRpcUrl to get block_hash if you need. */
export class CkbIndexer implements Indexer {
uri: string;
medianTimeEmitters: EventEmitter[] = [];
emitters: IndexerEmitter[] = [];
isSubscribeRunning: boolean = false;
constructor(public ckbRpcUrl: string, public ckbIndexerUrl: string) {
this.uri = ckbRpcUrl;
this.ckbIndexerUrl = ckbIndexerUrl;
}
private getCkbRpc(): RPC {
return new RPC(this.ckbRpcUrl);
}
async tip(): Promise<Tip> {
const res = await request(this.ckbIndexerUrl, "get_tip");
return res as Tip;
}
asyncSleep(timeout: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, timeout));
}
async waitForSync(blockDifference = 0): Promise<void> {
const rpcTipNumber = parseInt(
(await this.getCkbRpc().get_tip_header()).number,
16
);
while (true) {
const indexerTipNumber = parseInt((await this.tip()).block_number, 16);
if (indexerTipNumber + blockDifference >= rpcTipNumber) {
return;
}
await this.asyncSleep(1000);
}
}
/** collector cells without block_hash by default.if you need block_hash, please add OtherQueryOptions.withBlockHash and OtherQueryOptions.ckbRpcUrl.
* don't use OtherQueryOption if you don't need block_hash,cause it will slowly your collect.
*/
collector(
queries: CKBIndexerQueryOptions,
otherQueryOptions?: OtherQueryOptions
): CellCollector {
return new CKBCellCollector(this, queries, otherQueryOptions);
}
private async request(
method: string,
params?: any,
ckbIndexerUrl: string = this.ckbIndexerUrl
): Promise<any> {
return request(ckbIndexerUrl, method, params);
}
public async getCells(
searchKey: SearchKey,
terminator: Terminator = DefaultTerminator,
searchKeyFilter: SearchKeyFilter = {}
): Promise<GetCellsResults> {
const infos: Cell[] = [];
let cursor: string | undefined = searchKeyFilter.lastCursor;
let sizeLimit = searchKeyFilter.sizeLimit || 100;
let order = searchKeyFilter.order || Order.asc;
const index = 0;
while (true) {
let params = [searchKey, order, `0x${sizeLimit.toString(16)}`, cursor];
const res: GetLiveCellsResult = await this.request("get_cells", params);
const liveCells = res.objects;
cursor = res.last_cursor;
for (const liveCell of liveCells) {
const cell: Cell = {
cell_output: liveCell.output,
data: liveCell.output_data,
out_point: liveCell.out_point,
block_number: liveCell.block_number,
};
const { stop, push } = terminator(index, cell);
if (push) {
infos.push(cell);
}
if (stop) {
return {
objects: infos,
lastCursor: cursor,
};
}
}
if (liveCells.length < sizeLimit) {
break;
}
}
return {
objects: infos,
lastCursor: cursor,
};
}
public async getTransactions(
searchKey: SearchKey,
searchKeyFilter: SearchKeyFilter = {}
): Promise<GetTransactionsResults> {
let infos: GetTransactionsResult[] = [];
let cursor: string | undefined = searchKeyFilter.lastCursor;
let sizeLimit = searchKeyFilter.sizeLimit || 100;
let order = searchKeyFilter.order || Order.asc;
for (;;) {
const params = [searchKey, order, `0x${sizeLimit.toString(16)}`, cursor];
const res = await this.request("get_transactions", params);
const txs = res.objects;
cursor = res.last_cursor as string;
infos = infos.concat(txs);
if (txs.length < sizeLimit) {
break;
}
}
return {
objects: infos,
lastCursor: cursor,
};
}
running(): boolean {
return true;
}
start(): void {
defaultLogger(
"warn",
"deprecated: no need to start the ckb-indexer manually"
);
}
startForever(): void {
defaultLogger(
"warn",
"deprecated: no need to startForever the ckb-indexer manually"
);
}
stop(): void {
defaultLogger(
"warn",
"deprecated: no need to stop the ckb-indexer manually"
);
}
subscribe(queries: CKBIndexerQueryOptions): EventEmitter {
this.isSubscribeRunning = true;
this.scheduleLoop();
if (queries.lock && queries.type) {
throw new Error(
"The notification machanism only supports you subscribing for one script once so far!"
);
}
if (queries.toBlock !== null || queries.skip !== null) {
defaultLogger(
"warn",
"The passing fields such as toBlock and skip are ignored in subscribe() method."
);
}
let emitter = new IndexerEmitter();
emitter.argsLen = queries.argsLen;
emitter.outputData = queries.data;
if (queries.fromBlock) {
utils.assertHexadecimal("fromBlock", queries.fromBlock);
}
emitter.fromBlock = !queries.fromBlock ? BigInt(0) : BigInt(queries.fromBlock);
if (queries.lock) {
validators.ValidateScript(queries.lock);
emitter.lock = queries.lock as Script;
} else if (queries.type && queries.type !== "empty") {
validators.ValidateScript(queries.type);
emitter.type = queries.type as Script;
} else {
throw new Error("Either lock or type script must be provided!");
}
this.emitters.push(emitter);
return emitter;
}
private loop() {
if (!this.isSubscribeRunning) {
return;
}
this.poll()
.then((timeout) => {
this.scheduleLoop(timeout);
})
.catch((e) => {
defaultLogger(
"error",
`Error occurs: ${e} ${e.stack}, stopping indexer!`
);
this.isSubscribeRunning = false;
});
}
private scheduleLoop(timeout = 1) {
setTimeout(() => {
this.loop();
}, timeout);
}
private async poll() {
let timeout = 1;
const tip = await this.tip();
const { block_number, block_hash } = tip;
if (block_number === "0x0") {
const block: Block = await this.request(
"get_block_by_number",
[block_number],
this.ckbRpcUrl
);
await this.publishAppendBlockEvents(block);
}
const nextBlockNumber = BigInt(block_number) + BigInt(1);
const block = await this.request(
"get_block_by_number",
[`0x${nextBlockNumber.toString(16)}`],
this.ckbRpcUrl
);
if (block) {
if (block.header.parent_hash === block_hash) {
await this.publishAppendBlockEvents(block);
} else {
const block: Block = await this.request(
"get_block_by_number",
[block_number],
this.ckbRpcUrl
);
await this.publishAppendBlockEvents(block);
}
} else {
const block = await this.request(
"get_block_by_number",
[block_number],
this.ckbRpcUrl
);
await this.publishAppendBlockEvents(block);
timeout = 3 * 1000;
}
return timeout;
}
private async publishAppendBlockEvents(block: Block) {
for (const [txIndex, tx] of block.transactions.entries()) {
const blockNumber = block.header.number;
// publish changed events if subscribed script exists in previous output cells , skip the cellbase.
if (txIndex > 0) {
const requestData = tx.inputs.map((input, index) => {
return {
id: index,
jsonrpc: "2.0",
method: "get_transaction",
params: [input.previous_output.tx_hash],
};
});
// batch request by block
const transactionResponse: OutputToVerify[] = await requestBatch(
this.ckbRpcUrl,
requestData
).then((response: GetTransactionRPCResult[]) => {
return response.map(
(item: GetTransactionRPCResult, index: number) => {
const cellIndex = tx.inputs[index].previous_output.index;
const outputCell =
item.result.transaction.outputs[parseInt(cellIndex)];
const outputData =
item.result.transaction.outputs_data[parseInt(cellIndex)];
return { output: outputCell, outputData } as OutputToVerify;
}
);
});
transactionResponse.forEach(({ output, outputData }) => {
this.filterEvents(output, blockNumber, outputData);
});
}
// publish changed events if subscribed script exists in output cells.
for (const [outputIndex, output] of tx.outputs.entries()) {
const outputData = tx.outputs_data[outputIndex];
this.filterEvents(output, blockNumber, outputData);
}
}
await this.emitMedianTimeEvents();
}
private filterEvents(
output: Output,
blockNumber: string,
outputData: HexString
) {
for (const emitter of this.emitters) {
if (
emitter.lock !== undefined &&
this.checkFilterOptions(
emitter,
blockNumber,
outputData,
emitter.lock,
output.lock
)
) {
emitter.emit("changed");
}
}
if (output.type !== null) {
for (const emitter of this.emitters) {
if (
emitter.type !== undefined &&
this.checkFilterOptions(
emitter,
blockNumber,
outputData,
emitter.type,
output.type
)
) {
emitter.emit("changed");
}
}
}
}
private checkFilterOptions(
emitter: IndexerEmitter,
blockNumber: string,
outputData: string,
emitterScript: Script,
script: Script | undefined
) {
const checkBlockNumber = emitter.fromBlock
? emitter.fromBlock <= BigInt(blockNumber)
: true;
const checkOutputData =
emitter.outputData === "any" || !emitter.outputData
? true
: emitter.outputData === outputData;
const checkScript = !script
? true
: emitterScript.code_hash === script.code_hash &&
emitterScript.hash_type === script.hash_type &&
this.checkArgs(emitter.argsLen, emitterScript.args, script.args);
return checkBlockNumber && checkOutputData && checkScript;
}
private checkArgs(
argsLen: number | "any" | undefined,
emitterArgs: HexString,
args: HexString
) {
if (argsLen === -1 || (!argsLen && argsLen !== 0)) {
return emitterArgs === args;
} else if (typeof argsLen === "number" && args.length === argsLen * 2 + 2) {
return args.substring(0, emitterArgs.length) === emitterArgs;
} else if (argsLen === "any") {
return args.substring(0, emitterArgs.length) === emitterArgs;
} else {
return false;
}
}
private async emitMedianTimeEvents() {
if (this.medianTimeEmitters.length === 0) {
return;
}
const info = await request(this.ckbRpcUrl, "get_blockchain_info");
const medianTime = info.median_time;
for (const medianTimeEmitter of this.medianTimeEmitters) {
medianTimeEmitter.emit("changed", medianTime);
}
}
subscribeMedianTime(): EventEmitter {
this.isSubscribeRunning = true;
this.scheduleLoop();
const medianTimeEmitter = new EventEmitter();
this.medianTimeEmitters.push(medianTimeEmitter);
return medianTimeEmitter;
}
} | the_stack |
import { createElement, isNullOrUndefined, extend, compile, getValue, setValue } from '@syncfusion/ej2-base';
import { formatUnit, addClass } from '@syncfusion/ej2-base';
import { Gantt } from '../base/gantt';
import { isScheduledTask } from '../base/utils';
import { DataManager, Query } from '@syncfusion/ej2-data';
import * as cls from '../base/css-constants';
import { DateProcessor } from '../base/date-processor';
import { IGanttData, IQueryTaskbarInfoEventArgs, IParent, IIndicator, ITaskData, ITaskSegment } from '../base/interface';
import { Row, Column } from '@syncfusion/ej2-grids';
import { TaskFieldsModel } from '../models/models';
import { CObject } from '../base/enum';
/**
* To render the chart rows in Gantt
*/
export class ChartRows extends DateProcessor {
public ganttChartTableBody: Element;
public taskTable: HTMLElement;
protected parent: Gantt;
public taskBarHeight: number = 0;
public milestoneHeight: number = 0;
private milesStoneRadius: number = 0;
private baselineTop: number = 0;
public baselineHeight: number = 8;
private baselineColor: string;
private parentTaskbarTemplateFunction: Function;
private leftTaskLabelTemplateFunction: Function;
private rightTaskLabelTemplateFunction: Function;
private taskLabelTemplateFunction: Function;
private childTaskbarTemplateFunction: Function;
private milestoneTemplateFunction: Function;
private templateData: IGanttData;
private touchLeftConnectorpoint: string = '';
private touchRightConnectorpoint: string = '';
public connectorPointWidth: number;
private connectorPointMargin: number;
public taskBarMarginTop: number;
public milestoneMarginTop: number;
private dropSplit: boolean = false;
private refreshedTr: Element[] = [];
private refreshedData: IGanttData[] = [];
private isUpdated: boolean = true;
constructor(ganttObj?: Gantt) {
super(ganttObj);
this.parent = ganttObj;
this.initPublicProp();
this.addEventListener();
}
/**
* To initialize the public property.
*
* @returns {void}
* @private
*/
private initPublicProp(): void {
this.ganttChartTableBody = null;
}
private addEventListener(): void {
this.parent.on('renderPanels', this.createChartTable, this);
this.parent.on('dataReady', this.initiateTemplates, this);
this.parent.on('destroy', this.destroy, this);
}
public refreshChartByTimeline(): void {
this.taskTable.style.width = formatUnit(this.parent.timelineModule.totalTimelineWidth);
const prevDate: Date = getValue('prevProjectStartDate', this.parent.dataOperation);
let isUpdated: boolean = false;
if (prevDate) {
isUpdated = prevDate.getTime() === this.parent.cloneProjectStartDate.getTime();
}
this.isUpdated = this.parent.isFromOnPropertyChange && isUpdated &&
getValue('mutableData', this.parent.treeGrid.grid.contentModule) ? true : false;
this.refreshGanttRows();
this.isUpdated = true;
}
/**
* To render chart rows.
*
* @returns {void}
* @private
*/
private createChartTable(): void {
this.taskTable = createElement('table', {
className: cls.taskTable + ' ' + cls.zeroSpacing, id: 'GanttTaskTable' + this.parent.element.id,
styles: 'z-index: 2;position: absolute;width:' + this.parent.timelineModule.totalTimelineWidth + 'px;',
attrs: { cellspacing: '0.25px' }
});
const colgroup: Element = createElement('colgroup');
const column: Element = createElement('col', { styles: 'width:' + this.parent.timelineModule.totalTimelineWidth + 'px;' });
colgroup.appendChild(column);
this.taskTable.appendChild(colgroup);
this.ganttChartTableBody = createElement('tbody', {
id: this.parent.element.id + 'GanttTaskTableBody'
});
this.taskTable.appendChild(this.ganttChartTableBody);
this.parent.ganttChartModule.chartBodyContent.appendChild(this.taskTable);
}
public initiateTemplates(): void {
this.taskTable.style.width = formatUnit(this.parent.timelineModule.totalTimelineWidth);
this.initChartHelperPrivateVariable();
this.initializeChartTemplate();
}
/**
* To render chart rows.
*
* @returns {void}
* @private
*/
public renderChartRows(): void {
this.createTaskbarTemplate();
this.parent.isGanttChartRendered = true;
}
/**
* To get gantt Indicator.
*
* @param {IIndicator} indicator .
* @returns {NodeList} .
* @private
*/
private getIndicatorNode(indicator: IIndicator): NodeList {
const templateString: string = '<label class="' + cls.label + ' ' + cls.taskIndicatorDiv + '" role="LabelIndicator" style="line-height:'
+ (this.parent.rowHeight) + 'px;' +
'left:' + this.getIndicatorleft(indicator.date) + 'px;"><i class="' + indicator.iconClass + '"></i> </label>';
return this.createDivElement(templateString);
}
/**
* To get gantt Indicator.
*
* @param {Date | string} date .
* @returns {number} .
* @private
*/
public getIndicatorleft(date: Date | string): number {
date = this.parent.dateValidationModule.getDateFromFormat(date);
const left: number = this.parent.dataOperation.getTaskLeft(date, false);
return left;
}
/**
* To get child taskbar Node.
*
* @param {number} i .
* @param {NodeList} rootElement .
* @returns {NodeList} .
* @private
*/
private getChildTaskbarNode(i: number, rootElement?: NodeList): NodeList {
let childTaskbarNode: NodeList = null;
const data: IGanttData = this.templateData;
if (this.childTaskbarTemplateFunction) {
childTaskbarNode = this.childTaskbarTemplateFunction(
extend({ index: i }, data), this.parent, 'TaskbarTemplate',
this.getTemplateID('TaskbarTemplate'), false, undefined, rootElement[0], this.parent.treeGrid['root']);
} else {
let labelString: string = '';
let taskLabel: string = '';
let taskbarInnerDiv: NodeList;
let progressDiv: NodeList;
if (data.ganttProperties.startDate && data.ganttProperties.endDate
&& data.ganttProperties.duration) {
taskbarInnerDiv = this.createDivElement('<div class="' + cls.childTaskBarInnerDiv + ' ' + cls.traceChildTaskBar +
' ' + (data.ganttProperties.isAutoSchedule ? '' : cls.manualChildTaskBar) + '"' +
'style="width:' + data.ganttProperties.width + 'px;height:' +
(this.taskBarHeight) + 'px;"></div>');
progressDiv = this.createDivElement('<div class="' + cls.childProgressBarInnerDiv + ' ' +
cls.traceChildProgressBar + ' ' + (data.ganttProperties.isAutoSchedule ?
'' : cls.manualChildProgressBar) + '"' +
' style="border-style:' + (data.ganttProperties.progressWidth ? 'solid;' : 'none;') +
'width:' + data.ganttProperties.progressWidth + 'px;height:100%;' +
'border-top-right-radius:' + this.getBorderRadius(data.ganttProperties) + 'px;' +
'border-bottom-right-radius:' + this.getBorderRadius(data.ganttProperties) + 'px;">' +
'</div>');
}
let tempDiv: Element = createElement('div');
if (this.taskLabelTemplateFunction && !isNullOrUndefined(progressDiv) && progressDiv.length > 0) {
const taskLabelTemplateNode: NodeList = this.taskLabelTemplateFunction(
extend({ index: i }, data), this.parent, 'TaskLabelTemplate',
this.getTemplateID('TaskLabelTemplate'), false, undefined, progressDiv[0]);
if (taskLabelTemplateNode && taskLabelTemplateNode.length > 0) {
tempDiv.appendChild(taskLabelTemplateNode[0]);
labelString = tempDiv.innerHTML;
}
} else {
labelString = this.getTaskLabel(this.parent.labelSettings.taskLabel);
labelString = labelString === 'isCustomTemplate' ? this.parent.labelSettings.taskLabel : labelString;
}
if (labelString.indexOf('null') === -1) {
if (this.getTaskLabel(this.parent.labelSettings.taskLabel) === 'isCustomTemplate' && !this.isTemplate(this.parent.labelSettings.taskLabel)) {
labelString = '';
}
if (isNaN(parseInt(labelString))) {
taskLabel = '<span class="' + cls.taskLabel + '" style="line-height:' +
(this.taskBarHeight - 1) + 'px; text-align: left;' +
'display:' + 'inline-block;' +
'width:' + (data.ganttProperties.width - 10) + 'px; height:' +
this.taskBarHeight + 'px;">' + labelString + '</span>';
} else {
taskLabel = '<span class="' + cls.taskLabel + '" style="line-height:' +
(this.taskBarHeight - 1) + 'px;' + (this.parent.viewType === 'ResourceView' ? 'text-align: left;' : '') +
+ (this.parent.viewType === 'ResourceView' ? 'display:inline-flex;' : '') +
+ (this.parent.viewType === 'ResourceView' ? (data.ganttProperties.width - 10) : '') + 'px; height:' +
this.taskBarHeight + 'px;">' + labelString + '</span>';
}
}
const template: string = !isNullOrUndefined(data.ganttProperties.segments) && data.ganttProperties.segments.length > 0 ?
this.splitTaskbar(data, labelString) : (data.ganttProperties.startDate && data.ganttProperties.endDate
&& data.ganttProperties.duration) ? (taskLabel) :
(data.ganttProperties.startDate && !data.ganttProperties.endDate && !data.ganttProperties.duration) ? (
'<div class="' + cls.childProgressBarInnerDiv + ' ' + cls.traceChildTaskBar + ' ' +
cls.unscheduledTaskbarLeft + ' ' + (data.ganttProperties.isAutoSchedule ?
'' : cls.manualChildTaskBar) + '"' +
'style="left:' + data.ganttProperties.left + 'px; height:' + this.taskBarHeight + 'px;"></div>') :
(data.ganttProperties.endDate && !data.ganttProperties.startDate && !data.ganttProperties.duration) ?
('<div class="' + cls.childProgressBarInnerDiv + ' ' + cls.traceChildTaskBar + ' ' +
cls.unscheduledTaskbarRight + ' ' + (data.ganttProperties.isAutoSchedule ?
'' : cls.manualChildTaskBar) + '"' +
'style="left:' + data.ganttProperties.left + 'px; height:' + this.taskBarHeight + 'px;"></div>') :
(data.ganttProperties.duration && !data.ganttProperties.startDate && !data.ganttProperties.endDate) ?
('<div class="' + cls.childProgressBarInnerDiv + ' ' + cls.traceChildTaskBar + ' ' +
cls.unscheduledTaskbar + ' ' + (data.ganttProperties.isAutoSchedule ?
'' : cls.manualChildTaskBar) + '"' +
'style="left:' + data.ganttProperties.left + 'px; width:' + data.ganttProperties.width + 'px;' +
' height:' + this.taskBarHeight + 'px;"></div>') : '';
if (data.ganttProperties.startDate && data.ganttProperties.endDate && data.ganttProperties.duration &&
(isNullOrUndefined(data.ganttProperties.segments) || (!isNullOrUndefined(data.ganttProperties.segments) &&
data.ganttProperties.segments.length === 0))) {
if (template !== '' && !isNullOrUndefined(progressDiv) && progressDiv.length > 0) {
let templateElement: Node = this.createDivElement(template)[0];
let childLabel: string = this.parent.labelSettings.taskLabel;
if(childLabel && childLabel['elementRef'])
templateElement.appendChild(tempDiv);
progressDiv[0].appendChild(templateElement);
if ((progressDiv[0] as Element).querySelectorAll('.e-task-label')[0].textContent !== '' &&
!this.isTemplate(childLabel) &&
(progressDiv[0] as Element).querySelectorAll('.e-task-label')[0].children[0])
(progressDiv[0] as Element).querySelectorAll('.e-task-label')[0].children[0].remove();
if ((progressDiv[0] as Element).querySelectorAll('.e-task-label')[0].textContent == '' &&
childLabel && !childLabel['elementRef'] && tempDiv.innerHTML != '')
(progressDiv[0] as Element).querySelectorAll('.e-task-label')[0].textContent = childLabel;
}
if (!isNullOrUndefined(taskbarInnerDiv) && taskbarInnerDiv.length > 0) {
taskbarInnerDiv[0].appendChild([].slice.call(progressDiv)[0]);
}
childTaskbarNode = taskbarInnerDiv;
} else {
childTaskbarNode = this.createDivElement(template);
}
}
return childTaskbarNode;
}
private splitTaskbar(data: IGanttData, labelString: string): string {
let splitTasks: string = '';
for (let i: number = 0; i < data.ganttProperties.segments.length; i++) {
const segment: ITaskSegment = data.ganttProperties.segments[i];
const segmentPosition: string = (i === 0) ? 'e-segment-first' : (i === data.ganttProperties.segments.length - 1)
? 'e-segment-last' : 'e-segment-inprogress';
splitTasks += (
//split taskbar
'<div class="' + cls.childTaskBarInnerDiv + ' ' + segmentPosition + ' ' + cls.traceChildTaskBar + ' ' +
' e-segmented-taskbar' +
'"style="width:' + segment.width + 'px;position: absolute; left:' + segment.left + 'px;height:' +
(this.taskBarHeight) + 'px; overflow: initial;" data-segment-index = "' + i + '" aria-label = "' +
this.generateSpiltTaskAriaLabel(segment, data.ganttProperties) + '"> ' +
this.getSplitTaskbarLeftResizerNode() +
//split progress bar
'<div class="' + cls.childProgressBarInnerDiv + ' ' + cls.traceChildProgressBar + ' ' +
'" style="border-style:' + (segment.progressWidth ? 'solid;' : 'none;') +
'display:' + (segment.progressWidth >= 0 ? 'block;' : 'none;') +
'width:' + segment.progressWidth + 'px;height:100%;' +
'border-top-right-radius:' + this.getSplitTaskBorderRadius(segment) + 'px;' +
'border-bottom-right-radius:' + this.getSplitTaskBorderRadius(segment) + 'px;">' +
// progress label
'<span class="' + cls.taskLabel + '" style="line-height:' +
(this.taskBarHeight - 1) + 'px;display:' + (segment.showProgress ? 'inline;' : 'none;') +
'height:' + this.taskBarHeight + 'px;">' + labelString + '</span>' +
'</div>' +
this.getSplitTaskbarRightResizerNode(segment) +
(segment.showProgress ? this.getSplitProgressResizerNode(segment) : '') +
'</div></div>');
}
return splitTasks;
}
private getSplitTaskbarLeftResizerNode(): string {
const lResizerLeft: number = -(this.parent.isAdaptive ? 12 : 2);
const template: string = '<div class="' + cls.taskBarLeftResizer + ' ' + cls.icon + '"' +
' style="left:' + lResizerLeft + 'px;height:' + (this.taskBarHeight) + 'px;"></div>';
return template;
}
private getSplitTaskbarRightResizerNode(segment: ITaskSegment): string {
const rResizerLeft: number = this.parent.isAdaptive ? -2 : -10;
const template: string = '<div class="' + cls.taskBarRightResizer + ' ' + cls.icon + '"' +
' style="left:' + (segment.width + rResizerLeft) + 'px;' +
'height:' + (this.taskBarHeight) + 'px;"></div>';
return template;
}
private getSplitProgressResizerNode(segment: ITaskSegment): string {
const template: string = '<div class="' + cls.childProgressResizer + '"' +
' style="left:' + (segment.progressWidth - 6) + 'px;margin-top:' +
(this.taskBarHeight - 4) + 'px;"><div class="' + cls.progressBarHandler + '"' +
'><div class="' + cls.progressHandlerElement + '"></div>' +
'<div class="' + cls.progressBarHandlerAfter + '"></div></div>';
return template;
}
public getSegmentIndex(splitStartDate: Date, record: IGanttData): number {
let segmentIndex: number = -1;
const ganttProp: ITaskData = record.ganttProperties;
const segments: ITaskSegment[] = ganttProp.segments;
if (!isNullOrUndefined(segments)) {
segments.sort((a: ITaskSegment, b: ITaskSegment) => {
return a.startDate.getTime() - b.startDate.getTime();
});
const length: number = segments.length;
for (let i: number = 0; i < length; i++) {
const segment: ITaskSegment = segments[i];
// To find if user tend to split the start date of a main taskbar
// purpose of this to restrict the split action
if (splitStartDate.getTime() === ganttProp.startDate.getTime()) {
this.dropSplit = true;
segmentIndex = 0;
// To find the if user tend to split the first date of already segmented task.
// purpose of this to move on day of a segment
} else if (splitStartDate.getTime() === segment.startDate.getTime()) {
this.dropSplit = true;
let sDate: Date = segment.startDate;
sDate.setDate(sDate.getDate() + 1);
sDate = segment.startDate = this.parent.dataOperation.checkStartDate(sDate, ganttProp, false);
segment.startDate = sDate;
let eDate: Date = segment.endDate;
eDate = this.parent.dataOperation.getEndDate(
sDate, segment.duration, ganttProp.durationUnit, ganttProp, false
);
segment.endDate = eDate;
if (i === segments.length - 1) {
this.parent.setRecordValue('endDate', eDate, ganttProp, true);
}
this.incrementSegments(segments, i, record);
segmentIndex = segment.segmentIndex;
// To find if the user tend to split the segment and find the segment index
} else {
segment.endDate = this.parent.dataOperation.getEndDate(
segment.startDate, segment.duration, ganttProp.durationUnit, ganttProp, false
);
if (splitStartDate.getTime() >= segment.startDate.getTime() && splitStartDate.getTime() <= segment.endDate.getTime()) {
segmentIndex = segment.segmentIndex;
}
}
this.parent.setRecordValue('segments', ganttProp.segments, ganttProp, true);
}
}
if (segmentIndex === -1) {
this.dropSplit = true;
}
return segmentIndex;
}
public mergeTask(taskId: number | string, segmentIndexes: { firstSegmentIndex: number, secondSegmentIndex: number }[]): void {
const mergeArrayLength: number = segmentIndexes.length;
const taskFields: TaskFieldsModel = this.parent.taskFields;
const mergeData: IGanttData = this.parent.flatData.filter((x: IGanttData): IGanttData => {
if (x[taskFields.id] === taskId) {
return x;
} else {
return null;
}
})[0];
const segments: ITaskSegment[] = mergeData.ganttProperties.segments;
segmentIndexes = segmentIndexes.sort((a: { firstSegmentIndex: number, secondSegmentIndex: number },
b: { firstSegmentIndex: number, secondSegmentIndex: number }): number => {
return b.firstSegmentIndex - a.firstSegmentIndex;
});
for (let arrayLength: number = 0; arrayLength < mergeArrayLength; arrayLength++) {
const firstSegment: ITaskSegment = segments[segmentIndexes[arrayLength].firstSegmentIndex];
const secondSegment: ITaskSegment = segments[segmentIndexes[arrayLength].secondSegmentIndex];
const duration: number = firstSegment.duration + secondSegment.duration;
const endDate: Date = this.parent.dataOperation.getEndDate(
firstSegment.startDate, duration, mergeData.ganttProperties.durationUnit, mergeData.ganttProperties, false
);
const segment: ITaskSegment = {
startDate: firstSegment.startDate,
endDate: endDate,
duration: duration
};
const insertIndex: number = segmentIndexes[arrayLength].firstSegmentIndex;
segments.splice(insertIndex, 2, segment);
this.parent.setRecordValue('segments', segments, mergeData.ganttProperties, true);
this.parent.dataOperation.updateMappingData(mergeData, 'segments');
if (segments.length === 1) {
this.parent.setRecordValue('endDate', endDate, mergeData.ganttProperties, true);
this.parent.setRecordValue('segments', null, mergeData.ganttProperties, true);
this.parent.dataOperation.updateMappingData(mergeData, 'segments');
} else if (mergeData.ganttProperties.endDate !== segments[segments.length - 1].endDate) {
this.parent.setRecordValue('endDate', segments[segments.length - 1].endDate, mergeData.ganttProperties, true);
}
}
this.refreshChartAfterSegment(mergeData, 'mergeSegment');
}
private refreshChartAfterSegment(data: IGanttData, requestType: string): void {
this.parent.setRecordValue('segments', this.parent.dataOperation.setSegmentsInfo(data, false), data.ganttProperties, true);
this.parent.dataOperation.updateMappingData(data, 'segments');
this.parent.dataOperation.updateWidthLeft(data);
if (this.parent.predecessorModule && this.parent.taskFields.dependency) {
this.parent.predecessorModule.updatedRecordsDateByPredecessor();
this.parent.connectorLineModule.removePreviousConnectorLines(this.parent.flatData);
this.parent.connectorLineEditModule.refreshEditedRecordConnectorLine(this.parent.flatData);
if (data.parentItem && this.parent.getParentTask(data.parentItem).ganttProperties.isAutoSchedule
&& this.parent.isInPredecessorValidation) {
this.parent.dataOperation.updateParentItems(data.parentItem);
}
this.refreshRecords(this.parent.currentViewData);
} else {
this.refreshRow(this.parent.currentViewData.indexOf(data));
}
const tr: Element = this.ganttChartTableBody.querySelectorAll('tr')[this.parent.currentViewData.indexOf(data)];
const args: CObject = {
requestType: requestType,
rowData: data
};
this.triggerQueryTaskbarInfoByIndex(tr, data);
this.parent.selectionModule.clearSelection();
const segments: ITaskSegment[] = (args.rowData as IGanttData).taskData[this.parent.taskFields.segments];
if (this.parent.timezone && segments != null) {
for (let i: number = 0; i < segments.length; i++) {
segments[i][this.parent.taskFields.startDate] = this.parent.dateValidationModule.remove(
((args.rowData as IGanttData).ganttProperties.segments as ITaskSegment)[i].startDate, this.parent.timezone);
if (this.parent.taskFields.endDate) {
segments[i][this.parent.taskFields.endDate] = this.parent.dateValidationModule.remove(
((args.rowData as IGanttData).ganttProperties.segments as ITaskSegment)[i].endDate, this.parent.timezone);
}
}
}
this.parent.trigger('actionComplete', args);
setValue('isEdit', false, this.parent.contextMenuModule);
setValue('isEdit', false, this.parent);
}
/**
* public method to split task bar.
*
* @public
*/
public splitTask(taskId: number | string, splitDates: Date | Date[]): void {
const taskFields: TaskFieldsModel = this.parent.taskFields;
const splitDate: Date = splitDates as Date;
const splitRecord: IGanttData = this.parent.flatData.filter((x: IGanttData): IGanttData => {
if (x[taskFields.id] === taskId) {
return x;
} else {
return null;
}
})[0];
const ganttProp: ITaskData = splitRecord.ganttProperties;
this.dropSplit = false;
let segmentIndex: number = -1;
let segments: ITaskSegment[] = ganttProp.segments;
if (isNullOrUndefined((splitDates as Date[]).length) || (splitDates as Date[]).length < 0) {
const splitStartDate: Date = this.parent.dataOperation.checkStartDate(splitDate, ganttProp, false);
if (splitStartDate.getTime() !== ganttProp.startDate.getTime()) {
if (ganttProp.isAutoSchedule) {
if (!isNullOrUndefined(segments)) {
segmentIndex = this.getSegmentIndex(splitStartDate, splitRecord);
}
//check atleast one day difference is there to split
if (this.dropSplit === false && (splitDate as Date).getTime() > ganttProp.startDate.getTime() &&
(splitDate as Date).getTime() < ganttProp.endDate.getTime()) {
segments = segmentIndex !== -1 ? segments : [];
const startDate: Date = segmentIndex !== -1 ?
segments[segmentIndex].startDate : new Date(ganttProp.startDate.getTime());
const endDate: Date = segmentIndex !== -1 ? segments[segmentIndex].endDate : new Date(ganttProp.endDate.getTime());
const segmentDuration: number = this.parent.dataOperation.getDuration(
startDate, endDate, ganttProp.durationUnit, ganttProp.isAutoSchedule, ganttProp.isMilestone
);
this.parent.setRecordValue(
'segments', this.splitSegmentedTaskbar(
startDate, endDate, splitDate, segmentIndex, segments, splitRecord, segmentDuration
),
ganttProp, true
);
if (segmentIndex !== -1) {
this.incrementSegments(segments, segmentIndex + 1, splitRecord);
}
this.parent.setRecordValue('endDate', segments[segments.length - 1].endDate, ganttProp, true);
if (this.parent.taskFields.endDate) {
this.parent.dataOperation.updateMappingData(splitRecord, 'endDate');
}
}
this.refreshChartAfterSegment(splitRecord, 'splitTaskbar');
}
}
} else {
(splitDates as Date[]).sort((a: Date, b: Date) => {
return a.getTime() - b.getTime();
});
this.parent.setRecordValue(
'segments', this.constructSegments(
splitDates as Date[], splitRecord.ganttProperties
),
splitRecord.ganttProperties, true
);
this.refreshChartAfterSegment(splitRecord, 'splitTask');
}
}
private constructSegments(dates: Date[], taskData: ITaskData): ITaskSegment[] {
const segmentsArray: ITaskSegment[] = [];
let segment: ITaskSegment;
let startDate: Date = new Date();
let endDate: Date;
let duration: number;
for (let i: number = 0; i < dates.length + 1; i++) {
startDate = i === 0 ? taskData.startDate : startDate;
startDate = this.parent.dataOperation.checkStartDate(startDate, taskData, false);
endDate = i !== dates.length ? new Date(dates[i].getTime()) > taskData.endDate ? taskData.endDate
: new Date(dates[i].getTime()) : taskData.endDate;
endDate = this.parent.dataOperation.checkEndDate(endDate, taskData, false);
duration = this.parent.dataOperation.getDuration(
startDate, endDate, taskData.durationUnit, taskData.isAutoSchedule, taskData.isMilestone
);
if (endDate.getTime() >= startDate.getTime()) {
segment = {
startDate: startDate,
endDate: endDate,
duration: duration
};
segmentsArray.push(segment);
}
if (i === dates.length) {
break;
}
startDate = new Date(dates[i].getTime());
startDate.setDate(dates[i].getDate() + 1);
}
return segmentsArray;
}
private splitSegmentedTaskbar(
startDate: Date, endDate: Date, splitDate: Date, segmentIndex: number, segments: ITaskSegment[], ganttData: IGanttData,
segmentDuration: number): ITaskSegment[] {
const ganttProp: ITaskData = ganttData.ganttProperties;
const checkClickState: number = this.parent.nonWorkingDayIndex.indexOf(splitDate.getDay());
const increment: number = checkClickState === -1 ? 0 : checkClickState === 0 ? 1 : 2;
startDate = this.parent.dataOperation.checkStartDate(startDate, ganttProp, false);
let segmentEndDate: Date = new Date(splitDate.getTime());
segmentEndDate = this.parent.dataOperation.checkEndDate(segmentEndDate, ganttProp, false);
for (let i: number = 0; i < 2; i++) {
const segment: ITaskSegment = {
startDate: startDate,
endDate: segmentEndDate,
duration: this.parent.dataOperation.getDuration(
startDate, segmentEndDate, ganttProp.durationUnit,
ganttProp.isAutoSchedule, ganttProp.isMilestone),
offsetDuration: 1
};
const endDateState: number = this.parent.nonWorkingDayIndex.indexOf(segmentEndDate.getDay());
if (segmentIndex !== -1) {
segments.splice(segmentIndex, 1);
segmentIndex = -1;
}
segments.push(segment);
const mode: string = this.parent.timelineModule.customTimelineSettings.bottomTier.unit;
if (mode === 'Hour' || mode === 'Minutes') {
startDate = new Date(splitDate.getTime());
startDate = this.parent.dataOperation.checkStartDate(startDate, ganttProp, false);
const count: number = this.parent.timelineModule.customTimelineSettings.bottomTier.count;
const mode: string = this.parent.timelineModule.customTimelineSettings.bottomTier.unit;
let timeIncrement: number = this.parent.timelineModule.getIncrement(startDate, count, mode);
let newTime: number = startDate.getTime() + timeIncrement;
startDate.setTime(newTime + increment);
segmentEndDate = new Date(endDate.getTime());
timeIncrement = this.parent.timelineModule.getIncrement(segmentEndDate, count, mode);
newTime = segmentEndDate.getTime() + timeIncrement;
segmentEndDate.setTime(newTime + increment);
} else {
startDate = new Date(splitDate.getTime());
startDate.setDate(startDate.getDate() + 1 + increment);
startDate = this.parent.dataOperation.checkStartDate(startDate, ganttProp, false);
segmentEndDate = new Date(endDate.getTime());
segmentEndDate.setDate(segmentEndDate.getDate() + 1);
}
if (endDateState !== -1) {
const diff: number = segmentDuration - segment.duration;
segmentEndDate =
this.parent.dataOperation.getEndDate(startDate, diff, ganttProp.durationUnit, ganttProp, false);
} else {
segmentEndDate = this.parent.dataOperation.checkEndDate(segmentEndDate, ganttProp, false);
}
}
segments.sort((a: ITaskSegment, b: ITaskSegment) => {
return a.startDate.getTime() - b.startDate.getTime();
});
return segments;
}
public incrementSegments(segments: ITaskSegment[], segmentIndex: number, ganttData: IGanttData): void {
const ganttProp: ITaskData = ganttData.ganttProperties;
for (let i: number = segmentIndex + 1; i < segments.length; i++) {
const segment: ITaskSegment = segments[i];
let startDate: Date = i !== 0 ? new Date(segments[i - 1].endDate.getTime()) : new Date(segment.startDate.getTime());
startDate = this.parent.dataOperation.getEndDate(startDate, segment.offsetDuration, ganttProp.durationUnit, ganttProp, false);
startDate = this.parent.dataOperation.checkStartDate(startDate, ganttProp, false);
segment.startDate = startDate;
const endDate: Date = segment.endDate = this.parent.dataOperation.getEndDate(
startDate, segment.duration, ganttProp.durationUnit, ganttProp, false
);
segment.endDate = endDate;
if (i === segments.length - 1) {
this.parent.setRecordValue('endDate', endDate, ganttProp, true);
if (this.parent.taskFields.endDate) {
this.parent.dataOperation.updateMappingData(ganttData, 'endDate');
}
}
}
segments.sort((a: ITaskSegment, b: ITaskSegment) => {
return a.startDate.getTime() - b.startDate.getTime();
});
this.parent.setRecordValue('segments', segments, ganttProp, true);
this.parent.dataOperation.updateMappingData(ganttData, 'segments');
}
/**
* To get milestone node.
*
* @param {number} i .
* @param {NodeList} rootElement .
* @returns {NodeList} .
* @private
*/
private getMilestoneNode(i: number, rootElement?: NodeList): NodeList {
let milestoneNode: NodeList = null;
const data: IGanttData = this.templateData;
if (this.milestoneTemplateFunction) {
milestoneNode = this.milestoneTemplateFunction(
extend({ index: i }, data), this.parent, 'MilestoneTemplate',
this.getTemplateID('MilestoneTemplate'), false, undefined, rootElement[0], this.parent.treeGrid['root']);
} else {
const template: string = '<div class="' + cls.traceMilestone + '" style="position:absolute;">' +
'<div class="' + cls.milestoneTop + ' ' + ((!data.ganttProperties.startDate && !data.ganttProperties.endDate) ?
cls.unscheduledMilestoneTop : '') + '" style="border-right-width:' +
this.milesStoneRadius + 'px;border-left-width:' + this.milesStoneRadius + 'px;border-bottom-width:' +
this.milesStoneRadius + 'px;"></div>' +
'<div class="' + cls.milestoneBottom + ' ' + ((!data.ganttProperties.startDate && !data.ganttProperties.endDate) ?
cls.unscheduledMilestoneBottom : '') + '" style="top:' +
(this.milesStoneRadius) + 'px;border-right-width:' + this.milesStoneRadius + 'px; border-left-width:' +
this.milesStoneRadius + 'px; border-top-width:' + this.milesStoneRadius + 'px;"></div></div>';
milestoneNode = this.createDivElement(template);
}
return milestoneNode;
}
/**
* To get task baseline Node.
*
* @returns {NodeList} .
* @private
*/
private getTaskBaselineNode(): NodeList {
const data: IGanttData = this.templateData;
const template: string = '<div class="' + cls.baselineBar + ' ' + '" role="BaselineBar" style="margin-top:' + this.baselineTop +
'px;left:' + data.ganttProperties.baselineLeft + 'px;' +
'width:' + data.ganttProperties.baselineWidth + 'px;height:' +
this.baselineHeight + 'px;' + (this.baselineColor ? 'background-color: ' + this.baselineColor + ';' : '') + '"></div>';
return this.createDivElement(template);
}
/**
* To get milestone baseline node.
*
* @returns {NodeList} .
* @private
*/
private getMilestoneBaselineNode(): NodeList {
const data: IGanttData = this.templateData;
let baselineMilestoneHeight = this.parent.renderBaseline ? 5 : 2;
const template: string = '<div class="' + cls.baselineMilestoneContainer + ' ' + '" style="' +
'left:' + (data.ganttProperties.baselineLeft - this.milesStoneRadius) + 'px;' +
'margin-top:' + (-Math.floor(this.parent.rowHeight - this.milestoneMarginTop) + baselineMilestoneHeight) +
'px">' + '<div class="' + cls.baselineMilestoneDiv + '">' + '<div class="' + cls.baselineMilestoneDiv +
' ' + cls.baselineMilestoneTop + '" ' +
'style="top:' + (- this.milestoneHeight) + 'px;border-right:' + this.milesStoneRadius +
'px solid transparent;border-left:' + this.milesStoneRadius +
'px solid transparent;border-top:0px' +
'solid transparent;border-bottom-width:' + this.milesStoneRadius + 'px;' +
'border-bottom-style: solid;' + (this.baselineColor ? 'border-bottom-color: ' + this.baselineColor + ';' : '') +
'"></div>' +
'<div class="' + cls.baselineMilestoneDiv + ' ' + cls.baselineMilestoneBottom + '" ' +
'style="top:' + (this.milesStoneRadius - this.milestoneHeight) + 'px;border-right:' + this.milesStoneRadius +
'px solid transparent;border-left:' + this.milesStoneRadius +
'px solid transparent;border-bottom:0px' +
'solid transparent;border-top-width:' + this.milesStoneRadius + 'px;' +
'border-top-style: solid;' +
(this.baselineColor ? 'border-top-color: ' + this.baselineColor + ';' : '') + '"></div>' +
'</div></div>';
return this.createDivElement(template);
}
/**
* To get left label node.
*
* @param {number} i .
* @returns {NodeList} .
* @private
*/
private getLeftLabelNode(i: number): NodeList {
const leftLabelNode: NodeList = this.leftLabelContainer();
if(this.generateTaskLabelAriaLabel('left') !== "") {
(<HTMLElement>leftLabelNode[0]).setAttribute('aria-label', this.generateTaskLabelAriaLabel('left'));
}
let leftLabelTemplateNode: NodeList = null;
if (this.leftTaskLabelTemplateFunction) {
leftLabelTemplateNode = this.leftTaskLabelTemplateFunction(
extend({ index: i }, this.templateData), this.parent, 'LeftLabelTemplate',
this.getTemplateID('LeftLabelTemplate'), false, undefined, leftLabelNode[0],this.parent.treeGrid['root']);
} else {
const field: string = this.parent.labelSettings.leftLabel;
let labelString: string = this.getTaskLabel(field);
if (labelString) {
labelString = labelString === 'isCustomTemplate' ? field : labelString;
leftLabelTemplateNode = this.getLableText(labelString, cls.leftLabelInnerDiv);
}
}
if (leftLabelTemplateNode && leftLabelTemplateNode.length > 0) {
if (leftLabelTemplateNode[0]['data'] === 'null') {
leftLabelTemplateNode[0]['data'] = '';
}
leftLabelNode[0].appendChild([].slice.call(leftLabelTemplateNode)[0]);
}
return leftLabelNode;
}
private getLableText(labelString: string, labelDiv: string): NodeList {
let leftLabelHeight = this.parent.renderBaseline ? ((this.parent.rowHeight - this.taskBarHeight) / 2) : this.taskBarMarginTop;
const templateString: HTMLElement = createElement('div', {
className: labelDiv, styles: 'height:' + (this.taskBarHeight) + 'px;' +
'margin-top:' + leftLabelHeight + 'px;'
});
const spanElem: HTMLElement = createElement('span', { className: cls.label });
const property: string = this.parent.disableHtmlEncode ? 'textContent' : 'innerHTML';
spanElem[property] = labelString;
templateString.appendChild(spanElem);
const div: HTMLElement = createElement('div');
div.appendChild(templateString);
return div.childNodes;
}
/**
* To get right label node.
*
* @param {number} i .
* @returns {NodeList} .
* @private
*/
private getRightLabelNode(i: number): NodeList {
const rightLabelNode: NodeList = this.rightLabelContainer();
if(this.generateTaskLabelAriaLabel('right') !== "") {
(<HTMLElement>rightLabelNode[0]).setAttribute('aria-label', this.generateTaskLabelAriaLabel('right'));
}
let rightLabelTemplateNode: NodeList = null;
if (this.rightTaskLabelTemplateFunction) {
rightLabelTemplateNode = this.rightTaskLabelTemplateFunction(
extend({ index: i }, this.templateData), this.parent, 'RightLabelTemplate',
this.getTemplateID('RightLabelTemplate'), false, undefined, rightLabelNode[0], this.parent.treeGrid['root']);
} else {
const field: string = this.parent.labelSettings.rightLabel;
let labelString: string = this.getTaskLabel(field);
if (labelString) {
labelString = labelString === 'isCustomTemplate' ? field : labelString;
rightLabelTemplateNode = this.getLableText(labelString, cls.rightLabelInnerDiv);
}
}
if (rightLabelTemplateNode && rightLabelTemplateNode.length > 0) {
if (rightLabelTemplateNode[0]['data'] === 'null') {
rightLabelTemplateNode[0]['data'] = '';
}
rightLabelNode[0].appendChild([].slice.call(rightLabelTemplateNode)[0]);
}
return rightLabelNode;
}
private getManualTaskbar(): NodeList {
const data: IGanttData = this.templateData;
const taskbarHeight: number = (this.taskBarHeight / 2 - 1);
const innerDiv: string = (data.ganttProperties.startDate && data.ganttProperties.endDate && data.ganttProperties.duration) ?
('<div class="' + cls.manualParentTaskBar + '" style="width:' + data.ganttProperties.width + 'px;' + 'height:' +
taskbarHeight / 5 + 'px;border-left-width:' + taskbarHeight / 5 +
'px; border-bottom:' + taskbarHeight / 5 + 'px solid transparent;"></div>') :
(!data.ganttProperties.startDate && !data.ganttProperties.endDate && data.ganttProperties.duration) ?
('<div class="' + cls.manualParentTaskBar + ' ' + cls.traceManualUnscheduledTask +
'" style="width:' + data.ganttProperties.width + 'px;' + 'height:' +
(taskbarHeight / 5 + 1) + 'px;border-left-width:' + taskbarHeight / 5 +
'px; border-bottom:' + taskbarHeight / 5 + 'px solid transparent;"></div>') : ('<div class="' +
cls.manualParentTaskBar + ' ' + (data.ganttProperties.startDate ? cls.unscheduledTaskbarLeft : cls.unscheduledTaskbarRight) +
'" style="width:' + data.ganttProperties.width + 'px;' + 'height:' +
taskbarHeight * 2 + 'px;border-left-width:' + taskbarHeight / 5 +
'px; border-bottom:' + taskbarHeight / 5 + 'px solid transparent;"></div>');
const template: string = '<div class="' + cls.manualParentMainContainer + '"' +
'style=left:' + (data.ganttProperties.left - data.ganttProperties.autoLeft) + 'px;' +
'width:' + data.ganttProperties.width + 'px;' +
'height:' + taskbarHeight + 'px;>' + innerDiv + ((data.ganttProperties.startDate && data.ganttProperties.endDate &&
data.ganttProperties.duration) || data.ganttProperties.duration ? '<div class="e-gantt-manualparenttaskbar-left" style=' +
'"height:' + taskbarHeight + 'px;border-left-width:' + taskbarHeight / 5 +
'px; border-bottom:' + taskbarHeight / 5 + 'px solid transparent;"></div>' +
'<div class="e-gantt-manualparenttaskbar-right" style=' +
'left:' + (data.ganttProperties.width - taskbarHeight / 5) + 'px;height:' +
(taskbarHeight) + 'px;border-right-width:' + taskbarHeight / 5 + 'px;border-bottom:' +
taskbarHeight / 5 + 'px solid transparent;>' + '</div></div>' : '');
const milestoneTemplate: string = '<div class="' + cls.manualParentMilestone + '" style="position:absolute;left:' +
(data.ganttProperties.left - data.ganttProperties.autoLeft - (this.milestoneHeight / 2)) +
'px;width:' + (this.milesStoneRadius * 2) +
'px;">' + '<div class="' + cls.manualParentMilestoneTop + '" style="border-right-width:' +
this.milesStoneRadius + 'px;border-left-width:' + this.milesStoneRadius + 'px;border-bottom-width:' +
this.milesStoneRadius + 'px;"></div>' +
'<div class="' + cls.manualParentMilestoneBottom + '" style="top:' +
(this.milesStoneRadius) + 'px;border-right-width:' + this.milesStoneRadius + 'px; border-left-width:' +
this.milesStoneRadius + 'px; border-top-width:' + this.milesStoneRadius + 'px;"></div></div>';
return this.createDivElement(data.ganttProperties.width === 0 ? milestoneTemplate : template);
}
/**
* To get parent taskbar node.
*
* @param {number} i .
* @param {NodeList} rootElement .
* @returns {NodeList} .
* @private
*/
private getParentTaskbarNode(i: number, rootElement?: NodeList): NodeList {
let parentTaskbarNode: NodeList = null;
const data: IGanttData = this.templateData;
if (this.parentTaskbarTemplateFunction) {
parentTaskbarNode = this.parentTaskbarTemplateFunction(
extend({ index: i }, data), this.parent, 'ParentTaskbarTemplate',
this.getTemplateID('ParentTaskbarTemplate'), false, undefined, rootElement[0], this.parent.treeGrid['root']);
} else {
let labelString: string = ''; let labelDiv: string;
const tHeight: number = this.taskBarHeight / 5;
const template: NodeList = this.createDivElement('<div class="' + cls.parentTaskBarInnerDiv + ' ' +
this.getExpandClass(data) + ' ' + cls.traceParentTaskBar + '"' +
' style="width:' + (data.ganttProperties.isAutoSchedule ? data.ganttProperties.width :
data.ganttProperties.autoWidth) + 'px;height:' + (data.ganttProperties.isAutoSchedule ? this.taskBarHeight :
(tHeight * 3)) + 'px;margin-top:' + (data.ganttProperties.isAutoSchedule ? '' :
(tHeight * 2)) + 'px;">' +
'</div>');
const progressBarInnerDiv: NodeList = this.createDivElement('<div class="' + cls.parentProgressBarInnerDiv + ' ' +
this.getExpandClass(data) + ' ' + cls.traceParentProgressBar + '"' +
' style="border-style:' + (data.ganttProperties.progressWidth ? 'solid;' : 'none;') +
'width:' + data.ganttProperties.progressWidth + 'px;' +
'border-top-right-radius:' + this.getBorderRadius(data) + 'px;' +
'border-bottom-right-radius:' + this.getBorderRadius(data) + 'px;height:100%;"></div>');
let div: Element = createElement('div');
if (this.taskLabelTemplateFunction) {
const parentTaskLabelNode: NodeList = this.taskLabelTemplateFunction(
extend({ index: i }, data), this.parent, 'TaskLabelTemplate',
this.getTemplateID('TaskLabelTemplate'), false, undefined, progressBarInnerDiv[0]);
if (parentTaskLabelNode && parentTaskLabelNode.length > 0) {
div.appendChild(parentTaskLabelNode[0]);
labelString = div.innerHTML;
}
} else {
labelString = this.getTaskLabel(this.parent.labelSettings.taskLabel);
labelString = labelString === 'isCustomTemplate' ? this.parent.labelSettings.taskLabel : labelString;
}
if (labelString.indexOf('null') === -1) {
if (this.getTaskLabel(this.parent.labelSettings.taskLabel) === 'isCustomTemplate' && !this.isTemplate(this.parent.labelSettings.taskLabel)) {
labelString = '';
}
if (isNaN(parseInt(labelString))) {
labelDiv = '<span class="' + cls.taskLabel + '" style="line-height:' +
(this.taskBarHeight - 1) + 'px; text-align: left;' +
'display:' + 'inline-block;' +
'width:' + (data.ganttProperties.width - 10) + 'px; height:' +
this.taskBarHeight + 'px;">' + labelString + '</span>';
} else {
labelDiv = '<span class="' +
cls.taskLabel + '" style="line-height:' +
(this.taskBarHeight - 1) + 'px;' + (this.parent.viewType === 'ResourceView' ? 'display:inline-flex;' : '') +
(this.parent.viewType === 'ResourceView' ? 'width:' + (data.ganttProperties.width - 10) : '') + 'px; height:' +
(this.taskBarHeight - 1) + 'px;' + (this.parent.viewType === 'ResourceView' ? 'display: inline-flex;' : '') +
(this.parent.viewType === 'ResourceView' ? 'width:' + (data.ganttProperties.width - 10) : '') + 'px; height:' +
this.taskBarHeight + 'px;">' + labelString + '</span>';
}
let labelElement: Node = this.createDivElement(labelDiv)[0];
let parentLabel: string = this.parent.labelSettings.taskLabel;
if(parentLabel && parentLabel['elementRef'])
labelElement.appendChild(div);
progressBarInnerDiv[0].appendChild(labelElement);
if ((progressBarInnerDiv[0] as Element).querySelectorAll('.e-task-label')[0].textContent !== '' &&
!this.isTemplate(parentLabel) &&
(progressBarInnerDiv[0] as Element).querySelectorAll('.e-task-label')[0].children[0])
(progressBarInnerDiv[0] as Element).querySelectorAll('.e-task-label')[0].children[0].remove();
if ((progressBarInnerDiv[0] as Element).querySelectorAll('.e-task-label')[0].textContent == '' &&
parentLabel && !parentLabel['elementRef'] && div.innerHTML != '')
(progressBarInnerDiv[0] as Element).querySelectorAll('.e-task-label')[0].textContent = parentLabel;
}
const milestoneTemplate: string = '<div class="' + cls.parentMilestone + '" style="position:absolute;">' +
'<div class="' + cls.parentMilestoneTop + '" style="border-right-width:' +
this.milesStoneRadius + 'px;border-left-width:' + this.milesStoneRadius + 'px;border-bottom-width:' +
this.milesStoneRadius + 'px;"></div>' +
'<div class="' + cls.parentMilestoneBottom + '" style="top:' +
(this.milesStoneRadius) + 'px;border-right-width:' + this.milesStoneRadius + 'px; border-left-width:' +
this.milesStoneRadius + 'px; border-top-width:' + this.milesStoneRadius + 'px;"></div></div>';
template[0].appendChild([].slice.call(progressBarInnerDiv)[0]);
parentTaskbarNode = data.ganttProperties.isMilestone ?
this.createDivElement(data.ganttProperties.isAutoSchedule ? milestoneTemplate : '') : template;
}
return parentTaskbarNode;
}
/**
* To get taskbar row('TR') node
*
* @returns {NodeList} .
* @private
*/
private getTableTrNode(): NodeList {
const table: Element = createElement('table');
const className: string = (this.parent.gridLines === 'Horizontal' || this.parent.gridLines === 'Both') ?
'e-chart-row-border' : '';
table.innerHTML = '<tr class="' + this.getRowClassName(this.templateData) + ' ' + cls.chartRow + '"' +
'role="ChartRow" style="display:' + this.getExpandDisplayProp(this.templateData) + ';height:' +
this.parent.rowHeight + 'px;">' +
'<td class="' + cls.chartRowCell + ' ' + className
+ '" role="ChartCell" style="width:' + this.parent.timelineModule.totalTimelineWidth + 'px;"></td></tr>';
return table.childNodes;
}
/**
* To initialize chart templates.
*
* @returns {void}
* @private
*/
private initializeChartTemplate(): void {
if (!isNullOrUndefined(this.parent.parentTaskbarTemplate)) {
this.parentTaskbarTemplateFunction = this.templateCompiler(this.parent.parentTaskbarTemplate);
}
if (!isNullOrUndefined(this.parent.labelSettings.leftLabel) &&
this.isTemplate(this.parent.labelSettings.leftLabel)) {
this.leftTaskLabelTemplateFunction = this.templateCompiler(this.parent.labelSettings.leftLabel);
}
if (!isNullOrUndefined(this.parent.labelSettings.rightLabel) &&
this.isTemplate(this.parent.labelSettings.rightLabel)) {
this.rightTaskLabelTemplateFunction = this.templateCompiler(this.parent.labelSettings.rightLabel);
}
if (!isNullOrUndefined(this.parent.labelSettings.taskLabel) &&
this.isTemplate(this.parent.labelSettings.taskLabel)) {
this.taskLabelTemplateFunction = this.templateCompiler(this.parent.labelSettings.taskLabel);
}
if (!isNullOrUndefined(this.parent.taskbarTemplate)) {
this.childTaskbarTemplateFunction = this.templateCompiler(this.parent.taskbarTemplate);
}
if (!isNullOrUndefined(this.parent.milestoneTemplate)) {
this.milestoneTemplateFunction = this.templateCompiler(this.parent.milestoneTemplate);
}
}
private createDivElement(template: string): NodeList {
const div: Element = createElement('div');
div.innerHTML = template;
return div.childNodes;
}
private isTemplate(template: string): boolean {
let result: boolean = false;
for (let i: number = 0; i < this.parent.ganttColumns.length; i++) {
if (template === this.parent.ganttColumns[i].field) {
result = true;
break;
}
}
if (typeof template !== 'string' || template.indexOf('#') === 0 || template.indexOf('<') > -1
|| template.indexOf('$') > -1 || !result) {
result = true;
} else {
result = false
}
return result;
}
/**
* @param {string} templateName .
* @returns {string} .
* @private
*/
public getTemplateID(templateName: string): string {
const ganttID: string = this.parent.element.id;
return ganttID + templateName;
}
private leftLabelContainer(): NodeList {
const template: string = '<div class="' + ((this.leftTaskLabelTemplateFunction) ? cls.leftLabelTempContainer :
cls.leftLabelContainer) + ' ' + '" tabindex="-1" role="LeftLabel" style="height:' +
(this.parent.rowHeight - 2) + 'px;width:' + this.taskNameWidth(this.templateData) + '"></div>';
return this.createDivElement(template);
}
private taskbarContainer(): NodeList {
const data: IGanttData = this.templateData;
const manualParent: boolean = this.parent.editModule && this.parent.editSettings.allowTaskbarEditing &&
this.parent.editModule.taskbarEditModule.taskBarEditAction === 'ParentResizing' ?
true : false;
const template: string = '<div class="' + cls.taskBarMainContainer + ' ' +
this.parent.getUnscheduledTaskClass(data.ganttProperties) + ' ' +
((data.ganttProperties.cssClass) ? data.ganttProperties.cssClass : '') + '" ' +
' tabindex="-1" role="TaskBar" style="' + ((data.ganttProperties.isMilestone && !manualParent) ?
('width:' + this.milestoneHeight + 'px;height:' +
this.milestoneHeight + 'px;margin-top:' + this.milestoneMarginTop + 'px;left:' + (data.ganttProperties.left -
(this.milestoneHeight / 2)) + 'px;') : ('width:' + data.ganttProperties.width +
'px;margin-top:' + this.taskBarMarginTop + 'px;left:' + (!data.hasChildRecords || data.ganttProperties.isAutoSchedule ?
data.ganttProperties.left : data.ganttProperties.autoLeft) + 'px;height:' +
this.taskBarHeight + 'px;cursor:' + (data.ganttProperties.isAutoSchedule ? 'move;' : 'auto;'))) + '"></div>';
return this.createDivElement(template);
}
private rightLabelContainer(): NodeList {
const template: string = '<div class="' + ((this.rightTaskLabelTemplateFunction) ? cls.rightLabelTempContainer :
cls.rightLabelContainer) + '" ' + ' tabindex="-1" role="RightLabel" style="left:' + this.getRightLabelLeft(this.templateData) + 'px; height:'
+ (this.parent.rowHeight - 2) + 'px;"></div>';
return this.createDivElement(template);
}
private childTaskbarLeftResizer(): NodeList {
const lResizerLeft: number = -(this.parent.isAdaptive ? 12 : 2);
const template: string = '<div class="' + cls.taskBarLeftResizer + ' ' + cls.icon + '"' +
' role="LeftResizer" style="left:' + lResizerLeft + 'px;height:' + (this.taskBarHeight) + 'px;"></div>';
return this.createDivElement(template);
}
private childTaskbarRightResizer(): NodeList {
const rResizerLeft: number = this.parent.isAdaptive ? -2 : -10;
const template: string = '<div class="' + cls.taskBarRightResizer + ' ' + cls.icon + '"' +
' role="RightResizer" style="left:' + (this.templateData.ganttProperties.width + rResizerLeft) + 'px;' +
'height:' + (this.taskBarHeight) + 'px;"></div>';
return this.createDivElement(template);
}
private childTaskbarProgressResizer(): NodeList {
const template: string = '<div class="' + cls.childProgressResizer + '"' +
' role="ProgressResizer" style="left:' + (this.templateData.ganttProperties.progressWidth - 6) + 'px;margin-top:' +
(this.taskBarHeight - 4) + 'px;"><div class="' + cls.progressBarHandler + '"' +
'><div class="' + cls.progressHandlerElement + '"></div>' +
'<div class="' + cls.progressBarHandlerAfter + '"></div></div>';
return this.createDivElement(template);
}
private getLeftPointNode(): NodeList {
const data: IGanttData = this.templateData;
const pointerLeft: number = -((this.parent.isAdaptive ? 14 : 2) + this.connectorPointWidth);
const mileStoneLeft: number = -(this.connectorPointWidth + 2);
const pointerTop: number = Math.floor(this.milesStoneRadius - (this.connectorPointWidth / 2));
const template: string = '<div class="' + cls.leftConnectorPointOuterDiv + '" style="' +
((data.ganttProperties.isMilestone) ? ('margin-top:' + pointerTop + 'px;left:' + mileStoneLeft +
'px;') : ('margin-top:' + this.connectorPointMargin + 'px;left:' + pointerLeft + 'px;')) + '">' +
'<div class="' + cls.connectorPointLeft + ' ' + this.parent.getUnscheduledTaskClass(data.ganttProperties) +
'" style="width: ' + this.connectorPointWidth + 'px;' +
'height: ' + this.connectorPointWidth + 'px;">' + this.touchLeftConnectorpoint + '</div></div>';
return this.createDivElement(template);
}
private getRightPointNode(): NodeList {
const data: IGanttData = this.templateData;
const pointerRight: number = this.parent.isAdaptive ? 10 : -2;
const pointerTop: number = Math.floor(this.milesStoneRadius - (this.connectorPointWidth / 2));
const template: string = '<div class="' + cls.rightConnectorPointOuterDiv + '" style="' +
((data.ganttProperties.isMilestone) ? ('left:' + (this.milestoneHeight - 2) + 'px;margin-top:' +
pointerTop + 'px;') : ('left:' + (data.ganttProperties.width + pointerRight) + 'px;margin-top:' +
this.connectorPointMargin + 'px;')) + '">' +
'<div class="' + cls.connectorPointRight + ' ' + this.parent.getUnscheduledTaskClass(data.ganttProperties) +
'" style="width:' + this.connectorPointWidth + 'px;height:' + this.connectorPointWidth + 'px;">' +
this.touchRightConnectorpoint + '</div></div>';
return this.createDivElement(template);
}
/**
* To get task label.
*
* @param {string} field .
* @returns {string} .
* @private
*/
private getTaskLabel(field: string): string {
const length: number = this.parent.ganttColumns.length;
let resultString: string = null;
if (!isNullOrUndefined(field) && field !== '') {
if (field === this.parent.taskFields.resourceInfo) {
resultString = this.getResourceName(this.templateData);
} else {
for (let i: number = 0; i < length; i++) {
if (field === this.parent.ganttColumns[i].field) {
resultString = this.getFieldValue(this.templateData[field]).toString();
break;
}
}
if (isNullOrUndefined(resultString)) {
return 'isCustomTemplate';
}
}
} else {
resultString = '';
}
return resultString;
}
private getExpandDisplayProp(data: IGanttData): string {
data = this.templateData;
if (this.parent.getExpandStatus(data)) {
return 'table-row';
}
return 'none';
}
private getRowClassName(data: IGanttData): string {
data = this.templateData;
let rowClass: string = 'gridrowtaskId';
const parentItem: IParent = data.parentItem;
if (parentItem) {
rowClass += parentItem.taskId.toString();
}
rowClass += 'level';
rowClass += data.level.toString();
return rowClass;
}
private getBorderRadius(data: IGanttData): number {
data = this.templateData;
const diff: number = data.ganttProperties.width - data.ganttProperties.progressWidth;
if (diff <= 4) {
return 4 - diff;
} else {
return 0;
}
}
private getSplitTaskBorderRadius(data: ITaskSegment): number {
const diff: number = data.width - data.progressWidth;
if (diff <= 4) {
return 4 - diff;
} else {
return 0;
}
}
private taskNameWidth(ganttData: IGanttData): string {
ganttData = this.templateData;
const ganttProp: ITaskData = ganttData.ganttProperties;
let width: number;
if (ganttData.ganttProperties.isMilestone) {
width = (ganttData.ganttProperties.left - (this.parent.getTaskbarHeight() / 2));
} else if (ganttData.hasChildRecords && !ganttProp.isAutoSchedule) {
if (!this.parent.allowUnscheduledTasks) {
width = (ganttProp.autoStartDate.getTime() < ganttProp.startDate.getTime()) ?
ganttProp.autoLeft : ganttProp.left;
} else {
width = ganttProp.left < ganttProp.autoLeft ? ganttProp.left : ganttProp.autoLeft;
}
} else {
width = ganttData.ganttProperties.left;
}
if (width < 0) {
width = 0;
}
return width + 'px';
}
private getRightLabelLeft(ganttData: IGanttData): number {
ganttData = this.templateData;
const ganttProp: ITaskData = ganttData.ganttProperties;
let left: number;
let endLeft: number;
let width: number;
if (ganttData.ganttProperties.isMilestone) {
return ganttData.ganttProperties.left + (this.parent.getTaskbarHeight() / 2);
} else if (ganttData.hasChildRecords && !ganttProp.isAutoSchedule) {
if (!this.parent.allowUnscheduledTasks) {
left = ganttProp.autoStartDate.getTime() < ganttProp.startDate.getTime() ? ganttProp.autoLeft : ganttProp.left;
endLeft = ganttProp.autoEndDate.getTime() < ganttProp.endDate.getTime() ?
this.parent.dataOperation.getTaskLeft(ganttProp.endDate, ganttProp.isMilestone) :
this.parent.dataOperation.getTaskLeft(ganttProp.autoEndDate, ganttProp.isMilestone);
width = endLeft - left;
} else {
left = ganttProp.left < ganttProp.autoLeft ? ganttProp.left : ganttProp.autoLeft;
width = ganttProp.autoWidth;
}
return left + width;
} else {
return ganttData.ganttProperties.left + ganttData.ganttProperties.width;
}
}
private getExpandClass(data: IGanttData): string {
data = this.templateData;
if (data.expanded) {
return cls.rowExpand;
} else if (!data.expanded && data.hasChildRecords) {
return cls.rowCollapse;
}
return '';
}
private getFieldValue(field: string | number): string | number {
return isNullOrUndefined(field) ? '' : field;
}
private getResourceName(ganttData: IGanttData): string {
ganttData = this.templateData;
let resource: string = null;
if (!isNullOrUndefined(ganttData.ganttProperties.resourceInfo)) {
const length: number = ganttData.ganttProperties.resourceInfo.length;
if (length > 0) {
for (let i: number = 0; i < length; i++) {
let resourceName: string = ganttData.ganttProperties.resourceInfo[i][this.parent.resourceFields.name];
const resourceUnit: number = ganttData.ganttProperties.resourceInfo[i][this.parent.resourceFields.unit];
if (resourceUnit !== 100) {
resourceName += '[' + resourceUnit + '%' + ']';
}
if (isNullOrUndefined(resource)) {
resource = resourceName;
} else {
resource += ' , ' + resourceName;
}
}
return resource;
} else {
return '';
}
}
return '';
}
/**
* To initialize private variable help to render task bars.
*
* @returns {void}
* @private
*/
private initChartHelperPrivateVariable(): void {
let taskbarHeightValue = this.parent.renderBaseline ? 0.45 : 0.62;
let taskBarMarginTopValue = this.parent.renderBaseline ? 4 : 2;
let milestoneHeightValue = this.parent.renderBaseline ? 1.13 : 0.82;
this.baselineColor = !isNullOrUndefined(this.parent.baselineColor) &&
this.parent.baselineColor !== '' ? this.parent.baselineColor : null;
this.taskBarHeight = isNullOrUndefined(this.parent.taskbarHeight) || this.parent.taskbarHeight >= this.parent.rowHeight ?
Math.floor(this.parent.rowHeight * taskbarHeightValue) : this.parent.taskbarHeight; // 0.62 -- Standard Ratio.
if (this.parent.renderBaseline) {
let height: number;
if ((this.taskBarHeight + this.baselineHeight) <= this.parent.rowHeight) {
height = this.taskBarHeight;
} else {
height = this.taskBarHeight - (this.baselineHeight + 1);
}
this.taskBarHeight = height;
}
this.milestoneHeight = Math.floor(this.taskBarHeight * milestoneHeightValue); // 0.82 -- Standard Ratio.
this.taskBarMarginTop = Math.floor((this.parent.rowHeight - this.taskBarHeight) / taskBarMarginTopValue);
this.milestoneMarginTop = Math.floor((this.parent.rowHeight - this.milestoneHeight) / 2);
this.milesStoneRadius = Math.floor((this.milestoneHeight) / 2);
this.baselineTop = -(Math.floor((this.parent.rowHeight - (this.taskBarHeight + this.taskBarMarginTop))) - 4);
this.connectorPointWidth = this.parent.isAdaptive ? Math.round(this.taskBarHeight / 2) : 8;
this.connectorPointMargin = Math.floor((this.taskBarHeight / 2) - (this.connectorPointWidth / 2));
}
/**
* Function used to refresh Gantt rows.
*
* @returns {void}
* @private
*/
public refreshGanttRows(): void {
this.parent.currentViewData = this.parent.treeGrid.getCurrentViewRecords().slice();
this.createTaskbarTemplate();
if (this.parent.viewType === 'ResourceView' && this.parent.showOverAllocation) {
for (let i: number = 0; i < this.parent.currentViewData.length; i++) {
const data: IGanttData = this.parent.currentViewData[i];
if (data.childRecords.length > 0) {
this.parent.setRecordValue('workTimelineRanges', this.parent.dataOperation.mergeRangeCollections(data.ganttProperties.workTimelineRanges, true), data.ganttProperties, true);
this.parent.dataOperation.calculateRangeLeftWidth(data.ganttProperties.workTimelineRanges);
}
}
this.parent.ganttChartModule.renderRangeContainer(this.parent.currentViewData);
}
}
/**
* To render taskbars.
*
* @returns {void}
* @private
*/
private createTaskbarTemplate(): void {
const trs: Element[] = [].slice.call(this.ganttChartTableBody.querySelectorAll('tr'));
this.ganttChartTableBody.innerHTML = '';
const collapsedResourceRecord: IGanttData[] = [];
const prevCurrentView: Object[] = this.parent.treeGridModule.prevCurrentView as object[];
this.refreshedTr = []; this.refreshedData = [];
if (this.parent.enableImmutableMode && prevCurrentView && prevCurrentView.length > 0 && this.isUpdated) {
const oldKeys: object = {};
const oldRowElements: Element[] = [];
const key: string = this.parent.treeGrid.getPrimaryKeyFieldNames()[0];
for (let i: number = 0; i < prevCurrentView.length; i++) {
oldRowElements[i] = trs[i];
oldKeys[prevCurrentView[i][key]] = i;
}
for (let index: number = 0; index < this.parent.currentViewData.length; index++) {
const oldIndex: number = oldKeys[this.parent.currentViewData[index][key]];
const modifiedRecIndex: number = this.parent.modifiedRecords.indexOf(this.parent.currentViewData[index]);
if (isNullOrUndefined(oldIndex) || modifiedRecIndex !== -1) {
const tRow: Node = this.getGanttChartRow(index, this.parent.currentViewData[index]);
this.ganttChartTableBody.appendChild(tRow);
this.refreshedTr.push(this.ganttChartTableBody.querySelectorAll('tr')[index]);
this.refreshedData.push(this.parent.currentViewData[index]);
} else {
this.ganttChartTableBody.appendChild(oldRowElements[oldIndex]);
}
this.ganttChartTableBody.querySelectorAll('tr')[index].setAttribute('aria-rowindex', index.toString());
}
} else {
for (let i: number = 0; i < this.parent.currentViewData.length; i++) {
const tempTemplateData: IGanttData = this.parent.currentViewData[i];
if (this.parent.viewType === 'ResourceView' && !tempTemplateData.expanded && this.parent.enableMultiTaskbar) {
collapsedResourceRecord.push(tempTemplateData);
}
const tRow: Node = this.getGanttChartRow(i, tempTemplateData);
this.ganttChartTableBody.appendChild(tRow);
if (this.parent.enableImmutableMode) {
this.refreshedTr.push(this.ganttChartTableBody.querySelectorAll('tr')[i]);
this.refreshedData.push(this.parent.currentViewData[i]);
}
// To maintain selection when virtualization is enabled
if (this.parent.selectionModule && this.parent.allowSelection) {
this.parent.selectionModule.maintainSelectedRecords(parseInt((tRow as Element).getAttribute('aria-rowindex'), 10));
}
}
}
this.parent.renderTemplates();
this.triggerQueryTaskbarInfo();
this.parent.modifiedRecords = [];
if (collapsedResourceRecord.length) {
for (let j: number = 0; j < collapsedResourceRecord.length; j++) {
if (collapsedResourceRecord[j].hasChildRecords) {
this.parent.isGanttChartRendered = true;
this.parent.chartRowsModule.refreshRecords([collapsedResourceRecord[j]]);
}
}
}
this.parent.renderTemplates();
}
/**
* To render taskbars.
*
* @param {number} i .
* @param {IGanttData} tempTemplateData .
* @returns {Node} .
* @private
*/
public getGanttChartRow(i: number, tempTemplateData: IGanttData): Node {
this.templateData = tempTemplateData;
let taskBaselineTemplateNode: NodeList = null;
const parentTrNode: NodeList = this.getTableTrNode();
const leftLabelNode: NodeList = this.getLeftLabelNode(i);
const taskbarContainerNode: NodeList = this.taskbarContainer();
(<HTMLElement>taskbarContainerNode[0]).setAttribute('aria-label', this.generateAriaLabel(this.templateData));
(<HTMLElement>taskbarContainerNode[0]).setAttribute('rowUniqueId', this.templateData.ganttProperties.rowUniqueID);
if (!this.templateData.hasChildRecords) {
const connectorLineLeftNode: NodeList = this.getLeftPointNode();
taskbarContainerNode[0].appendChild([].slice.call(connectorLineLeftNode)[0]);
}
if (this.templateData.hasChildRecords) {
const parentTaskbarTemplateNode: NodeList = this.getParentTaskbarNode(i, taskbarContainerNode);
if (!this.templateData.ganttProperties.isAutoSchedule) {
const manualTaskbar: NodeList = this.getManualTaskbar();
taskbarContainerNode[0].appendChild([].slice.call(manualTaskbar)[0]);
}
if (parentTaskbarTemplateNode && parentTaskbarTemplateNode.length > 0) {
taskbarContainerNode[0].appendChild([].slice.call(parentTaskbarTemplateNode)[0]);
}
if (this.parent.renderBaseline && this.templateData.ganttProperties.baselineStartDate &&
this.templateData.ganttProperties.baselineEndDate) {
taskBaselineTemplateNode = this.getTaskBaselineNode();
}
} else if (this.templateData.ganttProperties.isMilestone) {
const milestoneTemplateNode: NodeList = this.getMilestoneNode(i, taskbarContainerNode);
if (milestoneTemplateNode && milestoneTemplateNode.length > 0) {
taskbarContainerNode[0].appendChild([].slice.call(milestoneTemplateNode)[0]);
}
if (this.parent.renderBaseline && this.templateData.ganttProperties.baselineStartDate &&
this.templateData.ganttProperties.baselineEndDate) {
taskBaselineTemplateNode = this.getMilestoneBaselineNode();
}
} else {
const scheduledTask: Boolean = isScheduledTask(this.templateData.ganttProperties);// eslint-disable-line
let childTaskbarProgressResizeNode: NodeList = null; let childTaskbarRightResizeNode: NodeList = null;
let childTaskbarLeftResizeNode: NodeList = null;
if (!isNullOrUndefined(scheduledTask)) {
if (scheduledTask || this.templateData.ganttProperties.duration) {
if (scheduledTask && (isNullOrUndefined(this.templateData.ganttProperties.segments)
|| this.templateData.ganttProperties.segments.length <= 0)) {
childTaskbarProgressResizeNode = this.childTaskbarProgressResizer();
childTaskbarLeftResizeNode = this.childTaskbarLeftResizer();
childTaskbarRightResizeNode = this.childTaskbarRightResizer();
}
}
const childTaskbarTemplateNode: NodeList = this.getChildTaskbarNode(i, taskbarContainerNode);
if (childTaskbarLeftResizeNode) {
taskbarContainerNode[0].appendChild([].slice.call(childTaskbarLeftResizeNode)[0]);
}
if (childTaskbarTemplateNode && childTaskbarTemplateNode.length > 0) {
if (this.templateData.ganttProperties.segments && this.templateData.ganttProperties.segments.length > 0) {
const length: number = this.templateData.ganttProperties.segments.length;
const connector: string = ('<div class="e-gantt-split-container-line"></div>');
let segmentConnector: NodeList = null;
segmentConnector = this.createDivElement(connector);
taskbarContainerNode[0].appendChild([].slice.call(segmentConnector)[0]);
for (let i: number = 0; i < length; i++) {
taskbarContainerNode[0].appendChild([].slice.call(childTaskbarTemplateNode)[0]);
}
} else {
taskbarContainerNode[0].appendChild([].slice.call(childTaskbarTemplateNode)[0]);
}
}
if (childTaskbarProgressResizeNode) {
taskbarContainerNode[0].appendChild([].slice.call(childTaskbarProgressResizeNode)[0]);
}
if (childTaskbarRightResizeNode) {
taskbarContainerNode[0].appendChild([].slice.call(childTaskbarRightResizeNode)[0]);
}
}
if (this.parent.renderBaseline && this.templateData.ganttProperties.baselineStartDate &&
this.templateData.ganttProperties.baselineEndDate) {
taskBaselineTemplateNode = this.getTaskBaselineNode();
}
}
if (!this.templateData.hasChildRecords) {
const connectorLineRightNode: NodeList = this.getRightPointNode();
taskbarContainerNode[0].appendChild([].slice.call(connectorLineRightNode)[0]);
}
const rightLabelNode: NodeList = this.getRightLabelNode(i);
parentTrNode[0].childNodes[0].childNodes[0].appendChild([].slice.call(leftLabelNode)[0]);
parentTrNode[0].childNodes[0].childNodes[0].appendChild([].slice.call(taskbarContainerNode)[0]);
if (this.templateData.ganttProperties.indicators && this.templateData.ganttProperties.indicators.length > 0) {
let taskIndicatorNode: NodeList;
let taskIndicatorTextFunction: Function;
let taskIndicatorTextNode: NodeList;
const indicators: IIndicator[] = this.templateData.ganttProperties.indicators;
for (let indicatorIndex: number = 0; indicatorIndex < indicators.length; indicatorIndex++) {
taskIndicatorNode = this.getIndicatorNode(indicators[indicatorIndex]);
(<HTMLElement>taskIndicatorNode[0]).setAttribute('aria-label',indicators[indicatorIndex].name);
if (indicators[indicatorIndex].name.indexOf('$') > -1 || indicators[indicatorIndex].name.indexOf('#') > -1) {
taskIndicatorTextFunction = this.templateCompiler(indicators[indicatorIndex].name);
taskIndicatorTextNode = taskIndicatorTextFunction(
extend({ index: i }, this.templateData), this.parent, 'indicatorLabelText');
} else {
const text: Element = createElement('Text');
text.innerHTML = indicators[indicatorIndex].name;
taskIndicatorTextNode = text.childNodes;
}
taskIndicatorNode[0].appendChild([].slice.call(taskIndicatorTextNode)[0]);
(taskIndicatorNode[0] as HTMLElement).title =
!isNullOrUndefined(indicators[indicatorIndex].tooltip) ? indicators[indicatorIndex].tooltip : '';
parentTrNode[0].childNodes[0].childNodes[0].appendChild([].slice.call(taskIndicatorNode)[0]);
}
}
if (rightLabelNode && rightLabelNode.length > 0) {
parentTrNode[0].childNodes[0].childNodes[0].appendChild([].slice.call(rightLabelNode)[0]);
}
if (!isNullOrUndefined(taskBaselineTemplateNode)) {
parentTrNode[0].childNodes[0].childNodes[0].appendChild([].slice.call(taskBaselineTemplateNode)[0]);
}
const tRow: Node = parentTrNode[0].childNodes[0];
this.setAriaRowIndex(tempTemplateData, tRow);
return tRow;
}
/**
* To set aria-rowindex for chart rows
*
* @returns {void} .
* @private
*/
public setAriaRowIndex(tempTemplateData: IGanttData, tRow: Node): void {
const dataSource: IGanttData[] = this.parent.treeGrid.getCurrentViewRecords() as IGanttData[];
const visualData: IGanttData[] = this.parent.virtualScrollModule && this.parent.enableVirtualization ?
getValue('virtualScrollModule.visualData', this.parent.treeGrid) : dataSource;
const index: number = visualData.indexOf(tempTemplateData);
(tRow as Element).setAttribute('aria-rowindex', index.toString());
}
/**
* To trigger query taskbar info event.
*
* @returns {void}
* @private
*/
public triggerQueryTaskbarInfo(): void {
if (!this.parent.queryTaskbarInfo) {
return;
}
const length: number = this.parent.enableImmutableMode ?
this.refreshedTr.length : this.ganttChartTableBody.querySelectorAll('tr').length;
let trElement: Element;
let data: IGanttData;
for (let index: number = 0; index < length; index++) {
trElement = this.parent.enableImmutableMode ? this.refreshedTr[index] : this.ganttChartTableBody.querySelectorAll('tr')[index];
data = this.refreshedData.length > 0 ? this.refreshedData[index] : this.parent.currentViewData[index];
const segmentLength: number = !isNullOrUndefined(data.ganttProperties.segments) && data.ganttProperties.segments.length;
if (segmentLength > 0) {
for (let i: number = 0; i < segmentLength; i++) {
const segmentedTasks: HTMLCollectionOf<HTMLElement> =
trElement.getElementsByClassName('e-segmented-taskbar') as HTMLCollectionOf<HTMLElement>;
const segmentElement: HTMLElement = segmentedTasks[i] as HTMLElement;
this.triggerQueryTaskbarInfoByIndex(segmentElement, data);
}
} else if (trElement) {
this.triggerQueryTaskbarInfoByIndex(trElement, data);
}
}
}
/**
*
* @param {Element} trElement .
* @param {IGanttData} data .
* @returns {void} .
* @private
*/
public triggerQueryTaskbarInfoByIndex(trElement: Element, data: IGanttData): void {
// eslint-disable-next-line
const taskbarElement: Element = !isNullOrUndefined(data.ganttProperties.segments) && data.ganttProperties.segments.length > 0 ? trElement :
trElement.querySelector('.' + cls.taskBarMainContainer);
let rowElement: Element;
let triggerTaskbarElement: Element;
const args: IQueryTaskbarInfoEventArgs = {
data: data,
rowElement: trElement,
taskbarElement: taskbarElement,
taskbarType: data.hasChildRecords ? 'ParentTask' : data.ganttProperties.isMilestone ? 'Milestone' : 'ChildTask'
};
const classCollections: string[] = this.getClassName(args);
if (args.taskbarType === 'Milestone') {
args.milestoneColor = taskbarElement.querySelector(classCollections[0]) ?
getComputedStyle(taskbarElement.querySelector(classCollections[0])).borderBottomColor : null;
args.baselineColor = trElement.querySelector(classCollections[1]) ?
getComputedStyle(trElement.querySelector(classCollections[1])).borderBottomColor : null;
} else {
const childTask: HTMLElement = taskbarElement.querySelector(classCollections[0]);
const progressTask: HTMLElement = taskbarElement.querySelector(classCollections[1]);
args.taskbarBgColor = isNullOrUndefined(childTask) ? null : taskbarElement.classList.contains(cls.traceChildTaskBar) ?
getComputedStyle(taskbarElement).backgroundColor :
getComputedStyle(taskbarElement.querySelector(classCollections[0])).backgroundColor;
args.taskbarBorderColor = isNullOrUndefined(childTask) ? null : taskbarElement.classList.contains(cls.traceChildTaskBar) ?
getComputedStyle(taskbarElement).backgroundColor :
getComputedStyle(taskbarElement.querySelector(classCollections[0])).borderColor;
args.progressBarBgColor = isNullOrUndefined(progressTask) ? null :
taskbarElement.classList.contains(cls.traceChildProgressBar) ?
getComputedStyle(taskbarElement).backgroundColor :
getComputedStyle(taskbarElement.querySelector(classCollections[1])).backgroundColor;
// args.progressBarBorderColor = taskbarElement.querySelector(progressBarClass) ?
// getComputedStyle(taskbarElement.querySelector(progressBarClass)).borderColor : null;
args.baselineColor = trElement.querySelector('.' + cls.baselineBar) ?
getComputedStyle(trElement.querySelector('.' + cls.baselineBar)).backgroundColor : null;
args.taskLabelColor = taskbarElement.querySelector('.' + cls.taskLabel) ?
getComputedStyle(taskbarElement.querySelector('.' + cls.taskLabel)).color : null;
}
args.rightLabelColor = trElement.querySelector('.' + cls.rightLabelContainer) &&
(trElement.querySelector('.' + cls.rightLabelContainer)).querySelector('.' + cls.label) ?
getComputedStyle((trElement.querySelector('.' + cls.rightLabelContainer)).querySelector('.' + cls.label)).color : null;
args.leftLabelColor = trElement.querySelector('.' + cls.leftLabelContainer) &&
(trElement.querySelector('.' + cls.leftLabelContainer)).querySelector('.' + cls.label) ?
getComputedStyle((trElement.querySelector('.' + cls.leftLabelContainer)).querySelector('.' + cls.label)).color : null;
this.parent.trigger('queryTaskbarInfo', args, (taskbarArgs: IQueryTaskbarInfoEventArgs) => {
this.updateQueryTaskbarInfoArgs(taskbarArgs, rowElement, triggerTaskbarElement);
});
}
/**
* To update query taskbar info args.
*
* @param {IQueryTaskbarInfoEventArgs} args .
* @param {Element} rowElement .
* @param {Element} taskBarElement .
* @returns {void}
* @private
*/
private updateQueryTaskbarInfoArgs(args: IQueryTaskbarInfoEventArgs, rowElement?: Element, taskBarElement?: Element): void {
const trElement: Element = args.rowElement;
const taskbarElement: Element = args.taskbarElement;
const classCollections: string[] = this.getClassName(args);
if (args.taskbarType === 'Milestone') {
if (taskbarElement.querySelector(classCollections[0]) &&
getComputedStyle(taskbarElement.querySelector(classCollections[0])).borderBottomColor !== args.milestoneColor) {
(taskbarElement.querySelector(classCollections[0]) as HTMLElement).style.borderBottomColor = args.milestoneColor;
(taskbarElement.querySelector('.' + cls.milestoneBottom) as HTMLElement).style.borderTopColor = args.milestoneColor;
}
if (trElement.querySelector(classCollections[1]) &&
getComputedStyle(trElement.querySelector(classCollections[1])).borderTopColor !== args.baselineColor) {
(trElement.querySelector(classCollections[1]) as HTMLElement).style.borderBottomColor = args.baselineColor;
(trElement.querySelector('.' + cls.baselineMilestoneBottom) as HTMLElement).style.borderTopColor = args.baselineColor;
}
} else {
if (taskbarElement.querySelector(classCollections[0]) &&
getComputedStyle(taskbarElement.querySelector(classCollections[0])).backgroundColor !== args.taskbarBgColor) {
(taskbarElement.querySelector(classCollections[0]) as HTMLElement).style.backgroundColor = args.taskbarBgColor;
}
if (taskbarElement.querySelector(classCollections[0]) &&
getComputedStyle(taskbarElement.querySelector(classCollections[0])).borderColor !== args.taskbarBorderColor) {
(taskbarElement.querySelector(classCollections[0]) as HTMLElement).style.borderColor = args.taskbarBorderColor;
}
if (taskbarElement.querySelector(classCollections[1]) &&
getComputedStyle(taskbarElement.querySelector(classCollections[1])).backgroundColor !== args.progressBarBgColor) {
(taskbarElement.querySelector(classCollections[1]) as HTMLElement).style.backgroundColor = args.progressBarBgColor;
}
if (taskbarElement.classList.contains(cls.traceChildTaskBar) &&
getComputedStyle(taskbarElement).backgroundColor !== args.taskbarBgColor) {
(taskbarElement as HTMLElement).style.backgroundColor = args.taskbarBgColor;
}
if (taskbarElement.classList.contains(cls.traceChildTaskBar) &&
getComputedStyle(taskbarElement).borderColor !== args.taskbarBorderColor) {
(taskbarElement as HTMLElement).style.borderColor = args.taskbarBorderColor;
}
if (taskbarElement.classList.contains(cls.traceChildProgressBar) &&
getComputedStyle(taskbarElement).backgroundColor !== args.progressBarBgColor) {
(taskbarElement as HTMLElement).style.backgroundColor = args.progressBarBgColor;
}
// if (taskbarElement.querySelector(progressBarClass) &&
// getComputedStyle(taskbarElement.querySelector(progressBarClass)).borderColor !== args.progressBarBorderColor) {
// (taskbarElement.querySelector(progressBarClass) as HTMLElement).style.borderColor = args.progressBarBorderColor;
// }
if (taskbarElement.querySelector('.' + cls.taskLabel) &&
getComputedStyle(taskbarElement.querySelector('.' + cls.taskLabel)).color !== args.taskLabelColor) {
(taskbarElement.querySelector('.' + cls.taskLabel) as HTMLElement).style.color = args.taskLabelColor;
}
if (trElement.querySelector('.' + cls.baselineBar) &&
getComputedStyle(trElement.querySelector('.' + cls.baselineBar)).backgroundColor !== args.baselineColor) {
(trElement.querySelector('.' + cls.baselineBar) as HTMLElement).style.backgroundColor = args.baselineColor;
}
}
if (trElement.querySelector('.' + cls.leftLabelContainer) &&
(trElement.querySelector('.' + cls.leftLabelContainer)).querySelector('.' + cls.label) &&
getComputedStyle(
(trElement.querySelector('.' + cls.leftLabelContainer)).querySelector('.' + cls.label)).color !== args.leftLabelColor) {
((trElement.querySelector(
'.' + cls.leftLabelContainer)).querySelector('.' + cls.label) as HTMLElement).style.color = args.leftLabelColor;
}
if (trElement.querySelector('.' + cls.rightLabelContainer) &&
(trElement.querySelector('.' + cls.rightLabelContainer)).querySelector('.' + cls.label) &&
getComputedStyle(
(trElement.querySelector('.' + cls.rightLabelContainer)).querySelector('.' + cls.label)).color !== args.rightLabelColor) {
((trElement.querySelector(
'.' + cls.rightLabelContainer)).querySelector('.' + cls.label) as HTMLElement).style.color = args.rightLabelColor;
}
}
private getClassName(args: IQueryTaskbarInfoEventArgs): string[] {
const classCollection: string[] = [];
classCollection.push('.' + (args.taskbarType === 'ParentTask' ?
cls.traceParentTaskBar : args.taskbarType === 'ChildTask' ? cls.traceChildTaskBar : cls.milestoneTop));
classCollection.push('.' + (args.taskbarType === 'ParentTask' ?
cls.traceParentProgressBar : args.taskbarType === 'ChildTask' ? cls.traceChildProgressBar : cls.baselineMilestoneTop));
return classCollection;
}
/**
* To compile template string.
*
* @param {string} template .
* @returns {Function} .
* @private
*/
public templateCompiler(template: string): Function {
if (!isNullOrUndefined(template) && template !== '') {
try {
if (document.querySelectorAll(template).length) {
return compile(document.querySelector(template).innerHTML.trim(), this.parent);
} else {
return compile(template, this.parent);
}
} catch (e) {
return compile(template, this.parent);
}
}
return null;
}
/**
* To refresh edited TR
*
* @param {number} index .
* @param {boolean} isValidateRange .
* @returns {void} .
* @private
*/
public refreshRow(index: number, isValidateRange?: boolean): void {
const tr: Node = this.ganttChartTableBody.childNodes[index];
const selectedItem: IGanttData = this.parent.currentViewData[index];
if (index !== -1 && selectedItem) {
const data: IGanttData = selectedItem;
if (this.parent.viewType === 'ResourceView' && data.hasChildRecords && !data.expanded && this.parent.enableMultiTaskbar) {
tr.replaceChild(this.getResourceParent(data).childNodes[0], tr.childNodes[0]);
} else {
tr.replaceChild(this.getGanttChartRow(index, data).childNodes[0], tr.childNodes[0]);
}
this.parent.renderTemplates();
if (this.parent.viewType === 'ResourceView' && data.hasChildRecords && this.parent.showOverAllocation) {
if (isValidateRange) {
this.parent.ganttChartModule.renderRangeContainer(this.parent.currentViewData);
} else {
this.parent.dataOperation.updateOverlappingValues(data);
this.parent.ganttChartModule.renderRangeContainer([data]);
}
}
const segmentLength: number = !isNullOrUndefined(data.ganttProperties.segments) && data.ganttProperties.segments.length;
if (segmentLength > 0) {
for (let i: number = 0; i < segmentLength; i++) {
const segmentedTasks: HTMLCollectionOf<HTMLElement> =
(tr as Element).getElementsByClassName('e-segmented-taskbar') as HTMLCollectionOf<HTMLElement>;
const segmentElement: HTMLElement = segmentedTasks[i] as HTMLElement;
this.triggerQueryTaskbarInfoByIndex(segmentElement, data);
}
} else {
this.triggerQueryTaskbarInfoByIndex(tr as Element, data);
}
const dataId: number | string = this.parent.viewType === 'ProjectView' ? data.ganttProperties.taskId : data.ganttProperties.rowUniqueID;
this.parent.treeGrid.grid.setRowData(dataId, data);
const row: Row<Column> = this.parent.treeGrid.grid.getRowObjectFromUID(
this.parent.treeGrid.grid.getDataRows()[index].getAttribute('data-uid'));
row.data = data;
}
}
private getResourceParent(record: IGanttData): Node {
const chartRows: NodeListOf<Element> = this.parent.ganttChartModule.getChartRows();
//Below code is for rendering taskbartemplate in resource view with multi taskbar
if (this.parent.initialChartRowElements) {
for (let j: number = 0; j <= this.parent.initialChartRowElements.length; j++) {
if (!isNullOrUndefined(chartRows[j])) {
if (!isNullOrUndefined(chartRows[j].childNodes[0].childNodes[1].childNodes[2]) &&
!isNullOrUndefined(this.parent.initialChartRowElements[j].childNodes[0].childNodes[1].childNodes[2])) {
// eslint-disable-next-line
chartRows[j].childNodes[0].childNodes[1].childNodes[2]['innerHTML'] = this.parent.initialChartRowElements[j].childNodes[0].childNodes[1].childNodes[2]['innerHTML'];
}
}
}
}
this.templateData = record;
const parentTrNode: NodeList = this.getTableTrNode();
const leftLabelNode: NodeList = this.leftLabelContainer();
const collapseParent: HTMLElement = createElement('div', {
className: 'e-collapse-parent'
});
parentTrNode[0].childNodes[0].childNodes[0].appendChild(collapseParent);
const tasks: IGanttData[] = this.parent.dataOperation.setSortedChildTasks(record);
this.parent.dataOperation.updateOverlappingIndex(tasks);
for (let i: number = 0; i < chartRows.length; i++) {
if ((<HTMLElement>chartRows[i]).classList.contains('gridrowtaskId'
+ record.ganttProperties.rowUniqueID + 'level' + (record.level + 1))) {
const cloneElement: HTMLElement = chartRows[i].querySelector('.e-taskbar-main-container');
addClass([cloneElement], 'collpse-parent-border');
const id: string = chartRows[i].querySelector('.' + cls.taskBarMainContainer).getAttribute('rowUniqueId');
const ganttData: IGanttData = this.parent.getRecordByID(id);
const zIndex: string = (ganttData.ganttProperties.eOverlapIndex).toString();
const cloneChildElement: HTMLElement = cloneElement.cloneNode(true) as HTMLElement;
cloneChildElement.style.zIndex = zIndex;
parentTrNode[0].childNodes[0].childNodes[0].childNodes[0].appendChild(cloneChildElement);
}
}
parentTrNode[0].childNodes[0].childNodes[0].appendChild([].slice.call(leftLabelNode)[0]);
return parentTrNode[0].childNodes[0];
}
/**
* To refresh all edited records
*
* @param {IGanttData} items .
* @param {boolean} isValidateRange .
* @returns {void} .
* @private
*/
public refreshRecords(items: IGanttData[], isValidateRange?: boolean): void {
if (this.parent.isGanttChartRendered) {
this.parent.renderTemplates();
if (this.parent.viewType === 'ResourceView' && this.parent.enableMultiTaskbar) {
let sortedRecords: IGanttData[] = [];
sortedRecords = new DataManager(items).executeLocal(new Query()
.sortBy('expanded', 'Descending'));
items = sortedRecords;
}
for (let i: number = 0; i < items.length; i++) {
const index: number = this.parent.currentViewData.indexOf(items[i]);
this.refreshRow(index, isValidateRange);
}
this.parent.ganttChartModule.updateLastRowBottomWidth();
}
}
private removeEventListener(): void {
if (this.parent.isDestroyed) {
return;
}
this.parent.off('renderPanels', this.createChartTable);
this.parent.off('dataReady', this.initiateTemplates);
this.parent.off('destroy', this.destroy);
}
private destroy(): void {
this.removeEventListener();
}
private generateAriaLabel(data: IGanttData): string {
data = this.templateData;
let defaultValue: string = '';
const nameConstant: string = this.parent.localeObj.getConstant('name');
const startDateConstant: string = this.parent.localeObj.getConstant('startDate');
const endDateConstant: string = this.parent.localeObj.getConstant('endDate');
const durationConstant: string = this.parent.localeObj.getConstant('duration');
const taskNameVal: string = data.ganttProperties.taskName;
const startDateVal: Date = data.ganttProperties.startDate;
const endDateVal: Date = data.ganttProperties.endDate;
const durationVal: number = data.ganttProperties.duration;
if (data.ganttProperties.isMilestone) {
defaultValue = nameConstant + ' ' + taskNameVal + ' ' + startDateConstant + ' '
+ this.parent.getFormatedDate(startDateVal);
} else {
if (taskNameVal) {
defaultValue += nameConstant + ' ' + taskNameVal + ' ';
}
if (startDateVal) {
defaultValue += startDateConstant + ' ' + this.parent.getFormatedDate(startDateVal) + ' ';
}
if (endDateVal) {
defaultValue += endDateConstant + ' ' + this.parent.getFormatedDate(endDateVal) + ' ';
}
if (durationVal) {
defaultValue += durationConstant + ' '
+ this.parent.getDurationString(durationVal, data.ganttProperties.durationUnit);
}
}
return defaultValue;
}
private generateSpiltTaskAriaLabel(data: ITaskSegment, ganttProp: ITaskData): string {
let defaultValue: string = '';
const startDateConstant: string = this.parent.localeObj.getConstant('startDate');
const endDateConstant: string = this.parent.localeObj.getConstant('endDate');
const durationConstant: string = this.parent.localeObj.getConstant('duration');
const startDateVal: Date = data.startDate;
const endDateVal: Date = data.endDate;
const durationVal: number = data.duration;
if (startDateVal) {
defaultValue += startDateConstant + ' ' + this.parent.getFormatedDate(startDateVal) + ' ';
}
if (endDateVal) {
defaultValue += endDateConstant + ' ' + this.parent.getFormatedDate(endDateVal) + ' ';
}
if (durationVal) {
defaultValue += durationConstant + ' '
+ this.parent.getDurationString(durationVal, ganttProp.durationUnit);
}
return defaultValue;
}
private generateTaskLabelAriaLabel(type: string): string {
let label: string = '';
if (type === 'left' && this.parent.labelSettings.leftLabel && !this.leftTaskLabelTemplateFunction) {
label += this.parent.localeObj.getConstant('leftTaskLabel') +
' ' + this.getTaskLabel(this.parent.labelSettings.leftLabel);
} else if (type === 'right' && this.parent.labelSettings.rightLabel && !this.rightTaskLabelTemplateFunction) {
label += this.parent.localeObj.getConstant('rightTaskLabel') +
' ' + this.getTaskLabel(this.parent.labelSettings.rightLabel);
}
return label;
}
} | the_stack |
import Chroma from 'chroma-js'
import { clamp, WindowPoint, roundTo } from '../../../core/shared/math-utils'
import { getControlStyles } from '../common/control-status'
import {
CSSColor,
cssColorToChromaColorOrDefault,
EmptyInputValue,
fallbackOnEmptyInputValueToCSSEmptyValue,
isHex,
isHSL,
isKeyword,
} from '../common/css-utils'
import { checkerboardBackground } from '../common/inspector-utils'
import { inspectorEdgePadding } from '../sections/style-section/background-subsection/background-picker'
import { InspectorModal } from '../widgets/inspector-modal'
import { StringControl } from './string-control'
import React from 'react'
//TODO: switch to functional component and make use of 'useColorTheme':
import { colorTheme, SimpleNumberInput, SimplePercentInput, UtopiaStyles } from '../../../uuiui'
export interface ColorPickerProps extends ColorPickerInnerProps {
closePopup: () => void
portalTarget?: HTMLElement
}
export const colorPickerWidth = 290
export const MetadataEditorModalPreviewHeight = 150
export const GradientStopSize = 24
export const GradientStopCaratSize = 5
export const StopsPadding = GradientStopSize / 2 + inspectorEdgePadding
export const GradientPickerWidth = colorPickerWidth - StopsPadding * 2
export const ColorPicker: React.FunctionComponent<ColorPickerProps> = ({
closePopup,
portalTarget,
...props
}) => {
return (
<InspectorModal
offsetX={props.offsetX - colorPickerWidth}
offsetY={props.offsetY}
closePopup={closePopup}
>
<div
id={props.id}
className='colorPicker-wrapper'
style={{
width: colorPickerWidth,
position: 'absolute',
overflow: 'hidden',
zIndex: 2,
marginBottom: 32,
...UtopiaStyles.popup,
}}
>
<ColorPickerInner {...props} />
</div>
</InspectorModal>
)
}
export interface ColorPickerInnerProps {
value: CSSColor
onSubmitValue: (value: CSSColor) => void
onTransientSubmitValue: (value: CSSColor) => void
offsetX: number
offsetY: number
id: string
testId: string
}
function toPassedInColorType(
color: Chroma.Color,
passedInColor: CSSColor,
stateNormalisedHuePosition: number,
): CSSColor {
if (isKeyword(passedInColor)) {
const name = color.name()
if (name.startsWith('#')) {
return {
type: 'Hex',
hex: name.toUpperCase(),
}
} else {
return {
type: 'Keyword',
keyword: name,
}
}
} else if (isHex(passedInColor)) {
return {
type: 'Hex',
hex: color.hex('auto').toUpperCase(),
}
} else if (isHSL(passedInColor)) {
const [h, s, l, a] = (color.hsl() as any) as [number, number, number, number] // again, the types are out of date
return {
type: 'HSL',
h: getSafeHue(h, stateNormalisedHuePosition),
s: roundTo(s * 100, 0),
l: roundTo(l * 100, 0),
a: a,
percentageAlpha: passedInColor.percentageAlpha,
}
} else {
const [r, g, b, a] = color.rgba()
return {
type: 'RGB',
r: r,
g: g,
b: b,
a: a,
percentageAlpha: passedInColor.percentageAlpha,
percentagesUsed: passedInColor.percentagesUsed,
}
}
}
function deriveStateFromNewColor(
color: Chroma.Color,
stateNormalisedHuePosition: number,
): ColorPickerInnerState {
const [h, s, v] = color.hsv()
return {
normalisedHuePosition: getSafeHue(h, stateNormalisedHuePosition) / 360,
normalisedSaturationPosition: s,
normalisedValuePosition: v,
normalisedAlphaPosition: color.alpha(),
dirty: false,
isScrubbing: false,
}
}
/**
* All shades of grey don't have an HSV hue component, so Chroma returns NaN,
* this safeguards against that.
*/
function getSafeHue(hue: number, stateNormalisedValue: number) {
return Math.round(isNaN(hue) ? stateNormalisedValue * 360 : hue)
}
/**
* State values for the HSVa sliders, normalised to 0.0—1.0.
*/
interface ColorPickerPositions {
normalisedHuePosition: number
normalisedSaturationPosition: number
normalisedValuePosition: number
normalisedAlphaPosition: number
}
export interface ColorPickerInnerState extends ColorPickerPositions {
dirty: boolean
isScrubbing: boolean
}
export class ColorPickerInner extends React.Component<
ColorPickerInnerProps,
ColorPickerInnerState
> {
private RefFirstControl = React.createRef<HTMLInputElement>()
private fullWidth = colorPickerWidth
private fullHeight = MetadataEditorModalPreviewHeight
private paddedWidth = this.fullWidth - inspectorEdgePadding * 2
private SVControlRef = React.createRef<HTMLDivElement>()
private SVOrigin: WindowPoint = { x: 0, y: 0 } as WindowPoint
private HueControlRef = React.createRef<HTMLDivElement>()
private HueOriginLeft: number = 0
private AlphaControlRef = React.createRef<HTMLDivElement>()
private AlphaOriginLeft: number = 0
constructor(props: ColorPickerInnerProps) {
super(props)
// Color values in different spaces need to be stored in state due to them not mapping 1:1 across color spaces. E.g. HSV(0, 0%, 100%) == HSV(180, 0%, 100%). A fully controlled component would be nice, but alas.
const calculatedState = deriveStateFromNewColor(
cssColorToChromaColorOrDefault(this.props.value),
0,
)
this.state = {
...calculatedState,
dirty: false,
isScrubbing: false,
}
}
componentDidMount() {
if (this.RefFirstControl.current != null) {
this.RefFirstControl.current.focus()
}
}
componentWillUnmount() {
document.removeEventListener('mousemove', this.onSVMouseMove)
document.removeEventListener('mouseup', this.onSVMouseUp)
document.removeEventListener('mousemove', this.onHueSliderMouseMove)
document.removeEventListener('mouseup', this.onHueSliderMouseUp)
document.removeEventListener('mousemove', this.onAlphaSliderMouseMove)
document.removeEventListener('mouseup', this.onAlphaSliderMouseUp)
}
static getHexaColorFromControlPositionState(state: ColorPickerInnerState): string {
const h = state.normalisedHuePosition
const s = state.normalisedSaturationPosition
const v = state.normalisedValuePosition
const a = state.normalisedAlphaPosition
return Chroma(h * 360, s, v, 'hsv')
.alpha(a)
.hex('auto')
.toUpperCase()
}
static getDerivedStateFromProps(props: ColorPickerInnerProps, state: ColorPickerInnerState) {
const chroma = cssColorToChromaColorOrDefault(props.value)
if (state.dirty) {
return {
dirty: false,
}
} else {
const controlStateHexa = ColorPickerInner.getHexaColorFromControlPositionState(state)
const newPropsHexa = chroma.hex('auto').toUpperCase()
if (controlStateHexa === newPropsHexa) {
return null
} else {
const newCalculatedState = deriveStateFromNewColor(chroma, state.normalisedHuePosition)
return { ...newCalculatedState, _propsHexa: chroma.hex('auto').toUpperCase() }
}
}
}
componentDidUpdate(prevProps: ColorPickerInnerProps) {
if (this.RefFirstControl.current != null && prevProps.id !== this.props.id) {
this.RefFirstControl.current.focus()
}
}
setNewHSVa = (
h: number = this.state.normalisedHuePosition * 360,
s: number = this.state.normalisedSaturationPosition,
v: number = this.state.normalisedValuePosition,
a: number = this.state.normalisedAlphaPosition,
transient: boolean,
) => {
const newChromaValue = Chroma(h, s, v, 'hsv').alpha(a)
const newHex = newChromaValue.hex('auto').toUpperCase()
this.setState({
normalisedHuePosition: h / 360,
normalisedSaturationPosition: s,
normalisedValuePosition: v,
normalisedAlphaPosition: a,
dirty: true,
})
this.submitNewColor(newChromaValue, transient)
}
setNewHex = (newHex: string) => {
try {
const newChromaValue = Chroma.hex(newHex)
const newHSV = newChromaValue.hsv()
this.setState((state) => ({
normalisedHuePosition: getSafeHue(newHSV[0], state.normalisedHuePosition) / 360,
normalisedSaturationPosition: newHSV[1],
normalisedValuePosition: newHSV[2],
hexa: newChromaValue.hex('auto').toUpperCase(),
normalisedAlphaPosition: newChromaValue.alpha(),
dirty: true,
isScrubbing: state.isScrubbing,
}))
this.submitNewColor(newChromaValue, false)
} catch (e) {
console.warn(e)
}
}
submitNewColor = (chromaColor: Chroma.Color, transient: boolean) => {
const newValue = toPassedInColorType(
chromaColor,
this.props.value,
this.state.normalisedHuePosition,
)
if (transient) {
this.props.onTransientSubmitValue(newValue)
} else {
this.props.onSubmitValue(newValue)
}
}
// Saturation and Value (SV) slider functions
setSVFromClientPosition = (clientX: number, clientY: number, transient: boolean) => {
const x = clamp(0, this.fullWidth, clientX - this.SVOrigin.x)
const y = clamp(0, this.fullHeight, clientY - this.SVOrigin.y)
const newS = x / this.fullWidth
const newV = 1 - y / this.fullHeight
this.setNewHSVa(undefined, newS, newV, undefined, transient)
}
onMouseDownSV = (e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation()
this.setState({
isScrubbing: true,
})
if (this.SVControlRef.current != null) {
const origin = this.SVControlRef.current.getBoundingClientRect()
this.SVOrigin = { x: origin.left, y: origin.top } as WindowPoint
this.setSVFromClientPosition(e.clientX, e.clientY, true)
document.addEventListener('mousemove', this.onSVMouseMove)
document.addEventListener('mouseup', this.onSVMouseUp)
}
}
onSVMouseMove = (e: MouseEvent) => {
e.stopPropagation()
this.setSVFromClientPosition(e.clientX, e.clientY, true)
}
onSVMouseUp = (e: MouseEvent) => {
this.setSVFromClientPosition(e.clientX, e.clientY, false)
document.removeEventListener('mousemove', this.onSVMouseMove)
document.removeEventListener('mouseup', this.onSVMouseUp)
this.setState({
isScrubbing: false,
})
e.stopPropagation()
}
// Hue slider functions
setHueFromClientX = (clientX: number, transient: boolean) => {
const x = clamp(0, this.paddedWidth, clientX - this.HueOriginLeft)
const newHue = Math.round(360 * (x / this.paddedWidth))
this.setNewHSVa(newHue, undefined, undefined, undefined, transient)
}
onHueSliderMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation()
if (this.HueControlRef.current != null) {
this.HueOriginLeft = this.HueControlRef.current.getBoundingClientRect().left
const clientX = e.clientX
this.setHueFromClientX(clientX, true)
this.setState({
isScrubbing: true,
})
document.addEventListener('mousemove', this.onHueSliderMouseMove)
document.addEventListener('mouseup', this.onHueSliderMouseUp)
}
}
onHueSliderMouseMove = (e: MouseEvent) => {
e.stopPropagation()
this.setHueFromClientX(e.clientX, true)
}
onHueSliderMouseUp = (e: MouseEvent) => {
this.setHueFromClientX(e.clientX, false)
document.removeEventListener('mousemove', this.onHueSliderMouseMove)
document.removeEventListener('mouseup', this.onHueSliderMouseUp)
this.setState({
isScrubbing: false,
})
e.stopPropagation()
}
// Alpha slider functions
setAlphaFromClientX = (clientX: number, transient: boolean) => {
const x = clamp(0, this.paddedWidth, clientX - this.AlphaOriginLeft)
const newAlpha = Number((x / this.paddedWidth).toFixed(2))
this.setNewHSVa(undefined, undefined, undefined, newAlpha, transient)
}
onAlphaSliderMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation()
if (this.AlphaControlRef.current != null) {
this.setState({
isScrubbing: true,
})
this.AlphaOriginLeft = this.AlphaControlRef.current.getBoundingClientRect().left
const clientX = e.clientX
this.setAlphaFromClientX(clientX, true)
document.addEventListener('mousemove', this.onAlphaSliderMouseMove)
document.addEventListener('mouseup', this.onAlphaSliderMouseUp)
}
}
onAlphaSliderMouseMove = (e: MouseEvent) => {
e.stopPropagation()
this.setAlphaFromClientX(e.clientX, true)
}
onAlphaSliderMouseUp = (e: MouseEvent) => {
this.setAlphaFromClientX(e.clientX, false)
document.removeEventListener('mousemove', this.onAlphaSliderMouseMove)
document.removeEventListener('mouseup', this.onAlphaSliderMouseUp)
this.setState({
isScrubbing: false,
})
}
// SubmitValue functions
onSubmitValueHue = (value: number | EmptyInputValue) => {
const newHue = getSafeHue(
fallbackOnEmptyInputValueToCSSEmptyValue(0, value),
this.state.normalisedHuePosition,
)
this.setNewHSVa(newHue, undefined, undefined, undefined, false)
}
onTransientSubmitValueHue = (value: number | EmptyInputValue) => {
const newHue = getSafeHue(
fallbackOnEmptyInputValueToCSSEmptyValue(0, value),
this.state.normalisedHuePosition,
)
this.setNewHSVa(newHue, undefined, undefined, undefined, true)
}
onSubmitValueSaturation = (value: number | EmptyInputValue) => {
const newSaturation = Number(fallbackOnEmptyInputValueToCSSEmptyValue(100, value).toFixed(2))
this.setNewHSVa(undefined, newSaturation, undefined, undefined, false)
}
onTransientSubmitValueSaturation = (value: number | EmptyInputValue) => {
const newSaturation = Number(fallbackOnEmptyInputValueToCSSEmptyValue(100, value).toFixed(2))
this.setNewHSVa(undefined, newSaturation, undefined, undefined, true)
}
onSubmitHSVValueValue = (value: number | EmptyInputValue) => {
const newValue = Number(fallbackOnEmptyInputValueToCSSEmptyValue(100, value).toFixed(2))
this.setNewHSVa(undefined, undefined, newValue, undefined, false)
}
onTransientSubmitHSVValueValue = (value: number | EmptyInputValue) => {
const newValue = Number(fallbackOnEmptyInputValueToCSSEmptyValue(100, value).toFixed(2))
this.setNewHSVa(undefined, undefined, newValue, undefined, true)
}
onSubmitValueAlpha = (value: number | EmptyInputValue) => {
const newValue = Number(fallbackOnEmptyInputValueToCSSEmptyValue(100, value).toFixed(2))
this.setNewHSVa(undefined, undefined, undefined, newValue, false)
}
onTransientSubmitValueAlpha = (value: number | EmptyInputValue) => {
const newValue = Number(fallbackOnEmptyInputValueToCSSEmptyValue(100, value).toFixed(2))
this.setNewHSVa(undefined, undefined, undefined, newValue, true)
}
onSubmitValueHex = (newValue: string) => {
this.setNewHex(newValue)
}
render() {
const h = this.state.normalisedHuePosition
const s = this.state.normalisedSaturationPosition
const v = this.state.normalisedValuePosition
const hueColor = Chroma(h * 360, 1, 1, 'hsv').css()
const chroma = Chroma(h * 360, s, v, 'hsv').alpha(this.state.normalisedAlphaPosition)
const cssWithAlpha = chroma.css()
const cssWith1Alpha = chroma.alpha(1).css()
const cssWith0Alpha = chroma.alpha(0).css()
const hsvHue = `
linear-gradient(to right,
red 0%,
yellow 16.66%,
lime 33.33%,
aqua 50%,
blue 66.66%,
fuchsia 83.33%,
red 100%
)`
return (
<div style={{ position: 'relative' }}>
<div>
<div
className='colorPicker-saturation-and-value'
onMouseDown={this.onMouseDownSV}
ref={this.SVControlRef}
style={{
height: MetadataEditorModalPreviewHeight,
width: '100%',
backgroundColor: hueColor,
backgroundImage: `
linear-gradient(to top, #000, rgba(0, 0, 0, 0)),
linear-gradient(to right, #fff, rgba(255, 255, 255, 0))`,
paddingBottom: 4,
position: 'relative',
display: 'flex',
flexWrap: 'wrap',
}}
>
<div
className='colorPicker-saturation-and-value-indicator'
style={{
width: 8,
height: 8,
backgroundColor: cssWith1Alpha,
borderRadius: '50%',
boxShadow:
'inset 0 0 1px rgba(0, 0, 0, 0.24), 0 0 0 2px white, 0 0 2px 2px rgba(0, 0, 0, 0.24)',
position: 'absolute',
margin: -4,
left: `${this.state.normalisedSaturationPosition * 100}%`,
top: `${(1 - this.state.normalisedValuePosition) * 100}%`,
pointerEvents: 'none',
}}
/>
</div>
<div
style={{
padding: inspectorEdgePadding,
}}
>
<div
className='colorPicker-hue'
ref={this.HueControlRef}
onMouseDown={this.onHueSliderMouseDown}
style={{
height: 20,
width: '100%',
borderRadius: 4,
boxShadow: `0 0 0 1px ${colorTheme.neutralBorder.value} inset`,
backgroundImage: hsvHue,
padding: '0 4px',
}}
>
<div style={{ position: 'relative' }}>
<div
className='colorPicker-hue-indicator'
style={{
width: 8,
height: 20,
backgroundColor: hueColor,
borderRadius: 1,
boxShadow: `inset 0 0 1px rgba(0, 0, 0, 0.24), 0px 0px 0px 2px white, 0px 0px 2px 2px rgba(0, 0, 0, 0.239216)`,
position: 'absolute',
margin: '0 -4px',
left: `${this.state.normalisedHuePosition * 100}%`,
top: 0,
pointerEvents: 'none',
}}
/>
</div>
</div>
<div
className='colorPicker-alpha'
ref={this.AlphaControlRef}
onMouseDown={this.onAlphaSliderMouseDown}
style={{
height: 20,
width: '100%',
backgroundColor: 'white',
borderRadius: 4,
boxShadow: `0 0 0 1px ${colorTheme.neutralBorder.value} inset`,
backgroundImage: `
linear-gradient(to right, ${cssWith0Alpha} 0%, ${cssWith1Alpha} 100%),
${checkerboardBackground.backgroundImage}`,
backgroundSize: `100% 100%, ${checkerboardBackground.backgroundSize}`,
backgroundPosition: `0 0, ${checkerboardBackground.backgroundPosition}`,
marginTop: 10,
padding: '0 4px',
}}
>
<div style={{ position: 'relative' }}>
<div
className='colorPicker-alpha-indicator'
style={{
width: 8,
height: 20,
backgroundImage: `
linear-gradient(${cssWithAlpha}, ${cssWithAlpha}),
${checkerboardBackground.backgroundImage},
linear-gradient(white, white)`,
backgroundSize: `100% 100%, ${checkerboardBackground.backgroundSize}, 100% 100%`,
backgroundPosition: `0 0, ${checkerboardBackground.backgroundPosition}, 0 0`,
borderRadius: 1,
boxShadow: `inset 0 0 1px rgba(0, 0, 0, 0.24), 0px 0px 0px 2px white, 0px 0px 2px 2px rgba(0, 0, 0, 0.239216)`,
position: 'absolute',
margin: '0 -4px',
left: `${this.state.normalisedAlphaPosition * 100}%`,
top: 0,
pointerEvents: 'none',
}}
/>
</div>
</div>
</div>
<div
className='colorPicker-controls'
style={{
display: 'grid',
gridTemplateColumns: '80px repeat(4, 1fr)',
columnGap: 4,
padding: '0 8px 8px',
}}
>
<StringControl
ref={this.RefFirstControl}
key={this.props.id}
value={chroma.hex('auto').toUpperCase()}
onSubmitValue={this.onSubmitValueHex}
controlStatus='simple'
controlStyles={getControlStyles('simple')}
id='colorPicker-controls-hex'
testId={`${this.props.testId}-colorPicker-controls-hex`}
style={{
gridColumn: 'span 1',
}}
DEPRECATED_controlOptions={{ DEPRECATED_labelBelow: 'Hex' }}
/>
<SimpleNumberInput
value={this.state.normalisedHuePosition * 360}
id='colorPicker-controls-hue'
testId={`${this.props.testId}-colorPicker-controls-hue`}
onSubmitValue={this.onSubmitValueHue}
onTransientSubmitValue={this.onTransientSubmitValueHue}
onForcedSubmitValue={this.onSubmitValueHue}
minimum={0}
maximum={360}
DEPRECATED_labelBelow='H'
labelInner={{
category: 'layout/systems',
type: 'transform-rotate',
color: 'secondary',
width: 10,
height: 10,
}}
defaultUnitToHide={null}
/>
<SimplePercentInput
value={Number(this.state.normalisedSaturationPosition.toFixed(2))}
id='colorPicker-controls-saturation'
testId={`${this.props.testId}-colorPicker-controls-saturation`}
onSubmitValue={this.onSubmitValueSaturation}
onTransientSubmitValue={this.onTransientSubmitValueSaturation}
onForcedSubmitValue={this.onSubmitValueSaturation}
style={{ gridColumn: 'span 1' }}
minimum={0}
maximum={1}
stepSize={0.01}
DEPRECATED_labelBelow='S'
defaultUnitToHide={null}
/>
<SimplePercentInput
value={Number(this.state.normalisedValuePosition.toFixed(2))}
id='colorPicker-controls-value'
testId={`${this.props.testId}-colorPicker-controls-value`}
onSubmitValue={this.onSubmitHSVValueValue}
onTransientSubmitValue={this.onTransientSubmitHSVValueValue}
onForcedSubmitValue={this.onSubmitHSVValueValue}
style={{ gridColumn: 'span 1' }}
minimum={0}
maximum={1}
stepSize={0.01}
DEPRECATED_labelBelow='V'
defaultUnitToHide={null}
/>
<SimplePercentInput
value={this.state.normalisedAlphaPosition}
id='colorPicker-controls-alpha'
testId={`${this.props.testId}-colorPicker-controls-alpha`}
onSubmitValue={this.onSubmitValueAlpha}
onTransientSubmitValue={this.onTransientSubmitValueAlpha}
onForcedSubmitValue={this.onSubmitValueAlpha}
style={{ gridColumn: 'span 1' }}
minimum={0}
maximum={1}
stepSize={0.01}
DEPRECATED_labelBelow='A'
defaultUnitToHide={null}
/>
</div>
</div>
{/* hover preventer: don't trigger other hover events while sliding / scrubbing */}
{this.state.isScrubbing ? (
<div
style={{
position: 'fixed',
left: 0,
top: 0,
right: 0,
bottom: 0,
background: 'transparent',
}}
/>
) : null}
</div>
)
}
} | the_stack |
import {
ConfiguredDocumentClass,
ConfiguredFlags,
FieldReturnType,
PropertiesToSource
} from '../../../../types/helperTypes';
import EmbeddedCollection from '../../abstract/embedded-collection.mjs';
import { DocumentData } from '../../abstract/module.mjs';
import * as documents from '../../documents.mjs';
import * as fields from '../fields.mjs';
import { AmbientLightDataConstructorData } from './ambientLightData';
import { AmbientSoundDataConstructorData } from './ambientSoundData';
import { DrawingDataConstructorData } from './drawingData';
import { MeasuredTemplateDataConstructorData } from './measuredTemplateData';
import { NoteDataConstructorData } from './noteData';
import { TileDataConstructorData } from './tileData';
import { TokenDataConstructorData } from './tokenData';
import { WallDataConstructorData } from './wallData';
interface SceneDataSchema extends DocumentSchema {
_id: fields.DocumentId;
name: fields.RequiredString;
active: fields.BooleanField;
navigation: FieldReturnType<fields.BooleanField, { default: true }>;
navOrder: fields.IntegerSortField;
navName: fields.BlankString;
img: fields.VideoField;
foreground: fields.VideoField;
thumb: fields.ImageField;
width: FieldReturnType<fields.PositiveIntegerField, { required: true; default: 4000 }>;
height: FieldReturnType<fields.PositiveIntegerField, { required: true; default: 3000 }>;
padding: DocumentField<Number> & {
type: typeof Number;
required: true;
default: 0.25;
validate: (p: unknown) => boolean;
validation: 'Invalid {name} {field} which must be a number between 0 and 0.5';
};
initial: DocumentField<Object> & {
type: typeof Object;
required: false;
nullable: true;
default: null;
validate: typeof _validateInitialViewPosition;
validationError: 'Invalid initial view position object provided for Scene';
};
backgroundColor: FieldReturnType<fields.ColorField, { required: true; default: '#999999' }>;
gridType: FieldReturnType<
fields.RequiredNumber,
{
default: typeof foundry.CONST.GRID_TYPES.SQUARE;
validate: (t: unknown) => t is foundry.CONST.GRID_TYPES;
validationError: 'Invalid {name } {field} which must be a value in CONST.GRID_TYPES';
}
>;
grid: DocumentField<Number> & {
type: typeof Number;
required: true;
default: 100;
validate: (n: unknown) => boolean;
validationError: `Invalid {name} {field} which must be an integer number of pixels, ${typeof foundry.CONST.GRID_MIN_SIZE} or greater`;
};
shiftX: FieldReturnType<fields.IntegerField, { required: true; default: 0 }>;
shiftY: FieldReturnType<fields.IntegerField, { required: true; default: 0 }>;
gridColor: FieldReturnType<fields.ColorField, { required: true; default: '#000000' }>;
gridAlpha: FieldReturnType<fields.AlphaField, { required: true; default: 0.2 }>;
gridDistance: FieldReturnType<fields.RequiredPositiveNumber, { default: () => number }>;
gridUnits: FieldReturnType<fields.BlankString, { default: () => string }>;
tokenVision: FieldReturnType<fields.BooleanField, { default: true }>;
fogExploration: FieldReturnType<fields.BooleanField, { default: true }>;
fogReset: fields.TimestampField;
globalLight: fields.BooleanField;
globalLightThreshold: DocumentField<Number> & {
type: typeof Number;
required: true;
nullable: true;
default: null;
validate: (n: unknown) => boolean;
validationError: 'Invalid {name} {field} which must be null, or a number between 0 and 1';
};
darkness: FieldReturnType<fields.AlphaField, { default: 0 }>;
drawings: fields.EmbeddedCollectionField<typeof documents.BaseDrawing>;
tokens: fields.EmbeddedCollectionField<typeof documents.BaseToken>;
lights: fields.EmbeddedCollectionField<typeof documents.BaseAmbientLight>;
notes: fields.EmbeddedCollectionField<typeof documents.BaseNote>;
sounds: fields.EmbeddedCollectionField<typeof documents.BaseAmbientSound>;
templates: fields.EmbeddedCollectionField<typeof documents.BaseMeasuredTemplate>;
tiles: fields.EmbeddedCollectionField<typeof documents.BaseTile>;
walls: fields.EmbeddedCollectionField<typeof documents.BaseWall>;
playlist: fields.ForeignDocumentField<{ type: typeof documents.BasePlaylist; required: false }>;
playlistSound: fields.ForeignDocumentField<{ type: typeof documents.BasePlaylistSound; required: false }>;
journal: fields.ForeignDocumentField<{ type: typeof documents.BaseJournalEntry; required: false }>;
weather: fields.BlankString;
folder: fields.ForeignDocumentField<{ type: typeof documents.BaseFolder }>;
sort: fields.IntegerSortField;
permission: fields.DocumentPermissions;
flags: fields.ObjectField;
}
interface SceneDataProperties {
/**
* The _id which uniquely identifies this Scene document
* @defaultValue `null`
*/
_id: string | null;
/**
* The name of this scene
*/
name: string;
/**
* Is this scene currently active? Only one scene may be active at a given time.
* @defaultValue `false`
*/
active: boolean;
/**
* Is this scene displayed in the top navigation bar?
* @defaultValue `true`
*/
navigation: boolean;
/**
* The integer sorting order of this Scene in the navigation bar relative to others
* @defaultValue `0`
*/
navOrder: number;
/**
* A string which overrides the canonical Scene name which is displayed in the navigation bar
* @defaultValue `""`
*/
navName: string;
/**
* An image or video file path which provides the background media for the scene
*/
img: string | null | undefined;
/**
* An image or video file path which is drawn on top of all other elements in the scene
*/
foreground: string | null | undefined;
/**
* A thumbnail image (base64) or file path which visually summarizes the scene
*/
thumb: string | null | undefined;
/**
* The width of the scene canvas, this should normally be the width of the background media
* @defaultValue `4000`
*/
width: number;
/**
* The height of the scene canvas, this should normally be the height of the background media
* @defaultValue `3000`
*/
height: number;
/**
* The proportion of canvas padding applied around the outside of the scene
* dimensions to provide additional buffer space
* @defaultValue `0.25`
*/
padding: number;
/**
* The initial view coordinates for the scene, or null
* @defaultValue `null`
*/
initial: { x: number; y: number; scale: number } | null;
/**
* The color of the canvas which is displayed behind the scene background
* @defaultValue `'#999999'`
*/
backgroundColor: string | null;
/**
* The type of grid used in this scene, a number from CONST.GRID_TYPES
* @defaultValue `CONST.GRID_TYPES.SQUARE`
*/
gridType: foundry.CONST.GRID_TYPES;
/**
* The grid size which represents the width (or height) of a single grid space
* @defaultValue `100`
*/
grid: number;
/**
* A number of offset pixels that the background image is shifted horizontally relative to the grid
* @defaultValue `0`
*/
shiftX: number;
/**
* A number of offset pixels that the background image is shifted vertically relative to the grid
* @defaultValue `0`
*/
shiftY: number;
/**
* A string representing the color used to render the grid lines
* @defaultValue `'#000000'`
*/
gridColor: string | null;
/**
* A number between 0 and 1 for the opacity of the grid lines
* @defaultValue `0.2`
*/
gridAlpha: number;
/**
* The number of distance units which are represented by a single grid space.
* @defaultValue `game.system.data.gridDistance || 1`
*/
gridDistance: number;
/**
* A label for the units of measure which are used for grid distance.
* @defaultValue `game.system.data.gridUnits ?? ""`
*/
gridUnits: string;
/**
* Do Tokens require vision in order to see the Scene environment?
* @defaultValue `true`
*/
tokenVision: boolean;
/**
* Should fog exploration progress be tracked for this Scene?
* @defaultValue `true`
*/
fogExploration: boolean;
/**
* The timestamp at which fog of war was last reset for this Scene.
* @defaultValue `Date.now()`
*/
fogReset: number;
/**
* Does this Scene benefit from global illumination which provides bright light everywhere?
* @defaultValue `false`
*/
globalLight: boolean;
/**
* A darkness level between 0 and 1, beyond which point global illumination is
* temporarily disabled if globalLight is true.
* @defaultValue `null`
*/
globalLightThreshold: number | null;
/**
* The ambient darkness level in this Scene, where 0 represents mid-day
* (maximum illumination) and 1 represents mid-night (maximum darkness)
* @defaultValue `0`
*/
darkness: number;
/**
* A collection of embedded Drawing objects.
* @defaultValue `new EmbeddedCollection(DrawingData, [], BaseDrawing.implementation)`
*/
drawings: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseDrawing>, SceneData>;
/**
* A collection of embedded Token objects.
* @defaultValue `new EmbeddedCollection(TokenData, [], BaseToken.implementation)`
*/
tokens: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseToken>, SceneData>;
/**
* A collection of embedded AmbientLight objects.
* @defaultValue `new EmbeddedCollection(AmbientLightData, [], BaseAmbientLight.implementation)`
*/
lights: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseAmbientLight>, SceneData>;
/**
* A collection of embedded Note objects.
* @defaultValue `new EmbeddedCollection(NoteData, [], BaseNote.implementation)`
*/
notes: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseNote>, SceneData>;
/**
* A collection of embedded AmbientSound objects.
* @defaultValue `new EmbeddedCollection(AmbientSoundData, [], BaseAmbientSound.implementation)`
*/
sounds: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseAmbientSound>, SceneData>;
/**
* A collection of embedded MeasuredTemplate objects.
* @defaultValue `new EmbeddedCollection(MeasuredTemplateData, [], BaseMeasuredTemplate.implementation)`
*/
templates: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseMeasuredTemplate>, SceneData>;
/**
* A collection of embedded Tile objects.
* @defaultValue `new EmbeddedCollection(TileData, [], BaseTile.implementation)`
*/
tiles: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseTile>, SceneData>;
/**
* A collection of embedded Wall objects
* @defaultValue `new EmbeddedCollection(WallData, [], BaseWall.implementation)`
*/
walls: EmbeddedCollection<ConfiguredDocumentClass<typeof documents.BaseWall>, SceneData>;
/**
* A linked Playlist document which should begin automatically playing when this
* Scene becomes active.
* @defaultValue `null`
*/
playlist: string | null;
/**
* A linked PlaylistSound document from the selected playlist that will
* begin automatically playing when this Scene becomes active.
* @defaultValue `null`
*/
playlistSound: string | null;
/**
* A linked JournalEntry document which provides narrative details about this Scene.
* @defaultValue `null`
*/
journal: string | null;
/**
* A named weather effect which should be rendered in this Scene.
* @defaultValue `""`
*/
weather: string;
/**
* The _id of a Folder which contains this Actor
* @defaultValue `null`
*/
folder: string | null;
/**
* The numeric sort value which orders this Actor relative to its siblings
* @defaultValue `0`
*/
sort: number;
/**
* An object which configures user permissions to this Scene
* @defaultValue `{ default: CONST.ENTITY_PERMISSIONS.NONE }`
*/
permission: Partial<Record<string, foundry.CONST.DOCUMENT_PERMISSION_LEVELS>>;
/**
* An object of optional key/value flags
*/
flags: ConfiguredFlags<'Scene'>;
}
interface SceneDataConstructorData {
/**
* The _id which uniquely identifies this Scene document
* @defaultValue `null`
*/
_id?: string | null | undefined;
/**
* The name of this scene
*/
name: string;
/**
* Is this scene currently active? Only one scene may be active at a given time.
* @defaultValue `false`
*/
active?: boolean | null | undefined;
/**
* Is this scene displayed in the top navigation bar?
* @defaultValue `true`
*/
navigation?: boolean | null | undefined;
/**
* The integer sorting order of this Scene in the navigation bar relative to others
* @defaultValue `0`
*/
navOrder?: number | null | undefined;
/**
* A string which overrides the canonical Scene name which is displayed in the navigation bar
* @defaultValue `""`
*/
navName?: string | null | undefined;
/**
* An image or video file path which provides the background media for the scene
*/
img?: string | null | undefined;
/**
* An image or video file path which is drawn on top of all other elements in the scene
*/
foreground?: string | null | undefined;
/**
* A thumbnail image (base64) or file path which visually summarizes the scene
*/
thumb?: string | null | undefined;
/**
* The width of the scene canvas, this should normally be the width of the background media
* @defaultValue `4000`
*/
width?: number | null | undefined;
/**
* The height of the scene canvas, this should normally be the height of the background media
* @defaultValue `3000`
*/
height?: number | null | undefined;
/**
* The proportion of canvas padding applied around the outside of the scene
* dimensions to provide additional buffer space
* @defaultValue `0.25`
*/
padding?: number | null | undefined;
/**
* The initial view coordinates for the scene, or null
* @defaultValue `null`
*/
initial?: { x: number; y: number; scale: number } | null | undefined;
/**
* The color of the canvas which is displayed behind the scene background
* @defaultValue `#999999`
*/
backgroundColor?: string | null | undefined;
/**
* The type of grid used in this scene, a number from CONST.GRID_TYPES
* @defaultValue `CONST.GRID_TYPES.SQUARE`
*/
gridType?: foundry.CONST.GRID_TYPES | null | undefined;
/**
* The grid size which represents the width (or height) of a single grid space
* @defaultValue `100`
*/
grid?: number | null | undefined;
/**
* A number of offset pixels that the background image is shifted horizontally relative to the grid
* @defaultValue `0`
*/
shiftX?: number | null | undefined;
/**
* A number of offset pixels that the background image is shifted vertically relative to the grid
* @defaultValue `0`
*/
shiftY?: number | null | undefined;
/**
* A string representing the color used to render the grid lines
* @defaultValue `#000000`
*/
gridColor?: string | null | undefined;
/**
* A number between 0 and 1 for the opacity of the grid lines
* @defaultValue `0.2`
*/
gridAlpha?: number | null | undefined;
/**
* The number of distance units which are represented by a single grid space.
* @defaultValue `game.system.data.gridDistance || 1`
*/
gridDistance?: number | null | undefined;
/**
* A label for the units of measure which are used for grid distance.
* @defaultValue `game.system.data.gridUnits ?? ""`
*/
gridUnits?: string | null | undefined;
/**
* Do Tokens require vision in order to see the Scene environment?
* @defaultValue `true`
*/
tokenVision?: boolean | null | undefined;
/**
* Should fog exploration progress be tracked for this Scene?
* @defaultValue `true`
*/
fogExploration?: boolean | null | undefined;
/**
* The timestamp at which fog of war was last reset for this Scene.
* @defaultValue `Date.now()`
*/
fogReset?: number | null | undefined;
/**
* Does this Scene benefit from global illumination which provides bright light everywhere?
* @defaultValue `false`
*/
globalLight?: boolean | null | undefined;
/**
* A darkness level between 0 and 1, beyond which point global illumination is
* temporarily disabled if globalLight is true.
* @defaultValue `null`
*/
globalLightThreshold?: number | null | undefined;
/**
* The ambient darkness level in this Scene, where 0 represents mid-day
* (maximum illumination) and 1 represents mid-night (maximum darkness)
* @defaultValue `0`
*/
darkness?: number | null | undefined;
/**
* A collection of embedded Drawing objects.
* @defaultValue `new EmbeddedCollection(DrawingData, [], BaseDrawing.implementation)`
*/
drawings?: DrawingDataConstructorData[] | null | undefined;
/**
* A collection of embedded Token objects.
* @defaultValue `new EmbeddedCollection(TokenData, [], BaseToken.implementation)`
*/
tokens?: TokenDataConstructorData[] | null | undefined;
/**
* A collection of embedded AmbientLight objects.
* @defaultValue `new EmbeddedCollection(AmbientLightData, [], BaseAmbientLight.implementation)`
*/
lights?: AmbientLightDataConstructorData[] | null | undefined;
/**
* A collection of embedded Note objects.
* @defaultValue `new EmbeddedCollection(NoteData, [], BaseNote.implementation)`
*/
notes?: NoteDataConstructorData[] | null | undefined;
/**
* A collection of embedded AmbientSound objects.
* @defaultValue `new EmbeddedCollection(AmbientSoundData, [], BaseAmbientSound.implementation)`
*/
sounds?: AmbientSoundDataConstructorData[] | null | undefined;
/**
* A collection of embedded MeasuredTemplate objects.
* @defaultValue `new EmbeddedCollection(MeasuredTemplateData, [], BaseMeasuredTemplate.implementation)`
*/
templates?: MeasuredTemplateDataConstructorData[] | null | undefined;
/**
* A collection of embedded Tile objects.
* @defaultValue `new EmbeddedCollection(TileData, [], BaseTile.implementation)`
*/
tiles?: TileDataConstructorData[] | null | undefined;
/**
* A collection of embedded Wall objects
* @defaultValue `new EmbeddedCollection(WallData, [], BaseWall.implementation)`
*/
walls?: WallDataConstructorData[] | null | undefined;
/**
* A linked Playlist document which should begin automatically playing when this
* Scene becomes active.
* @defaultValue `null`
*/
playlist?: InstanceType<ConfiguredDocumentClass<typeof documents.BasePlaylist>> | string | null | undefined;
/**
* A linked PlaylistSound document from the selected playlist that will
* begin automatically playing when this Scene becomes active.
* @defaultValue `null`
*/
playlistSound?: InstanceType<ConfiguredDocumentClass<typeof documents.BasePlaylistSound>> | string | null | undefined;
/**
* A linked JournalEntry document which provides narrative details about this Scene.
* @defaultValue `null`
*/
journal?: InstanceType<ConfiguredDocumentClass<typeof documents.BaseJournalEntry>> | string | null | undefined;
/**
* A named weather effect which should be rendered in this Scene.
* @defaultValue `""`
*/
weather?: string | null | undefined;
/**
* The _id of a Folder which contains this Actor
* @defaultValue `null`
*/
folder?: InstanceType<ConfiguredDocumentClass<typeof documents.BaseFolder>> | string | null | undefined;
/**
* The numeric sort value which orders this Actor relative to its siblings
* @defaultValue `0`
*/
sort?: number | null | undefined;
/**
* An object which configures user permissions to this Scene
* @defaultValue `{ default: CONST.ENTITY_PERMISSIONS.NONE }`
*/
permission?: Partial<Record<string, foundry.CONST.DOCUMENT_PERMISSION_LEVELS>> | null | undefined;
/**
* An object of optional key/value flags
*/
flags?: ConfiguredFlags<'Scene'> | null | undefined;
}
/**
* The data schema for a Scene document.
* @see BaseScene
*/
export class SceneData extends DocumentData<
SceneDataSchema,
SceneDataProperties,
PropertiesToSource<SceneDataProperties>,
SceneDataConstructorData,
documents.BaseScene
> {
/**
* @remarks This override does not exist in foundry but is added here to prevent runtime errors.
*/
constructor(data: SceneDataConstructorData, document?: documents.BaseScene | null);
/** @override */
static defineSchema(): SceneDataSchema;
/** @override */
protected _initialize(): void;
size: number;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SceneData extends SceneDataProperties {}
/**
* Verify that the initial view position for a Scene is valid
* @param pos - The scene position object, or null
* @returns Is the position valid?
*/
declare function _validateInitialViewPosition(pos: unknown): pos is { x: number; y: number; scale: number } | null; | the_stack |
import type {
Pine as PineBase,
PineStrict as PineStrictBase,
} from '../typings/balena-pine';
import type { BalenaRequest, Interceptor } from '../typings/balena-request';
import type { ResourceTypeMap } from './types/models';
import { globalEnv } from './util/global-env';
export type Pine = PineBase<ResourceTypeMap>;
export type PineStrict = PineStrictBase<ResourceTypeMap>;
export * from './types/models';
export * from './types/jwt';
export * from './types/contract';
export type { Interceptor };
export type {
WithId,
PineDeferred,
NavigationResource,
OptionalNavigationResource,
ReverseNavigationResource,
ParamsObj as PineParams,
ParamsObjWithId as PineParamsWithId,
Filter as PineFilter,
Expand as PineExpand,
ODataOptions as PineOptions,
SubmitBody as PineSubmitBody,
ODataOptionsWithFilter as PineOptionsWithFilter,
ODataOptionsWithSelect as PineOptionsWithSelect,
SelectableProps as PineSelectableProps,
ExpandableProps as PineExpandableProps,
ExpandResultObject as PineExpandResultObject,
TypedResult as PineTypedResult,
} from '../typings/pinejs-client-core';
// TODO: Drop in the next major
/** @deprecated */
export type PineWithSelectOnGet = PineStrict;
export type { ApplicationMembershipCreationOptions } from './models/application-membership';
export type { ApplicationInviteOptions } from './models/application-invite';
export type {
BankAccountBillingInfo,
BillingAccountAddressInfo,
BillingAccountInfo,
BillingAddonPlanInfo,
BillingInfo,
BillingInfoType,
BillingPlanBillingInfo,
BillingPlanInfo,
CardBillingInfo,
InvoiceInfo,
PlanChangeOptions,
TokenBillingSubmitInfo,
} from './models/billing';
export type { GaConfig, Config, DeviceTypeJson } from './models/config';
export type {
DeviceState,
DeviceMetrics,
OverallStatus,
SupervisorStatus,
} from './models/device';
export type {
OsTypes,
OsLines,
OsVersion,
OsVersionsByDeviceType,
} from './models/hostapp';
export type { ReleaseWithImageDetails } from './models/release';
export type { OrganizationMembershipCreationOptions } from './models/organization-membership';
export type { OrganizationInviteOptions } from './models/organization-invite';
export type {
ImgConfigOptions,
OsVersions,
OsUpdateVersions,
} from './models/os';
export type { OsUpdateActionResult } from './util/device-actions/os-update';
export type { BuilderUrlDeployOptions } from './util/builder';
export type {
CurrentService,
CurrentServiceWithCommit,
CurrentGatewayDownload,
DeviceWithServiceDetails,
} from './util/device-service-details';
export type {
BaseLog,
ServiceLog,
SystemLog,
LogMessage,
LogsSubscription,
LogsOptions,
} from './logs';
export interface InjectedDependenciesParam {
sdkInstance: BalenaSDK;
settings: {
get(key: string): string;
getAll(): { [key: string]: string };
};
request: BalenaRequest;
auth: import('balena-auth').default;
pine: Pine;
pubsub: import('./util/pubsub').PubSub;
}
export interface SdkOptions {
apiUrl?: string;
builderUrl?: string;
dashboardUrl?: string;
dataDirectory?: string;
isBrowser?: boolean;
debug?: boolean;
deviceUrlsBase?: string;
}
export interface InjectedOptionsParam extends SdkOptions {
apiUrl: string;
apiVersion: string;
}
// These constants are used to create globals for sharing defualt options between
// multiple instances of the SDK.
// See the `setSharedOptions()` and `fromSharedOptions()` methods.
const BALENA_SDK_SHARED_OPTIONS = 'BALENA_SDK_SHARED_OPTIONS';
const BALENA_SDK_HAS_USED_SHARED_OPTIONS = 'BALENA_SDK_HAS_USED_SHARED_OPTIONS';
const BALENA_SDK_HAS_SET_SHARED_OPTIONS = 'BALENA_SDK_HAS_SET_SHARED_OPTIONS';
const sdkTemplate = {
auth() {
const { addCallbackSupportToModuleFactory } =
require('./util/callbacks') as typeof import('./util/callbacks');
return addCallbackSupportToModuleFactory(
(require('./auth') as typeof import('./auth')).default,
);
},
models() {
// don't try to add callbacks for this, since it's just a namespace
// and it would otherwise break lazy loading since it would enumerate
// all properties
return require('./models') as typeof import('./models');
},
logs() {
const { addCallbackSupportToModuleFactory } =
require('./util/callbacks') as typeof import('./util/callbacks');
return addCallbackSupportToModuleFactory(
(require('./logs') as typeof import('./logs')).default,
);
},
settings() {
const { addCallbackSupportToModuleFactory } =
require('./util/callbacks') as typeof import('./util/callbacks');
return addCallbackSupportToModuleFactory(
(require('./settings') as typeof import('./settings')).default,
);
},
};
export type BalenaSDK = {
[key in keyof typeof sdkTemplate]: ReturnType<
ReturnType<typeof sdkTemplate[key]>
>;
} & {
interceptors: Interceptor[];
request: BalenaRequest;
pine: Pine;
errors: typeof import('balena-errors');
version: string;
};
/**
* @namespace balena
*/
/**
* @module balena-sdk
*/
/**
* @summary Creates a new SDK instance using the default or the provided options.
*
* @description
* The module exports a single factory function.
*
* @example
* // with es6 imports
* import { getSdk } from 'balena-sdk';
* // or with node require
* const { getSdk } = require('balena-sdk');
*
* const balena = getSdk({
* apiUrl: "https://api.balena-cloud.com/",
* dataDirectory: "/opt/local/balena"
* });
*/
export const getSdk = function ($opts?: SdkOptions) {
const opts: InjectedOptionsParam = {
apiUrl: 'https://api.balena-cloud.com/',
builderUrl: 'https://builder.balena-cloud.com/',
isBrowser: typeof window !== 'undefined' && window !== null,
// API version is configurable but only do so if you know what you're doing,
// as the SDK is directly tied to a specific version.
apiVersion: 'v6',
...$opts,
};
const version = (
require('./util/sdk-version') as typeof import('./util/sdk-version')
).default;
const { getRequest } = require('balena-request') as {
getRequest: (
opts: SdkOptions & { auth: InjectedDependenciesParam['auth'] },
) => BalenaRequest;
};
const BalenaAuth = (require('balena-auth') as typeof import('balena-auth'))
.default;
const { BalenaPine } = require('balena-pine') as typeof import('balena-pine');
const errors = require('balena-errors') as typeof import('balena-errors');
const { PubSub } = require('./util/pubsub') as typeof import('./util/pubsub');
/**
* @namespace models
* @memberof balena
*/
/**
* @namespace auth
* @memberof balena
*/
/**
* @namespace logs
* @memberof balena
*/
/**
* @namespace settings
* @memberof balena
*/
let settings: InjectedDependenciesParam['settings'];
if (opts.isBrowser) {
const { notImplemented } = require('./util') as typeof import('./util');
settings = {
get: notImplemented,
getAll: notImplemented,
};
} else {
settings =
require('balena-settings-client') as typeof import('balena-settings-client') as InjectedDependenciesParam['settings'];
if (opts.dataDirectory == null) {
opts.dataDirectory = settings.get('dataDirectory');
}
}
if ('apiKey' in opts) {
// to prevent exposing it to balena-request directly
// which would add it as a query sting option
// @ts-expect-error
delete opts.apiKey;
}
const auth = new BalenaAuth(opts);
const request = getRequest({ ...opts, auth });
const pine = new BalenaPine(
{},
{ ...opts, auth, request },
) as unknown as Pine;
const pubsub = new PubSub();
const sdk = {} as BalenaSDK;
const deps: InjectedDependenciesParam = {
settings,
request,
auth,
pine,
pubsub,
sdkInstance: sdk,
};
Object.keys(sdkTemplate).forEach(function (
moduleName: keyof typeof sdkTemplate,
) {
Object.defineProperty(sdk, moduleName, {
enumerable: true,
configurable: true,
get() {
const moduleFactory = sdkTemplate[moduleName]();
// We need the delete first as the current property is read-only
// and the delete removes that restriction
delete this[moduleName];
return (this[moduleName] = moduleFactory(deps, opts));
},
});
});
/**
* @typedef Interceptor
* @type {object}
* @memberof balena.interceptors
*
* @description
* An interceptor implements some set of the four interception hook callbacks.
* To continue processing, each function should return a value or a promise that
* successfully resolves to a value.
*
* To halt processing, each function should throw an error or return a promise that
* rejects with an error.
*
* @property {function} [request] - Callback invoked before requests are made. Called with
* the request options, should return (or resolve to) new request options, or throw/reject.
*
* @property {function} [response] - Callback invoked before responses are returned. Called with
* the response, should return (or resolve to) a new response, or throw/reject.
*
* @property {function} [requestError] - Callback invoked if an error happens before a request.
* Called with the error itself, caused by a preceeding request interceptor rejecting/throwing
* an error for the request, or a failing in preflight token validation. Should return (or resolve
* to) new request options, or throw/reject.
*
* @property {function} [responseError] - Callback invoked if an error happens in the response.
* Called with the error itself, caused by a preceeding response interceptor rejecting/throwing
* an error for the request, a network error, or an error response from the server. Should return
* (or resolve to) a new response, or throw/reject.
*/
/**
* @summary Array of interceptors
* @member {Interceptor[]} interceptors
* @public
* @memberof balena
*
* @description
* The current array of interceptors to use. Interceptors intercept requests made
* internally and are executed in the order they appear in this array for requests,
* and in the reverse order for responses.
*
* @example
* balena.interceptors.push({
* responseError: function (error) {
* console.log(error);
* throw error;
* })
* });
*/
Object.defineProperty(sdk, 'interceptors', {
get(): Interceptor[] {
return request.interceptors;
},
set(interceptors: Interceptor[]) {
return (request.interceptors = interceptors);
},
});
const versionHeaderInterceptor: Interceptor = {
request($request) {
let { url } = $request;
if (typeof url !== 'string') {
return $request;
}
if (typeof $request.baseUrl === 'string') {
url = $request.baseUrl + url;
}
if (url.indexOf(opts.apiUrl) === 0) {
$request.headers['X-Balena-Client'] = `balena-sdk/${version}`;
}
return $request;
},
};
sdk.interceptors.push(versionHeaderInterceptor);
/**
* @summary Balena request instance
* @member {Object} request
* @public
* @memberof balena
*
* @description
* The balena-request instance used internally. This should not be necessary
* in normal usage, but can be useful if you want to make an API request directly,
* using the same token and hooks as the SDK.
*
* @example
* balena.request.send({ url: 'http://api.balena-cloud.com/ping' });
*/
sdk.request = request;
/**
* @summary Balena pine instance
* @member {Object} pine
* @public
* @memberof balena
*
* @description
* The balena-pine instance used internally. This should not be necessary
* in normal usage, but can be useful if you want to directly make pine
* queries to the api for some resource that isn't directly supported
* in the SDK.
*
* @example
* balena.pine.get({
* resource: 'release',
* options: {
* $count: {
* $filter: { belongs_to__application: applicationId }
* }
* }
* });
*/
sdk.pine = pine;
/**
* @summary Balena errors module
* @member {Object} errors
* @public
* @memberof balena
*
* @description
* The balena-errors module used internally. This is provided primarily for
* convenience, and to avoid the necessity for separate balena-errors
* dependencies. You'll want to use this if you need to match on the specific
* type of error thrown by the SDK.
*
* @example
* balena.models.device.get(123).catch(function (error) {
* if (error.code === balena.errors.BalenaDeviceNotFound.code) {
* ...
* } else if (error.code === balena.errors.BalenaRequestError.code) {
* ...
* }
* });
*/
sdk.errors = errors;
sdk.version = version;
return sdk;
};
/**
* @summary Set shared default options
* @public
* @function
*
* @description
* Set options that are used by calls to `fromSharedOptions()`.
* The options accepted are the same as those used in the main SDK factory function.
* If you use this method, it should be called as soon as possible during app
* startup and before any calls to `fromSharedOptions()` are made.
*
* @param {Object} options - The shared default options
* @param {String} [options.apiUrl='https://api.balena-cloud.com/'] - the balena API url to use.
* @param {String} [options.builderUrl='https://builder.balena-cloud.com/'] - the balena builder url to use.
* @param {String} [options.deviceUrlsBase='balena-devices.com'] - the base balena device API url to use.
* @param {String} [options.dataDirectory='$HOME/.balena'] - *ignored in the browser*, the directory where the user settings are stored, normally retrieved like `require('balena-settings-client').get('dataDirectory')`.
* @param {Boolean} [options.isBrowser] - the flag to tell if the module works in the browser. If not set will be computed based on the presence of the global `window` value.
* @param {Boolean} [options.debug] - when set will print some extra debug information.
*
* @example
* import { setSharedOptions } from 'balena-sdk';
* setSharedOptions({
* apiUrl: 'https://api.balena-cloud.com/',
* builderUrl: 'https://builder.balena-cloud.com/',
* isBrowser: true,
* });
*/
export const setSharedOptions = function (options: SdkOptions) {
if (globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS]) {
console.error(
'Shared SDK options have already been used. You may have a race condition in your code.',
);
}
if (globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS]) {
console.error(
'Shared SDK options have already been set. You may have a race condition in your code.',
);
}
globalEnv[BALENA_SDK_SHARED_OPTIONS] = options;
globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] = true;
};
/**
* @summary Create an SDK instance using shared default options
* @public
* @function
*
* @description
* Create an SDK instance using shared default options set using the `setSharedOptions()` method.
* If options have not been set using this method, then this method will use the
* same defaults as the main SDK factory function.
*
* @example
* import { fromSharedOptions } from 'balena-sdk';
* const sdk = fromSharedOptions();
*/
export const fromSharedOptions = function () {
const sharedOpts = globalEnv[BALENA_SDK_SHARED_OPTIONS];
globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] = true;
return getSdk(sharedOpts);
}; | the_stack |
import assert from 'assert';
import { makeModelSortDirectionEnumObject } from '@aws-amplify/graphql-model-transformer';
import { TransformerContextProvider } from '@aws-amplify/graphql-transformer-interfaces';
import { DirectiveNode, FieldDefinitionNode, InputObjectTypeDefinitionNode, Kind, ObjectTypeDefinitionNode } from 'graphql';
import {
blankObject,
blankObjectExtension,
extensionWithFields,
getBaseType,
isListType,
isNonNullType,
isScalar,
makeField,
makeInputValueDefinition,
makeListType,
makeNamedType,
makeNonNullType,
makeScalarKeyConditionForType,
ModelResourceIDs,
toCamelCase,
toPascalCase,
toUpper,
wrapNonNull,
} from 'graphql-transformer-common';
import {
BelongsToDirectiveConfiguration,
HasManyDirectiveConfiguration,
HasOneDirectiveConfiguration,
ManyToManyDirectiveConfiguration,
} from './types';
import { getConnectionAttributeName } from './utils';
export function extendTypeWithConnection(config: HasManyDirectiveConfiguration, ctx: TransformerContextProvider) {
const { field, object } = config;
generateModelXConnectionType(config, ctx);
// Extensions are not allowed to redeclare fields so we must replace it in place.
const type = ctx.output.getType(object.name.value) as ObjectTypeDefinitionNode;
assert(type?.kind === Kind.OBJECT_TYPE_DEFINITION || type?.kind === Kind.INTERFACE_TYPE_DEFINITION);
const newFields = type.fields!.map((f: FieldDefinitionNode) => {
if (f.name.value === field.name.value) {
return makeModelConnectionField(config);
}
return f;
});
const updatedType = {
...type,
fields: newFields,
};
ctx.output.putType(updatedType);
ensureModelSortDirectionEnum(ctx);
generateFilterAndKeyConditionInputs(config, ctx);
}
function generateModelXConnectionType(
config: HasManyDirectiveConfiguration | HasOneDirectiveConfiguration,
ctx: TransformerContextProvider,
): void {
const { relatedType } = config;
const tableXConnectionName = ModelResourceIDs.ModelConnectionTypeName(relatedType.name.value);
if (ctx.output.hasType(tableXConnectionName)) {
return;
}
const connectionType = blankObject(tableXConnectionName);
let connectionTypeExtension = blankObjectExtension(tableXConnectionName);
connectionTypeExtension = extensionWithFields(connectionTypeExtension, [
makeField('items', [], makeNonNullType(makeListType(makeNamedType(relatedType.name.value)))),
]);
connectionTypeExtension = extensionWithFields(connectionTypeExtension, [makeField('nextToken', [], makeNamedType('String'))]);
ctx.output.addObject(connectionType);
ctx.output.addObjectExtension(connectionTypeExtension);
}
function generateFilterAndKeyConditionInputs(config: HasManyDirectiveConfiguration, ctx: TransformerContextProvider) {
const { relatedTypeIndex } = config;
const tableXQueryFilterInput = makeModelXFilterInputObject(config, ctx);
if (!ctx.output.hasType(tableXQueryFilterInput.name.value)) {
ctx.output.addInput(tableXQueryFilterInput);
}
if (relatedTypeIndex.length === 2) {
const sortKeyType = relatedTypeIndex[1].type;
const baseType = getBaseType(sortKeyType);
const namedType = makeNamedType(baseType);
const sortKeyConditionInput = makeScalarKeyConditionForType(namedType);
if (!ctx.output.hasType(sortKeyConditionInput.name.value)) {
ctx.output.addInput(sortKeyConditionInput);
}
}
}
function ensureModelSortDirectionEnum(ctx: TransformerContextProvider): void {
if (!ctx.output.hasType('ModelSortDirection')) {
const modelSortDirection = makeModelSortDirectionEnumObject();
ctx.output.addEnum(modelSortDirection);
}
}
export function ensureHasOneConnectionField(
config: HasOneDirectiveConfiguration,
ctx: TransformerContextProvider,
connectionAttributeName?: string,
) {
const { field, fieldNodes, object } = config;
// If fields were explicitly provided to the directive, there is nothing else to do here.
if (fieldNodes.length > 0) {
return;
}
// Update the create and update input objects for this type.
if (!connectionAttributeName) {
connectionAttributeName = getConnectionAttributeName(object.name.value, field.name.value);
}
const typeObject = ctx.output.getType(object.name.value) as ObjectTypeDefinitionNode;
if (typeObject) {
const updated = updateTypeWithConnectionField(typeObject, connectionAttributeName, isNonNullType(field.type));
ctx.output.putType(updated);
}
const createInputName = ModelResourceIDs.ModelCreateInputObjectName(object.name.value);
const createInput = ctx.output.getType(createInputName) as InputObjectTypeDefinitionNode;
if (createInput) {
ctx.output.putType(updateInputWithConnectionField(createInput, connectionAttributeName, isNonNullType(field.type)));
}
const updateInputName = ModelResourceIDs.ModelUpdateInputObjectName(object.name.value);
const updateInput = ctx.output.getType(updateInputName) as InputObjectTypeDefinitionNode;
if (updateInput) {
ctx.output.putType(updateInputWithConnectionField(updateInput, connectionAttributeName));
}
const filterInputName = toPascalCase(['Model', object.name.value, 'FilterInput']);
const filterInput = ctx.output.getType(filterInputName) as InputObjectTypeDefinitionNode;
if (filterInput) {
ctx.output.putType(updateFilterConnectionInputWithConnectionField(filterInput, connectionAttributeName));
}
const conditionInputName = toPascalCase(['Model', object.name.value, 'ConditionInput']);
const conditionInput = ctx.output.getType(conditionInputName) as InputObjectTypeDefinitionNode;
if (conditionInput) {
ctx.output.putType(updateFilterConnectionInputWithConnectionField(conditionInput, connectionAttributeName));
}
config.connectionFields.push(connectionAttributeName);
}
/**
* If the related type is a hasOne relationship, this creates a hasOne relation going the other way
* but using the same foreign key name as the hasOne model
* If the related type is a hasMany relationship, this function sets the foreign key name to the name of the hasMany foreign key
* but does not add additional fields as this will be handled by the hasMany directive
*/
export function ensureBelongsToConnectionField(config: BelongsToDirectiveConfiguration, ctx: TransformerContextProvider) {
const { relationType, relatedType, relatedField } = config;
if (relationType === 'hasOne') {
ensureHasOneConnectionField(config, ctx);
} else {
// hasMany
config.connectionFields.push(getConnectionAttributeName(relatedType.name.value, relatedField.name.value));
}
}
export function ensureHasManyConnectionField(
config: HasManyDirectiveConfiguration | ManyToManyDirectiveConfiguration,
ctx: TransformerContextProvider,
) {
const { field, fieldNodes, object, relatedType } = config;
// If fields were explicitly provided to the directive, there is nothing else to do here.
if (fieldNodes.length > 0) {
return;
}
const connectionAttributeName = getConnectionAttributeName(object.name.value, field.name.value);
const relatedTypeObject = ctx.output.getType(relatedType.name.value) as ObjectTypeDefinitionNode;
if (relatedTypeObject) {
ctx.output.putType(updateTypeWithConnectionField(relatedTypeObject, connectionAttributeName, isNonNullType(field.type)));
}
const createInputName = ModelResourceIDs.ModelCreateInputObjectName(relatedType.name.value);
const createInput = ctx.output.getType(createInputName) as InputObjectTypeDefinitionNode;
if (createInput) {
ctx.output.putType(updateInputWithConnectionField(createInput, connectionAttributeName, isNonNullType(field.type)));
}
const updateInputName = ModelResourceIDs.ModelUpdateInputObjectName(relatedType.name.value);
const updateInput = ctx.output.getType(updateInputName) as InputObjectTypeDefinitionNode;
if (updateInput) {
ctx.output.putType(updateInputWithConnectionField(updateInput, connectionAttributeName));
}
const filterInputName = toPascalCase(['Model', relatedType.name.value, 'FilterInput']);
const filterInput = ctx.output.getType(filterInputName) as InputObjectTypeDefinitionNode;
if (filterInput) {
ctx.output.putType(updateFilterConnectionInputWithConnectionField(filterInput, connectionAttributeName));
}
const conditionInputName = toPascalCase(['Model', relatedType.name.value, 'ConditionInput']);
const conditionInput = ctx.output.getType(conditionInputName) as InputObjectTypeDefinitionNode;
if (conditionInput) {
ctx.output.putType(updateFilterConnectionInputWithConnectionField(conditionInput, connectionAttributeName));
}
let connectionFieldName = 'id';
for (const field of object.fields!) {
for (const directive of field.directives!) {
if (directive.name.value === 'primaryKey') {
connectionFieldName = field.name.value;
break;
}
}
}
config.connectionFields.push(connectionFieldName);
}
function updateTypeWithConnectionField(
object: ObjectTypeDefinitionNode,
connectionFieldName: string,
nonNull: boolean = false,
): ObjectTypeDefinitionNode {
const keyFieldExists = object.fields!.some(f => f.name.value === connectionFieldName);
// If the key field already exists then do not change the input.
if (keyFieldExists) {
return object;
}
const updatedFields = [
...object.fields!,
makeField(connectionFieldName, [], nonNull ? makeNonNullType(makeNamedType('ID')) : makeNamedType('ID'), []),
];
return {
...object,
fields: updatedFields,
};
}
function updateInputWithConnectionField(
input: InputObjectTypeDefinitionNode,
connectionFieldName: string,
nonNull: boolean = false,
): InputObjectTypeDefinitionNode {
const keyFieldExists = input.fields!.some(f => f.name.value === connectionFieldName);
// If the key field already exists then do not change the input.
if (keyFieldExists) {
return input;
}
const updatedFields = [
...input.fields!,
makeInputValueDefinition(connectionFieldName, nonNull ? makeNonNullType(makeNamedType('ID')) : makeNamedType('ID')),
];
return {
...input,
fields: updatedFields,
};
}
function updateFilterConnectionInputWithConnectionField(
input: InputObjectTypeDefinitionNode,
connectionFieldName: string,
): InputObjectTypeDefinitionNode {
const keyFieldExists = input.fields!.some(f => f.name.value === connectionFieldName);
// If the key field already exists then do not change the input.
if (keyFieldExists) {
return input;
}
const updatedFields = [...input.fields!, makeInputValueDefinition(connectionFieldName, makeNamedType('ModelIDInput'))];
return {
...input,
fields: updatedFields,
};
}
function makeModelConnectionField(config: HasManyDirectiveConfiguration): FieldDefinitionNode {
const { field, fields, indexName, relatedType, relatedTypeIndex } = config;
const args = [
makeInputValueDefinition('filter', makeNamedType(ModelResourceIDs.ModelFilterInputTypeName(relatedType.name.value))),
makeInputValueDefinition('sortDirection', makeNamedType('ModelSortDirection')),
makeInputValueDefinition('limit', makeNamedType('Int')),
makeInputValueDefinition('nextToken', makeNamedType('String')),
];
// Add sort key input if necessary.
if (fields.length < 2 && relatedTypeIndex.length > 1) {
let fieldName;
let namedType;
if (relatedTypeIndex.length === 2) {
const sortKeyField = relatedTypeIndex[1];
const baseType = getBaseType(sortKeyField.type);
fieldName = sortKeyField.name.value;
namedType = makeNamedType(ModelResourceIDs.ModelKeyConditionInputTypeName(baseType));
} else {
const sortKeyFieldNames = relatedTypeIndex.slice(1).map(field => field.name.value);
fieldName = toCamelCase(sortKeyFieldNames);
namedType = makeNamedType(
ModelResourceIDs.ModelCompositeKeyConditionInputTypeName(relatedType.name.value, toUpper(indexName ?? 'Primary')),
);
}
args.unshift(makeInputValueDefinition(fieldName, namedType));
}
return makeField(
field.name.value,
args,
makeNamedType(ModelResourceIDs.ModelConnectionTypeName(relatedType.name.value)),
field.directives! as DirectiveNode[],
);
}
function makeModelXFilterInputObject(
config: HasManyDirectiveConfiguration,
ctx: TransformerContextProvider,
): InputObjectTypeDefinitionNode {
const { relatedType } = config;
const name = ModelResourceIDs.ModelFilterInputTypeName(relatedType.name.value);
const fields = relatedType
.fields!.filter((field: FieldDefinitionNode) => {
const fieldType = ctx.output.getType(getBaseType(field.type));
return isScalar(field.type) || (fieldType && fieldType.kind === Kind.ENUM_TYPE_DEFINITION);
})
.map((field: FieldDefinitionNode) => {
const baseType = getBaseType(field.type);
const isList = isListType(field.type);
let filterTypeName = baseType;
if (isScalar(field.type) || isList) {
filterTypeName = isList
? ModelResourceIDs.ModelFilterListInputTypeName(baseType, true)
: ModelResourceIDs.ModelScalarFilterInputTypeName(baseType, false);
}
return {
kind: Kind.INPUT_VALUE_DEFINITION,
name: field.name,
type: makeNamedType(filterTypeName),
directives: [],
};
});
fields.push(
{
kind: Kind.INPUT_VALUE_DEFINITION,
name: {
kind: 'Name',
value: 'and',
},
type: makeListType(makeNamedType(name)) as any,
directives: [],
},
{
kind: Kind.INPUT_VALUE_DEFINITION,
name: {
kind: 'Name',
value: 'or',
},
type: makeListType(makeNamedType(name)) as any,
directives: [],
},
{
kind: Kind.INPUT_VALUE_DEFINITION,
name: {
kind: 'Name',
value: 'not',
},
type: makeNamedType(name),
directives: [],
},
);
return {
kind: 'InputObjectTypeDefinition',
name: {
kind: 'Name',
value: name,
},
fields,
directives: [],
};
}
export function getPartitionKeyField(ctx: TransformerContextProvider, object: ObjectTypeDefinitionNode): FieldDefinitionNode {
const outputObject = ctx.output.getType(object.name.value) as ObjectTypeDefinitionNode;
assert(outputObject);
const fieldMap = new Map<string, FieldDefinitionNode>();
let name = 'id';
for (const field of outputObject.fields!) {
fieldMap.set(field.name.value, field);
for (const directive of field.directives!) {
if (directive.name.value === 'primaryKey') {
name = field.name.value;
break;
}
}
}
return fieldMap.get(name) ?? makeField('id', [], wrapNonNull(makeNamedType('ID')));
} | the_stack |
import _ from 'lodash';
// Services & Utils
import syntax, {
QUERY_COMMANDS,
AGGREGATION_FUNCTIONS_STATS,
STRING_FUNCTIONS,
DATETIME_FUNCTIONS,
IP_FUNCTIONS,
BOOLEAN_FUNCTIONS,
NUMERIC_OPERATORS,
FIELD_AND_FILTER_FUNCTIONS,
} from './syntax';
// Types
import { CloudWatchQuery } from './types';
import { AbsoluteTimeRange, LanguageProvider, HistoryItem } from '@grafana/data';
import { CloudWatchDatasource } from './datasource';
import { TypeaheadInput, TypeaheadOutput, Token } from '@grafana/ui';
import Prism, { Grammar } from 'prismjs';
export type CloudWatchHistoryItem = HistoryItem<CloudWatchQuery>;
type TypeaheadContext = {
history?: CloudWatchHistoryItem[];
absoluteRange?: AbsoluteTimeRange;
logGroupNames?: string[];
};
export class CloudWatchLanguageProvider extends LanguageProvider {
started: boolean;
initialRange: AbsoluteTimeRange;
datasource: CloudWatchDatasource;
constructor(datasource: CloudWatchDatasource, initialValues?: any) {
super();
this.datasource = datasource;
Object.assign(this, initialValues);
}
// Strip syntax chars
cleanText = (s: string) => s.replace(/[()]/g, '').trim();
getSyntax(): Grammar {
return syntax;
}
request = (url: string, params?: any): Promise<{ data: { data: string[] } }> => {
return this.datasource.awsRequest(url, params);
};
start = () => {
if (!this.startTask) {
this.startTask = Promise.resolve().then(() => {
this.started = true;
return [];
});
}
return this.startTask;
};
isStatsQuery(query: string): boolean {
const grammar = this.getSyntax();
const tokens = Prism.tokenize(query, grammar) ?? [];
return !!tokens.find(
token =>
typeof token !== 'string' &&
token.content.toString().toLowerCase() === 'stats' &&
token.type === 'query-command'
);
}
/**
* Return suggestions based on input that can be then plugged into a typeahead dropdown.
* Keep this DOM-free for testing
* @param input
* @param context Is optional in types but is required in case we are doing getLabelCompletionItems
* @param context.absoluteRange Required in case we are doing getLabelCompletionItems
* @param context.history Optional used only in getEmptyCompletionItems
*/
async provideCompletionItems(input: TypeaheadInput, context?: TypeaheadContext): Promise<TypeaheadOutput> {
const { value } = input;
// Get tokens
const tokens = value?.data.get('tokens');
if (!tokens || !tokens.length) {
return { suggestions: [] };
}
const curToken: Token = tokens.filter(
(token: any) =>
token.offsets.start <= value!.selection?.start?.offset && token.offsets.end >= value!.selection?.start?.offset
)[0];
const isFirstToken = !curToken.prev;
const prevToken = prevNonWhitespaceToken(curToken);
const isCommandStart = isFirstToken || (!isFirstToken && prevToken?.types.includes('command-separator'));
if (isCommandStart) {
return this.getCommandCompletionItems();
}
if (isInsideFunctionParenthesis(curToken)) {
return await this.getFieldCompletionItems(context?.logGroupNames ?? []);
}
if (isAfterKeyword('by', curToken)) {
return this.handleKeyword(context);
}
if (prevToken?.types.includes('comparison-operator')) {
return this.handleComparison(context);
}
const commandToken = previousCommandToken(curToken);
if (commandToken) {
return await this.handleCommand(commandToken, curToken, context);
}
return {
suggestions: [],
};
}
private fetchedFieldsCache:
| {
time: number;
logGroups: string[];
fields: string[];
}
| undefined;
private fetchFields = async (logGroups: string[]): Promise<string[]> => {
if (
this.fetchedFieldsCache &&
Date.now() - this.fetchedFieldsCache.time < 30 * 1000 &&
_.sortedUniq(this.fetchedFieldsCache.logGroups).join('|') === _.sortedUniq(logGroups).join('|')
) {
return this.fetchedFieldsCache.fields;
}
const results = await Promise.all(
logGroups.map(logGroup => this.datasource.getLogGroupFields({ logGroupName: logGroup }))
);
const fields = [
...new Set<string>(
results.reduce((acc: string[], cur) => acc.concat(cur.logGroupFields?.map(f => f.name) as string[]), [])
).values(),
];
this.fetchedFieldsCache = {
time: Date.now(),
logGroups,
fields,
};
return fields;
};
private handleKeyword = async (context?: TypeaheadContext): Promise<TypeaheadOutput> => {
const suggs = await this.getFieldCompletionItems(context?.logGroupNames ?? []);
const functionSuggestions = [
{ prefixMatch: true, label: 'Functions', items: STRING_FUNCTIONS.concat(DATETIME_FUNCTIONS, IP_FUNCTIONS) },
];
suggs.suggestions.push(...functionSuggestions);
return suggs;
};
private handleCommand = async (
commandToken: Token,
curToken: Token,
context?: TypeaheadContext
): Promise<TypeaheadOutput> => {
const queryCommand = commandToken.content.toLowerCase();
const prevToken = prevNonWhitespaceToken(curToken);
const currentTokenIsFirstArg = prevToken === commandToken;
if (queryCommand === 'sort') {
return this.handleSortCommand(currentTokenIsFirstArg, curToken, context);
}
if (queryCommand === 'parse') {
if (currentTokenIsFirstArg) {
return await this.getFieldCompletionItems(context?.logGroupNames ?? []);
}
}
const currentTokenIsAfterCommandAndEmpty = isTokenType(commandToken.next, 'whitespace') && !commandToken.next?.next;
const currentTokenIsAfterCommand =
currentTokenIsAfterCommandAndEmpty || nextNonWhitespaceToken(commandToken) === curToken;
const currentTokenIsComma = isTokenType(curToken, 'punctuation', ',');
const currentTokenIsCommaOrAfterComma = currentTokenIsComma || isTokenType(prevToken, 'punctuation', ',');
// We only show suggestions if we are after a command or after a comma which is a field separator
if (!(currentTokenIsAfterCommand || currentTokenIsCommaOrAfterComma)) {
return { suggestions: [] };
}
if (['display', 'fields'].includes(queryCommand)) {
const typeaheadOutput = await this.getFieldCompletionItems(context?.logGroupNames ?? []);
typeaheadOutput.suggestions.push(...this.getFieldAndFilterFunctionCompletionItems().suggestions);
return typeaheadOutput;
}
if (queryCommand === 'stats') {
const typeaheadOutput = this.getStatsAggCompletionItems();
if (currentTokenIsComma || currentTokenIsAfterCommandAndEmpty) {
typeaheadOutput?.suggestions.forEach(group => {
group.skipFilter = true;
});
}
return typeaheadOutput;
}
if (queryCommand === 'filter' && currentTokenIsFirstArg) {
const sugg = await this.getFieldCompletionItems(context?.logGroupNames ?? []);
const boolFuncs = this.getBoolFuncCompletionItems();
sugg.suggestions.push(...boolFuncs.suggestions);
return sugg;
}
return { suggestions: [] };
};
private async handleSortCommand(
isFirstArgument: boolean,
curToken: Token,
context?: TypeaheadContext
): Promise<TypeaheadOutput> {
if (isFirstArgument) {
return await this.getFieldCompletionItems(context?.logGroupNames ?? []);
} else if (isTokenType(prevNonWhitespaceToken(curToken), 'field-name')) {
// suggest sort options
return {
suggestions: [
{
prefixMatch: true,
label: 'Sort Order',
items: [
{
label: 'asc',
},
{ label: 'desc' },
],
},
],
};
}
return { suggestions: [] };
}
private handleComparison = async (context?: TypeaheadContext) => {
const fieldsSuggestions = await this.getFieldCompletionItems(context?.logGroupNames ?? []);
const comparisonSuggestions = this.getComparisonCompletionItems();
fieldsSuggestions.suggestions.push(...comparisonSuggestions.suggestions);
return fieldsSuggestions;
};
private getCommandCompletionItems = (): TypeaheadOutput => {
return { suggestions: [{ prefixMatch: true, label: 'Commands', items: QUERY_COMMANDS }] };
};
private getFieldAndFilterFunctionCompletionItems = (): TypeaheadOutput => {
return { suggestions: [{ prefixMatch: true, label: 'Functions', items: FIELD_AND_FILTER_FUNCTIONS }] };
};
private getStatsAggCompletionItems = (): TypeaheadOutput => {
return { suggestions: [{ prefixMatch: true, label: 'Functions', items: AGGREGATION_FUNCTIONS_STATS }] };
};
private getBoolFuncCompletionItems = (): TypeaheadOutput => {
return {
suggestions: [
{
prefixMatch: true,
label: 'Functions',
items: BOOLEAN_FUNCTIONS,
},
],
};
};
private getComparisonCompletionItems = (): TypeaheadOutput => {
return {
suggestions: [
{
prefixMatch: true,
label: 'Functions',
items: NUMERIC_OPERATORS.concat(BOOLEAN_FUNCTIONS),
},
],
};
};
private getFieldCompletionItems = async (logGroups: string[]): Promise<TypeaheadOutput> => {
const fields = await this.fetchFields(logGroups);
return {
suggestions: [
{
label: 'Fields',
items: fields.map(field => ({
label: field,
insertText: field.match(/@?[_a-zA-Z]+[_.0-9a-zA-Z]*/) ? undefined : `\`${field}\``,
})),
},
],
};
};
}
function nextNonWhitespaceToken(token: Token): Token | null {
let curToken = token;
while (curToken.next) {
if (curToken.next.types.includes('whitespace')) {
curToken = curToken.next;
} else {
return curToken.next;
}
}
return null;
}
function prevNonWhitespaceToken(token: Token): Token | null {
let curToken = token;
while (curToken.prev) {
if (isTokenType(curToken.prev, 'whitespace')) {
curToken = curToken.prev;
} else {
return curToken.prev;
}
}
return null;
}
function previousCommandToken(startToken: Token): Token | null {
let thisToken = startToken;
while (!!thisToken.prev) {
thisToken = thisToken.prev;
if (
thisToken.types.includes('query-command') &&
(!thisToken.prev || isTokenType(prevNonWhitespaceToken(thisToken), 'command-separator'))
) {
return thisToken;
}
}
return null;
}
const funcsWithFieldArgs = [
'avg',
'count',
'count_distinct',
'earliest',
'latest',
'sortsFirst',
'sortsLast',
'max',
'min',
'pct',
'stddev',
'ispresent',
'fromMillis',
'toMillis',
'isempty',
'isblank',
'isValidIp',
'isValidIpV4',
'isValidIpV6',
'isIpInSubnet',
'isIpv4InSubnet',
'isIpv6InSubnet',
].map(funcName => funcName.toLowerCase());
/**
* Returns true if cursor is currently inside a function parenthesis for example `count(|)` or `count(@mess|)` should
* return true.
*/
function isInsideFunctionParenthesis(curToken: Token): boolean {
const prevToken = prevNonWhitespaceToken(curToken);
if (!prevToken) {
return false;
}
const parenthesisToken = curToken.content === '(' ? curToken : prevToken.content === '(' ? prevToken : undefined;
if (parenthesisToken) {
const maybeFunctionToken = prevNonWhitespaceToken(parenthesisToken);
if (maybeFunctionToken) {
return (
funcsWithFieldArgs.includes(maybeFunctionToken.content.toLowerCase()) &&
maybeFunctionToken.types.includes('function')
);
}
}
return false;
}
function isAfterKeyword(keyword: string, token: Token): boolean {
const maybeKeyword = getPreviousTokenExcluding(token, [
'whitespace',
'function',
'punctuation',
'field-name',
'number',
]);
if (isTokenType(maybeKeyword, 'keyword', 'by')) {
const prev = getPreviousTokenExcluding(token, ['whitespace']);
if (prev === maybeKeyword || isTokenType(prev, 'punctuation', ',')) {
return true;
}
}
return false;
}
function isTokenType(token: Token | undefined | null, type: string, content?: string): boolean {
if (!token?.types.includes(type)) {
return false;
}
if (content) {
if (token?.content.toLowerCase() !== content) {
return false;
}
}
return true;
}
type TokenDef = string | { type: string; value: string };
function getPreviousTokenExcluding(token: Token, exclude: TokenDef[]): Token | undefined | null {
let curToken = token.prev;
main: while (curToken) {
for (const item of exclude) {
if (typeof item === 'string') {
if (curToken.types.includes(item)) {
curToken = curToken.prev;
continue main;
}
} else {
if (curToken.types.includes(item.type) && curToken.content.toLowerCase() === item.value) {
curToken = curToken.prev;
continue main;
}
}
}
break;
}
return curToken;
} | the_stack |
import assert from 'assert';
import Stream from 'stream';
import * as Utils from '../../utils/misc-utils';
import { requoteProgram, getFunctions, getDevices } from '../requoting';
import { stripOutTypeAnnotations } from './eval_utils';
import * as I18n from '../../i18n';
import * as ThingTalkUtils from '../../utils/thingtalk';
import { ParserClient, PredictionResult } from '../../prediction/parserclient';
import { SentenceExample } from '../parsers';
function iterEquals<T>(iterable1 : Iterable<T>, iterable2 : Iterable<T>) : boolean {
const iter1 = iterable1[Symbol.iterator]();
const iter2 = iterable2[Symbol.iterator]();
for (;;) {
const { value: value1, done: done1 } = iter1.next();
const { value: value2, done: done2 } = iter2.next();
if (done1 !== done2)
return false;
if (done1)
break;
if (value1 !== value2)
return false;
}
return true;
}
const COMPLEXITY_METRICS = {
num_params(id : string, code : string) : number {
let params = 0;
let joins = 0;
let inString = false;
for (const token of code.split(' ')) {
if (token === '"')
inString = !inString;
if (inString)
continue;
// distance is computed by geo, which will be counted
if (token.startsWith('param:') && !token.startsWith('param:distance'))
params ++;
else if (token === 'join')
joins ++;
}
return params + joins;
},
turn_number(id : string, code : string) : number {
const match = /\/([0-9]+)(?:-[0-9]+)*$/.exec(id)!;
return parseInt(match[1]);
}
};
type SentenceEvaluatorOptions = {
locale : string;
targetLanguage : string;
debug : boolean;
tokenized ?: boolean;
oracle ?: boolean;
complexityMetric ?: keyof typeof COMPLEXITY_METRICS;
includeEntityValue ?: boolean
ignoreEntityType ?: boolean
} & ThingTalkUtils.ParseOptions;
export interface ExampleEvaluationResult {
id : string;
preprocessed : string;
target_code : string[];
target_devices : string[];
ok : boolean[];
ok_without_param : boolean[];
ok_function : boolean[];
ok_device : boolean[];
ok_num_function : boolean[];
ok_syntax : boolean[];
is_primitive : boolean;
complexity : number|undefined;
has_numeric : boolean;
}
export type EvaluationResult = {
total : number;
primitives : number;
compounds : number;
ok : number[];
ok_without_param : number[];
ok_function : number[];
ok_device : number[];
ok_num_function : number[];
ok_syntax : number[];
'prim/ok' : number[];
'prim/ok_without_param' : number[];
'prim/ok_function' : number[];
'prim/ok_device' : number[];
'prim/ok_num_function' : number[];
'prim/ok_syntax' : number[];
'comp/ok' : number[];
'comp/ok_without_param' : number[];
'comp/ok_function' : number[];
'comp/ok_device' : number[];
'comp/ok_num_function' : number[];
'comp/ok_syntax' : number[];
// the rules of how this record is accessed are too messy to write down
// so we allow free property accesses
[key : string] : any;
}
class SentenceEvaluator {
private _parser : ParserClient|null;
private _options : SentenceEvaluatorOptions;
private _locale : string;
private _tokenized : boolean;
private _debug : boolean;
private _oracle : boolean;
private _includeEntityValue : boolean;
private _ignoreEntityType : boolean;
private _tokenizer : I18n.BaseTokenizer;
private _computeComplexity : ((id : string, code : string) => number)|undefined;
private _id : string;
private _context : string|undefined;
private _preprocessed : string;
private _targetPrograms : string[];
private _predictions : string[][]|undefined;
constructor(parser : ParserClient|null,
options : SentenceEvaluatorOptions,
tokenizer : I18n.BaseTokenizer,
ex : SentenceExample) {
this._parser = parser;
this._options = options;
this._locale = options.locale;
this._tokenized = !!options.tokenized;
this._debug = options.debug;
this._oracle = !!options.oracle;
this._includeEntityValue = !!options.includeEntityValue;
this._ignoreEntityType = !!options.ignoreEntityType;
this._tokenizer = tokenizer;
if (options.complexityMetric)
this._computeComplexity = COMPLEXITY_METRICS[options.complexityMetric];
this._id = ex.id;
this._context = ex.context;
this._preprocessed = ex.preprocessed;
if (Array.isArray(ex.target_code))
this._targetPrograms = ex.target_code;
else
this._targetPrograms = [ex.target_code];
this._predictions = ex.predictions;
}
private _hasNumeric(code : string) {
for (const token of code.split(' ')) {
if (!Number.isNaN(Number(token)))
return true;
if (token === '>=' || token === '<=')
return true;
if (token.startsWith('NUMBER_'))
return true;
}
return false;
}
private _equals(thingtalk1 : string, thingtalk2 : string) : boolean {
if (this._ignoreEntityType) {
thingtalk1 = thingtalk1.replace(/\^\^\S+/g, '^^entity');
thingtalk2 = thingtalk2.replace(/\^\^\S+/g, '^^entity');
}
return thingtalk1 === thingtalk2;
}
async evaluate() : Promise<ExampleEvaluationResult|undefined> {
const result : ExampleEvaluationResult = {
id: this._id,
preprocessed: this._preprocessed,
target_code: this._targetPrograms,
target_devices: [],
ok: [],
ok_without_param: [],
ok_function: [],
ok_device: [],
ok_num_function: [],
ok_syntax: [],
is_primitive: false,
complexity: undefined,
has_numeric: false
};
let contextCode = undefined, contextEntities = {};
if (this._context !== undefined) {
contextCode = this._context.split(' ');
contextEntities = Utils.makeDummyEntities(this._context);
}
let tokens, entities;
if (this._tokenized) {
tokens = this._preprocessed.split(' ');
entities = Utils.makeDummyEntities(this._preprocessed);
Object.assign(entities, contextEntities);
} else {
const tokenized = await this._tokenizer.tokenize(this._preprocessed);
Utils.renumberEntities(tokenized, contextEntities);
tokens = tokenized.tokens;
entities = tokenized.entities;
}
assert(Array.isArray(this._targetPrograms));
assert(this._targetPrograms.length > 0);
const normalizedTargetCode = [];
const firstTargetCode = this._targetPrograms[0];
try {
const parsed = await ThingTalkUtils.parsePrediction(firstTargetCode, entities, this._options, true);
normalizedTargetCode.push(ThingTalkUtils.serializePrediction(parsed!, tokens, entities, {
locale: this._locale,
timezone: this._options.timezone,
includeEntityValue: this._includeEntityValue
}).join(' '));
} catch(e) {
// if the target_code did not parse due to missing functions in thingpedia, ignore it
if (e.message.indexOf('has no query') >= 0 || e.message.indexOf('has no action') >= 0)
return undefined;
console.error(this._id, this._preprocessed, this._targetPrograms);
throw e;
}
if (this._computeComplexity)
result.complexity = this._computeComplexity(this._id, this._targetPrograms[0]);
else
result.complexity = 0;
result.has_numeric = this._hasNumeric(this._targetPrograms[0]);
// normalized other target codes
for (let i = 1; i < this._targetPrograms.length; i++) {
try {
const parsed = await ThingTalkUtils.parsePrediction(this._targetPrograms[i], entities, this._options);
normalizedTargetCode.push(ThingTalkUtils.serializePrediction(parsed!, tokens, entities, {
locale: this._locale,
timezone: this._options.timezone,
includeEntityValue: this._includeEntityValue
}).join(' '));
} catch(e) {
console.error(this._id, this._preprocessed, this._targetPrograms);
throw e;
}
}
const requotedGold = normalizedTargetCode.map((code) => Array.from(requoteProgram(code)));
const goldFunctions = normalizedTargetCode.map((code) => Array.from(getFunctions(code)));
const goldDevices = normalizedTargetCode.map((code) => Array.from(getDevices(code)));
result.is_primitive = goldFunctions[0].length === 1;
result.target_devices = goldDevices[0];
let first = true;
let ok = false, ok_without_param = false, ok_function = false,
ok_device = false, ok_num_function = false, ok_syntax = false;
let predictions;
if (this._predictions) {
predictions = this._predictions;
} else {
try {
let answer = undefined;
if (this._oracle)
answer = firstTargetCode;
const parsed : PredictionResult = await this._parser!.sendUtterance(this._preprocessed, contextCode, contextEntities, {
answer: answer,
tokenized: this._tokenized,
skip_typechecking: true,
example_id: this._id
});
if (!entities)
entities = parsed.entities;
predictions = parsed.candidates
.filter((beam) => beam.score !== 'Infinity') // ignore exact matches
.map((beam) => beam.code);
} catch(e) {
console.error(`Sentence ${this._id} failed to predict`);
console.error(e);
predictions = [[]];
}
}
for (const beam of predictions) {
const target = normalizedTargetCode[0];
// first check if the program parses and typechecks (no hope otherwise)
const parsed = await ThingTalkUtils.parsePrediction(beam, entities, this._options);
if (!parsed) {
// push the previous result, so the stats
// stay cumulative along the beam
result.ok.push(ok);
result.ok_without_param.push(ok_without_param);
result.ok_function.push(ok_function);
result.ok_device.push(ok_device);
result.ok_num_function.push(ok_num_function);
result.ok_syntax.push(ok_syntax);
if (first && this._debug)
console.log(`${this._id}\twrong_syntax\t${this._preprocessed}\t${target}\t${beam.join(' ')}`);
first = false;
continue;
}
ok_syntax = true;
// do some light syntactic normalization
const beamString = Array.from(stripOutTypeAnnotations(beam)).join(' ');
// do the actual normalization, using the full ThingTalk algorithm
// we pass "ignoreSentence: true", which means strings are tokenized and then put in the
// program regardless of what the sentence contains (because the neural network might
// get creative in copying, and we don't want to crash here)
const normalized = ThingTalkUtils.serializePrediction(parsed, tokens, entities, {
locale: this._locale,
timezone: this._options.timezone,
ignoreSentence: true,
includeEntityValue: this._includeEntityValue
});
const normalizedCode = normalized.join(' ');
// check that by normalizing we did not accidentally mark wrong a program that
// was correct before
if (this._equals(beamString, normalizedTargetCode[0]) && !this._equals(normalizedCode, normalizedTargetCode[0])) {
console.error();
console.error('NORMALIZATION ERROR');
console.error(normalizedTargetCode[0]);
console.error(normalizedCode);
console.error(beam);
throw new Error('Normalization Error');
}
let beam_ok = false, beam_ok_without_param = false, beam_ok_function = false,
beam_ok_device = false, beam_ok_num_function = false;
let result_string = 'ok_syntax';
for (let referenceId = 0; referenceId < this._targetPrograms.length; referenceId++) {
if (this._equals(normalizedCode, normalizedTargetCode[referenceId])) {
// we have a match!
beam_ok = true;
beam_ok_without_param = true;
beam_ok_function = true;
beam_ok_device = true;
beam_ok_num_function = true;
result_string = 'ok';
break;
}
const this_ok_without_param = iterEquals(requotedGold[referenceId], requoteProgram(normalized));
beam_ok_without_param = beam_ok_without_param || this_ok_without_param;
if (this_ok_without_param && !beam_ok)
result_string = 'ok_without_param';
const functions = Array.from(getFunctions(normalized));
const this_ok_function = this_ok_without_param || iterEquals(goldFunctions[referenceId], functions);
beam_ok_function = beam_ok_function || this_ok_function;
if (this_ok_function && !beam_ok_without_param)
result_string = 'ok_function';
const this_ok_device = this_ok_function || iterEquals(goldDevices[referenceId], getDevices(normalized));
beam_ok_device = beam_ok_device || this_ok_device;
if (this_ok_device && !beam_ok_function)
result_string = 'ok_device';
const this_ok_num_function = this_ok_device || goldFunctions[referenceId].length === functions.length;
beam_ok_num_function = beam_ok_num_function || this_ok_num_function;
if (this_ok_num_function && !beam_ok_device)
result_string = 'ok_num_function';
}
if (first && this._debug && result_string !== 'ok')
console.log(`${this._id}\t${result_string}\t${this._preprocessed}\t${target}\t${normalizedCode}`);
first = false;
ok = ok || beam_ok;
ok_without_param = ok_without_param || beam_ok_without_param;
ok_function = ok_function || beam_ok_function;
ok_device = ok_device || beam_ok_device;
ok_num_function = ok_num_function || beam_ok_num_function;
result.ok.push(ok);
result.ok_without_param.push(ok_without_param);
result.ok_function.push(ok_function);
result.ok_device.push(ok_device);
result.ok_num_function.push(ok_num_function);
result.ok_syntax.push(ok_syntax);
}
return result;
}
}
const MINIBATCH_SIZE = 100;
export class SentenceEvaluatorStream extends Stream.Transform {
private _parser : ParserClient|null;
private _options : SentenceEvaluatorOptions;
private _tokenizer : I18n.BaseTokenizer;
private _minibatch : Array<Promise<ExampleEvaluationResult|undefined>>;
constructor(parser : ParserClient|null, options : SentenceEvaluatorOptions) {
super({ objectMode: true });
this._parser = parser;
this._options = options;
this._tokenizer = I18n.get(options.locale).getTokenizer();
this._minibatch = [];
}
private _evaluate(ex : SentenceExample) {
const evaluator = new SentenceEvaluator(this._parser, this._options, this._tokenizer, ex);
return evaluator.evaluate();
}
private async _flushMinibatch() {
for (const res of await Promise.all(this._minibatch)) {
if (res)
this.push(res);
}
this._minibatch = [];
}
private async _pushExample(ex : SentenceExample) {
this._minibatch.push(this._evaluate(ex));
if (this._minibatch.length >= MINIBATCH_SIZE)
await this._flushMinibatch();
}
_transform(ex : SentenceExample, encoding : BufferEncoding, callback : (err : Error|null) => void) {
this._pushExample(ex).then(() => callback(null), (err) => callback(err));
}
_flush(callback : (err : Error|null) => void) {
this._flushMinibatch().then(() => callback(null), (err) => callback(err));
}
}
interface CollectSentenceStatisticsOptions {
minComplexity ?: number;
maxComplexity ?: number;
splitByDevice ?: boolean;
}
const KEYS : Array<'ok' | 'ok_without_param' | 'ok_function' | 'ok_device' | 'ok_num_function' | 'ok_syntax'> = ['ok', 'ok_without_param', 'ok_function', 'ok_device', 'ok_num_function', 'ok_syntax'];
export class CollectSentenceStatistics extends Stream.Writable {
private _minComplexity : number;
private _maxComplexity : number;
private _splitByDevice : boolean;
private _buffer : Record<string, EvaluationResult>;
constructor(options : CollectSentenceStatisticsOptions = {}) {
super({ objectMode: true });
this._minComplexity = options.minComplexity || 0;
this._maxComplexity = options.maxComplexity || Infinity;
this._splitByDevice = !!options.splitByDevice;
// _buffer will map devices to individual buffers. If splitByDevice is
// false, there will only be a single buffer. Otherwise, these individual
// buffers will be created ad-hoc, as new devices come up.
this._buffer = {};
}
_write(ex : ExampleEvaluationResult, encoding : BufferEncoding, callback : () => void) {
let uniqueDevices;
if (this._splitByDevice) {
uniqueDevices = Array.from(new Set(ex.target_devices));
if (uniqueDevices.length === 0)
uniqueDevices.push('generic'); // generic device, for deviceless acts
} else {
uniqueDevices = ['all_devices'];
}
for (const device of uniqueDevices) {
if (!(device in this._buffer)) {
this._buffer[device] = {
total: 0,
primitives: 0,
compounds: 0,
ok: [],
ok_without_param: [],
ok_function: [],
ok_device: [],
ok_num_function: [],
ok_syntax: [],
'prim/ok': [],
'prim/ok_without_param': [],
'prim/ok_function': [],
'prim/ok_device': [],
'prim/ok_num_function': [],
'prim/ok_syntax': [],
'comp/ok': [],
'comp/ok_without_param': [],
'comp/ok_function': [],
'comp/ok_device': [],
'comp/ok_num_function': [],
'comp/ok_syntax': [],
};
}
this._buffer[device].total ++;
if (ex.is_primitive)
this._buffer[device].primitives ++;
else
this._buffer[device].compounds ++;
let compkey;
if (this._minComplexity > 0 && ex.complexity !== undefined && ex.complexity <= this._minComplexity)
compkey = 'complexity_<=' + this._minComplexity + '/';
else if (this._maxComplexity && ex.complexity !== undefined && ex.complexity >= this._maxComplexity)
compkey = 'complexity_>=' + this._maxComplexity + '/';
else
compkey = 'complexity_' + ex.complexity + '/';
if (!this._buffer[device][compkey + 'total']) {
this._buffer[device][compkey + 'total'] = 0;
for (const key of KEYS)
this._buffer[device][compkey + key] = [];
}
const numericKey = ex.has_numeric ? 'with_numeric_' : 'without_numeric_';
if (!this._buffer[device][numericKey + 'total']) {
this._buffer[device][numericKey + 'total'] = 0;
for (const key of KEYS)
this._buffer[device][numericKey + key] = [];
}
this._buffer[device][compkey + 'total'] += 1;
this._buffer[device][numericKey + 'total'] += 1;
for (const key of KEYS) {
for (let beampos = 0; beampos < ex[key].length; beampos++) {
while (this._buffer[device][key].length <= beampos)
this._buffer[device][key].push(0);
if (ex[key][beampos])
this._buffer[device][key][beampos] ++;
let subkey = ex.is_primitive ? 'prim/' + key : 'comp/' + key;
while (this._buffer[device][subkey].length <= beampos)
this._buffer[device][subkey].push(0);
if (ex[key][beampos])
this._buffer[device][subkey][beampos] ++;
subkey = compkey + key;
while (this._buffer[device][subkey].length <= beampos)
this._buffer[device][subkey].push(0);
if (ex[key][beampos])
this._buffer[device][subkey][beampos] ++;
assert(!isNaN(this._buffer[device][subkey][beampos]));
subkey = numericKey + key;
while (this._buffer[device][subkey].length <= beampos)
this._buffer[device][subkey].push(0);
if (ex[key][beampos])
this._buffer[device][subkey][beampos] ++;
}
}
}
callback();
}
_final(callback : () => void) {
for (const device in this._buffer) {
// convert to percentages
for (const key of ['ok', 'ok_without_param', 'ok_function', 'ok_device', 'ok_num_function', 'ok_syntax']) {
for (let beampos = 0; beampos < this._buffer[device][key].length; beampos++) {
//this._buffer[device][key][beampos] = (this._buffer[device][key][beampos] * 100 / this._buffer[device].total).toFixed(2);
//this._buffer[device]['prim/' + key][beampos] = (this._buffer[device]['prim/' + key][beampos] * 100 / this._buffer[device].primitives).toFixed(2);
//this._buffer[device]['comp/' + key][beampos] = (this._buffer[device]['comp/' + key][beampos] * 100 / this._buffer[device].compounds).toFixed(2);
this._buffer[device][key][beampos] /= this._buffer[device].total;
this._buffer[device]['prim/' + key][beampos] /= this._buffer[device].primitives;
this._buffer[device]['comp/' + key][beampos] /= this._buffer[device].compounds;
let compkey = this._minComplexity > 0 ? 'complexity_<=' + this._minComplexity + '/' : 'complexity_0/';
if (this._buffer[device][compkey + 'total']) {
this._buffer[device][compkey + key][beampos] /= this._buffer[device][compkey + 'total'];
assert(!isNaN(this._buffer[device][compkey + key][beampos]), this._buffer[device][compkey + key]);
}
for (let i = this._minComplexity + 1; i < 20; i++) {
compkey = 'complexity_' + i + '/';
if (this._buffer[device][compkey + 'total']) {
this._buffer[device][compkey + key][beampos] /= this._buffer[device][compkey + 'total'];
assert(!isNaN(this._buffer[device][compkey + key][beampos]), this._buffer[device][compkey + key]);
}
}
if (this._maxComplexity) {
compkey = 'complexity_>=' + this._maxComplexity + '/';
if (this._buffer[device][compkey + 'total']) {
this._buffer[device][compkey + key][beampos] /= this._buffer[device][compkey + 'total'];
assert(!isNaN(this._buffer[device][compkey + key][beampos]), this._buffer[device][compkey + key]);
}
}
let numerickey = 'with_numeric_';
if (this._buffer[device][numerickey + 'total']) {
this._buffer[device][numerickey + key][beampos] /= this._buffer[device][numerickey + 'total'];
assert(!isNaN(this._buffer[device][numerickey + key][beampos]), this._buffer[device][numerickey + key]);
}
numerickey = 'without_numeric_';
if (this._buffer[device][numerickey + 'total']) {
this._buffer[device][numerickey + key][beampos] /= this._buffer[device][numerickey + 'total'];
assert(!isNaN(this._buffer[device][numerickey + key][beampos]), this._buffer[device][numerickey + key]);
}
}
}
}
callback();
}
read() {
return new Promise<Record<string, EvaluationResult>>((resolve, reject) => {
this.on('finish', () => resolve(this._buffer));
this.on('error', reject);
});
}
} | the_stack |
import * as FC from 'fast-check';
import * as K from '../../src/Kit';
import {genInCharset, property, prettyPrint} from '../utils';
import {produce} from 'immer';
import * as _ from 'lodash';
import * as UnicodeProperty from '../../src/UnicodeProperty';
import {Omit} from 'utility-types';
import Unicode from '../../src/Unicode';
import * as AST from '../../src/AST';
import * as JSRE from '../../src/grammar/JSRE';
import * as GBase from '../../src/grammar/Base';
import * as path from 'path';
import * as fs from 'fs';
import {assert} from 'chai';
import {AssertionError} from 'assert';
import {Arbitrary} from 'fast-check';
export interface TestCase<T> {
expect: T;
source: string;
state: GenState;
}
export type GenNode<N extends AST.Node = AST.Node> = FC.Arbitrary<TestCase<N>>;
// Avoid use DeepReadonly because of immer Draft type does not work well with ReadonlyArray
export type GenState = Readonly<{
pos: number;
groups: Readonly<{
depth: number;
count: number;
names: string[];
}>;
liveGroups: Readonly<{
indices: number[];
names: string[];
}>;
liveGroupsBackup: Array<
Readonly<{
indices: number[];
names: string[];
}>
>;
}>;
export function makeGenState(): GenState {
return {pos: 0, groups: {depth: 0, count: 0, names: []}, liveGroups: {indices: [], names: []}, liveGroupsBackup: []};
}
export type GenFn<N extends AST.Node = AST.Expr> = (state: GenState) => GenNode<N>;
/**
"\0" + "1" will result in OctEscape or Backref error
*/
export function isSticky(t1: TestCase<any>, t2: TestCase<any>) {
return /\\\d*$/.test(t1.source) && /^\d/.test(t2.source);
}
export type PartialTest<N extends AST.Node = AST.Node> = Omit<TestCase<Omit<N, 'range'>>, 'state'> & {state?: GenState};
export function fixStateRange<N extends AST.Node>(initialState: GenState): (t: PartialTest<N>) => TestCase<N> {
return t1 =>
produce(t1 as TestCase<N>, t2 => {
t2.state = produce(t2.state || initialState, st => void (st.pos = initialState.pos + t2.source.length));
t2.expect.range = [initialState.pos, t2.state.pos];
});
}
export abstract class BaseGen {
constructor(public readonly flags: AST.RegexFlags, public readonly maxGroupDepth = 30) {}
Dot(state: GenState): GenNode<AST.DotNode> {
return FC.constant({
source: '.',
expect: {type: 'Dot' as const}
}).map(fixStateRange(state));
}
Char(state: GenState): GenNode<AST.CharNode> {
let {flags} = this;
let UnicodeEscape = flags.unicode
? FC.oneof(UtilGen.BaseUnicodeEscape, UtilGen.CodePointEscape, UtilGen.UnicodePairEscape)
: UtilGen.BaseUnicodeEscape;
let ExactChar = flags.unicode ? UtilGen.ExactChar : UtilGen.ExactChar16;
// Use constantFrom for better shrink result
return FC.tuple(
UtilGen.AlphaChar,
UtilGen.AlphanumChar,
ExactChar,
UtilGen.IdentityEscape,
UtilGen.HexEscape,
UtilGen.ControlEscape,
UtilGen.ControlLetter,
UtilGen.NullChar,
UnicodeEscape
)
.chain(a => FC.constantFrom(...a))
.map(t => {
return {
source: t.source,
expect: {type: 'Char' as const, value: t.expect}
};
})
.map(fixStateRange(state));
}
CharClassEscape(state: GenState): GenNode<AST.CharClassEscapeNode> {
let {flags} = this;
type T = {source: string; expect: AST.BaseCharClass | AST.UnicodeCharClass};
let gen = flags.unicode ? FC.oneof<T>(UtilGen.BaseCharClass, UtilGen.UnicodeCharClass) : UtilGen.BaseCharClass;
return gen
.map(t => {
return {
source: '\\' + t.source,
expect: {type: 'CharClassEscape' as const, charClass: t.expect}
};
})
.map(fixStateRange(state));
}
CharClass(state: GenState): GenNode<AST.CharClassNode> {
type ItemF = GenFn<AST.CharClassItem>;
let genCharItemF: GenFn<AST.CharNode> = st =>
this.Char(st)
.map(t1 => {
if (!'-^'.includes(t1.source)) return t1;
return produce(t1, t2 => {
t2.source = '\\' + t1.source;
});
})
.map(fixStateRange(st));
let genRangeItemF: ItemF = st =>
FC.tuple(genCharItemF(st), genCharItemF(st))
.map(a => {
a = produce(a, a => {
let [c1, c2] = a.sort((t1, t2) => K.compareFullUnicode(t1.expect.value, t2.expect.value));
AST.indent(c2.expect, c1.source.length + 1);
});
let source = a.map(t => t.source).join('-');
return {
source,
expect: {
type: 'CharRange' as const,
begin: a[0].expect,
end: a[1].expect
}
};
})
.map(fixStateRange(st));
let genCharClassItemF = FC.constantFrom<ItemF>(genCharItemF, state => this.CharClassEscape(state), genRangeItemF);
return FC.record({
invert: FC.boolean(),
bodyFns: FC.array(genCharClassItemF)
})
.chain(t => {
let {invert, bodyFns} = t;
let state1 = produce(state, st => {
st.pos += invert ? 2 : 1;
});
let bodyGen = FC.constant({state: state1, source: '', expect: [] as AST.CharClassItem[]});
for (let fn of bodyFns) {
bodyGen = bodyGen.chain(acc => {
return fn(acc.state).map(t2 => {
if (isSticky(acc, t2)) return acc;
return {
source: acc.source + t2.source,
state: t2.state,
expect: acc.expect.concat(t2.expect)
};
});
});
}
return bodyGen.map(g => {
return {
source: '[' + (invert ? '^' : '') + g.source + ']',
expect: {
type: 'CharClass' as const,
invert,
body: g.expect
}
};
});
})
.map(fixStateRange(state));
}
BaseAssertion(state: GenState): GenNode<AST.BaseAssertionNode> {
let symbols = Object.keys(GBase.baseAssertionTypeMap);
return FC.constantFrom(...symbols)
.map(source => {
let a = GBase.baseAssertionTypeMap[source];
return {
source,
expect: {type: 'BaseAssertion' as const, kind: a}
};
})
.map(fixStateRange(state));
}
Backref(state: GenState): GenNode<AST.BackrefNode> {
FC.pre(state.liveGroups.indices.length > 0);
type IndexGen = FC.Arbitrary<{source: string; index: number | string}>;
let numRef: IndexGen = FC.constantFrom(...state.liveGroups.indices).map(i => {
return {source: '\\' + i, index: i};
});
let ref: IndexGen = numRef;
if (state.liveGroups.names.length > 0) {
let nameRef = FC.constantFrom(...state.liveGroups.names).map(n => {
return {source: '\\k<' + n + '>', index: n};
});
ref = FC.oneof(numRef, nameRef);
}
return ref
.map(({source, index}) => {
return {
source,
expect: {type: 'Backref' as const, index}
};
})
.map(fixStateRange(state));
}
Expr<TA extends Array<AST.Expr['type']> = []>(
state: GenState,
excludes?: TA
): GenNode<Exclude<AST.Expr, AST.NodeOfType<TA[number]>>> {
type A = Array<AST.Expr['type']>;
const leafGenNames: A = ['Dot', 'Char', 'CharClassEscape', 'CharClass', 'BaseAssertion'];
const recurGenNames: A = ['GroupAssertion', 'Group', 'List', 'Disjunction', 'Repeat'];
let names = leafGenNames.slice();
if (state.liveGroups.indices.length > 0) {
names.push('Backref');
}
if (state.groups.depth < this.maxGroupDepth) {
names = names.concat(recurGenNames);
}
if (excludes) {
names = names.filter(n => !excludes.includes(n));
}
return FC.constantFrom(...names).chain(fname => (this[fname] as GenFn<any>)(state));
}
Disjunction(state: GenState): GenNode<AST.DisjunctionNode> {
let liveGroups0 = state.liveGroups;
let state1 = produce(state, st => void st.liveGroupsBackup.push(st.liveGroups));
let bodyGen = FC.integer(2, 10).chain(n => {
let genAcc = FC.constant({source: [] as string[], expect: [] as AST.DisjunctionNode['body'], state: state1});
while (n--) {
genAcc = genAcc.chain(acc => {
let state2 = produce(acc.state, st => void (st.liveGroups = liveGroups0));
return this.Expr(state2, ['Disjunction']).map(t => {
let newState = produce(t.state, st => {
st.pos++;
// merge groups in each branch when leave Disjunction
let g = st.liveGroupsBackup.slice(-1)[0];
g.indices.push(...st.liveGroups.indices.slice(liveGroups0.indices.length));
g.names.push(...st.liveGroups.names.slice(liveGroups0.names.length));
});
return {
state: newState,
source: acc.source.concat(t.source),
expect: acc.expect.concat(t.expect)
};
});
});
}
return genAcc;
});
return bodyGen
.map(t => {
return {
source: t.source.join('|'),
state: produce(t.state, st => void st.liveGroupsBackup.pop()),
expect: {
type: 'Disjunction' as const,
body: t.expect
}
};
})
.map(fixStateRange(state));
}
List(state: GenState): GenNode<AST.ListNode> {
let genBody: Arbitrary<TestCase<AST.ListNode['body']>> = FC.integer(0, this.maxGroupDepth).chain(n => {
let genAcc = FC.constant({source: '', state, expect: [] as AST.ListNode['body']});
while (n--) {
genAcc = genAcc.chain(acc => {
return this.Expr(acc.state, ['List', 'Disjunction']).map(t => {
if (isSticky(acc, t)) return acc;
return {
source: acc.source + t.source,
state: t.state,
expect: acc.expect.concat(t.expect)
};
});
});
}
return genAcc.map(t => {
if (t.expect.length === 1) {
// When ListNode body only contains one node N, it will be unwrapped to N in parsing.
// But here we must return a ListNode, so does the empty body
return {source: '', state, expect: []};
}
return t;
});
});
return genBody.map(({source, state: newState, expect: body}) => ({
source,
state: newState,
expect: {type: 'List' as const, body, range: [state.pos, newState.pos]}
}));
}
abstract GroupBehavior(state: GenState): Arbitrary<TestCase<AST.GroupBehavior>>;
Group(state: GenState): GenNode<AST.GroupNode> {
return this.GroupBehavior(produce(state, st => void st.pos++)).chain(behaviorCase => {
let behavior = behaviorCase.expect;
let state1 = produce(behaviorCase.state, st => {
st.groups.depth++;
if (behavior.type === 'Capturing') {
st.groups.count++;
if (behavior.name) {
st.groups.names.push(behavior.name);
}
}
});
return this.Expr(state1).map(bodyCase => {
let source = '(' + behaviorCase.source + bodyCase.source + ')';
let newState = produce(bodyCase.state, st => {
st.pos++;
st.groups.depth--;
if (behavior.type === 'Capturing') {
st.liveGroups.indices.push(state1.groups.count);
if (behavior.name) {
st.liveGroups.names.push(behavior.name);
}
}
});
let expect: AST.GroupNode = {
type: 'Group' as const,
body: bodyCase.expect,
behavior,
range: [state.pos, newState.pos]
};
return {source, expect, state: newState};
});
});
}
GroupAssertion(state: GenState): GenNode<AST.GroupAssertionNode> {
let specifierGen: FC.Arbitrary<Pick<AST.GroupAssertionNode, 'look' | 'negative'>> = FC.record({
look: FC.constantFrom('Lookahead', 'Lookbehind'),
negative: FC.boolean()
});
return specifierGen.chain(sp => {
let liveGroupsBackup = state.liveGroups;
let spSource = GBase.invGroupAssertionTypeMap[[sp.look, sp.negative] + ''];
let state1 = produce(state, st => {
st.pos += spSource.length + 1;
st.groups.depth++;
});
return this.Expr(state1).map(bodyCase => {
let newState = produce(bodyCase.state, st => {
st.pos++;
st.groups.depth--;
if (sp.negative) {
st.liveGroups = liveGroupsBackup;
}
});
return {
source: '(' + spSource + bodyCase.source + ')',
state: newState,
expect: {
type: 'GroupAssertion' as const,
look: sp.look,
negative: sp.negative,
body: bodyCase.expect,
range: [state.pos, newState.pos]
}
};
});
});
}
Quantifier(state: GenState): GenNode<AST.QuantifierNode> {
let baseQuantifiers = '+?*'.split('').map(c => ({source: c, expect: GBase.parseBaseQuantifier(c)}));
return FC.record({
greedy: FC.boolean(),
test: FC.oneof(
FC.constantFrom(...baseQuantifiers),
FC.record({
min: FC.nat(),
max: FC.oneof(FC.nat(), FC.constant(Infinity))
})
.filter(({min, max}) => min <= max)
.map(({min, max}) => {
let q = {type: 'Quantifier', min, max, greedy: true} as AST.QuantifierNode;
let source = GBase.showQuantifier(q);
return {source, expect: q};
})
)
})
.map(({greedy, test}) =>
produce(test, t => {
t.expect.greedy = greedy;
if (greedy === false) {
t.source += '?';
}
})
)
.map(fixStateRange(state));
}
Repeat(state: GenState): GenNode<AST.RepeatNode> {
return this.Expr(state, ['Repeat', 'BaseAssertion', 'GroupAssertion', 'List', 'Disjunction']).chain(bodyCase => {
return this.Quantifier(bodyCase.state).map(q => ({
source: bodyCase.source + q.source,
state: q.state,
expect: {
type: 'Repeat' as const,
quantifier: q.expect,
body: bodyCase.expect,
range: [state.pos, q.state.pos]
}
}));
});
}
}
export module UtilGen {
export const unicode16 = K.Charset.fromPattern('\0-\uFFFF');
export const patternChar = K.Charset.fromChars(GBase.syntaxChars).inverted();
export const patternChar16 = patternChar.intersect(unicode16);
export const alphanum = K.Charset.fromPattern('A-Za-z0-9');
export const alpha = K.Charset.fromPattern('A-Za-z');
export const Flags = FC.constant(AST.RegexFlags.create({unicode: true}));
export const ExactChar16 = genInCharset(patternChar16).map(c => ({source: c, expect: c}));
export const ExactChar = genInCharset(patternChar).map(c => ({source: c, expect: c}));
export const AlphaChar = genInCharset(alpha).map(c => ({source: c, expect: c}));
export const AlphanumChar = genInCharset(alphanum).map(c => ({source: c, expect: c}));
export const HexEscape = FC.char().map(c => ({source: K.Char.hexEscape(c), expect: c}));
export const ControlEscape = FC.constantFrom(...'fnrtv').map(c => ({
source: '\\' + c,
expect: GBase.controlEscapeMap[c]
}));
export const ControlLetter = genInCharset(alpha).map(c => ({
source: '\\c' + c,
expect: K.Char.ctrl(c)
}));
export const NullChar = FC.constant({source: '\\0', expect: '\0'});
export const BaseUnicodeEscape = FC.unicode().map(c => ({source: K.Char.unicodeEscape(c), expect: c}));
export const CodePointEscape = FC.fullUnicode().map(c => ({source: K.Char.codePointEscape(c), expect: c}));
export const UnicodePairEscape = FC.integer(0x10000, K.Char.MAX_CODE_POINT).map(cp => {
let c = String.fromCodePoint(cp);
return {source: K.escapeUnicodes(c, false), expect: c};
});
export const IdentityEscape = FC.constantFrom(...(GBase.syntaxChars + '/')).map(c => ({source: '\\' + c, expect: c}));
export const BaseCharClass = FC.constantFrom(
...Object.entries(GBase.charClassEscapeTypeMap).map(a => ({source: a[0], expect: a[1]}))
);
export const BinaryUnicodeCharClass: FC.Arbitrary<AST.UnicodeCharClass> = FC.constantFrom(
...UnicodeProperty.canonical.Binary_Property
).map(name => ({name, invert: false}));
export const NonBinaryUnicodeCharClass: FC.Arbitrary<AST.UnicodeCharClass> = FC.constantFrom(
...UnicodeProperty.canonical.NonBinary_Property
).chain(name =>
FC.constantFrom(...K.IndexSig(UnicodeProperty.canonical)[name]).map(value => ({name, value, invert: false}))
);
export const UnicodeCharClass = FC.record({
invert: FC.boolean(),
cat: FC.oneof(BinaryUnicodeCharClass, NonBinaryUnicodeCharClass)
})
.map(c => produce(c.cat, a => void (a.invert = c.invert)))
.chain(cat =>
FC.constantFrom(...getAliasForms(cat).map(s => ({source: (cat.invert ? 'P' : 'p') + '{' + s + '}', expect: cat})))
);
const invAliasMap = K.invertMap(UnicodeProperty.aliasMap);
export function getAliasForms(cat: AST.UnicodeCharClass): string[] {
let toCode = (name: string, value?: string) => name + (value ? '=' + value : '');
let forms = [toCode(cat.name, cat.value)];
let nameAlias = invAliasMap.get(cat.name);
let valueAlias = cat.value && invAliasMap.get(cat.value);
if (nameAlias) {
forms.push(toCode(nameAlias, cat.value));
if (valueAlias) {
forms.push(toCode(nameAlias, valueAlias));
}
}
if (valueAlias) {
forms.push(toCode(cat.name, valueAlias));
}
return forms;
}
export const ID = {
Start: genInCharset(Unicode.Binary_Property.ID_Start),
Continue: genInCharset(Unicode.Binary_Property.ID_Continue)
};
export const ID16Bit = {
Start: genInCharset(Unicode.Binary_Property.ID_Start.intersect(unicode16)),
Continue: genInCharset(Unicode.Binary_Property.ID_Continue.intersect(unicode16))
};
}
export function cleanNodeRange(node: AST.Node): void {
AST.visit(node, {
defaults(n) {
n.range = [0, 0];
}
});
}
export function runGrammarTest(
title: string,
parse: typeof JSRE.parse,
gen: Arbitrary<{flags: AST.RegexFlags; testCase: TestCase<AST.Node>}>
) {
let runProp = property(gen, ({testCase, flags}) => {
let result = parse(testCase.source, flags);
if (!K.isResultOK(result)) {
assert(K.isResultOK(result));
return;
}
assert.deepEqual(result.value.expr, testCase.expect, K.escapeUnicodes(testCase.source));
// Test toSource parse idempotency
let cleanExpr = _.cloneDeep(testCase.expect);
cleanNodeRange(cleanExpr);
let source2 = GBase.toSource(cleanExpr);
let result2 = parse(source2, flags);
if (!K.isResultOK(result2)) {
assert(K.isResultOK(result2));
return;
}
cleanNodeRange(result2.value.expr);
assert.deepEqual(cleanExpr, result2.value.expr, K.escapeUnicodes(source2));
});
it(title, () => {
try {
runProp();
} catch (e) {
if (e instanceof AssertionError) {
let errorLog = './test/log/grammar/' + path.basename(__filename);
fs.mkdirSync('./test/log/grammar/', {recursive: true});
fs.writeFileSync(
errorLog,
'export const expected = ' +
prettyPrint(e.expected) +
';\n' +
'export const actual = ' +
prettyPrint(e.actual) +
';\n'
);
console.error('See error log:' + errorLog);
}
throw e;
}
});
} | the_stack |
import { promises as fs } from 'fs'
import path from 'path'
import { LOCKFILE_VERSION, WANTED_LOCKFILE } from '@pnpm/constants'
import { RootLog } from '@pnpm/core-loggers'
import PnpmError from '@pnpm/error'
import { Lockfile, TarballResolution } from '@pnpm/lockfile-file'
import { prepareEmpty, preparePackages } from '@pnpm/prepare'
import { fromDir as readPackageJsonFromDir } from '@pnpm/read-package-json'
import { getIntegrity, REGISTRY_MOCK_PORT } from '@pnpm/registry-mock'
import { ProjectManifest } from '@pnpm/types'
import readYamlFile from 'read-yaml-file'
import {
addDependenciesToPackage,
install,
mutateModules,
} from '@pnpm/core'
import rimraf from '@zkochan/rimraf'
import loadJsonFile from 'load-json-file'
import nock from 'nock'
import exists from 'path-exists'
import sinon from 'sinon'
import writeYamlFile from 'write-yaml-file'
import {
addDistTag,
testDefaults,
} from './utils'
const LOCKFILE_WARN_LOG = {
level: 'warn',
message: `A ${WANTED_LOCKFILE} file exists. The current configuration prohibits to read or write a lockfile`,
name: 'pnpm',
}
test('lockfile has correct format', async () => {
const project = prepareEmpty()
await addDependenciesToPackage({},
[
'pkg-with-1-dep',
'@rstacruz/tap-spec@4.1.1',
'kevva/is-negative#1d7e288222b53a0cab90a331f1865220ec29560c',
], await testDefaults({ fastUnpack: false, save: true }))
const modules = await project.readModulesManifest()
expect(modules).toBeTruthy()
expect(modules!.pendingBuilds.length).toBe(0)
const lockfile = await project.readLockfile()
const id = '/pkg-with-1-dep/100.0.0'
expect(lockfile.lockfileVersion).toBe(LOCKFILE_VERSION)
expect(lockfile.specifiers).toBeTruthy()
expect(lockfile.dependencies).toBeTruthy()
expect(lockfile.dependencies['pkg-with-1-dep']).toBe('100.0.0')
expect(lockfile.dependencies).toHaveProperty(['@rstacruz/tap-spec'])
expect(lockfile.dependencies['is-negative']).toContain('/') // has not shortened tarball from the non-standard registry
expect(lockfile.packages).toBeTruthy() // has packages field
expect(lockfile.packages).toHaveProperty([id])
expect(lockfile.packages[id].dependencies).toBeTruthy()
expect(lockfile.packages[id].dependencies).toHaveProperty(['dep-of-pkg-with-1-dep'])
expect(lockfile.packages[id].resolution).toBeTruthy()
expect((lockfile.packages[id].resolution as {integrity: string}).integrity).toBeTruthy()
expect((lockfile.packages[id].resolution as TarballResolution).tarball).toBeFalsy()
const absDepPath = 'github.com/kevva/is-negative/1d7e288222b53a0cab90a331f1865220ec29560c'
expect(lockfile.packages).toHaveProperty([absDepPath])
expect(lockfile.packages[absDepPath].name).toBeTruthy() // github-hosted package has name specified
})
test('lockfile has dev deps even when installing for prod only', async () => {
const project = prepareEmpty()
await install({
devDependencies: {
'is-negative': '2.1.0',
},
}, await testDefaults({ production: true }))
const lockfile = await project.readLockfile()
const id = '/is-negative/2.1.0'
expect(lockfile.devDependencies).toBeTruthy()
expect(lockfile.devDependencies['is-negative']).toBe('2.1.0')
expect(lockfile.packages[id]).toBeTruthy()
})
test('lockfile with scoped package', async () => {
prepareEmpty()
await writeYamlFile(WANTED_LOCKFILE, {
dependencies: {
'@types/semver': '5.3.31',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/@types/semver/5.3.31': {
resolution: {
integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=',
},
},
},
specifiers: {
'@types/semver': '^5.3.31',
},
}, { lineWidth: 1000 })
await install({
dependencies: {
'@types/semver': '^5.3.31',
},
}, await testDefaults({ frozenLockfile: true }))
})
test("lockfile doesn't lock subdependencies that don't satisfy the new specs", async () => {
const project = prepareEmpty()
// dependends on react-onclickoutside@5.9.0
const manifest = await addDependenciesToPackage({}, ['react-datetime@2.8.8'], await testDefaults({ fastUnpack: false, save: true }))
// dependends on react-onclickoutside@0.3.4
await addDependenciesToPackage(manifest, ['react-datetime@1.3.0'], await testDefaults({ save: true }))
expect(
project.requireModule('.pnpm/react-datetime@1.3.0/node_modules/react-onclickoutside/package.json').version
).toBe('0.3.4') // react-datetime@1.3.0 has react-onclickoutside@0.3.4 in its node_modules
const lockfile = await project.readLockfile()
expect(Object.keys(lockfile.dependencies).length).toBe(1) // resolutions not duplicated
})
test('lockfile not created when no deps in package.json', async () => {
const project = prepareEmpty()
await install({}, await testDefaults())
expect(await project.readLockfile()).toBeFalsy()
expect(await exists('node_modules')).toBeFalsy()
})
test('lockfile removed when no deps in package.json', async () => {
const project = prepareEmpty()
await writeYamlFile(WANTED_LOCKFILE, {
dependencies: {
'is-negative': '2.1.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/is-negative/2.1.0': {
resolution: {
tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-negative/-/is-negative-2.1.0.tgz`,
},
},
},
specifiers: {
'is-negative': '2.1.0',
},
}, { lineWidth: 1000 })
await install({}, await testDefaults())
expect(await project.readLockfile()).toBeFalsy()
})
test('lockfile is fixed when it does not match package.json', async () => {
const project = prepareEmpty()
await writeYamlFile(WANTED_LOCKFILE, {
dependencies: {
'@types/semver': '5.3.31',
'is-negative': '2.1.0',
'is-positive': '3.1.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/@types/semver/5.3.31': {
resolution: {
integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=',
},
},
'/is-negative/2.1.0': {
resolution: {
tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-negative/-/is-negative-2.1.0.tgz`,
},
},
'/is-positive/3.1.0': {
resolution: {
integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=',
},
},
},
specifiers: {
'@types/semver': '5.3.31',
'is-negative': '^2.1.0',
'is-positive': '^3.1.0',
},
}, { lineWidth: 1000 })
const reporter = sinon.spy()
await install({
devDependencies: {
'is-negative': '^2.1.0',
},
optionalDependencies: {
'is-positive': '^3.1.0',
},
}, await testDefaults({ reporter }))
const progress = sinon.match({
name: 'pnpm:progress',
status: 'resolving',
})
expect(reporter.withArgs(progress).callCount).toBe(0)
const lockfile = await project.readLockfile()
expect(lockfile.devDependencies['is-negative']).toBe('2.1.0')
expect(lockfile.optionalDependencies['is-positive']).toBe('3.1.0')
expect(lockfile.dependencies).toBeFalsy()
expect(lockfile.packages).not.toHaveProperty(['/@types/semver/5.3.31'])
})
test(`doing named installation when ${WANTED_LOCKFILE} exists already`, async () => {
const project = prepareEmpty()
await writeYamlFile(WANTED_LOCKFILE, {
dependencies: {
'@types/semver': '5.3.31',
'is-negative': '2.1.0',
'is-positive': '3.1.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/@types/semver/5.3.31': {
resolution: {
integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=',
},
},
'/is-negative/2.1.0': {
resolution: {
tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-negative/-/is-negative-2.1.0.tgz`,
},
},
'/is-positive/3.1.0': {
resolution: {
integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=',
},
},
},
specifiers: {
'@types/semver': '5.3.31',
'is-negative': '^2.1.0',
'is-positive': '^3.1.0',
},
}, { lineWidth: 1000 })
const reporter = sinon.spy()
const manifest = await addDependenciesToPackage({
dependencies: {
'@types/semver': '5.3.31',
'is-negative': '^2.1.0',
'is-positive': '^3.1.0',
},
}, ['is-positive'], await testDefaults({ reporter }))
await install(manifest, await testDefaults({ reporter }))
expect(reporter.calledWithMatch(LOCKFILE_WARN_LOG)).toBeFalsy()
await project.has('is-negative')
})
test(`respects ${WANTED_LOCKFILE} for top dependencies`, async () => {
const project = prepareEmpty()
const reporter = sinon.spy()
// const fooProgress = sinon.match({
// name: 'pnpm:progress',
// status: 'resolving',
// manifest: {
// name: 'foo',
// },
// })
const pkgs = ['foo', 'bar', 'qar']
await Promise.all(pkgs.map(async (pkgName) => addDistTag(pkgName, '100.0.0', 'latest')))
let manifest = await addDependenciesToPackage({}, ['foo'], await testDefaults({ save: true, reporter }))
// t.equal(reporter.withArgs(fooProgress).callCount, 1, 'reported foo once')
manifest = await addDependenciesToPackage(manifest, ['bar'], await testDefaults({ targetDependenciesField: 'optionalDependencies' }))
manifest = await addDependenciesToPackage(manifest, ['qar'], await testDefaults({ addDependenciesToPackage: 'devDependencies' }))
manifest = await addDependenciesToPackage(manifest, ['foobar'], await testDefaults({ save: true }))
expect((await readPackageJsonFromDir(path.resolve('node_modules', 'foo'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules', 'bar'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules', 'qar'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules/.pnpm/foobar@100.0.0/node_modules/foo'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules/.pnpm/foobar@100.0.0/node_modules/bar'))).version).toBe('100.0.0')
await Promise.all(pkgs.map(async (pkgName) => addDistTag(pkgName, '100.1.0', 'latest')))
await rimraf('node_modules')
await rimraf(path.join('..', '.store'))
reporter.resetHistory()
// shouldn't care about what the registry in npmrc is
// the one in lockfile should be used
await install(manifest, await testDefaults({
rawConfig: {
registry: 'https://registry.npmjs.org',
},
registry: 'https://registry.npmjs.org',
reporter,
}))
// t.equal(reporter.withArgs(fooProgress).callCount, 0, 'not reported foo')
await project.storeHasNot('foo', '100.1.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules', 'foo'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules', 'bar'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules', 'qar'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules/.pnpm/foobar@100.0.0/node_modules/foo'))).version).toBe('100.0.0')
expect((await readPackageJsonFromDir(path.resolve('node_modules/.pnpm/foobar@100.0.0/node_modules/bar'))).version).toBe('100.0.0')
})
test(`subdeps are updated on repeat install if outer ${WANTED_LOCKFILE} does not match the inner one`, async () => {
const project = prepareEmpty()
await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest')
const manifest = await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults())
await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0')
const lockfile = await project.readLockfile()
expect(lockfile.packages).toHaveProperty(['/dep-of-pkg-with-1-dep/100.0.0'])
delete lockfile.packages['/dep-of-pkg-with-1-dep/100.0.0']
lockfile.packages['/dep-of-pkg-with-1-dep/100.1.0'] = {
resolution: {
integrity: getIntegrity('dep-of-pkg-with-1-dep', '100.1.0'),
},
}
lockfile.packages['/pkg-with-1-dep/100.0.0'].dependencies!['dep-of-pkg-with-1-dep'] = '100.1.0'
await writeYamlFile(WANTED_LOCKFILE, lockfile, { lineWidth: 1000 })
await install(manifest, await testDefaults())
await project.storeHas('dep-of-pkg-with-1-dep', '100.1.0')
})
test("recreates lockfile if it doesn't match the dependencies in package.json", async () => {
const project = prepareEmpty()
let manifest = await addDependenciesToPackage({}, ['is-negative@1.0.0'], await testDefaults({ pinnedVersion: 'patch', targetDependenciesField: 'dependencies' }))
manifest = await addDependenciesToPackage(manifest, ['is-positive@1.0.0'], await testDefaults({ pinnedVersion: 'patch', targetDependenciesField: 'devDependencies' }))
manifest = await addDependenciesToPackage(manifest, ['map-obj@1.0.0'], await testDefaults({ pinnedVersion: 'patch', targetDependenciesField: 'optionalDependencies' }))
const lockfile1 = await project.readLockfile()
expect(lockfile1.dependencies['is-negative']).toBe('1.0.0')
expect(lockfile1.specifiers['is-negative']).toBe('1.0.0')
manifest.dependencies!['is-negative'] = '^2.1.0'
manifest.devDependencies!['is-positive'] = '^2.0.0'
manifest.optionalDependencies!['map-obj'] = '1.0.1'
await install(manifest, await testDefaults())
const lockfile = await project.readLockfile()
expect(lockfile.dependencies['is-negative']).toBe('2.1.0')
expect(lockfile.specifiers['is-negative']).toBe('^2.1.0')
expect(lockfile.devDependencies['is-positive']).toBe('2.0.0')
expect(lockfile.specifiers['is-positive']).toBe('^2.0.0')
expect(lockfile.optionalDependencies['map-obj']).toBe('1.0.1')
expect(lockfile.specifiers['map-obj']).toBe('1.0.1')
})
test('repeat install with lockfile should not mutate lockfile when dependency has version specified with v prefix', async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['highmaps-release@5.0.11'], await testDefaults())
const lockfile1 = await project.readLockfile()
expect(lockfile1.dependencies['highmaps-release']).toBe('5.0.11')
await rimraf('node_modules')
await install(manifest, await testDefaults())
const lockfile2 = await project.readLockfile()
expect(lockfile1).toStrictEqual(lockfile2) // lockfile hasn't been changed
})
test('package is not marked dev if it is also a subdep of a regular dependency', async () => {
const project = prepareEmpty()
await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest')
const manifest = await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults())
console.log('installed pkg-with-1-dep')
await addDependenciesToPackage(manifest, ['dep-of-pkg-with-1-dep'], await testDefaults({ targetDependenciesField: 'devDependencies' }))
console.log('installed optional dependency which is also a dependency of pkg-with-1-dep')
const lockfile = await project.readLockfile()
expect(lockfile.packages['/dep-of-pkg-with-1-dep/100.0.0'].dev).toBeFalsy()
})
test('package is not marked optional if it is also a subdep of a regular dependency', async () => {
const project = prepareEmpty()
await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest')
const manifest = await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults())
await addDependenciesToPackage(manifest, ['dep-of-pkg-with-1-dep'], await testDefaults({ targetDependenciesField: 'optionalDependencies' }))
const lockfile = await project.readLockfile()
expect(lockfile.packages['/dep-of-pkg-with-1-dep/100.0.0'].optional).toBeFalsy()
})
test('scoped module from different registry', async () => {
const project = prepareEmpty()
const opts = await testDefaults()
opts.registries!.default = 'https://registry.npmjs.org/' // eslint-disable-line
opts.registries!['@zkochan'] = `http://localhost:${REGISTRY_MOCK_PORT}` // eslint-disable-line
opts.registries!['@foo'] = `http://localhost:${REGISTRY_MOCK_PORT}` // eslint-disable-line
await addDependenciesToPackage({}, ['@zkochan/foo', '@foo/has-dep-from-same-scope', 'is-positive'], opts)
await project.has('@zkochan/foo')
const lockfile = await project.readLockfile()
expect(lockfile).toStrictEqual({
dependencies: {
'@foo/has-dep-from-same-scope': '1.0.0',
'@zkochan/foo': '1.0.0',
'is-positive': '3.1.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/@foo/has-dep-from-same-scope/1.0.0': {
dependencies: {
'@foo/no-deps': '1.0.0',
'is-negative': '1.0.0',
},
dev: false,
resolution: {
integrity: getIntegrity('@foo/has-dep-from-same-scope', '1.0.0'),
},
},
'/@foo/no-deps/1.0.0': {
dev: false,
resolution: {
integrity: getIntegrity('@foo/no-deps', '1.0.0'),
},
},
'/@zkochan/foo/1.0.0': {
dev: false,
resolution: {
integrity: 'sha512-IFvrYpq7E6BqKex7A7czIFnFncPiUVdhSzGhAOWpp8RlkXns4y/9ZdynxaA/e0VkihRxQkihE2pTyvxjfe/wBg==',
},
},
'/is-negative/1.0.0': {
dev: false,
engines: {
node: '>=0.10.0',
},
resolution: {
integrity: 'sha1-clmHeoPIAKwxkd17nZ+80PdS1P4=',
},
},
'/is-positive/3.1.0': {
dev: false,
engines: {
node: '>=0.10.0',
},
resolution: {
integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=',
},
},
},
specifiers: {
'@foo/has-dep-from-same-scope': '^1.0.0',
'@zkochan/foo': '^1.0.0',
'is-positive': '^3.1.0',
},
})
})
test('repeat install with no inner lockfile should not rewrite packages in node_modules', async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['is-negative@1.0.0'], await testDefaults())
await rimraf('node_modules/.pnpm/lock.yaml')
await install(manifest, await testDefaults())
await project.has('is-negative')
})
test('packages are placed in devDependencies even if they are present as non-dev as well', async () => {
const project = prepareEmpty()
await addDistTag('dep-of-pkg-with-1-dep', '100.1.0', 'latest')
const reporter = sinon.spy()
await install({
devDependencies: {
'dep-of-pkg-with-1-dep': '^100.1.0',
'pkg-with-1-dep': '^100.0.0',
},
}, await testDefaults({ reporter }))
const lockfile = await project.readLockfile()
expect(lockfile.devDependencies).toHaveProperty(['dep-of-pkg-with-1-dep'])
expect(lockfile.devDependencies).toHaveProperty(['pkg-with-1-dep'])
expect(reporter.calledWithMatch({
added: {
dependencyType: 'dev',
name: 'dep-of-pkg-with-1-dep',
version: '100.1.0',
},
level: 'debug',
name: 'pnpm:root',
} as RootLog)).toBeTruthy()
expect(reporter.calledWithMatch({
added: {
dependencyType: 'dev',
name: 'pkg-with-1-dep',
version: '100.0.0',
},
level: 'debug',
name: 'pnpm:root',
} as RootLog)).toBeTruthy()
})
// This testcase verifies that pnpm is not failing when trying to preserve dependencies.
// Only when a dependency is a range dependency, should pnpm try to compare versions of deps with semver.satisfies().
test('updating package that has a github-hosted dependency', async () => {
prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['has-github-dep@1'], await testDefaults())
await addDependenciesToPackage(manifest, ['has-github-dep@latest'], await testDefaults())
})
test('updating package that has deps with peers', async () => {
prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['abc-grand-parent-with-c@0'], await testDefaults())
await addDependenciesToPackage(manifest, ['abc-grand-parent-with-c@1'], await testDefaults())
})
test('pendingBuilds gets updated if install removes packages', async () => {
const project = prepareEmpty()
await install({
dependencies: {
'pre-and-postinstall-scripts-example': '*',
'with-postinstall-b': '*',
},
}, await testDefaults({ fastUnpack: false, ignoreScripts: true }))
const modules1 = await project.readModulesManifest()
await install({
dependencies: {
'pre-and-postinstall-scripts-example': '*',
},
}, await testDefaults({ fastUnpack: false, ignoreScripts: true }))
const modules2 = await project.readModulesManifest()
expect(modules1).toBeTruthy()
expect(modules2).toBeTruthy()
expect(modules1!.pendingBuilds.length > modules2!.pendingBuilds.length).toBeTruthy()
})
test('dev properties are correctly updated on named install', async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage(
{},
['inflight@1.0.6'],
await testDefaults({ targetDependenciesField: 'devDependencies' })
)
await addDependenciesToPackage(manifest, ['foo@npm:inflight@1.0.6'], await testDefaults({}))
const lockfile = await project.readLockfile()
expect(
Object.values(lockfile.packages).filter((dep) => typeof dep.dev !== 'undefined')
).toStrictEqual([])
})
test('optional properties are correctly updated on named install', async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['inflight@1.0.6'], await testDefaults({ targetDependenciesField: 'optionalDependencies' }))
await addDependenciesToPackage(manifest, ['foo@npm:inflight@1.0.6'], await testDefaults({}))
const lockfile = await project.readLockfile()
expect(Object.values(lockfile.packages).filter((dep) => typeof dep.optional !== 'undefined')).toStrictEqual([])
})
test('dev property is correctly set for package that is duplicated to both the dependencies and devDependencies group', async () => {
const project = prepareEmpty()
// TODO: use a smaller package for testing
await addDependenciesToPackage({}, ['overlap@2.2.8'], await testDefaults())
const lockfile = await project.readLockfile()
expect(lockfile.packages['/couleurs/5.0.0'].dev === false).toBeTruthy()
})
test('no lockfile', async () => {
const project = prepareEmpty()
const reporter = sinon.spy()
await addDependenciesToPackage({}, ['is-positive'], await testDefaults({ useLockfile: false, reporter }))
expect(reporter.calledWithMatch(LOCKFILE_WARN_LOG)).toBeFalsy()
await project.has('is-positive')
expect(await project.readLockfile()).toBeFalsy()
})
test('lockfile is ignored when lockfile = false', async () => {
const project = prepareEmpty()
await writeYamlFile(WANTED_LOCKFILE, {
dependencies: {
'is-negative': '2.1.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/is-negative/2.1.0': {
resolution: {
integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp10=', // Invalid integrity
tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-negative/-/is-negative-2.1.0.tgz`,
},
},
},
specifiers: {
'is-negative': '2.1.0',
},
}, { lineWidth: 1000 })
const reporter = sinon.spy()
await install({
dependencies: {
'is-negative': '2.1.0',
},
}, await testDefaults({ useLockfile: false, reporter }))
expect(reporter.calledWithMatch(LOCKFILE_WARN_LOG)).toBeTruthy()
await project.has('is-negative')
expect(await project.readLockfile()).toBeTruthy()
})
test(`don't update ${WANTED_LOCKFILE} during uninstall when useLockfile: false`, async () => {
const project = prepareEmpty()
let manifest!: ProjectManifest
{
const reporter = sinon.spy()
manifest = await addDependenciesToPackage({}, ['is-positive'], await testDefaults({ reporter }))
expect(reporter.calledWithMatch(LOCKFILE_WARN_LOG)).toBeFalsy()
}
{
const reporter = sinon.spy()
await mutateModules([
{
dependencyNames: ['is-positive'],
manifest,
mutation: 'uninstallSome',
rootDir: process.cwd(),
},
], await testDefaults({ useLockfile: false, reporter }))
expect(reporter.calledWithMatch(LOCKFILE_WARN_LOG)).toBeTruthy()
}
await project.hasNot('is-positive')
expect(await project.readLockfile()).toBeTruthy()
})
test('fail when installing with useLockfile: false and lockfileOnly: true', async () => {
prepareEmpty()
try {
await install({}, await testDefaults({ useLockfile: false, lockfileOnly: true }))
throw new Error('installation should have failed')
} catch (err: any) { // eslint-disable-line
expect(err.message).toBe(`Cannot generate a ${WANTED_LOCKFILE} because lockfile is set to false`)
}
})
test("don't remove packages during named install when useLockfile: false", async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['is-positive'], await testDefaults({ useLockfile: false }))
await addDependenciesToPackage(manifest, ['is-negative'], await testDefaults({ useLockfile: false }))
await project.has('is-positive')
await project.has('is-negative')
})
test('save tarball URL when it is non-standard', async () => {
const project = prepareEmpty()
await addDependenciesToPackage({}, ['esprima-fb@3001.1.0-dev-harmony-fb'], await testDefaults({ fastUnpack: false }))
const lockfile = await project.readLockfile()
expect((lockfile.packages['/esprima-fb/3001.1.0-dev-harmony-fb'].resolution as TarballResolution).tarball).toBe('esprima-fb/-/esprima-fb-3001.0001.0000-dev-harmony-fb.tgz')
})
test('packages installed via tarball URL from the default registry are normalized', async () => {
const project = prepareEmpty()
await addDependenciesToPackage({}, [
`http://localhost:${REGISTRY_MOCK_PORT}/pkg-with-tarball-dep-from-registry/-/pkg-with-tarball-dep-from-registry-1.0.0.tgz`,
'https://registry.npmjs.org/is-positive/-/is-positive-1.0.0.tgz',
], await testDefaults())
const lockfile = await project.readLockfile()
expect(lockfile).toStrictEqual({
dependencies: {
'is-positive': '@registry.npmjs.org/is-positive/-/is-positive-1.0.0.tgz',
'pkg-with-tarball-dep-from-registry': '1.0.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/dep-of-pkg-with-1-dep/100.0.0': {
dev: false,
resolution: {
integrity: getIntegrity('dep-of-pkg-with-1-dep', '100.0.0'),
},
},
'/pkg-with-tarball-dep-from-registry/1.0.0': {
dependencies: {
'dep-of-pkg-with-1-dep': '100.0.0',
},
dev: false,
resolution: {
integrity: getIntegrity('pkg-with-tarball-dep-from-registry', '1.0.0'),
},
},
'@registry.npmjs.org/is-positive/-/is-positive-1.0.0.tgz': {
dev: false,
engines: { node: '>=0.10.0' },
name: 'is-positive',
resolution: {
tarball: 'https://registry.npmjs.org/is-positive/-/is-positive-1.0.0.tgz',
},
version: '1.0.0',
},
},
specifiers: {
'is-positive': 'https://registry.npmjs.org/is-positive/-/is-positive-1.0.0.tgz',
'pkg-with-tarball-dep-from-registry': `http://localhost:${REGISTRY_MOCK_PORT}/pkg-with-tarball-dep-from-registry/-/pkg-with-tarball-dep-from-registry-1.0.0.tgz`,
},
})
})
test('lockfile file has correct format when lockfile directory does not equal the prefix directory', async () => {
prepareEmpty()
const storeDir = path.resolve('..', '.store')
const manifest = await addDependenciesToPackage(
{},
[
'pkg-with-1-dep',
'@zkochan/foo@1.0.0',
'kevva/is-negative#1d7e288222b53a0cab90a331f1865220ec29560c',
],
await testDefaults({ save: true, lockfileDir: path.resolve('..'), storeDir })
)
expect(!await exists('node_modules/.modules.yaml')).toBeTruthy()
process.chdir('..')
const modules = await readYamlFile<object>(path.resolve('node_modules', '.modules.yaml'))
expect(modules).toBeTruthy()
expect(modules['pendingBuilds'].length).toBe(0) // eslint-disable-line @typescript-eslint/dot-notation
{
const lockfile: Lockfile = await readYamlFile(WANTED_LOCKFILE)
const id = '/pkg-with-1-dep/100.0.0'
expect(lockfile.lockfileVersion).toBe(LOCKFILE_VERSION)
expect(lockfile.importers).toBeTruthy()
expect(lockfile.importers.project).toBeTruthy()
expect(lockfile.importers.project.specifiers).toBeTruthy()
expect(lockfile.importers.project.dependencies).toBeTruthy()
expect(lockfile.importers.project.dependencies!['pkg-with-1-dep']).toBe('100.0.0')
expect(lockfile.importers.project.dependencies!['@zkochan/foo']).toBeTruthy()
expect(lockfile.importers.project.dependencies!['is-negative']).toContain('/')
expect(lockfile.packages![id].dependencies).toHaveProperty(['dep-of-pkg-with-1-dep'])
expect(lockfile.packages![id].resolution).toHaveProperty(['integrity'])
expect(lockfile.packages![id].resolution).not.toHaveProperty(['tarball'])
const absDepPath = 'github.com/kevva/is-negative/1d7e288222b53a0cab90a331f1865220ec29560c'
expect(lockfile.packages).toHaveProperty([absDepPath])
expect(lockfile.packages![absDepPath].name).toBeTruthy()
}
await fs.mkdir('project-2')
process.chdir('project-2')
await addDependenciesToPackage(manifest, ['is-positive'], await testDefaults({ save: true, lockfileDir: path.resolve('..'), storeDir }))
{
const lockfile = await readYamlFile<Lockfile>(path.join('..', WANTED_LOCKFILE))
expect(lockfile.importers).toHaveProperty(['project-2'])
// previous entries are not removed
const id = '/pkg-with-1-dep/100.0.0'
expect(lockfile.importers.project.specifiers).toBeTruthy()
expect(lockfile.importers.project.dependencies!['pkg-with-1-dep']).toBe('100.0.0')
expect(lockfile.importers.project.dependencies).toHaveProperty(['@zkochan/foo'])
expect(lockfile.importers.project.dependencies!['is-negative']).toContain('/')
expect(lockfile.packages).toHaveProperty([id])
expect(lockfile.packages![id].dependencies).toBeTruthy()
expect(lockfile.packages![id].dependencies).toHaveProperty(['dep-of-pkg-with-1-dep'])
expect(lockfile.packages![id].resolution).toHaveProperty(['integrity']) // eslint-disable-line
expect(lockfile.packages![id].resolution).not.toHaveProperty(['tarball']) // eslint-disable-line
const absDepPath = 'github.com/kevva/is-negative/1d7e288222b53a0cab90a331f1865220ec29560c'
expect(lockfile.packages).toHaveProperty([absDepPath])
expect(lockfile.packages![absDepPath].name).toBeTruthy()
}
})
test(`doing named installation when shared ${WANTED_LOCKFILE} exists already`, async () => {
const pkg1 = {
name: 'pkg1',
version: '1.0.0',
dependencies: {
'is-negative': '^2.1.0',
},
}
let pkg2: ProjectManifest = {
name: 'pkg2',
version: '1.0.0',
dependencies: {
'is-positive': '^3.1.0',
},
}
const projects = preparePackages([
pkg1,
pkg2,
])
await writeYamlFile(WANTED_LOCKFILE, {
importers: {
pkg1: {
dependencies: {
'is-negative': '2.1.0',
},
specifiers: {
'is-negative': '^2.1.0',
},
},
pkg2: {
dependencies: {
'is-positive': '3.1.0',
},
specifiers: {
'is-positive': '^3.1.0',
},
},
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'/is-negative/2.1.0': {
resolution: {
tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-negative/-/is-negative-2.1.0.tgz`,
},
},
'/is-positive/3.1.0': {
resolution: {
integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=',
},
},
},
}, { lineWidth: 1000 })
pkg2 = await addDependenciesToPackage(
pkg2,
['is-positive'],
await testDefaults({
dir: path.resolve('pkg2'),
lockfileDir: process.cwd(),
})
)
const currentLockfile = await readYamlFile<Lockfile>(path.resolve('node_modules/.pnpm/lock.yaml'))
expect(Object.keys(currentLockfile['importers'])).toStrictEqual(['pkg2'])
await mutateModules(
[
{
buildIndex: 0,
manifest: pkg1,
mutation: 'install',
rootDir: path.resolve('pkg1'),
},
{
buildIndex: 0,
manifest: pkg2,
mutation: 'install',
rootDir: path.resolve('pkg2'),
},
],
await testDefaults()
)
await projects['pkg1'].has('is-negative')
await projects['pkg2'].has('is-positive')
})
// Covers https://github.com/pnpm/pnpm/issues/1200
test(`use current ${WANTED_LOCKFILE} as initial wanted one, when wanted was removed`, async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['lodash@4.17.11', 'underscore@1.9.0'], await testDefaults())
await rimraf(WANTED_LOCKFILE)
await addDependenciesToPackage(manifest, ['underscore@1.9.1'], await testDefaults())
await project.has('lodash')
await project.has('underscore')
})
// Covers https://github.com/pnpm/pnpm/issues/1876
test('existing dependencies are preserved when updating a lockfile to a newer format', async () => {
const project = prepareEmpty()
await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest')
const manifest = await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults())
const initialLockfile = await project.readLockfile()
await writeYamlFile(WANTED_LOCKFILE, { ...initialLockfile, lockfileVersion: 5.01 }, { lineWidth: 1000 })
await addDistTag('dep-of-pkg-with-1-dep', '100.1.0', 'latest')
await mutateModules([
{
buildIndex: 0,
manifest,
mutation: 'install',
rootDir: process.cwd(),
},
], await testDefaults())
const updatedLockfile = await project.readLockfile()
expect(initialLockfile.packages).toStrictEqual(updatedLockfile.packages)
})
test('lockfile is not getting broken if the used registry changes', async () => {
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({}, ['is-positive@1'], await testDefaults())
const newOpts = await testDefaults({ registries: { default: 'https://registry.npmjs.org/' } })
let err!: PnpmError
try {
await addDependenciesToPackage(manifest, ['is-negative@1'], newOpts)
} catch (_err: any) { // eslint-disable-line
err = _err
}
expect(err.code).toBe('ERR_PNPM_REGISTRIES_MISMATCH')
await mutateModules([
{
buildIndex: 0,
manifest,
mutation: 'install',
rootDir: process.cwd(),
},
], newOpts)
await addDependenciesToPackage(manifest, ['is-negative@1'], newOpts)
expect(Object.keys((await project.readLockfile()).packages)).toStrictEqual([
'/is-negative/1.0.1',
'/is-positive/1.0.0',
])
})
test('broken lockfile is fixed even if it seems like up-to-date at first. Unless frozenLockfile option is set to true', async () => {
const project = prepareEmpty()
await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest')
const manifest = await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults({ lockfileOnly: true }))
{
const lockfile = await project.readLockfile()
expect(lockfile.packages).toHaveProperty(['/dep-of-pkg-with-1-dep/100.0.0'])
delete lockfile.packages['/dep-of-pkg-with-1-dep/100.0.0']
await writeYamlFile(WANTED_LOCKFILE, lockfile, { lineWidth: 1000 })
}
let err!: PnpmError
try {
await mutateModules([
{
buildIndex: 0,
manifest,
mutation: 'install',
rootDir: process.cwd(),
},
], await testDefaults({ frozenLockfile: true }))
} catch (_err: any) { // eslint-disable-line
err = _err
}
expect(err.code).toBe('ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY')
await mutateModules([
{
buildIndex: 0,
manifest,
mutation: 'install',
rootDir: process.cwd(),
},
], await testDefaults({ preferFrozenLockfile: true }))
await project.has('pkg-with-1-dep')
const lockfile = await project.readLockfile()
expect(lockfile.packages).toHaveProperty(['/dep-of-pkg-with-1-dep/100.0.0'])
})
const REGISTRY_MIRROR_DIR = path.join(__dirname, '../../../registry-mirror')
/* eslint-disable @typescript-eslint/no-explicit-any */
const isPositiveMeta = loadJsonFile.sync<any>(path.join(REGISTRY_MIRROR_DIR, 'is-positive.json'))
/* eslint-enable @typescript-eslint/no-explicit-any */
const tarballPath = path.join(REGISTRY_MIRROR_DIR, 'is-positive-3.1.0.tgz')
test('tarball domain differs from registry domain', async () => {
nock('https://registry.example.com', { allowUnmocked: true })
.get('/is-positive')
.reply(200, isPositiveMeta)
nock('https://registry.npmjs.org', { allowUnmocked: true })
.get('/is-positive/-/is-positive-3.1.0.tgz')
.replyWithFile(200, tarballPath)
const project = prepareEmpty()
await addDependenciesToPackage({},
[
'is-positive',
], await testDefaults({
fastUnpack: false,
lockfileOnly: true,
registries: {
default: 'https://registry.example.com',
},
save: true,
})
)
const lockfile = await project.readLockfile()
expect(lockfile).toStrictEqual({
dependencies: {
'is-positive': 'registry.npmjs.org/is-positive/3.1.0',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'registry.npmjs.org/is-positive/3.1.0': {
dev: false,
engines: { node: '>=0.10.0' },
name: 'is-positive',
resolution: {
integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=',
registry: 'https://registry.example.com/',
tarball: 'https://registry.npmjs.org/is-positive/-/is-positive-3.1.0.tgz',
},
version: '3.1.0',
},
},
specifiers: { 'is-positive': '^3.1.0' },
})
})
test('tarball installed through non-standard URL endpoint from the registry domain', async () => {
nock('https://registry.npmjs.org', { allowUnmocked: true })
.get('/is-positive/download/is-positive-3.1.0.tgz')
.replyWithFile(200, tarballPath)
const project = prepareEmpty()
await addDependenciesToPackage({},
[
'https://registry.npmjs.org/is-positive/download/is-positive-3.1.0.tgz',
], await testDefaults({
fastUnpack: false,
lockfileOnly: true,
registries: {
default: 'https://registry.npmjs.org/',
},
save: true,
})
)
const lockfile = await project.readLockfile()
expect(lockfile).toStrictEqual({
dependencies: {
'is-positive': '@registry.npmjs.org/is-positive/download/is-positive-3.1.0.tgz',
},
lockfileVersion: LOCKFILE_VERSION,
packages: {
'@registry.npmjs.org/is-positive/download/is-positive-3.1.0.tgz': {
dev: false,
engines: { node: '>=0.10.0' },
name: 'is-positive',
resolution: {
tarball: 'https://registry.npmjs.org/is-positive/download/is-positive-3.1.0.tgz',
},
version: '3.1.0',
},
},
specifiers: {
'is-positive': 'https://registry.npmjs.org/is-positive/download/is-positive-3.1.0.tgz',
},
})
})
test('a lockfile with merge conflicts is autofixed', async () => {
const project = prepareEmpty()
await fs.writeFile(WANTED_LOCKFILE, `\
importers:
.:
dependencies:
<<<<<<< HEAD
dep-of-pkg-with-1-dep: 100.0.0
=======
dep-of-pkg-with-1-dep: 100.1.0
>>>>>>> next
specifiers:
dep-of-pkg-with-1-dep: '>100.0.0'
lockfileVersion: ${LOCKFILE_VERSION}
packages:
<<<<<<< HEAD
/dep-of-pkg-with-1-dep/100.0.0:
dev: false
resolution:
integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}
=======
/dep-of-pkg-with-1-dep/100.1.0:
dev: false
resolution:
integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.1.0')}
>>>>>>> next`, 'utf8')
await install({
dependencies: {
'dep-of-pkg-with-1-dep': '>100.0.0',
},
}, await testDefaults())
const lockfile = await project.readLockfile()
expect(lockfile.dependencies['dep-of-pkg-with-1-dep']).toBe('100.1.0')
})
test('a lockfile with duplicate keys is fixed', async () => {
const project = prepareEmpty()
await fs.writeFile(WANTED_LOCKFILE, `\
importers:
.:
dependencies:
dep-of-pkg-with-1-dep: 100.0.0
specifiers:
dep-of-pkg-with-1-dep: '100.0.0'
lockfileVersion: ${LOCKFILE_VERSION}
packages:
/dep-of-pkg-with-1-dep/100.0.0:
resolution: {integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}}
dev: false
resolution: {integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}}
`, 'utf8')
const reporter = jest.fn()
await install({
dependencies: {
'dep-of-pkg-with-1-dep': '100.0.0',
},
}, await testDefaults({ reporter }))
const lockfile = await project.readLockfile()
expect(lockfile.dependencies['dep-of-pkg-with-1-dep']).toBe('100.0.0')
expect(reporter).toBeCalledWith(expect.objectContaining({
level: 'warn',
name: 'pnpm',
prefix: process.cwd(),
message: expect.stringMatching(/^Ignoring broken lockfile at .* duplicated mapping key/),
}))
})
test('a lockfile with duplicate keys is causes an exception, when frozenLockfile is true', async () => {
prepareEmpty()
await fs.writeFile(WANTED_LOCKFILE, `\
importers:
.:
dependencies:
dep-of-pkg-with-1-dep: 100.0.0
specifiers:
dep-of-pkg-with-1-dep: '100.0.0'
lockfileVersion: ${LOCKFILE_VERSION}
packages:
/dep-of-pkg-with-1-dep/100.0.0:
resolution: {integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}}
dev: false
resolution: {integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}}
`, 'utf8')
await expect(
install({
dependencies: {
'dep-of-pkg-with-1-dep': '100.0.0',
},
}, await testDefaults({ frozenLockfile: true }))
).rejects.toThrow(/^The lockfile at .* is broken: duplicated mapping key/)
})
test('a broken private lockfile is ignored', async () => {
prepareEmpty()
const manifest = await install({
dependencies: {
'dep-of-pkg-with-1-dep': '100.0.0',
},
}, await testDefaults())
await fs.writeFile('node_modules/.pnpm/lock.yaml', `\
importers:
.:
dependencies:
dep-of-pkg-with-1-dep: 100.0.0
specifiers:
dep-of-pkg-with-1-dep: '100.0.0'
lockfileVersion: ${LOCKFILE_VERSION}
packages:
/dep-of-pkg-with-1-dep/100.0.0:
resolution: {integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}}
dev: false
resolution: {integrity: ${getIntegrity('dep-of-pkg-with-1-dep', '100.0.0')}}
`, 'utf8')
const reporter = jest.fn()
await mutateModules([
{
buildIndex: 0,
mutation: 'install',
manifest,
rootDir: process.cwd(),
},
], await testDefaults({ reporter }))
expect(reporter).toBeCalledWith(expect.objectContaining({
level: 'warn',
name: 'pnpm',
prefix: process.cwd(),
message: expect.stringMatching(/^Ignoring broken lockfile at .* duplicated mapping key/),
}))
})
// Covers https://github.com/pnpm/pnpm/issues/2928
test('build metadata is always ignored in versions and the lockfile is not flickering because of them', async () => {
await addDistTag('@monorepolint/core', '0.5.0-alpha.51', 'latest')
const project = prepareEmpty()
const manifest = await addDependenciesToPackage({},
[
'@monorepolint/cli@0.5.0-alpha.51',
], await testDefaults({ lockfileOnly: true }))
const depPath = '/@monorepolint/core/0.5.0-alpha.51'
const initialLockfile = await project.readLockfile()
const initialPkgEntry = initialLockfile.packages[depPath]
expect(initialPkgEntry?.resolution).toStrictEqual({
integrity: 'sha512-ihFonHDppOZyG717OW6Bamd37mI2gQHjd09buTjbKhRX8NAHsTbRUKwp39ZYVI5AYgLF1eDlLpgOY4dHy2xGQw==',
})
await addDependenciesToPackage(manifest, ['is-positive'], await testDefaults({ lockfileOnly: true }))
const updatedLockfile = await project.readLockfile()
expect(initialPkgEntry).toStrictEqual(updatedLockfile.packages[depPath])
}) | the_stack |
import { BinaryOp } from "../../expression";
import {
NumericRangePattern,
NumericRangeLimit,
NumericAggregationPattern,
EmptyPattern,
isNumericAggregationPattern,
NeverPattern,
isNeverPattern,
isNumericRangePattern,
} from "./pattern";
/**
* Join two numeric ranges together to represent values in both ranges.
* Throw an error if the range could not match a single value.
* x > 10 && x > 5 => x > 10
* x >= 10 && x > 9 => x >= 10
* x > 10 && x >= 10 => x > 10
*/
export const intersectNumericRange = (
pattern1: NumericRangePattern | NeverPattern,
pattern2: NumericRangePattern | NeverPattern,
allowZeroRange?: boolean
): NumericRangePattern | NeverPattern => {
if (isNeverPattern(pattern1) || isNeverPattern(pattern2)) {
return isNeverPattern(pattern1) ? pattern1 : pattern2;
}
const newLower = maxComparison(pattern1.lower, pattern2.lower);
const newUpper = minComparison(pattern1.upper, pattern2.upper);
// merging ranges that are conflicting 1.lower = 10, 2.upper = 5
const newRange = { upper: newUpper, lower: newLower };
if (!allowZeroRange && !validateNumericRange(newRange)) {
return {
never: true,
reason: `Found zero range numeric range lower ${newRange.lower?.value} inclusive: ${newRange.lower?.inclusive}, upper ${newRange.upper?.value} inclusive: ${newRange.upper?.inclusive}`,
};
}
return newRange;
};
/**
* Given two limits of two ranges, return the limit that is the largest.
*
* The symbol of the limit doesn't matter.
*
* 10, 9 => 10
* 100, 1000 => 1000
* 100 (inclusive), 100 (exclusive) => 100 (exclusive)
*/
const maxComparison = (
limit1: NumericRangeLimit,
limit2: NumericRangeLimit
): NumericRangeLimit => {
// one is strictly greater than the other
if (limit1.value > limit2.value) return limit1;
if (limit2.value > limit1.value) return limit2;
// resolve conflicting inclusivity - inclusive is lower
return {
value: limit1.value,
inclusive: limit1.inclusive && limit2.inclusive,
};
};
/**
* Given two limits of two ranges, return the limit that is the smallest.
*
* The symbol of the limit doesn't matter.
*
* 10, 9 => 9
* 100, 1000 => 100
* 100 (inclusive), 100 (exclusive) => 100 (inclusive)
* 100 (exclusive), 100 (exclusive) => 100 (exclusive)
*/
const minComparison = (
limit1: NumericRangeLimit,
limit2: NumericRangeLimit
): NumericRangeLimit => {
// one is strictly less than the other
if (limit1.value < limit2.value) return limit1;
if (limit2.value < limit1.value) return limit2;
// resolve conflicting inclusivity - inclusive is lower
return {
value: limit1.value,
inclusive: limit1.inclusive || limit2.inclusive,
};
};
/**
* If the ranges overlap, return the union of them.
* If the range are mutually exclusive, return an aggregate with two ranges.
*
* [10, 20] [15, 30] => [10, 30]
* [10, 20] [21, 30] => [10, 20] [21, 30]
* [10, 20] [20, 30] => [10, 30]
* [10, 20) (20, 30] => [10, 20) (20, 30]
*/
export const unionNumericRange = (
pattern1: NumericRangePattern,
pattern2: NumericRangePattern
): NumericAggregationPattern | NumericRangePattern => {
if (isOverlappngRange(pattern1, pattern2)) {
// merge the overlapping ranges by finding the min lower and max upper
const minLower = minComparison(pattern1.lower, pattern2.lower);
const maxUpper = maxComparison(pattern1.upper, pattern2.upper);
return { lower: minLower, upper: maxUpper };
}
// when not overlapping, return who sets of numeric ranges
return { ranges: [pattern1, pattern2] };
};
// [lower1, upper1]
// [lower2, upper2]
// https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap/325964#325964
// When one of the factors is exclusive in a pair, use > or <
// [lower1, upper1)
// (lower2, upper2]
// (lower1, upper2]
// [lower2, upper2)
export const isOverlappngRange = (
pattern1: NumericRangePattern,
pattern2: NumericRangePattern
) => {
const lower1 = pattern1.lower?.value ?? Number.NEGATIVE_INFINITY;
const lower2 = pattern2.lower?.value ?? Number.NEGATIVE_INFINITY;
const upper1 = pattern1.upper?.value ?? Number.POSITIVE_INFINITY;
const upper2 = pattern2.upper?.value ?? Number.POSITIVE_INFINITY;
const firstInclusive = pattern1.lower?.inclusive && pattern2.upper?.inclusive;
const secondInclusive =
pattern1.upper?.inclusive && pattern2.lower?.inclusive;
return (
(firstInclusive ? lower1 <= upper2 : lower1 < upper2) &&
(secondInclusive ? upper1 >= lower2 : upper1 > lower2)
);
};
/**
* In a valid range, the lower is before the upper.
*
* [10, 5] => invalid
* [5, 10] => valid
* [10, 10) => invalid
* [10, 10] => valid
*/
export const validateNumericRange = (range: NumericRangePattern): boolean => {
if (range.lower) {
if (range.upper) {
// when both lower and upper are given, the lower must be lower than the upper
// when the lower and the upper are the same, the values must be inclusive, else there is zero range.
if (range.lower.value == range.upper.value) {
// x >= 10 && x <= 10 => valid (can be 10)
// x >= 10 && x < 10 => invalid (zero range)
// x > 10 && x <= 10 => invalid (zero range)
// x > 10 && x < 10 => invalid (zero range)
if (range.lower.inclusive && range.upper.inclusive) {
return true;
}
return false;
}
// lower value must be less than upper value
// x > 10 && x < 100
return range.lower?.value < range.upper?.value;
}
}
return !!range.lower || !!range.upper;
};
/**
* Runs {@link reduceNumericRanges} and then checks to see if the outcome is
* empty, singular, or still an aggregate.
*/
export const reduceNumericAggregate = (
pattern: NumericAggregationPattern
): EmptyPattern | NumericRangePattern | NumericAggregationPattern => {
const reduced = reduceNumericRanges(pattern.ranges);
if (reduced.length === 0) {
return { empty: true };
} else if (reduced.length === 1) {
return reduced[0];
}
return { ranges: reduced };
};
/**
* Given one to many ranges, collapse them all to the least number of ranges when one or more overlap.
* This operation may take multiple iterations to find all overlappting ranges.
*
* TODO: this can probably be simplified to a single iteration by ordering the ranges, the performance impact will be minimal.
*
* one or more ranges merge with multiple other ranges
* [1, 10], [11, 20], [8, 12]
* [1, 10], [11, 20]
* [1, 12], [8, 20]
* [1, 20]
*
* one or more ranges merge with one other range
* [1, 10], [11, 20], [12, 21]
* [1, 10], [11, 20]
* [1, 10], [11, 21]
*
* one or more ranges merge with multiple other range early
* [8, 12], [1, 10], [11, 20]
* [1, 12]
* [1, 20]
*
* no ranges merge
* [1, 10], [11, 20], [21, 22]
* [1, 10], [11, 20], [21, 22]
*/
export const reduceNumericRanges = (
ranges: NumericRangePattern[]
): NumericRangePattern[] => {
return ranges.reduce((newRanges, range) => {
const [overlappingRanges, otherRanges] = newRanges.reduce(
([over, other], r) =>
isOverlappngRange(range, r)
? [[...over, r], other]
: [over, [...other, r]],
[[], []] as [NumericRangePattern[], NumericRangePattern[]]
);
if (overlappingRanges.length === 0) {
return [...newRanges, range];
}
const mergedRanges = overlappingRanges
.map((r) => unionNumericRange(r, range))
.reduce(
(acc, r) => [
...acc,
...(isNumericAggregationPattern(r) ? r.ranges : [r]),
],
[] as NumericRangePattern[]
);
const reducedRanges = reduceNumericRanges(mergedRanges);
return [...reducedRanges, ...otherRanges];
}, [] as NumericRangePattern[]);
};
/**
* Invert numeric ranges!
*
* [10, 20] => [neg_inf, 10), (20, inf]
* (10, 20) => [neg_inf, 10], [20, inf]
* (10, inf] => [neg_inf, 10]
* [neg_inf, 20] => (20, inf]
*/
export const negateNumericRange = (
pattern: NumericRangePattern
): NumericRangePattern => ({
lower:
pattern.upper.value !== Number.POSITIVE_INFINITY
? { inclusive: !pattern.upper.inclusive, value: pattern.upper.value }
: { value: Number.NEGATIVE_INFINITY, inclusive: true },
upper:
pattern.lower.value !== Number.NEGATIVE_INFINITY
? { inclusive: !pattern.lower.inclusive, value: pattern.lower.value }
: { value: Number.POSITIVE_INFINITY, inclusive: true },
});
/**
* Intersect multiple numeric ranges.
* 1. attempt to intersect each numeric ranges.
* 2. validate each result
* 3. filter invalid result.
* 4. Fail if no results are valid.
*
* [10, 20] AND ( [5, 15] OR [25, 30] ) => [10, 15]
* [10, 20] AND ( [25, 30] OR [35, 40] ) => INVALID (cannot AND either range on the other side)
* ([10, 20] OR [30, 40]) AND ( [5, 15] OR [25, 30] ) => [10,15] OR 30
* ([10, 20] OR [30, 40]) AND ( [5, 15] OR [25, 30) ) => INVALID
*/
export const intersectNumericAggregation = (
aggregation1: NumericAggregationPattern,
aggregation2: NumericAggregationPattern
):
| NumericAggregationPattern
| NumericRangePattern
| EmptyPattern
| NeverPattern => {
const joinedRanges = aggregation1.ranges.reduce((ranges, range) => {
const joinedRanges = aggregation2.ranges
.map((r) => intersectNumericRange(r, range, true))
.filter(isNumericRangePattern)
.filter(validateNumericRange);
return [...ranges, ...joinedRanges];
}, [] as NumericRangePattern[]);
if (joinedRanges.length === 0) {
return {
never: true,
reason: "Zero intersection numeric ranges.",
};
}
return reduceNumericAggregate({ ranges: joinedRanges });
};
/**
* Apply intersection logic between a single range and set of aggregate ranges (OR logic).
*/
export const intersectNumericAggregationWithRange = (
aggregation: NumericAggregationPattern,
range: NumericRangePattern
):
| NumericAggregationPattern
| NumericRangePattern
| EmptyPattern
| NeverPattern => {
const joinedRanges = aggregation.ranges
.map((r) => intersectNumericRange(range, r))
.filter(isNumericRangePattern)
.filter(validateNumericRange);
if (joinedRanges.length === 0) {
return {
never: true,
reason: "Zero intersection numeric ranges.",
};
}
return reduceNumericAggregate({ ranges: joinedRanges });
};
/**
* Creates a single numeric range entry with only one limit (lower or upper) set.
*/
export const createSingleNumericRange = (
value: number,
op: BinaryOp
): NumericRangePattern | undefined => {
if (op === "<" || op === "<=") {
return {
upper: { value, inclusive: op === "<=" },
lower: { value: Number.NEGATIVE_INFINITY, inclusive: true },
};
} else if (op === ">" || op === ">=") {
return {
lower: { value, inclusive: op === ">=" },
upper: { value: Number.POSITIVE_INFINITY, inclusive: true },
};
}
return;
}; | the_stack |
import { LuaParse } from './LuaParse'
import { LuaFiledCompletionInfo } from "./provider/LuaFiledCompletionInfo"
import { LuaInfoManager } from './LuaInfoManager'
import { LuaParseTool } from './LuaParseTool'
import cp = require('child_process');
import vscode = require('vscode');
var fs = require('fs');
import { LuaInfo, TokenInfo, TokenTypes, LuaComment, LuaRange, LuaErrorEnum, LuaError, LuaInfoType } from './TokenInfo';
import { ExtensionManager } from "./ex/ExtensionManager";
export function CLog(message?: any, ...optionalParams: any[]) {
var i = 1;
// console.log(message, ...optionalParams);
}
/**
* 判断是否是空格
* */
export function isWhiteSpace(charCode): boolean {
return 9 === charCode || 32 === charCode || 0xB === charCode || 0xC === charCode;
}
/**
* 判断是否换行
* */
export function isLineTerminator(charCode): boolean {
return 10 === charCode || 13 === charCode;
}
export function isIdentifierPart(charCode): boolean {
return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode || (charCode >= 48 && charCode <= 57);
}
export function getTokens(document: vscode.TextDocument, position: vscode.Position, lpt?: LuaParseTool): Array<TokenInfo> {
var start: vscode.Position = new vscode.Position(0, 0)
if (lpt == null) {
var lp: LuaParse = LuaParse.lp;
lpt = LuaParse.lp.lpt;
}
var tokens: Array<TokenInfo> = new Array<TokenInfo>();
if (position == null) {
lpt.Reset(document.getText())
} else {
lpt.Reset(document.getText(new vscode.Range(start, position)))
}
while (true) {
CLog();
var token: TokenInfo = lpt.lex();
if (token.error != null) {
return;
}
if (token.type == TokenTypes.EOF) {
break;
}
token.index = tokens.length;
tokens.push(token);
}
return tokens;
}
export function getComments(comments: Array<LuaComment>): string {
if (comments == null) return "";
var commentStr: string = "";
if (comments.length == 1) {
return comments[0].content;
}
for (var i: number = 0; i < comments.length; i++) {
var comment = comments[i].content
var index = comment.trim().indexOf("==");
if (index == 0) { continue }
commentStr = commentStr + comment;
}
return commentStr;
}
export function getDescComment(comment: string) {
var commentStr: string = ""
var commentIndex: number = comment.indexOf("@desc")
if (commentIndex > -1) {
commentStr = comment.substring(commentIndex + 5);
commentStr = trimCommentStr(commentStr)
} else {
if (comment.indexOf("@") == 0) {
commentStr = ""
} else {
commentStr = comment;
}
}
return commentStr
}
export function getFirstComments(comments: Array<LuaComment>): string {
if (comments == null) return "";
var commentStr: string = null;
if (comments.length == 1) {
return getDescComment(comments[0].content);
}
for (var i: number = 0; i < comments.length; i++) {
var comment = comments[i].content
var index = comment.trim().indexOf("==");
if (index == 0) { continue }
commentStr = getDescComment(comments[i].content)
if (commentStr != "") {
break
}
}
return commentStr;
}
export function trimCommentStr(commentStr: string): string {
commentStr = commentStr.trim()
if (commentStr.indexOf(":") == 0) {
return commentStr.substring(1)
} else {
return commentStr
}
}
/**
* 忽略end
*/
export function ignoreEnd(index: number, tokens: Array<TokenInfo>) {
var lp: LuaParse = LuaParse.lp;
var endCount: number = 1;
while (index >= 0) {
var token: TokenInfo = tokens[index]
index--;
if (lp.consume('do', token, TokenTypes.Keyword) ||
lp.consume('then', token, TokenTypes.Keyword) ||
lp.consume('function', token, TokenTypes.Keyword)
) {
endCount--;
if (endCount == 0) {
return index;
}
} else if (lp.consume('end', token, TokenTypes.Keyword)) {
endCount++;
}
}
return index
}
// export function getCurrentFunctionName(tokens: Array<TokenInfo>): Array<string> {
// var lp: LuaParse = LuaParse.lp;
// //检查end
// var maxLine = tokens.length
// var index = tokens.length - 1
// var funNames: Array<string> = new Array<string>();
// var endCount = 0;
// var lastEndCount = 0;
// var isBreak: boolean = false
// while (index >= 0) {
// if (isBreak) break
// var token: TokenInfo = tokens[index]
// if (lp.consume('end', token, TokenTypes.Keyword)) {
// index--;
// index = ignoreEnd(index, tokens)
// }
// else if (lp.consume("function", token, TokenTypes.Keyword)) {
// var starIndex = 0;
// var endIndex = 0;
// //获得参数列表
// var nextIndex = index + 1
// //往下找 <maxLine 表示参数列表
// while (nextIndex < maxLine) {
// var nextToken: TokenInfo = tokens[nextIndex]
// if (lp.consume('(', nextToken, TokenTypes.Punctuator)) {
// //先确定有参数并且不是在编写参数
// starIndex = nextIndex;
// }
// if (lp.consume(')', nextToken, TokenTypes.Punctuator)) {
// //先确定有参数并且不是在编写参数
// endIndex = nextIndex;
// break;
// }
// nextIndex++;
// }
// var isArgFun: boolean = false
// if (starIndex - index == 1) {
// isArgFun = true
// }
// var funName: string = "";
// if (starIndex <= endIndex && starIndex != 0) {
// if (isArgFun) {
// funName = "TempFun_" + token.line + "_" + token.lineStart
// funNames.push(funName);
// // console.log(funName)
// } else {
// var findex: number = index + 1;
// //找到方法名
// var functionNameToken: TokenInfo = tokens[findex];
// funName = funName + functionNameToken.value;
// while (true) {
// findex++;
// var nextToken: TokenInfo = tokens[findex]
// if (
// lp.consume('.', nextToken, TokenTypes.Punctuator) ||
// lp.consume(':', nextToken, TokenTypes.Punctuator)
// ) {
// findex++;
// funName += nextToken.value;
// functionNameToken = tokens[findex];
// funName = funName + functionNameToken.value;
// isBreak = true
// }
// if (findex == starIndex) {
// break;
// }
// }
// // console.log(funName)
// funNames.push(funName);
// //找出参数列表
// }
// }
// }
// index--;
// }
// // console.log("==================")
// // console.log(funNames)
// var newFunNames: Array<string> = new Array<string>();
// for (var i = 0; i < funNames.length; i++) {
// var fn = "";
// for (var j = funNames.length - 1; j > i; j--) {
// fn += funNames[j] + "->";
// }
// fn += funNames[i]
// newFunNames.push(fn)
// }
// return newFunNames;
// }
/**
* 获取方法名 采用倒叙 获取一个或者多个方法 直到遇到xxx:fun 或者 xxx.fun
* @param tokens
*/
export function getCurrentFunctionName(tokens: Array<TokenInfo>): Array<string> {
var lp: LuaParse = LuaParse.lp;
var funNames: Array<string> = new Array<string>();
var index = tokens.length - 1
while (index >= 0) {
var token: TokenInfo = tokens[index]
index--
if (token.type == TokenTypes.Keyword && token.value == "function") {
var nextIndex = token.index + 1
if (nextIndex < tokens.length) {
var nextToken: TokenInfo = tokens[nextIndex]
var funName = ""
if (nextToken.type == TokenTypes.Punctuator && nextToken.value == "(") {
funName = "TempFun_" + token.line + "_" + token.lineStart
} else {
funName = this.getFunName(tokens, nextIndex)
}
if(funName != null){
funNames.push(funName)
if (funName.indexOf(".") > -1 || funName.indexOf(":") > -1) {
break
}
}else
{
return []
}
} else {
return []
}
} else if (lp.consume('end', token, TokenTypes.Keyword)) {
index = ignoreEnd(index, tokens)
}
}
var newFunNames: Array<string> = new Array<string>();
for (var i = 0; i < funNames.length; i++) {
var fn = "";
for (var j = funNames.length - 1; j > i; j--) {
fn += funNames[j] + "->";
}
fn += funNames[i]
newFunNames.push(fn)
}
return newFunNames
}
export function getFunName(tokens: Array<TokenInfo>, index: number): string {
var length = tokens.length - 1
var funName: string = ""
while (index < length) {
var token: TokenInfo = tokens[index]
if (token.type == TokenTypes.Punctuator && token.value == "(") {
return funName;
} else {
funName += token.value
}
index++;
}
return funName;
}
export function getSelfToModuleName(tokens: Array<TokenInfo>, lp: LuaParse): any {
var index: number = tokens.length - 1;
while (true) {
CLog();
if (index < 0) break;
var token: TokenInfo = tokens[index]
if (lp.consume('function', token, TokenTypes.Keyword)) {
var nextToken: TokenInfo = tokens[index + 1]
if (nextToken.type == TokenTypes.Identifier) {
var nextToken1: TokenInfo = tokens[index + 2]
if (lp.consume(':', nextToken1, TokenTypes.Punctuator)) {
var moduleName: string = nextToken.value;
var data = { moduleName: moduleName, token: nextToken };
return data
}
else index--
} else {
index--;
}
} else {
index--;
}
}
return null
}
export function getParamComment(param: string, comments: Array<LuaComment>) {
var paramName: string = "@" + param + "";
for (var i: number = 0; i < comments.length; i++) {
var comment = comments[i].content
if (comment.indexOf(paramName) > -1) {
comment = comment.replace(paramName, "")
comment = trimCommentStr(comment)
return comment;
}
}
return "";
}
export function openFolderInExplorer(folder) {
var command = null;
switch (process.platform) {
case 'linux':
command = 'xdg-open ' + folder;
break;
case 'darwin':
command = 'open ' + folder;
break;
case 'win32':
command = 'start ' + folder;
;
break;
}
if (command != null) {
cp.exec(command);
}
}
/**
* 如果文件夹不存在就创建一个
*/
export function createDirIfNotExists(dir: string): boolean {
if (!fs.existsSync(dir)) {
try {
fs.mkdirSync(dir);
console.log('Common目录创建成功');
return true
} catch (error) {
console.log(error)
return false
}
}
}; | the_stack |
import { AgentFrameworkError, Class } from '../../dependencies/core';
import { Disposable } from './Helpers/Disposable';
import { Agent, AgentReference, Params } from './Agent';
import { Domain } from './Domain';
import { IsPromise } from './Helpers/IsPromise';
import { IsObservable } from './Helpers/IsObservable';
import { CreateDomainAgent } from './Agent/CreateDomainAgent';
import { GetDomainAgent } from './Agent/GetDomainAgent';
// import { DomainKnowledge } from './DomainKnowledge';
class InMemory {
static readonly _types = new WeakMap<object, Map<Function, any>>(); // type-type mapping
static readonly _agents = new WeakMap<object, Map<AgentReference, any>>(); // type-instance mapping
static readonly _incomingAgents = new WeakMap<object, Map<any, Promise<any>>>();
// type-agent mapping
static types(domain: Domain): Map<Function, any> {
let value = this._types.get(domain);
if (!value) {
value = new Map();
this._types.set(domain, value);
}
return value;
}
// type-instance mapping
static agents(domain: Domain): Map<AgentReference, any> {
let value = this._agents.get(domain);
if (!value) {
value = new Map();
this._agents.set(domain, value);
}
return value;
}
static incomingAgents(domain: Domain): Map<any, Promise<any>> {
let value = this._incomingAgents.get(domain);
if (!value) {
value = new Map();
this._incomingAgents.set(domain, value);
}
return value;
}
}
/**
* In memory domain
*/
export class InMemoryDomain extends Domain implements Disposable {
/**
* Return true if this domain disposed
*/
disposed?: boolean;
/**
* Return true if this domain disposing
*/
disposing?: boolean;
/**
* Domain name
*/
get name(): string {
return this.constructor.name;
}
// /**
// * Check if have agent
// */
// hasInstance<T extends AgentIdentifier>(type: T): boolean {
// return this._singletons.has(type);
// }
/**
* Get agent of giving type, return undefined if don't have
*/
getAgent<T extends AgentReference>(identifier: T): Agent<T> | undefined {
return InMemory.agents(this).get(identifier);
}
// /**
// * Get agent of giving type, throw an error if don't have
// */
// getInstanceOrThrow<T extends AgentIdentifier>(type: T): Agent<T> {
// const agent = this.getInstance(type);
// if (!agent) {
// throw new AgentNotFoundError(type);
// }
// return agent;
// }
// /**
// * Check if have type registered
// */
// hasType<T extends AnyClass>(type: T): boolean {
// return this._types.has(type);
// }
/**
* Get constructor for current type, return undefined if don't have
*/
getType<T extends Function>(type: T): T | undefined {
return InMemory.types(this).get(type);
}
// /**
// * Get constructor for current type, throw an error if don't have
// */
// getTypeOrThrow<T extends AnyClass, P extends T>(type: T): P {
// const resolvedType = this.getType(type);
// if (!resolvedType) {
// throw new TypeNotFoundError(type);
// }
// return <P>resolvedType;
// }
// /**
// * Get agent
// */
// getDomainAgent<T extends AnyClass>(type: T): T | undefined {
// return this._agents.get(type);
// }
//region Factory
/**
* Create and initial an agent
*/
construct<T extends Function>(target: T, params?: Params<T>, transit?: boolean): Agent<T> {
const register = !transit;
if (register) {
const exists = this.getAgent(target);
if (exists !== undefined) {
return exists;
}
}
// find extended type
const type = this.getType<T>(target) || target;
// find domainAgent
const domainAgent = GetDomainAgent(this, type) || CreateDomainAgent(this, type);
// console.log('construct', target.name, 'from', type.name);
// initialize agent class
const agent = Reflect.construct(domainAgent, params || []);
// console.log('AGENT ====>', agent.constructor.name);
// note: to prevent human mistake
// do not allow construct promise or observable using constructor
if (IsPromise(agent)) {
// drop agent
throw new AgentFrameworkError('NotAllowConstructPromiseObject');
}
if (IsObservable(agent)) {
throw new AgentFrameworkError('NotAllowConstructObservableObject');
}
// no need register instance with domain
// if (agent === target) {
// RememberDomain(instance, this);
// }
if (register) {
// register agent to domain only if not transit
this.addAgent(type, agent);
}
// InitializeDomainAgent(type, agent);
return agent;
}
/**
* Create and initial an agent asynchronously
*/
resolve<T extends Function>(target: T, params?: Params<T>, transit?: boolean): Promise<Agent<T>> {
try {
const _incomingAgents = InMemory.incomingAgents(this);
const register = !transit;
if (register) {
const exists = this.getAgent(target);
if (exists !== undefined) {
return Promise.resolve(exists);
}
const pending = _incomingAgents.get(target);
if (pending) {
return <Promise<Agent<T>>>pending;
}
}
// find extended type
const type = this.getType<T>(target) || target;
// find domainAgent
const domainAgent = GetDomainAgent(this, type) || CreateDomainAgent(this, type);
// initialize agent class
const newCreated = Reflect.construct(domainAgent, params || []);
if (IsPromise<Agent<T>>(newCreated)) {
if (register) {
_incomingAgents.set(type, newCreated);
}
return newCreated.then(
(agent) => {
// no need register instance with domain
// if (agent === target) {
// RememberDomain(instance, this);
// }
if (register) {
this.addAgent(type, agent);
_incomingAgents.delete(type);
}
// InitializeDomainAgent(type, newCreatedAgent);
return agent;
},
(err) => {
if (!transit) {
_incomingAgents.delete(type);
}
throw err;
}
);
} else if (IsObservable(newCreated)) {
// TODO: add observable support later version
throw new AgentFrameworkError('NotSupportResolveObservableObject');
} else {
// no need register instance with domain
// DomainCore.SetDomain(newCreated, this);
if (!transit) this.addAgent(type, newCreated);
// InitializeDomainAgent(type, newCreated);
return Promise.resolve(newCreated);
}
} catch (err) {
return Promise.reject(err);
}
}
//endregion
//region Manage Type / Instance in this Domain
/**
* Register type
*/
addType<T extends object>(type: Class<T>): void {
let ctor: Function | null | undefined = type;
const types = InMemory.types(this);
while (ctor && !types.has(ctor) && Function.prototype !== ctor) {
types.set(ctor, type);
ctor = Reflect.getPrototypeOf(ctor) as Function;
}
}
/**
* Add an agent
*/
addAgent<T extends AgentReference>(identifier: T, agent: Agent<T>): void {
const _agents = InMemory.agents(this);
if (typeof identifier === 'function') {
let ctor: Function | null | undefined = identifier;
// console.log('add agent 1', identifier, agent)
while (ctor && !_agents.has(ctor) && Function.prototype !== ctor) {
// console.log('add agent 2', ctor, agent)
_agents.set(ctor, agent);
ctor = Reflect.getPrototypeOf(ctor) as Function;
}
} else {
_agents.set(identifier, agent);
}
}
/**
* Replace type
*/
setType<T extends object>(type: Class<T>, replacement: Class<T>): void {
// this._types.add(replacement);
InMemory.types(this).set(type, replacement);
}
// /**
// * Get all registered types in this domain
// */
// getTypes(): Array<Class> {
// const types: Array<Class> = [];
// const uniqueTypes = new Set(types);
// for (const type of this._types.values()) {
// if (!uniqueTypes.has(type)) {
// uniqueTypes.add(type);
// types.push(type);
// }
// }
// return types;
// }
/**
* Set agent instance
*/
setAgent<T extends AgentReference>(identifier: T, agent: Agent<T>): void {
InMemory.agents(this).set(identifier, agent);
}
// /**
// * Replace agent, throw error if origin agent not match
// */
// replaceAgent<T extends AgentIdentifier>(type: T, origin: Agent<T>, replace: Agent<T>): void {
// if (!this._agents.has(type)) {
// throw new Error('OriginAgentNotFound');
// }
// if (this._agents.get(type) !== origin) {
// throw new Error('OriginAgentNotMatch');
// }
// this._agents.set(type, replace);
// }
/**
* Delete type mapping for giving type
*/
removeType<T extends object>(type: Class<T>): void {
InMemory.types(this).delete(type);
}
/**
* Delete agent. do nothing if agent not match
*/
removeAgent<T extends AgentReference>(identifier: T, agent: Agent<T>): boolean {
const _agents = InMemory.agents(this);
if (_agents.has(identifier) && _agents.get(identifier) === agent) {
_agents.delete(identifier);
// do not dispose because this agent may used by others
return true;
}
return false;
}
//endregion
// public beforeDecorate(attribute: IAttribute, target: Function): boolean {
// return true;
// }
// /**
// * Get all registered agents in this domain
// */
// getAgents(): Iterable<any> {
// return this._agents.values();
// }
/**
* Dispose this domain and all created agents
*/
dispose(): void {
if (this.disposed) {
return;
}
const _incomingAgents = InMemory.incomingAgents(this);
const _agents = InMemory.agents(this);
this.disposing = true;
for (const promise of _incomingAgents.values()) {
promise.then((agent) => {
if (typeof agent === 'object' && agent != null && typeof agent.dispose === 'function') {
// only dispose the agent of current domain
agent.dispose();
}
});
}
for (const agent of _agents.values()) {
if (typeof agent === 'object' && agent != null && typeof agent.dispose === 'function') {
// only dispose the agent of current domain
agent.dispose();
}
}
_incomingAgents.clear();
_agents.clear();
InMemory.types(this).clear();
this.disposed = true;
}
} | the_stack |
import { test } from '@japa/runner'
import type { ManyToMany } from '@ioc:Adonis/Lucid/Orm'
import { FactoryManager } from '../../src/Factory/index'
import { column, manyToMany } from '../../src/Orm/Decorators'
import {
fs,
setup,
getDb,
cleanup,
ormAdapter,
resetTables,
getBaseModel,
getFactoryModel,
setupApplication,
} from '../../test-helpers'
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
let db: ReturnType<typeof getDb>
let app: ApplicationContract
let BaseModel: ReturnType<typeof getBaseModel>
const FactoryModel = getFactoryModel()
const factoryManager = new FactoryManager()
test.group('Factory | ManyToMany | make', (group) => {
group.setup(async () => {
app = await setupApplication()
db = getDb(app)
BaseModel = getBaseModel(ormAdapter(db), app)
await setup()
})
group.teardown(async () => {
await db.manager.closeAll()
await cleanup()
await fs.cleanup()
})
group.each.teardown(async () => {
await resetTables()
})
test('make model with relationship', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory.with('skills').makeStubbed()
assert.exists(user.id)
assert.isFalse(user.$isPersisted)
assert.lengthOf(user.skills, 1)
assert.exists(user.skills[0].id)
assert.instanceOf(user.skills[0], Skill)
assert.deepEqual(user.skills[0].$extras, {})
assert.isFalse(user.skills[0].$isPersisted)
})
test('pass custom attributes to relationship', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory
.with('skills', 1, (related) => {
related.merge({ name: 'Dancing' })
})
.makeStubbed()
assert.isFalse(user.$isPersisted)
assert.lengthOf(user.skills, 1)
assert.instanceOf(user.skills[0], Skill)
assert.isFalse(user.skills[0].$isPersisted)
assert.equal(user.skills[0].name, 'Dancing')
})
test('make many relationship', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory
.with('skills', 2, (related) => {
related.merge({ name: 'Dancing' })
})
.makeStubbed()
assert.isFalse(user.$isPersisted)
assert.lengthOf(user.skills, 2)
assert.instanceOf(user.skills[0], Skill)
assert.isFalse(user.skills[0].$isPersisted)
assert.equal(user.skills[0].name, 'Dancing')
assert.instanceOf(user.skills[1], Skill)
assert.isFalse(user.skills[1].$isPersisted)
assert.equal(user.skills[1].name, 'Dancing')
})
})
test.group('Factory | ManyToMany | create', (group) => {
group.setup(async () => {
app = await setupApplication()
db = getDb(app)
BaseModel = getBaseModel(ormAdapter(db), app)
await setup()
})
group.teardown(async () => {
await db.manager.closeAll()
await cleanup()
await fs.cleanup()
})
group.each.teardown(async () => {
await resetTables()
})
test('create model with relationship', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory.with('skills').create()
assert.isTrue(user.$isPersisted)
assert.lengthOf(user.skills, 1)
assert.instanceOf(user.skills[0], Skill)
assert.isTrue(user.skills[0].$isPersisted)
const users = await db.from('users').select('*')
const skills = await db.from('skills').select('*')
const skillUsers = await db.from('skill_user').select('*')
assert.lengthOf(skills, 1)
assert.lengthOf(users, 1)
assert.equal(skillUsers[0].user_id, users[0].id)
assert.equal(skillUsers[0].skill_id, skills[0].id)
})
test('pass custom attributes', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory
.with('skills', 1, (related) => related.merge({ name: 'Dancing' }))
.create()
assert.isTrue(user.$isPersisted)
assert.lengthOf(user.skills, 1)
assert.instanceOf(user.skills[0], Skill)
assert.isTrue(user.skills[0].$isPersisted)
assert.equal(user.skills[0].name, 'Dancing')
})
test('create many relationships', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory
.with('skills', 2, (related) => related.merge([{ name: 'Dancing' }, { name: 'Programming' }]))
.create()
assert.isTrue(user.$isPersisted)
assert.lengthOf(user.skills, 2)
assert.instanceOf(user.skills[0], Skill)
assert.isTrue(user.skills[0].$isPersisted)
assert.equal(user.skills[0].name, 'Dancing')
assert.instanceOf(user.skills[1], Skill)
assert.isTrue(user.skills[1].$isPersisted)
assert.equal(user.skills[1].name, 'Programming')
})
test('rollback changes on error', async ({ assert }) => {
assert.plan(4)
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
try {
await factory.with('skills').create()
} catch (error) {
assert.exists(error)
}
const users = await db.from('users').exec()
const skills = await db.from('skills').exec()
const userSkills = await db.from('skill_user').exec()
assert.lengthOf(users, 0)
assert.lengthOf(skills, 0)
assert.lengthOf(userSkills, 0)
})
test('define pivot attributes for the pivot table', async ({ assert }) => {
class Skill extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public name: string
}
Skill.boot()
class User extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public username: string
@column()
public points: number = 0
@manyToMany(() => Skill)
public skills: ManyToMany<typeof Skill>
}
const postFactory = new FactoryModel(
Skill,
() => {
return {
name: 'Programming',
}
},
factoryManager
).build()
const factory = new FactoryModel(
User,
() => {
return {}
},
factoryManager
)
.relation('skills', () => postFactory)
.build()
const user = await factory
.with('skills', 2, (related) => {
related
.merge([{ name: 'Dancing' }, { name: 'Programming' }])
.pivotAttributes({ proficiency: 'master' })
})
.create()
assert.isTrue(user.$isPersisted)
assert.lengthOf(user.skills, 2)
assert.instanceOf(user.skills[0], Skill)
assert.isTrue(user.skills[0].$isPersisted)
assert.equal(user.skills[0].name, 'Dancing')
assert.instanceOf(user.skills[1], Skill)
assert.isTrue(user.skills[1].$isPersisted)
assert.equal(user.skills[1].name, 'Programming')
const skills = await user.related('skills').query().pivotColumns(['proficiency'])
assert.containsSubset(skills, [
{ $extras: { pivot_proficiency: 'master' } },
{ $extras: { pivot_proficiency: 'master' } },
])
})
}) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.