text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
import { onUnexpectedError } from 'vs/base/common/errors';
import { KeyChord, KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { Location } from 'vs/editor/common/languages';
import { getOuterEditor, PeekContext } from 'vs/editor/contrib/peekView/browser/peekView';
import * as nls from 'vs/nls';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { TextEditorSelectionSource } from 'vs/platform/editor/common/editor';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IListService, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse, WorkbenchTreeElementCanExpand } from 'vs/platform/list/browser/listService';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { OneReference, ReferencesModel } from '../referencesModel';
import { LayoutData, ReferenceWidget } from './referencesWidget';
export const ctxReferenceSearchVisible = new RawContextKey<boolean>('referenceSearchVisible', false, nls.localize('referenceSearchVisible', "Whether reference peek is visible, like 'Peek References' or 'Peek Definition'"));
export abstract class ReferencesController implements IEditorContribution {
static readonly ID = 'editor.contrib.referencesController';
private readonly _disposables = new DisposableStore();
private _widget?: ReferenceWidget;
private _model?: ReferencesModel;
private _peekMode?: boolean;
private _requestIdPool = 0;
private _ignoreModelChangeEvent = false;
private readonly _referenceSearchVisible: IContextKey<boolean>;
static get(editor: ICodeEditor): ReferencesController | null {
return editor.getContribution<ReferencesController>(ReferencesController.ID);
}
constructor(
private readonly _defaultTreeKeyboardSupport: boolean,
private readonly _editor: ICodeEditor,
@IContextKeyService contextKeyService: IContextKeyService,
@ICodeEditorService private readonly _editorService: ICodeEditorService,
@INotificationService private readonly _notificationService: INotificationService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IStorageService private readonly _storageService: IStorageService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
) {
this._referenceSearchVisible = ctxReferenceSearchVisible.bindTo(contextKeyService);
}
dispose(): void {
this._referenceSearchVisible.reset();
this._disposables.dispose();
this._widget?.dispose();
this._model?.dispose();
this._widget = undefined;
this._model = undefined;
}
toggleWidget(range: Range, modelPromise: CancelablePromise<ReferencesModel>, peekMode: boolean): void {
// close current widget and return early is position didn't change
let widgetPosition: Position | undefined;
if (this._widget) {
widgetPosition = this._widget.position;
}
this.closeWidget();
if (!!widgetPosition && range.containsPosition(widgetPosition)) {
return;
}
this._peekMode = peekMode;
this._referenceSearchVisible.set(true);
// close the widget on model/mode changes
this._disposables.add(this._editor.onDidChangeModelLanguage(() => { this.closeWidget(); }));
this._disposables.add(this._editor.onDidChangeModel(() => {
if (!this._ignoreModelChangeEvent) {
this.closeWidget();
}
}));
const storageKey = 'peekViewLayout';
const data = LayoutData.fromJSON(this._storageService.get(storageKey, StorageScope.GLOBAL, '{}'));
this._widget = this._instantiationService.createInstance(ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data);
this._widget.setTitle(nls.localize('labelLoading', "Loading..."));
this._widget.show(range);
this._disposables.add(this._widget.onDidClose(() => {
modelPromise.cancel();
if (this._widget) {
this._storageService.store(storageKey, JSON.stringify(this._widget.layoutData), StorageScope.GLOBAL, StorageTarget.MACHINE);
this._widget = undefined;
}
this.closeWidget();
}));
this._disposables.add(this._widget.onDidSelectReference(event => {
const { element, kind } = event;
if (!element) {
return;
}
switch (kind) {
case 'open':
if (event.source !== 'editor' || !this._configurationService.getValue('editor.stablePeek')) {
// when stable peek is configured we don't close
// the peek window on selecting the editor
this.openReference(element, false, false);
}
break;
case 'side':
this.openReference(element, true, false);
break;
case 'goto':
if (peekMode) {
this._gotoReference(element);
} else {
this.openReference(element, false, true);
}
break;
}
}));
const requestId = ++this._requestIdPool;
modelPromise.then(model => {
// still current request? widget still open?
if (requestId !== this._requestIdPool || !this._widget) {
model.dispose();
return undefined;
}
this._model?.dispose();
this._model = model;
// show widget
return this._widget.setModel(this._model).then(() => {
if (this._widget && this._model && this._editor.hasModel()) { // might have been closed
// set title
if (!this._model.isEmpty) {
this._widget.setMetaTitle(nls.localize('metaTitle.N', "{0} ({1})", this._model.title, this._model.references.length));
} else {
this._widget.setMetaTitle('');
}
// set 'best' selection
const uri = this._editor.getModel().uri;
const pos = new Position(range.startLineNumber, range.startColumn);
const selection = this._model.nearestReference(uri, pos);
if (selection) {
return this._widget.setSelection(selection).then(() => {
if (this._widget && this._editor.getOption(EditorOption.peekWidgetDefaultFocus) === 'editor') {
this._widget.focusOnPreviewEditor();
}
});
}
}
return undefined;
});
}, error => {
this._notificationService.error(error);
});
}
changeFocusBetweenPreviewAndReferences() {
if (!this._widget) {
// can be called while still resolving...
return;
}
if (this._widget.isPreviewEditorFocused()) {
this._widget.focusOnReferenceTree();
} else {
this._widget.focusOnPreviewEditor();
}
}
async goToNextOrPreviousReference(fwd: boolean) {
if (!this._editor.hasModel() || !this._model || !this._widget) {
// can be called while still resolving...
return;
}
const currentPosition = this._widget.position;
if (!currentPosition) {
return;
}
const source = this._model.nearestReference(this._editor.getModel().uri, currentPosition);
if (!source) {
return;
}
const target = this._model.nextOrPreviousReference(source, fwd);
const editorFocus = this._editor.hasTextFocus();
const previewEditorFocus = this._widget.isPreviewEditorFocused();
await this._widget.setSelection(target);
await this._gotoReference(target);
if (editorFocus) {
this._editor.focus();
} else if (this._widget && previewEditorFocus) {
this._widget.focusOnPreviewEditor();
}
}
async revealReference(reference: OneReference): Promise<void> {
if (!this._editor.hasModel() || !this._model || !this._widget) {
// can be called while still resolving...
return;
}
await this._widget.revealReference(reference);
}
closeWidget(focusEditor = true): void {
this._widget?.dispose();
this._model?.dispose();
this._referenceSearchVisible.reset();
this._disposables.clear();
this._widget = undefined;
this._model = undefined;
if (focusEditor) {
this._editor.focus();
}
this._requestIdPool += 1; // Cancel pending requests
}
private _gotoReference(ref: Location): Promise<any> {
if (this._widget) {
this._widget.hide();
}
this._ignoreModelChangeEvent = true;
const range = Range.lift(ref.range).collapseToStart();
return this._editorService.openCodeEditor({
resource: ref.uri,
options: { selection: range, selectionSource: TextEditorSelectionSource.JUMP }
}, this._editor).then(openedEditor => {
this._ignoreModelChangeEvent = false;
if (!openedEditor || !this._widget) {
// something went wrong...
this.closeWidget();
return;
}
if (this._editor === openedEditor) {
//
this._widget.show(range);
this._widget.focusOnReferenceTree();
} else {
// we opened a different editor instance which means a different controller instance.
// therefore we stop with this controller and continue with the other
const other = ReferencesController.get(openedEditor);
const model = this._model!.clone();
this.closeWidget();
openedEditor.focus();
other?.toggleWidget(
range,
createCancelablePromise(_ => Promise.resolve(model)),
this._peekMode ?? false
);
}
}, (err) => {
this._ignoreModelChangeEvent = false;
onUnexpectedError(err);
});
}
openReference(ref: Location, sideBySide: boolean, pinned: boolean): void {
// clear stage
if (!sideBySide) {
this.closeWidget();
}
const { uri, range } = ref;
this._editorService.openCodeEditor({
resource: uri,
options: { selection: range, selectionSource: TextEditorSelectionSource.JUMP, pinned }
}, this._editor, sideBySide);
}
}
function withController(accessor: ServicesAccessor, fn: (controller: ReferencesController) => void): void {
const outerEditor = getOuterEditor(accessor);
if (!outerEditor) {
return;
}
const controller = ReferencesController.get(outerEditor);
if (controller) {
fn(controller);
}
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'togglePeekWidgetFocus',
weight: KeybindingWeight.EditorContrib,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyCode.F2),
when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
handler(accessor) {
withController(accessor, controller => {
controller.changeFocusBetweenPreviewAndReferences();
});
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'goToNextReference',
weight: KeybindingWeight.EditorContrib - 10,
primary: KeyCode.F4,
secondary: [KeyCode.F12],
when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
handler(accessor) {
withController(accessor, controller => {
controller.goToNextOrPreviousReference(true);
});
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'goToPreviousReference',
weight: KeybindingWeight.EditorContrib - 10,
primary: KeyMod.Shift | KeyCode.F4,
secondary: [KeyMod.Shift | KeyCode.F12],
when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
handler(accessor) {
withController(accessor, controller => {
controller.goToNextOrPreviousReference(false);
});
}
});
// commands that aren't needed anymore because there is now ContextKeyExpr.OR
CommandsRegistry.registerCommandAlias('goToNextReferenceFromEmbeddedEditor', 'goToNextReference');
CommandsRegistry.registerCommandAlias('goToPreviousReferenceFromEmbeddedEditor', 'goToPreviousReference');
// close
CommandsRegistry.registerCommandAlias('closeReferenceSearchEditor', 'closeReferenceSearch');
CommandsRegistry.registerCommand(
'closeReferenceSearch',
accessor => withController(accessor, controller => controller.closeWidget())
);
KeybindingsRegistry.registerKeybindingRule({
id: 'closeReferenceSearch',
weight: KeybindingWeight.EditorContrib - 101,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape],
when: ContextKeyExpr.and(PeekContext.inPeekEditor, ContextKeyExpr.not('config.editor.stablePeek'))
});
KeybindingsRegistry.registerKeybindingRule({
id: 'closeReferenceSearch',
weight: KeybindingWeight.WorkbenchContrib + 50,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape],
when: ContextKeyExpr.and(ctxReferenceSearchVisible, ContextKeyExpr.not('config.editor.stablePeek'))
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'revealReference',
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyCode.Enter,
mac: {
primary: KeyCode.Enter,
secondary: [KeyMod.CtrlCmd | KeyCode.DownArrow]
},
when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
handler(accessor: ServicesAccessor) {
const listService = accessor.get(IListService);
const focus = <any[]>listService.lastFocusedList?.getFocus();
if (Array.isArray(focus) && focus[0] instanceof OneReference) {
withController(accessor, controller => controller.revealReference(focus[0]));
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'openReferenceToSide',
weight: KeybindingWeight.EditorContrib,
primary: KeyMod.CtrlCmd | KeyCode.Enter,
mac: {
primary: KeyMod.WinCtrl | KeyCode.Enter
},
when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
handler(accessor: ServicesAccessor) {
const listService = accessor.get(IListService);
const focus = <any[]>listService.lastFocusedList?.getFocus();
if (Array.isArray(focus) && focus[0] instanceof OneReference) {
withController(accessor, controller => controller.openReference(focus[0], true, true));
}
}
});
CommandsRegistry.registerCommand('openReference', (accessor) => {
const listService = accessor.get(IListService);
const focus = <any[]>listService.lastFocusedList?.getFocus();
if (Array.isArray(focus) && focus[0] instanceof OneReference) {
withController(accessor, controller => controller.openReference(focus[0], false, true));
}
}); | the_stack |
import React, { useEffect, useState } from 'react';
import { RouteComponentProps, withRouter } from 'react-router';
import Editor from '../components/editor';
import { languageToEditorMode } from '../config/mappings';
import API from '../utils/API';
import { debounce } from '../utils/utils';
import SplitPane from 'react-split-pane';
import socket from './../utils/socket';
import { baseURL } from '../config/config';
import Peer from 'peerjs';
import { diff_match_patch } from 'diff-match-patch';
interface RoomProps {
updatePreviousRooms: (room: string) => any;
}
var myPeer: Peer;
var audios: { [id: string]: { id: string; stream: MediaStream } } = {};
var peers: { [id: string]: Peer.MediaConnection } = {};
var myAudio: MediaStream | null;
// Audio rooms work fine for the most part, except for the asynchrousity caused by hooks that sometimes leads
// to trying to destroy an already destoyed thing, or when we were in process of it.
// So yeah, something to work on #TODO
const Room: React.FC<RouteComponentProps<any> & RoomProps> = (props) => {
const [id, setId] = useState<string>('');
const [title, setTitle] = useState<string>('');
const [body, setBody] = useState<string>('');
const [input, setInput] = useState<string>('');
const [output, setOutput] = useState<string>('');
const [widthLeft, setWidthLeft] = useState<string>('');
const [widthRight, setWidthRight] = useState<string>('');
const [windowWidth, setWindowWidth] = useState<number>(window.innerWidth);
const languages = Object.keys(languageToEditorMode);
const fontSizes = ['8', '10', '12', '14', '16', '18', '20', '22', '24', '26', '28', '30', '32'];
const themes = [
'monokai',
'github',
'solarized_dark',
'dracula',
'eclipse',
'tomorrow_night',
'tomorrow_night_blue',
'xcode',
'ambiance',
'solarized_light'
].sort();
const [language, setLanguage] = useState<string>(localStorage.getItem('language') ?? 'c');
const [theme, setTheme] = useState<string>(localStorage.getItem('theme') ?? 'monokai');
const [fontSize, setFontSize] = useState<string>(localStorage.getItem('fontSize') ?? '12');
const idleStatus = 'Idle';
const runningStatus = 'running';
const compeletedStatus = 'completed';
const errorStatus = 'Some error occured';
const [submissionStatus, setSubmissionStatus] = useState<string>(idleStatus);
const [submissionId, setSubmissionId] = useState<string>('');
const [submissionCheckerId, setSubmissionCheckerId] = useState<NodeJS.Timeout | null>(null);
const [inAudio, setInAudio] = useState<boolean>(false);
const [isMuted, setIsMuted] = useState<boolean>(false);
const dmp = new diff_match_patch();
useEffect(() => {
socket.off('userjoined');
socket.on('userjoined', () => {
socket.emit('setBody', { value: body, roomId: id });
socket.emit('setLanguage', { value: language, roomId: id });
socket.emit('setInput', { value: input, roomId: id });
socket.emit('setOutput', { value: output, roomId: id });
});
}, [body, language, input, output]);
useEffect(() => {
socket.off('updateBody');
socket.on('updateBody', (patch) => {
const [newBody, res] = dmp.patch_apply(patch, body);
if (res[0]) setBody(newBody);
else console.log('Failed', body, patch);
});
}, [body]);
useEffect(() => {
socket.off('updateInput');
socket.on('updateInput', (patch) => {
const [newInput, res] = dmp.patch_apply(patch, input);
if (res[0]) setInput(newInput);
else console.log('Failed', body, patch);
});
}, [input]);
useEffect(() => {
const id = props.match.params.id;
setId(id);
socket.emit('joinroom', id);
API.get(`/api/room/${id}`)
.then((res) => {
const { title, body, language, input } = res.data.data;
if (title) {
setTitle(title);
document.title = `Discode: ${title}`;
props.updatePreviousRooms(`${id}!${title}`);
}
setBody(body ?? '');
setInput(input ?? '');
if (language) setLanguage(language);
console.log(language);
})
.catch((err) => {
props.history.push('/404');
});
return () => {
if (myPeer) {
socket.emit('leaveAudioRoom', myPeer.id);
destroyConnection();
}
myAudio = null;
socket.emit('leaveroom', id);
};
}, [props.match.params.id]);
useEffect(() => {
socket.on('setBody', (body) => {
setBody(body);
});
socket.on('setInput', (input) => {
setInput(input);
});
socket.on('setLanguage', (language) => {
setLanguage(language);
});
socket.on('setOutput', (output) => {
setOutput(output);
});
const resizeCallback = () => setWindowWidth(window.innerWidth);
window.addEventListener('resize', resizeCallback);
return () => {
window.removeEventListener('resize', resizeCallback);
};
}, []);
useEffect(() => {
setInAudio(false);
}, [id]);
useEffect(() => {
if (submissionCheckerId && submissionStatus == compeletedStatus) {
clearInterval(submissionCheckerId);
setSubmissionCheckerId(null);
const params = new URLSearchParams({
id: submissionId,
api_key: 'guest'
});
const querystring = params.toString();
API.get(`https://api.paiza.io/runners/get_details?${querystring}`).then((res) => {
const { stdout, stderr, build_stderr } = res.data;
console.log(res.data);
let output = '';
if (stdout) output += stdout;
if (stderr) output += stderr;
if (build_stderr) output += build_stderr;
setOutput(output);
socket.emit('setOutput', { value: output, roomId: id });
});
}
}, [submissionStatus]);
const handleSubmit = () => {
if (submissionStatus === runningStatus) return;
setSubmissionStatus(runningStatus);
API.patch(`/api/room/${id}`, { title, body, input, language })
.then()
.catch((err) => {
setSubmissionStatus(errorStatus);
return;
});
const params = {
source_code: body,
language: language,
input: input,
api_key: 'guest'
};
API.post(`https://api.paiza.io/runners/create`, params)
.then((res) => {
const { id, status } = res.data;
setSubmissionId(id);
setSubmissionStatus(status);
})
.catch((err) => {
setSubmissionId('');
setSubmissionStatus(errorStatus);
});
};
useEffect(() => {
if (submissionId) {
setSubmissionCheckerId(setInterval(() => updateSubmissionStatus(), 1000));
}
}, [submissionId]);
const updateSubmissionStatus = () => {
const params = new URLSearchParams({
id: submissionId,
api_key: 'guest'
});
const querystring = params.toString();
API.get(`https://api.paiza.io/runners/get_status?${querystring}`).then((res) => {
const { status } = res.data;
setSubmissionStatus(status);
});
};
const handleUpdateBody = (value: string) => {
const patch = dmp.patch_make(body, value);
setBody(value);
debounce(() => socket.emit('updateBody', { value: patch, roomId: id }), 100)();
};
const handleUpdateInput = (value: string) => {
const patch = dmp.patch_make(input, value);
setInput(value);
debounce(() => socket.emit('updateInput', { value: patch, roomId: id }), 100)();
};
const handleWidthChange = (x: number) => {
setWidthRight((100 - x).toString());
setWidthLeft(x.toString());
};
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);
useEffect(() => {
localStorage.setItem('language', language);
}, [language]);
useEffect(() => {
localStorage.setItem('fontSize', fontSize);
}, [fontSize]);
// Voice room stuff
const getAudioStream = () => {
const myNavigator =
navigator.mediaDevices.getUserMedia ||
// @ts-ignore
navigator.mediaDevices.webkitGetUserMedia ||
// @ts-ignore
navigator.mediaDevices.mozGetUserMedia ||
// @ts-ignore
navigator.mediaDevices.msGetUserMedia;
return myNavigator({ audio: true });
};
const createAudio = (data: { id: string; stream: MediaStream }) => {
const { id, stream } = data;
if (!audios[id]) {
const audio = document.createElement('audio');
audio.id = id;
audio.srcObject = stream;
if (myPeer && id == myPeer.id) {
myAudio = stream;
audio.muted = true;
}
audio.autoplay = true;
audios[id] = data;
console.log('Adding audio: ', id);
} // } else {
// console.log('adding audio: ', id);
// // @ts-ignore
// document.getElementById(id).srcObject = stream;
// }
};
const removeAudio = (id: string) => {
delete audios[id];
const audio = document.getElementById(id);
if (audio) audio.remove();
};
const destroyConnection = () => {
console.log('distroying', audios, myPeer.id);
if (audios[myPeer.id]) {
const myMediaTracks = audios[myPeer.id].stream.getTracks();
myMediaTracks.forEach((track) => {
track.stop();
});
}
if (myPeer) myPeer.destroy();
};
const setPeersListeners = (stream: MediaStream) => {
myPeer.on('call', (call) => {
call.answer(stream);
call.on('stream', (userAudioStream) => {
createAudio({ id: call.metadata.id, stream: userAudioStream });
});
call.on('close', () => {
removeAudio(call.metadata.id);
});
call.on('error', () => {
console.log('peer error');
if (!myPeer.destroyed) removeAudio(call.metadata.id);
});
peers[call.metadata.id] = call;
});
};
const newUserConnection = (stream: MediaStream) => {
socket.on('userJoinedAudio', (userId) => {
const call = myPeer.call(userId, stream, { metadata: { id: myPeer.id } });
call.on('stream', (userAudioStream) => {
createAudio({ id: userId, stream: userAudioStream });
});
call.on('close', () => {
removeAudio(userId);
});
call.on('error', () => {
console.log('peer error');
if (!myPeer.destroyed) removeAudio(userId);
});
peers[userId] = call;
});
};
useEffect(() => {
if (inAudio) {
myPeer = new Peer();
myPeer.on('open', (userId) => {
console.log('opened');
getAudioStream().then((stream) => {
socket.emit('joinAudioRoom', id, userId);
stream.getAudioTracks()[0].enabled = !isMuted;
newUserConnection(stream);
setPeersListeners(stream);
createAudio({ id: myPeer.id, stream });
});
});
myPeer.on('error', (err) => {
console.log('peerjs error: ', err);
if (!myPeer.destroyed) myPeer.reconnect();
});
socket.on('userLeftAudio', (userId) => {
console.log('user left aiudio:', userId);
if (peers[userId]) peers[userId].close();
removeAudio(userId);
});
} else {
console.log('leaving', myPeer);
if (myPeer) {
socket.emit('leaveAudioRoom', myPeer.id);
destroyConnection();
}
myAudio = null;
}
}, [inAudio]);
useEffect(() => {
if (inAudio) {
if (myAudio) {
myAudio.getAudioTracks()[0].enabled = !isMuted;
}
}
}, [isMuted]);
return (
<div>
<div className="row container-fluid text-center justify-content-center">
<div className="form-group col-lg-2 col-md-3">
<label>Choose Language</label>
<select
className="form-select"
defaultValue={language}
onChange={(event) => {
setLanguage(event.target.value);
socket.emit('setLanguage', {
value: event.target.value,
roomId: id
});
}}
>
{languages.map((lang, index) => {
return (
<option key={index} value={lang} selected={lang == language}>
{lang}
</option>
);
})}
</select>
</div>
<div className="form-group col-lg-2 col-md-3">
<label>Choose Theme</label>
<select
className="form-select"
defaultValue={theme}
onChange={(event) => setTheme(event.target.value)}
>
{themes.map((theme, index) => {
return (
<option key={index} value={theme}>
{theme}
</option>
);
})}
</select>
</div>
<div className="form-group col-lg-2 col-md-3">
<label>Font Size</label>
<select
className="form-select"
defaultValue={fontSize}
onChange={(event) => setFontSize(event.target.value)}
>
{fontSizes.map((fontSize, index) => {
return (
<option key={index} value={fontSize}>
{fontSize}
</option>
);
})}
</select>
</div>
<div className="form-group col-lg-2 col-md-3">
<br />
<button
className="btn btn-secondary"
onClick={() => {
navigator.clipboard.writeText(window.location.href);
}}
>
Copy room link
</button>
</div>
<div className="form-group col-lg-2 col-md-2">
<br />
<button
className={`btn btn-${inAudio ? 'primary' : 'secondary'}`}
onClick={() => setInAudio(!inAudio)}
>
{inAudio ? 'Leave Audio' : 'Join Audio'} Room
</button>
</div>
{inAudio ? (
<div className="form-group col-lg-1 col-md-2">
<br />
<button
className={`btn btn-${!isMuted ? 'primary' : 'secondary'}`}
onClick={() => setIsMuted(!isMuted)}
>
{isMuted ? 'Muted' : 'Speaking'}
</button>
</div>
) : (
<div className="form-group col-lg-1 col-md-2" />
)}
<div className="form-group col-lg-1 col-md-2">
<br />
<label>Status: {submissionStatus}</label>
</div>
</div>
<hr />
<SplitPane
split="vertical"
minSize={150}
maxSize={windowWidth - 150}
defaultSize={windowWidth / 2}
className="row text-center "
style={{ height: '78vh', width: '100vw', marginRight: '0' }}
onChange={handleWidthChange}
>
<div>
<div className="row mb-1">
<h5 className="col">Code Here</h5>
<div className="form-group col">
<button
className="btn btn-secondary"
onClick={() => {
navigator.clipboard.writeText(body);
}}
>
Copy Code
</button>
</div>
<div className="form-group col">
<button
className="btn btn-primary"
onClick={handleSubmit}
disabled={submissionStatus === runningStatus}
>
Save and Run
</button>
</div>
</div>
<Editor
theme={theme}
width={widthLeft}
// @ts-ignore
language={languageToEditorMode[language]}
body={body}
setBody={handleUpdateBody}
fontSize={fontSize}
/>
</div>
<div className="text-center">
<h5>Input</h5>
<Editor
theme={theme}
language={''}
body={input}
setBody={handleUpdateInput}
height={'35vh'}
width={widthRight}
fontSize={fontSize}
/>
<h5>Output</h5>
<Editor
theme={theme}
language={''}
body={output}
setBody={setOutput}
readOnly={true}
height={'39vh'}
width={widthRight}
fontSize={fontSize}
/>
</div>
</SplitPane>
</div>
);
};
export default withRouter(Room); | the_stack |
import { Properties } from '@posthog/plugin-scaffold'
import * as Sentry from '@sentry/node'
import crypto from 'crypto'
import { ProducerRecord } from 'kafkajs'
import { DateTime } from 'luxon'
import { defaultConfig } from '../../config/config'
import { KAFKA_PERSON } from '../../config/kafka-topics'
import { BasePerson, Element, Person, RawPerson, TimestampFormat } from '../../types'
import { castTimestampOrNow } from '../../utils/utils'
export function unparsePersonPartial(person: Partial<Person>): Partial<RawPerson> {
return { ...(person as BasePerson), ...(person.created_at ? { created_at: person.created_at.toISO() } : {}) }
}
export function escapeQuotes(input: string): string {
return input.replace(/"/g, '\\"')
}
export function elementsToString(elements: Element[]): string {
const ret = elements.map((element) => {
let el_string = ''
if (element.tag_name) {
el_string += element.tag_name
}
if (element.attr_class) {
element.attr_class.sort()
for (const single_class of element.attr_class) {
el_string += `.${single_class.replace(/"/g, '')}`
}
}
let attributes: Record<string, any> = {
...(element.text ? { text: element.text } : {}),
'nth-child': element.nth_child ?? 0,
'nth-of-type': element.nth_of_type ?? 0,
...(element.href ? { href: element.href } : {}),
...(element.attr_id ? { attr_id: element.attr_id } : {}),
...element.attributes,
}
attributes = Object.fromEntries(
Object.entries(attributes)
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, value]) => [escapeQuotes(key.toString()), escapeQuotes(value.toString())])
)
el_string += ':'
el_string += Object.entries(attributes)
.map(([key, value]) => `${key}="${value}"`)
.join('')
return el_string
})
return ret.join(';')
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function sanitizeEventName(eventName: any): string {
if (typeof eventName !== 'string') {
try {
eventName = JSON.stringify(eventName)
} catch {
eventName = String(eventName)
}
}
return eventName.substr(0, 200)
}
/** Escape UTF-8 characters into `\u1234`. */
function jsonEscapeUtf8(s: string): string {
return s.replace(/[^\x20-\x7F]/g, (x) => '\\u' + ('000' + x.codePointAt(0)?.toString(16)).slice(-4))
}
/** Produce output compatible with that of Python's `json.dumps`. */
function jsonDumps(obj: any): string {
if (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj)) {
return `[${obj.map(jsonDumps).join(', ')}]` // space after comma
} else {
return `{${Object.keys(obj) // no space after '{' or before '}'
.sort() // must sort the keys of the object!
.map((k) => `${jsonDumps(k)}: ${jsonDumps(obj[k])}`) // space after ':'
.join(', ')}}` // space after ','
}
} else if (typeof obj === 'string') {
return jsonEscapeUtf8(JSON.stringify(obj))
} else {
return JSON.stringify(obj)
}
}
export function hashElements(elements: Element[]): string {
const elementsList = elements.map((element) => ({
attributes: element.attributes ?? null,
text: element.text ?? null,
tag_name: element.tag_name ?? null,
href: element.href ?? null,
attr_id: element.attr_id ?? null,
attr_class: element.attr_class ?? null,
nth_child: element.nth_child ?? null,
nth_of_type: element.nth_of_type ?? null,
order: element.order ?? null,
}))
const serializedString = jsonDumps(elementsList)
return crypto.createHash('md5').update(serializedString).digest('hex')
}
export function chainToElements(chain: string): Element[] {
const elements: Element[] = []
// Below splits all elements by ;, while ignoring escaped quotes and semicolons within quotes
const splitChainRegex = /(?:[^\s;"]|"(?:\\.|[^"])*")+/g
// Below splits the tag/classes from attributes
// Needs a regex because classes can have : too
const splitClassAttributes = /(.*?)($|:([a-zA-Z\-_0-9]*=.*))/g
const parseAttributesRegex = /((.*?)="(.*?[^\\])")/gm
Array.from(chain.matchAll(splitChainRegex))
.map((r) => r[0])
.forEach((elString, index) => {
const elStringSplit = Array.from(elString.matchAll(splitClassAttributes))[0]
const attributes =
elStringSplit.length > 3
? Array.from(elStringSplit[3].matchAll(parseAttributesRegex)).map((a) => [a[2], a[3]])
: []
const element: Element = {
attributes: {},
order: index,
}
if (elStringSplit[1]) {
const tagAndClass = elStringSplit[1].split('.')
element.tag_name = tagAndClass[0]
if (tagAndClass.length > 1) {
const [_, ...rest] = tagAndClass
element.attr_class = rest.filter((t) => t)
}
}
for (const [key, value] of attributes) {
if (key == 'href') {
element.href = value
} else if (key == 'nth-child') {
element.nth_child = parseInt(value)
} else if (key == 'nth-of-type') {
element.nth_of_type = parseInt(value)
} else if (key == 'text') {
element.text = value
} else if (key == 'attr_id') {
element.attr_id = value
} else if (key) {
if (!element.attributes) {
element.attributes = {}
}
element.attributes[key] = value
}
}
elements.push(element)
})
return elements
}
export function extractElements(elements: Record<string, any>[]): Element[] {
return elements.map((el) => ({
text: el['$el_text']?.slice(0, 400),
tag_name: el['tag_name'],
href: el['attr__href']?.slice(0, 2048),
attr_class: el['attr__class']?.split(' '),
attr_id: el['attr__id'],
nth_child: el['nth_child'],
nth_of_type: el['nth_of_type'],
attributes: Object.fromEntries(Object.entries(el).filter(([key]) => key.startsWith('attr__'))),
}))
}
export function timeoutGuard(
message: string,
context?: Record<string, any>,
timeout = defaultConfig.TASK_TIMEOUT * 1000
): NodeJS.Timeout {
return setTimeout(() => {
console.log(`⌛⌛⌛ ${message}`, context)
Sentry.captureMessage(message, context ? { extra: context } : undefined)
}, timeout)
}
const campaignParams = new Set(['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gclid'])
const initialParams = new Set([
'$browser',
'$browser_version',
'$device_type',
'$current_url',
'$os',
'$referring_domain',
'$referrer',
])
const combinedParams = new Set([...campaignParams, ...initialParams])
/** If we get new UTM params, make sure we set those **/
export function personInitialAndUTMProperties(properties: Properties): Properties {
const propertiesCopy = { ...properties }
const maybeSet = Object.entries(properties).filter(([key, value]) => campaignParams.has(key))
const maybeSetInitial = Object.entries(properties)
.filter(([key, value]) => combinedParams.has(key))
.map(([key, value]) => [`$initial_${key.replace('$', '')}`, value])
if (Object.keys(maybeSet).length > 0) {
propertiesCopy.$set = { ...(properties.$set || {}), ...Object.fromEntries(maybeSet) }
}
if (Object.keys(maybeSetInitial).length > 0) {
propertiesCopy.$set_once = { ...(properties.$set_once || {}), ...Object.fromEntries(maybeSetInitial) }
}
return propertiesCopy
}
/** Returns string in format: ($1, $2, $3, $4, $5, $6, $7, $8, ..., $N) */
export function generatePostgresValuesString(numberOfColumns: number, rowNumber: number): string {
return (
'(' +
Array.from(Array(numberOfColumns).keys())
.map((x) => `$${x + 1 + rowNumber * numberOfColumns}`)
.join(', ') +
')'
)
}
export function generateKafkaPersonUpdateMessage(
createdAt: DateTime | string,
properties: Properties,
teamId: number,
isIdentified: boolean,
id: string,
version: number | null,
isDeleted = 0
): ProducerRecord {
return {
topic: KAFKA_PERSON,
messages: [
{
value: Buffer.from(
JSON.stringify({
id,
created_at: castTimestampOrNow(createdAt, TimestampFormat.ClickHouseSecondPrecision),
properties: JSON.stringify(properties),
team_id: teamId,
is_identified: isIdentified,
is_deleted: isDeleted,
...(version ? { version } : {}),
})
),
},
],
}
}
// Very useful for debugging queries
export function getFinalPostgresQuery(queryString: string, values: any[]): string {
return queryString.replace(/\$([0-9]+)/g, (m, v) => JSON.stringify(values[parseInt(v) - 1]))
}
export function transformPostgresElementsToEventPayloadFormat(
rawElements: Record<string, any>[]
): Record<string, any>[] {
const elementTransformations: Record<string, string> = {
text: '$el_text',
attr_class: 'attr__class',
attr_id: 'attr__id',
href: 'attr__href',
}
const elements = []
for (const element of rawElements) {
for (const [key, val] of Object.entries(element)) {
if (key in elementTransformations) {
element[elementTransformations[key]] = val
delete element[key]
}
}
delete element['attributes']
elements.push(element)
}
return elements
} | the_stack |
import {
Component,
Output,
EventEmitter,
Input,
HostListener,
ViewChildren,
QueryList,
HostBinding,
DoCheck,
OnInit
} from '@angular/core';
import { ICalendarDate, isDateInRanges } from '../../calendar/calendar';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { IgxDayItemComponent } from './day-item.component';
import { DateRangeDescriptor, DateRangeType } from '../../core/dates';
import { IgxCalendarBaseDirective, CalendarSelection } from '../calendar-base';
import { isEqual, PlatformUtil } from '../../core/utils';
import { IViewChangingEventArgs } from './days-view.interface';
import { IgxDaysViewNavigationService } from '../days-view/daysview-navigation.service';
let NEXT_ID = 0;
@Component({
providers: [
{
multi: true,
provide: NG_VALUE_ACCESSOR,
useExisting: IgxDaysViewComponent
},
{ provide: IgxDaysViewNavigationService, useClass: IgxDaysViewNavigationService }
],
selector: 'igx-days-view',
templateUrl: 'days-view.component.html'
})
export class IgxDaysViewComponent extends IgxCalendarBaseDirective implements DoCheck, OnInit {
/**
* Sets/gets the `id` of the days view.
* If not set, the `id` will have value `"igx-days-view-0"`.
* ```html
* <igx-days-view id="my-days-view"></igx-days-view>
* ```
* ```typescript
* let daysViewId = this.daysView.id;
* ```
*/
@HostBinding('attr.id')
@Input()
public id = `igx-days-view-${NEXT_ID++}`;
/**
* @hidden
*/
@Input()
public changeDaysView = false;
/**
* Show/hide week numbers
*
* @example
* ```html
* <igx-days-view [showWeekNumbers]="true"></igx-days-view>
* ``
*/
@Input()
public showWeekNumbers: boolean;
/**
* @hidden
* @internal
*/
@Input()
public set activeDate(value: string) {
this._activeDate = value;
this.activeDateChange.emit(this._activeDate);
}
public get activeDate() {
return this._activeDate ? this._activeDate : this.viewDate.toLocaleDateString();
}
/**
* @hidden
*/
@Output()
public dateSelection = new EventEmitter<ICalendarDate>();
/**
* @hidden
*/
@Output()
public viewChanging = new EventEmitter<IViewChangingEventArgs>();
/**
* @hidden
*/
@Output()
public activeDateChange = new EventEmitter<string>();
/**
* @hidden
*/
@Output()
public monthsViewBlur = new EventEmitter<any>();
/**
* @hidden
*/
@ViewChildren(IgxDayItemComponent, { read: IgxDayItemComponent })
public dates: QueryList<IgxDayItemComponent>;
/**
* The default css class applied to the component.
*
* @hidden
*/
@HostBinding('class.igx-calendar')
public styleClass = true;
/**
* @hidden
*/
public outOfRangeDates: DateRangeDescriptor[];
/**
* @hidden
*/
public nextMonthView: IgxDaysViewComponent;
/** @hidden */
public prevMonthView: IgxDaysViewComponent;
/** @hidden */
public shouldResetDate = true;
private _activeDate;
/**
* @hidden
*/
constructor(
public daysNavService: IgxDaysViewNavigationService,
protected platform: PlatformUtil
) {
super(platform);
}
/**
* @hidden
* @internal
*/
@HostListener('focusout')
public resetActiveMonth() {
if (this.shouldResetDate) {
const date = this.dates.find(day => day.selected && day.isCurrentMonth) ||
this.dates.find(day => day.isToday && day.isCurrentMonth) ||
this.dates.find(d => d.isFocusable);
if (date) {
this.activeDate = date.date.date.toLocaleDateString();
}
this.monthsViewBlur.emit();
}
this.shouldResetDate = true;
}
/**
* @hidden
* @internal
*/
@HostListener('keydown.pagedown')
@HostListener('keydown.pageup')
@HostListener('keydown.shift.pagedown')
@HostListener('keydown.shift.pageup')
@HostListener('pointerdown')
public pointerDown() {
this.shouldResetDate = false;
}
/**
* @hidden
*/
@HostListener('keydown.arrowleft', ['$event'])
@HostListener('keydown.arrowright', ['$event'])
@HostListener('keydown.arrowup', ['$event'])
@HostListener('keydown.arrowdown', ['$event'])
public onKeydownArrow(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.shouldResetDate = false;
this.daysNavService.focusNextDate(event.target as HTMLElement, event.key);
}
/**
* @hidden
*/
@HostListener('keydown.home', ['$event'])
public onKeydownHome(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.shouldResetDate = false;
this.getFirstMonthView().daysNavService.focusHomeDate();
}
/**
* @hidden
*/
@HostListener('keydown.end', ['$event'])
public onKeydownEnd(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.shouldResetDate = false;
this.getLastMonthView().daysNavService.focusEndDate();
}
/**
* @hidden
*/
public get getCalendarMonth(): ICalendarDate[][] {
return this.calendarModel.monthdatescalendar(this.viewDate.getFullYear(), this.viewDate.getMonth(), true);
}
/**
* @hidden
*/
public ngOnInit() {
this.daysNavService.monthView = this;
}
/**
* @hidden
*/
public ngDoCheck() {
if (!this.changeDaysView && this.dates) {
this.disableOutOfRangeDates();
}
}
/**
* @hidden
* @internal
*/
public tabIndex(day: ICalendarDate): number {
return this.activeDate && this.activeDate === day.date.toLocaleDateString() && day.isCurrentMonth ? 0 : -1;
}
/**
* Returns the week number by date
*
* @hidden
*/
public getWeekNumber(date): number {
return this.calendarModel.getWeekNumber(date);
}
/**
* Returns the locale representation of the date in the days view.
*
* @hidden
*/
public formattedDate(value: Date): string {
if (this.formatViews.day) {
return this.formatterDay.format(value);
}
return `${value.getDate()}`;
}
/**
* @hidden
*/
public generateWeekHeader(): string[] {
const dayNames = [];
const rv = this.calendarModel.monthdatescalendar(this.viewDate.getFullYear(), this.viewDate.getMonth())[0];
for (const day of rv) {
dayNames.push(this.formatterWeekday.format(day.date));
}
return dayNames;
}
/**
* @hidden
*/
public rowTracker(index, item): string {
return `${item[index].date.getMonth()}${item[index].date.getDate()}`;
}
/**
* @hidden
*/
public dateTracker(index, item): string {
return `${item.date.getMonth()}--${item.date.getDate()}`;
}
/**
* @hidden
*/
public isCurrentMonth(value: Date): boolean {
return this.viewDate.getMonth() === value.getMonth();
}
/**
* @hidden
*/
public isCurrentYear(value: Date): boolean {
return this.viewDate.getFullYear() === value.getFullYear();
}
/**
* @hidden
*/
public isSelected(date: ICalendarDate): boolean {
let selectedDates: Date | Date[];
if (this.isDateDisabled(date.date) || !this.value ||
(Array.isArray(this.value) && this.value.length === 0)
) {
return false;
}
if (this.selection === CalendarSelection.SINGLE) {
selectedDates = (this.value as Date);
return this.getDateOnly(selectedDates).getTime() === date.date.getTime();
}
selectedDates = (this.value as Date[]);
if (this.selection === CalendarSelection.RANGE && selectedDates.length === 1) {
return this.getDateOnly(selectedDates[0]).getTime() === date.date.getTime();
}
if (this.selection === CalendarSelection.MULTI) {
const start = this.getDateOnly(selectedDates[0]);
const end = this.getDateOnly(selectedDates[selectedDates.length - 1]);
if (this.isWithinRange(date.date, false, start, end)) {
const currentDate = selectedDates.find(element => element.getTime() === date.date.getTime());
return !!currentDate;
} else {
return false;
}
} else {
return this.isWithinRange(date.date, true);
}
}
/**
* @hidden
*/
public isLastInRange(date: ICalendarDate): boolean {
if (this.isSingleSelection || !this.value) {
return false;
}
const dates = this.value as Date[];
const lastDate = dates[dates.length - 1];
return isEqual(lastDate, date.date);
}
/**
* @hidden
*/
public isFirstInRange(date: ICalendarDate): boolean {
if (this.isSingleSelection || !this.value) {
return false;
}
return isEqual((this.value as Date[])[0], date.date);
}
/**
* @hidden
*/
public isWithinRange(date: Date, checkForRange: boolean, min?: Date, max?: Date): boolean {
if (checkForRange && !(Array.isArray(this.value) && this.value.length > 1)) {
return false;
}
min = min ? min : this.value[0];
max = max ? max : this.value[(this.value as Date[]).length - 1];
return isDateInRanges(date,
[
{
type: DateRangeType.Between,
dateRange: [min, max]
}
]
);
}
/**
* @hidden
*/
public focusActiveDate() {
let date = this.dates.find((d) => d.selected);
if (!date) {
date = this.dates.find((d) => d.isToday);
}
if (date.isFocusable) {
date.nativeElement.focus();
}
}
/**
* @hidden
*/
public selectDay(event) {
this.selectDateFromClient(event.date);
this.dateSelection.emit(event);
this.selected.emit(this.selectedDates);
}
/**
* @hidden
*/
public getFirstMonthView(): IgxDaysViewComponent {
let monthView = this as IgxDaysViewComponent;
while (monthView.prevMonthView) {
monthView = monthView.prevMonthView;
}
return monthView;
}
/**
* @hidden
*/
private disableOutOfRangeDates() {
const dateRange = [];
this.dates.toArray().forEach((date) => {
if (!date.isCurrentMonth) {
dateRange.push(date.date.date);
}
});
this.outOfRangeDates = [{
type: DateRangeType.Specific,
dateRange
}];
}
/**
* @hidden
*/
private getLastMonthView(): IgxDaysViewComponent {
let monthView = this as IgxDaysViewComponent;
while (monthView.nextMonthView) {
monthView = monthView.nextMonthView;
}
return monthView;
}
/**
* @hidden
*/
private get isSingleSelection(): boolean {
return this.selection !== CalendarSelection.RANGE;
}
} | the_stack |
import type { TVec3, TVec4, TVec8 } from '@oito/types';
class DualQuat extends Float32Array{
//#region STATIC VALUES
static BYTESIZE = 8 * Float32Array.BYTES_PER_ELEMENT;
//#endregion ////////////////////////////////////////////////////////
//#region CONSTRUCTORS
constructor()
constructor( q: TVec4 )
constructor( q: TVec4, t: TVec3 )
constructor( q?: TVec4, t?: TVec3 ){
super( 8 );
if( q && t ) this.fromQuatTran( q, t );
else if( q ){
this[ 0 ] = q[ 0 ];
this[ 1 ] = q[ 1 ];
this[ 2 ] = q[ 2 ];
this[ 3 ] = q[ 3 ];
}else this[ 3 ] = 1;
}
//#endregion ////////////////////////////////////////////////////////
//#region BASIC SETTERS / GETTERS
reset() : this{
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
this[4] = 0;
this[5] = 0;
this[6] = 0;
this[7] = 0;
return this;
}
clone() : DualQuat{
const out = new DualQuat();
out[0] = this[0];
out[1] = this[1];
out[2] = this[2];
out[3] = this[3];
out[4] = this[4];
out[5] = this[5];
out[6] = this[6];
out[7] = this[7];
return out;
}
copy( a : TVec8 ) : this{
this[0] = a[0];
this[1] = a[1];
this[2] = a[2];
this[3] = a[3];
this[4] = a[4];
this[5] = a[5];
this[6] = a[6];
this[7] = a[7];
return this;
}
lenSqr() : number{ return this[0]*this[0] + this[1]*this[1] + this[2]*this[2] + this[3]*this[3]; }
//----------------------------------------------------
/** DUAL Part of DQ */
getTranslation( out ?: TVec3 ) : TVec3{
const ax = this[4], ay = this[5], az = this[6], aw = this[7],
bx = -this[0], by = -this[1], bz = -this[2], bw = this[3];
out = out || new Array(3);
out[0] = ( ax * bw + aw * bx + ay * bz - az * by ) * 2;
out[1] = ( ay * bw + aw * by + az * bx - ax * bz ) * 2;
out[2] = ( az * bw + aw * bz + ax * by - ay * bx ) * 2;
return out;
}
/** REAL Part of DQ */
getQuat( out ?: TVec4 ) : TVec4{
out = out || [0,0,0,0];
out[ 0 ] = this[ 0 ];
out[ 1 ] = this[ 1 ];
out[ 2 ] = this[ 2 ];
out[ 3 ] = this[ 3 ];
return out;
}
//----------------------------------------------------
// FLAT BUFFERS
/** Used to get data from a flat buffer of dualquat */
fromBuf( ary : Array<number> | Float32Array, idx: number ) : this {
this[ 0 ] = ary[ idx ];
this[ 1 ] = ary[ idx + 1 ];
this[ 2 ] = ary[ idx + 2 ];
this[ 3 ] = ary[ idx + 3 ];
this[ 4 ] = ary[ idx + 4 ];
this[ 5 ] = ary[ idx + 5 ];
this[ 6 ] = ary[ idx + 6 ];
this[ 7 ] = ary[ idx + 7 ];
return this;
}
/** Put data into a flat buffer of dualquat */
toBuf( ary : Array<number> | Float32Array, idx: number ) : this {
ary[ idx ] = this[ 0 ];
ary[ idx + 1 ] = this[ 1 ];
ary[ idx + 2 ] = this[ 2 ];
ary[ idx + 3 ] = this[ 3 ];
ary[ idx + 4 ] = this[ 4 ];
ary[ idx + 5 ] = this[ 5 ];
ary[ idx + 6 ] = this[ 6 ];
ary[ idx + 7 ] = this[ 7 ];
return this;
}
//#endregion ////////////////////////////////////////////////////////
//#region FROM SETTERS
/** Create a DualQuat from Quaternion and Translation Vector */
fromQuatTran( q: TVec4, t: TVec4 ) : this {
const ax = t[0] * 0.5, ay = t[1] * 0.5, az = t[2] * 0.5,
bx = q[0], by = q[1], bz = q[2], bw = q[3];
this[0] = bx;
this[1] = by;
this[2] = bz;
this[3] = bw;
this[4] = ax * bw + ay * bz - az * by;
this[5] = ay * bw + az * bx - ax * bz;
this[6] = az * bw + ax * by - ay * bx;
this[7] = -ax * bx - ay * by - az * bz;
return this;
}
fromTranslation( t: TVec3 ) : this{
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
this[4] = t[0] * 0.5;
this[5] = t[1] * 0.5;
this[6] = t[2] * 0.5;
this[7] = 0;
return this;
}
fromQuat( q: TVec4 ) : this{
this[0] = q[0];
this[1] = q[1];
this[2] = q[2];
this[3] = q[3];
this[4] = 0;
this[5] = 0;
this[6] = 0;
this[7] = 0;
return this;
}
fromMul( a: TVec8, b: TVec8 ) : this{
const ax0 = a[0], ay0 = a[1], az0 = a[2], aw0 = a[3],
ax1 = a[4], ay1 = a[5], az1 = a[6], aw1 = a[7],
bx0 = b[0], by0 = b[1], bz0 = b[2], bw0 = b[3],
bx1 = b[4], by1 = b[5], bz1 = b[6], bw1 = b[7];
this[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
this[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
this[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
this[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
this[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
this[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
this[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
this[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
return this;
}
fromNorm( a: TVec8 ) : this {
let magnitude = a[0]**2 + a[1]**2 + a[2]**2 + a[3]**2;
if( magnitude == 0 ) return this;
magnitude = 1 / Math.sqrt( magnitude );
const a0 = a[0] * magnitude;
const a1 = a[1] * magnitude;
const a2 = a[2] * magnitude;
const a3 = a[3] * magnitude;
const b0 = a[4];
const b1 = a[5];
const b2 = a[6];
const b3 = a[7];
const a_dot_b = (a0 * b0) + (a1 * b1) + (a2 * b2) + (a3 * b3);
this[0] = a0;
this[1] = a1;
this[2] = a2;
this[3] = a3;
this[4] = ( b0 - (a0 * a_dot_b) ) * magnitude;
this[5] = ( b1 - (a1 * a_dot_b) ) * magnitude;
this[6] = ( b2 - (a2 * a_dot_b) ) * magnitude;
this[7] = ( b3 - (a3 * a_dot_b) ) * magnitude;
return this;
}
/** Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper */
fromInvert( a: DualQuat ) : this{
const sqlen = 1 / a.lenSqr();
this[0] = -a[0] * sqlen;
this[1] = -a[1] * sqlen;
this[2] = -a[2] * sqlen;
this[3] = a[3] * sqlen;
this[4] = -a[4] * sqlen;
this[5] = -a[5] * sqlen;
this[6] = -a[6] * sqlen;
this[7] = a[7] * sqlen;
return this;
}
/** If dual quaternion is normalized, this is faster than inverting and produces the same value. */
fromConjugate( a: TVec8 ) : this {
this[0] = -a[0];
this[1] = -a[1];
this[2] = -a[2];
this[3] = a[3];
this[4] = -a[4];
this[5] = -a[5];
this[6] = -a[6];
this[7] = a[7];
return this;
}
//#endregion ////////////////////////////////////////////////////////
//#region BASIC OPERATIONS
add( q: TVec8 ) : this{
this[0] = this[0] + q[0];
this[1] = this[1] + q[1];
this[2] = this[2] + q[2];
this[3] = this[3] + q[3];
this[4] = this[4] + q[4];
this[5] = this[5] + q[5];
this[6] = this[6] + q[6];
this[7] = this[7] + q[7];
return this;
}
mul( q: TVec8 ) : this{
const ax0 = this[0], ay0 = this[1], az0 = this[2], aw0 = this[3],
ax1 = this[4], ay1 = this[5], az1 = this[6], aw1 = this[7],
bx0 = q[0], by0 = q[1], bz0 = q[2], bw0 = q[3],
bx1 = q[4], by1 = q[5], bz1 = q[6], bw1 = q[7];
this[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
this[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
this[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
this[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
this[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
this[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
this[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
this[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
return this;
}
pmul( q: TVec8 ) : this{
const ax0 = q[0], ay0 = q[1], az0 = q[2], aw0 = q[3],
ax1 = q[4], ay1 = q[5], az1 = q[6], aw1 = q[7],
bx0 = this[0], by0 = this[1], bz0 = this[2], bw0 = this[3],
bx1 = this[4], by1 = this[5], bz1 = this[6], bw1 = this[7];
this[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
this[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
this[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
this[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
this[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
this[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
this[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
this[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
return this;
}
scale( s: number ) : this{
this[0] = this[0] * s;
this[1] = this[1] * s;
this[2] = this[2] * s;
this[3] = this[3] * s;
this[4] = this[4] * s;
this[5] = this[5] * s;
this[6] = this[6] * s;
this[7] = this[7] * s;
return this;
}
norm() : this {
let magnitude = this[0]**2 + this[1]**2 + this[2]**2 + this[3]**2;
if( magnitude == 0 ) return this;
magnitude = 1 / Math.sqrt( magnitude );
const a0 = this[0] * magnitude;
const a1 = this[1] * magnitude;
const a2 = this[2] * magnitude;
const a3 = this[3] * magnitude;
const b0 = this[4];
const b1 = this[5];
const b2 = this[6];
const b3 = this[7];
const a_dot_b = (a0 * b0) + (a1 * b1) + (a2 * b2) + (a3 * b3);
this[0] = a0;
this[1] = a1;
this[2] = a2;
this[3] = a3;
this[4] = ( b0 - (a0 * a_dot_b) ) * magnitude;
this[5] = ( b1 - (a1 * a_dot_b) ) * magnitude;
this[6] = ( b2 - (a2 * a_dot_b) ) * magnitude;
this[7] = ( b3 - (a3 * a_dot_b) ) * magnitude;
return this;
}
/** Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper */
invert() : this{
const sqlen = 1 / this.lenSqr();
this[0] = -this[0] * sqlen;
this[1] = -this[1] * sqlen;
this[2] = -this[2] * sqlen;
this[3] = this[3] * sqlen;
this[4] = -this[4] * sqlen;
this[5] = -this[5] * sqlen;
this[6] = -this[6] * sqlen;
this[7] = this[7] * sqlen;
return this;
}
/** If dual quaternion is normalized, this is faster than inverting and produces the same value. */
conjugate() : this {
this[0] = -this[0];
this[1] = -this[1];
this[2] = -this[2];
//this[3] = this[3];
this[4] = -this[4];
this[5] = -this[5];
this[6] = -this[6];
//this[7] = this[7];
return this;
}
/** Translates a dual quat by the given vector */
translate( v: TVec3 ) : this{
const ax1 = this[0], ay1 = this[1], az1 = this[2], aw1 = this[3],
ax2 = this[4], ay2 = this[5], az2 = this[6], aw2 = this[7],
bx1 = v[0] * 0.5, by1 = v[1] * 0.5, bz1 = v[2] * 0.5;
this[0] = ax1;
this[1] = ay1;
this[2] = az1;
this[3] = aw1;
this[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2;
this[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2;
this[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2;
this[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2;
return this;
}
/** Rotates a dual quat by a given quaternion (dq * q) */
mulQuat( q: TVec4 ) : this {
const qx = q[0], qy = q[1], qz = q[2], qw = q[3];
let ax = this[0], ay = this[1], az = this[2], aw = this[3];
this[0] = ax * qw + aw * qx + ay * qz - az * qy;
this[1] = ay * qw + aw * qy + az * qx - ax * qz;
this[2] = az * qw + aw * qz + ax * qy - ay * qx;
this[3] = aw * qw - ax * qx - ay * qy - az * qz;
ax = this[4]; ay = this[5]; az = this[6]; aw = this[7];
this[4] = ax * qw + aw * qx + ay * qz - az * qy;
this[5] = ay * qw + aw * qy + az * qx - ax * qz;
this[6] = az * qw + aw * qz + ax * qy - ay * qx;
this[7] = aw * qw - ax * qx - ay * qy - az * qz;
return this;
}
/** Rotates a dual quat by a given quaternion (q * dq) */
pmulQuat( q: TVec4 ) : this {
const qx = q[0], qy = q[1], qz = q[2], qw = q[3];
let bx = this[0], by = this[1], bz = this[2], bw = this[3];
this[0] = qx * bw + qw * bx + qy * bz - qz * by;
this[1] = qy * bw + qw * by + qz * bx - qx * bz;
this[2] = qz * bw + qw * bz + qx * by - qy * bx;
this[3] = qw * bw - qx * bx - qy * by - qz * bz;
bx = this[4]; by = this[5]; bz = this[6]; bw = this[7];
this[4] = qx * bw + qw * bx + qy * bz - qz * by;
this[5] = qy * bw + qw * by + qz * bx - qx * bz;
this[6] = qz * bw + qw * bz + qx * by - qy * bx;
this[7] = qw * bw - qx * bx - qy * by - qz * bz;
return this;
}
//#endregion ////////////////////////////////////////////////////////
//#region ROTATION OPERATIONS
rotX( rad: number ) : this {
const bbx = this[0], bby = this[1], bbz = this[2], bbw = this[3]; // Quat
let bx = -this[0], by = -this[1], bz = -this[2], bw = this[3]; // Neg XYZ
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
//----------------------------------------
// Reverse Trans
const ax1 = ax * bw + aw * bx + ay * bz - az * by,
ay1 = ay * bw + aw * by + az * bx - ax * bz,
az1 = az * bw + aw * bz + ax * by - ay * bx,
aw1 = aw * bw - ax * bx - ay * by - az * bz;
//----------------------------------------
// Rotate Quaternion
rad *= 0.5;
const sin = Math.sin( rad ),
cos = Math.cos( rad );
bx = this[0] = bbx * cos + bbw * sin;
by = this[1] = bby * cos + bbz * sin;
bz = this[2] = bbz * cos - bby * sin;
bw = this[3] = bbw * cos - bbx * sin;
//----------------------------------------
this[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
return this;
}
rotY( rad : number ) : this {
const bbx = this[0], bby = this[1], bbz = this[2], bbw = this[3]; // Quat
let bx = -this[0], by = -this[1], bz = -this[2], bw = this[3]; // Neg XYZ
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
//----------------------------------------
// Reverse Trans
const ax1 = ax * bw + aw * bx + ay * bz - az * by,
ay1 = ay * bw + aw * by + az * bx - ax * bz,
az1 = az * bw + aw * bz + ax * by - ay * bx,
aw1 = aw * bw - ax * bx - ay * by - az * bz;
//----------------------------------------
// Rotate Quaternion
rad *= 0.5;
const sin = Math.sin( rad ),
cos = Math.cos( rad );
bx = this[0] = bbx * cos - bbz * sin;
by = this[1] = bby * cos + bbw * sin;
bz = this[2] = bbz * cos + bbx * sin;
bw = this[3] = bbw * cos - bby * sin;
//----------------------------------------
this[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
return this;
}
rotZ( rad : number ) : this{
const bbx = this[0], bby = this[1], bbz = this[2], bbw = this[3]; // Quat
let bx = -this[0], by = -this[1], bz = -this[2], bw = this[3]; // Neg XYZ
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
//----------------------------------------
// Reverse Trans
const ax1 = ax * bw + aw * bx + ay * bz - az * by,
ay1 = ay * bw + aw * by + az * bx - ax * bz,
az1 = az * bw + aw * bz + ax * by - ay * bx,
aw1 = aw * bw - ax * bx - ay * by - az * bz;
//----------------------------------------
// Rotate Quaternion
rad *= 0.5;
const sin = Math.sin( rad ),
cos = Math.cos( rad );
bx = this[0] = bbx * cos + bby * sin;
by = this[1] = bby * cos - bbx * sin;
bz = this[2] = bbz * cos + bbw * sin;
bw = this[3] = bbw * cos - bbz * sin;
//----------------------------------------
this[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
return this;
}
/** Rotates a dual quat around a given axis. Does the normalisation automatically */
rotAxisAngle( axis: TVec3, rad: number ) : this{
// Special case for rad = 0
if( Math.abs( rad ) < 0.000001 ) return this;
const axisLength = 1 / Math.sqrt( axis[0]**2 + axis[1]**2 + axis[2]**2 );
rad = rad * 0.5;
const s = Math.sin(rad);
const bx = s * axis[ 0 ] * axisLength;
const by = s * axis[ 1 ] * axisLength;
const bz = s * axis[ 2 ] * axisLength;
const bw = Math.cos( rad );
const ax1 = this[0], ay1 = this[1], az1 = this[2], aw1 = this[3];
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
this[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
this[4] = ax * bw + aw * bx + ay * bz - az * by;
this[5] = ay * bw + aw * by + az * bx - ax * bz;
this[6] = az * bw + aw * bz + ax * by - ay * bx;
this[7] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
//#endregion ////////////////////////////////////////////////////////
//#region TRANSFORMATIONS
transformVec3( v: TVec3, out ?: TVec3 ) : TVec3{
// Quaternion Transform on a Vec3, Then Add Position to results
const pos = this.getTranslation();
const qx = this[ 0 ], qy = this[ 1 ], qz = this[ 2 ], qw = this[ 3 ],
vx = v[ 0 ], vy = v[ 1 ], vz = v[ 2 ],
x1 = qy * vz - qz * vy,
y1 = qz * vx - qx * vz,
z1 = qx * vy - qy * vx,
x2 = qw * x1 + qy * z1 - qz * y1,
y2 = qw * y1 + qz * x1 - qx * z1,
z2 = qw * z1 + qx * y1 - qy * x1;
out = out || v;
out[ 0 ] = ( vx + 2 * x2 ) + pos[ 0 ];
out[ 1 ] = ( vy + 2 * y2 ) + pos[ 1 ];
out[ 2 ] = ( vz + 2 * z2 ) + pos[ 2 ];
return out;
}
//#endregion ////////////////////////////////////////////////////////
}
export default DualQuat; | the_stack |
// To run the test, use command "tsc stamplay.tests.ts"
// Note that the below examples are in the same order as they appear on the Stamplay docs website
import * as Stamplay from "./stamplay";
var car = {
make: "Volkswagen",
model: "Jetta",
year: 2013,
color: "silver",
top_speed: 140
}
Stamplay.Object("car").save(car)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("car").get({})
.then(function (res) {
// success
}, function (err) {
// error
})
var credentials = {
email: "user@provider.com",
password: "123123"
};
Stamplay.User.signup(credentials)
.then(function (res) {
// success
}, function (err) {
// error
})
var credentials = {
email: "user@provider.com",
password: "123123"
}
Stamplay.User.login(credentials)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").get({
page: 2,
per_page: 30
}).then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("picture")
.get({ status: "published" })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").get({ sort: "-dt_create" })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").get({ select: "dt_create,owner,title" })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie")
.get({ populate: true })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie")
.get({ where: JSON.stringify({ rating: { $gt: 5 } }) })
.then(function (res) {
// success
}, function (err) {
// error
})
var credentials = {
email: "user@stamplay.com",
password: "my_password"
}
Stamplay.User.signup(credentials)
.then(function (res) {
// success
}, function (err) {
// error
})
var credentials = {
email: "user@stamplay.com",
password: "my_password"
}
Stamplay.User.login(credentials)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.init("APP-ID", {
isMobile: true,
absoluteUrl: true,
autorefreshSocialLogin: false
})
Stamplay.User.socialLogin("facebook")
var emailAndNewPass = {
email: "user@stamplay.com",
newPassword: "stamplay_rocks!"
}
Stamplay.User.resetPassword(emailAndNewPass)
.then(function (res) {
// success
}, function (err) {
// error
})
//sync
Stamplay.User.logout();
//async
Stamplay.User.logout(true, function (err, res) {
})
Stamplay.User.currentUser()
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.User.get({ _id: "user_id" })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.User.get({})
.then(function (res) {
// success
}, function (err) {
// error
})
var query = {
name: "John",
age: 30
}
Stamplay.User.get(query)
.then(function (res) {
// success
}, function (err) {
// error
})
var updatedInfo = {
name: "John",
age: 30
}
Stamplay.User.update("user_id", updatedInfo)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.User.remove("user_id")
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.User.getRoles()
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.User.getRole("role_Id")
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.User.setRole("userId", "role_id")
.then(function (res) {
// success
}, function (err) {
// error
})
var data = {
title: "Hello World",
year: 2016
}
Stamplay.Object("movie").save(data)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").get({ _id: "object_id" })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").get({})
.then(function (res) {
// success
}, function (err) {
// error
})
var query2 = {
year: 1998
}
Stamplay.Object("movie").get(query2)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").findByCurrentUser('director')
.then(function (res) {
// Success
}, function (err) {
// Error
})
var data2 = {
"title": "Goodbye World"
}
Stamplay.Object("movie").patch("object_id", data2)
.then(function (res) {
// success
}, function (err) {
// error
})
var data3 = {
"title": "Goodbye World"
}
Stamplay.Object("movie").update("object_id", data3)
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").remove("object_id")
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").push("object_id", "characters", "57cf08e362641ca813b1ae6c")
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Object("movie").get({ populate: true })
.then(function (res) {
// success
}, function (err) {
// error
})
// returns records where the rating is greater than 4
Stamplay.Query('object', 'movie')
.greaterThan('actions.ratings.total', 4)
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records that were created after January 15, 2015
Stamplay.Query('object', 'movie')
.greaterThan('dt_create', "2015-01-15T08:00:00.000Z")
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records with a rating of 4 or greater
Stamplay.Query('object', 'movie')
.greaterThanOrEqual('actions.ratings.total', 4)
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records that were last updated on or after April 11, 2012
Stamplay.Query('object', 'movie')
.greaterThanOrEqual('dt_update', "2012-04-11T07:00:00.000Z")
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records with a rating of less than 4
Stamplay.Query('object', 'movie')
.lessThan('actions.ratings.total', 4)
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records that were created before January 15, 2015
Stamplay.Query('object', 'movie')
.lessThan('actions.ratings.total', 4)
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records with a rating of 4 or less
Stamplay.Query('object', 'movie')
.lessThanOrEqual('actions.ratings.total', 4)
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// returns records that were last updated on or before April 11, 2012
Stamplay.Query('object', 'movie')
.lessThanOrEqual('dt_update', "2012-04-11T07:00:00.000Z")
.exec()
.then(function () {
// success
}, function (err) {
// error
})
Stamplay.Query("object", "cobject_id")
.select("title", "actions.ratings.total")
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// sort by title in ascending order
Stamplay.Query("object", "cobject_id")
.sortAscending("title")
.exec()
.then(function () {
// success
}, function (err) {
// error
})
// sort by title in descending order
Stamplay.Query("object", "cobject_id")
.sortDescending("title")
.exec()
.then(function () {
// success
}, function (err) {
// error
})
Stamplay.Query('object', 'question')
.regex('title', '^Star', 'i')
.exec()
.then(function (res) {
// success
}, function (err) {
// error
})
var ratedFourOrMore = Stamplay.Query("object", "movie");
var titleIsStarWars = Stamplay.Query("object", "movie");
ratedFourOrMore.greaterThanOrEqual("actions.ratings.total", 4);
titleIsStarWars.equalTo("title", "Star Wars");
var combinedQuery = Stamplay.Query("object", "movie");
combinedQuery.or(ratedFourOrMore, titleIsStarWars);
combinedQuery.exec()
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Query("object", "movie")
.geoWithinGeometry('Polygon',
[
[[-70, 40], [-72, 40], [-72, 50], [-70, 50], [-70, 40]]
]).exec()
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Query("object", "movie")
.geoIntersects('Point', [74.0059, 40.7127])
.exec()
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Query("object", "dinners")
.near('Point', [74.0059, 40.7127], 500)
.exec()
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Query("object", "dinners")
.nearSphere('Point', [74.0059, 40.7127], 1000)
.exec()
.then(function (res) {
// success
}, function (err) {
// error
})
var data4 = { message: "Hello" }
var params = { name: "Stamplay", bar: "foo" }
//Stamplay.Codeblock("codeblock_name").run() sends a POST request by default
Stamplay.Codeblock("codeblock_name").run(data4, params)
.then(function (err) {
// success
}, function (err) {
// error
})
var params1 = { name: "Stamplay" }
//GET
Stamplay.Codeblock("codeblock_name").get(params1, function (err, res) {
// manage the response and the error
})
//POST
var data5 = { bodyparam: "Stamplay" }
Stamplay.Codeblock("codeblock_name").post(data5)
.then(function (err) {
// success
}, function (err) {
// error
})
//PUT
Stamplay.Codeblock("codeblock_name").put(data)
.then(function (err) {
// success
}, function (err) {
// error
})
//PATCH
Stamplay.Codeblock("codeblock_name").patch(data)
.then(function (err) {
// success
}, function (err) {
// error
})
Stamplay.Webhook("webhook_id")
.post({ name: "Johne" })
.then(function (res) {
// success
}, function (err) {
// error
})
Stamplay.Stripe.createCustomer("userId")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.getSubscription("userId",
"subscriptionId")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.getSubscriptions("userId",
{ someOption: "value" })
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.createSubscription("userId",
"planId")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.updateSubscription("userId", "planId",
{ plan: "subscription_one" })
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.deleteSubscription("userId",
"planId")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.getCreditCard("userId")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.createCreditCard("userId",
"token")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.updateCreditCard("userId",
"token")
.then(function (res) {
// success
},
function (err) {
// error
})
Stamplay.Stripe.charge("userId",
"token",
"amount",
"currency")
.then(function (res) {
// Success
},
function (err) {
// Handle Error
}); | the_stack |
import {
Bip39,
EnglishMnemonic,
HdPath,
pathToString,
Random,
Secp256k1,
Secp256k1Keypair,
sha256,
Slip10,
Slip10Curve,
stringToPath,
} from "@cosmjs/crypto";
import { Bech32, fromBase64, fromUtf8, toBase64, toUtf8 } from "@cosmjs/encoding";
import { assert, isNonNullObject } from "@cosmjs/utils";
import { rawSecp256k1PubkeyToRawAddress } from "./addresses";
import { makeCosmoshubPath } from "./paths";
import { encodeSecp256k1Signature } from "./signature";
import { serializeSignDoc, StdSignDoc } from "./signdoc";
import { AccountData, AminoSignResponse, OfflineAminoSigner } from "./signer";
import {
decrypt,
encrypt,
EncryptionConfiguration,
executeKdf,
KdfConfiguration,
supportedAlgorithms,
} from "./wallet";
interface AccountDataWithPrivkey extends AccountData {
readonly privkey: Uint8Array;
}
const serializationTypeV1 = "secp256k1wallet-v1";
/**
* A KDF configuration that is not very strong but can be used on the main thread.
* It takes about 1 second in Node.js 16.0.0 and should have similar runtimes in other modern Wasm hosts.
*/
const basicPasswordHashingOptions: KdfConfiguration = {
algorithm: "argon2id",
params: {
outputLength: 32,
opsLimit: 24,
memLimitKib: 12 * 1024,
},
};
/**
* This interface describes a JSON object holding the encrypted wallet and the meta data.
* All fields in here must be JSON types.
*/
export interface Secp256k1HdWalletSerialization {
/** A format+version identifier for this serialization format */
readonly type: string;
/** Information about the key derivation function (i.e. password to encryption key) */
readonly kdf: KdfConfiguration;
/** Information about the symmetric encryption */
readonly encryption: EncryptionConfiguration;
/** An instance of Secp256k1HdWalletData, which is stringified, encrypted and base64 encoded. */
readonly data: string;
}
/**
* Derivation information required to derive a keypair and an address from a mnemonic.
* All fields in here must be JSON types.
*/
interface DerivationInfoJson {
readonly hdPath: string;
readonly prefix: string;
}
function isDerivationJson(thing: unknown): thing is DerivationInfoJson {
if (!isNonNullObject(thing)) return false;
if (typeof (thing as DerivationInfoJson).hdPath !== "string") return false;
if (typeof (thing as DerivationInfoJson).prefix !== "string") return false;
return true;
}
/**
* The data of a wallet serialization that is encrypted.
* All fields in here must be JSON types.
*/
interface Secp256k1HdWalletData {
readonly mnemonic: string;
readonly accounts: readonly DerivationInfoJson[];
}
function extractKdfConfigurationV1(doc: any): KdfConfiguration {
return doc.kdf;
}
export function extractKdfConfiguration(serialization: string): KdfConfiguration {
const root = JSON.parse(serialization);
if (!isNonNullObject(root)) throw new Error("Root document is not an object.");
switch ((root as any).type) {
case serializationTypeV1:
return extractKdfConfigurationV1(root);
default:
throw new Error("Unsupported serialization type");
}
}
/**
* Derivation information required to derive a keypair and an address from a mnemonic.
*/
interface DerivationInfo {
readonly hdPath: HdPath;
/** The bech32 address prefix (human readable part). */
readonly prefix: string;
}
export interface Secp256k1HdWalletOptions {
/** The password to use when deriving a BIP39 seed from a mnemonic. */
readonly bip39Password: string;
/** The BIP-32/SLIP-10 derivation paths. Defaults to the Cosmos Hub/ATOM path `m/44'/118'/0'/0/0`. */
readonly hdPaths: readonly HdPath[];
/** The bech32 address prefix (human readable part). Defaults to "cosmos". */
readonly prefix: string;
}
interface Secp256k1HdWalletConstructorOptions extends Partial<Secp256k1HdWalletOptions> {
readonly seed: Uint8Array;
}
const defaultOptions: Secp256k1HdWalletOptions = {
bip39Password: "",
hdPaths: [makeCosmoshubPath(0)],
prefix: "cosmos",
};
export class Secp256k1HdWallet implements OfflineAminoSigner {
/**
* Restores a wallet from the given BIP39 mnemonic.
*
* @param mnemonic Any valid English mnemonic.
* @param options An optional `Secp256k1HdWalletOptions` object optionally containing a bip39Password, hdPaths, and prefix.
*/
public static async fromMnemonic(
mnemonic: string,
options: Partial<Secp256k1HdWalletOptions> = {},
): Promise<Secp256k1HdWallet> {
const mnemonicChecked = new EnglishMnemonic(mnemonic);
const seed = await Bip39.mnemonicToSeed(mnemonicChecked, options.bip39Password);
return new Secp256k1HdWallet(mnemonicChecked, {
...options,
seed: seed,
});
}
/**
* Generates a new wallet with a BIP39 mnemonic of the given length.
*
* @param length The number of words in the mnemonic (12, 15, 18, 21 or 24).
* @param options An optional `Secp256k1HdWalletOptions` object optionally containing a bip39Password, hdPaths, and prefix.
*/
public static async generate(
length: 12 | 15 | 18 | 21 | 24 = 12,
options: Partial<Secp256k1HdWalletOptions> = {},
): Promise<Secp256k1HdWallet> {
const entropyLength = 4 * Math.floor((11 * length) / 33);
const entropy = Random.getBytes(entropyLength);
const mnemonic = Bip39.encode(entropy);
return Secp256k1HdWallet.fromMnemonic(mnemonic.toString(), options);
}
/**
* Restores a wallet from an encrypted serialization.
*
* @param password The user provided password used to generate an encryption key via a KDF.
* This is not normalized internally (see "Unicode normalization" to learn more).
*/
public static async deserialize(serialization: string, password: string): Promise<Secp256k1HdWallet> {
const root = JSON.parse(serialization);
if (!isNonNullObject(root)) throw new Error("Root document is not an object.");
switch ((root as any).type) {
case serializationTypeV1:
return Secp256k1HdWallet.deserializeTypeV1(serialization, password);
default:
throw new Error("Unsupported serialization type");
}
}
/**
* Restores a wallet from an encrypted serialization.
*
* This is an advanced alternative to calling `deserialize(serialization, password)` directly, which allows
* you to offload the KDF execution to a non-UI thread (e.g. in a WebWorker).
*
* The caller is responsible for ensuring the key was derived with the given KDF configuration. This can be
* done using `extractKdfConfiguration(serialization)` and `executeKdf(password, kdfConfiguration)` from this package.
*/
public static async deserializeWithEncryptionKey(
serialization: string,
encryptionKey: Uint8Array,
): Promise<Secp256k1HdWallet> {
const root = JSON.parse(serialization);
if (!isNonNullObject(root)) throw new Error("Root document is not an object.");
const untypedRoot: any = root;
switch (untypedRoot.type) {
case serializationTypeV1: {
const decryptedBytes = await decrypt(
fromBase64(untypedRoot.data),
encryptionKey,
untypedRoot.encryption,
);
const decryptedDocument = JSON.parse(fromUtf8(decryptedBytes));
const { mnemonic, accounts } = decryptedDocument;
assert(typeof mnemonic === "string");
if (!Array.isArray(accounts)) throw new Error("Property 'accounts' is not an array");
if (!accounts.every((account) => isDerivationJson(account))) {
throw new Error("Account is not in the correct format.");
}
const firstPrefix = accounts[0].prefix;
if (!accounts.every(({ prefix }) => prefix === firstPrefix)) {
throw new Error("Accounts do not all have the same prefix");
}
const hdPaths = accounts.map(({ hdPath }) => stringToPath(hdPath));
return Secp256k1HdWallet.fromMnemonic(mnemonic, {
hdPaths: hdPaths,
prefix: firstPrefix,
});
}
default:
throw new Error("Unsupported serialization type");
}
}
private static async deserializeTypeV1(
serialization: string,
password: string,
): Promise<Secp256k1HdWallet> {
const root = JSON.parse(serialization);
if (!isNonNullObject(root)) throw new Error("Root document is not an object.");
const encryptionKey = await executeKdf(password, (root as any).kdf);
return Secp256k1HdWallet.deserializeWithEncryptionKey(serialization, encryptionKey);
}
/** Base secret */
private readonly secret: EnglishMnemonic;
/** BIP39 seed */
private readonly seed: Uint8Array;
/** Derivation instruction */
private readonly accounts: readonly DerivationInfo[];
protected constructor(mnemonic: EnglishMnemonic, options: Secp256k1HdWalletConstructorOptions) {
const hdPaths = options.hdPaths ?? defaultOptions.hdPaths;
const prefix = options.prefix ?? defaultOptions.prefix;
this.secret = mnemonic;
this.seed = options.seed;
this.accounts = hdPaths.map((hdPath) => ({
hdPath: hdPath,
prefix,
}));
}
public get mnemonic(): string {
return this.secret.toString();
}
public async getAccounts(): Promise<readonly AccountData[]> {
const accountsWithPrivkeys = await this.getAccountsWithPrivkeys();
return accountsWithPrivkeys.map(({ algo, pubkey, address }) => ({
algo: algo,
pubkey: pubkey,
address: address,
}));
}
public async signAmino(signerAddress: string, signDoc: StdSignDoc): Promise<AminoSignResponse> {
const accounts = await this.getAccountsWithPrivkeys();
const account = accounts.find(({ address }) => address === signerAddress);
if (account === undefined) {
throw new Error(`Address ${signerAddress} not found in wallet`);
}
const { privkey, pubkey } = account;
const message = sha256(serializeSignDoc(signDoc));
const signature = await Secp256k1.createSignature(message, privkey);
const signatureBytes = new Uint8Array([...signature.r(32), ...signature.s(32)]);
return {
signed: signDoc,
signature: encodeSecp256k1Signature(pubkey, signatureBytes),
};
}
/**
* Generates an encrypted serialization of this wallet.
*
* @param password The user provided password used to generate an encryption key via a KDF.
* This is not normalized internally (see "Unicode normalization" to learn more).
*/
public async serialize(password: string): Promise<string> {
const kdfConfiguration = basicPasswordHashingOptions;
const encryptionKey = await executeKdf(password, kdfConfiguration);
return this.serializeWithEncryptionKey(encryptionKey, kdfConfiguration);
}
/**
* Generates an encrypted serialization of this wallet.
*
* This is an advanced alternative to calling `serialize(password)` directly, which allows you to
* offload the KDF execution to a non-UI thread (e.g. in a WebWorker).
*
* The caller is responsible for ensuring the key was derived with the given KDF options. If this
* is not the case, the wallet cannot be restored with the original password.
*/
public async serializeWithEncryptionKey(
encryptionKey: Uint8Array,
kdfConfiguration: KdfConfiguration,
): Promise<string> {
const dataToEncrypt: Secp256k1HdWalletData = {
mnemonic: this.mnemonic,
accounts: this.accounts.map(({ hdPath, prefix }) => ({
hdPath: pathToString(hdPath),
prefix: prefix,
})),
};
const dataToEncryptRaw = toUtf8(JSON.stringify(dataToEncrypt));
const encryptionConfiguration: EncryptionConfiguration = {
algorithm: supportedAlgorithms.xchacha20poly1305Ietf,
};
const encryptedData = await encrypt(dataToEncryptRaw, encryptionKey, encryptionConfiguration);
const out: Secp256k1HdWalletSerialization = {
type: serializationTypeV1,
kdf: kdfConfiguration,
encryption: encryptionConfiguration,
data: toBase64(encryptedData),
};
return JSON.stringify(out);
}
private async getKeyPair(hdPath: HdPath): Promise<Secp256k1Keypair> {
const { privkey } = Slip10.derivePath(Slip10Curve.Secp256k1, this.seed, hdPath);
const { pubkey } = await Secp256k1.makeKeypair(privkey);
return {
privkey: privkey,
pubkey: Secp256k1.compressPubkey(pubkey),
};
}
private async getAccountsWithPrivkeys(): Promise<readonly AccountDataWithPrivkey[]> {
return Promise.all(
this.accounts.map(async ({ hdPath, prefix }) => {
const { privkey, pubkey } = await this.getKeyPair(hdPath);
const address = Bech32.encode(prefix, rawSecp256k1PubkeyToRawAddress(pubkey));
return {
algo: "secp256k1" as const,
privkey: privkey,
pubkey: pubkey,
address: address,
};
}),
);
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Represents a TargetHttpsProxy resource, which is used by one or more
* global forwarding rule to route incoming HTTPS requests to a URL map.
*
* To get more information about TargetHttpsProxy, see:
*
* * [API documentation](https://cloud.google.com/compute/docs/reference/v1/targetHttpsProxies)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/compute/docs/load-balancing/http/target-proxies)
*
* ## Example Usage
* ### Target Https Proxy Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const defaultSSLCertificate = new gcp.compute.SSLCertificate("defaultSSLCertificate", {
* privateKey: fs.readFileSync("path/to/private.key"),
* certificate: fs.readFileSync("path/to/certificate.crt"),
* });
* const defaultHttpHealthCheck = new gcp.compute.HttpHealthCheck("defaultHttpHealthCheck", {
* requestPath: "/",
* checkIntervalSec: 1,
* timeoutSec: 1,
* });
* const defaultBackendService = new gcp.compute.BackendService("defaultBackendService", {
* portName: "http",
* protocol: "HTTP",
* timeoutSec: 10,
* healthChecks: [defaultHttpHealthCheck.id],
* });
* const defaultURLMap = new gcp.compute.URLMap("defaultURLMap", {
* description: "a description",
* defaultService: defaultBackendService.id,
* hostRules: [{
* hosts: ["mysite.com"],
* pathMatcher: "allpaths",
* }],
* pathMatchers: [{
* name: "allpaths",
* defaultService: defaultBackendService.id,
* pathRules: [{
* paths: ["/*"],
* service: defaultBackendService.id,
* }],
* }],
* });
* const defaultTargetHttpsProxy = new gcp.compute.TargetHttpsProxy("defaultTargetHttpsProxy", {
* urlMap: defaultURLMap.id,
* sslCertificates: [defaultSSLCertificate.id],
* });
* ```
*
* ## Import
*
* TargetHttpsProxy can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:compute/targetHttpsProxy:TargetHttpsProxy default projects/{{project}}/global/targetHttpsProxies/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/targetHttpsProxy:TargetHttpsProxy default {{project}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/targetHttpsProxy:TargetHttpsProxy default {{name}}
* ```
*/
export class TargetHttpsProxy extends pulumi.CustomResource {
/**
* Get an existing TargetHttpsProxy resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: TargetHttpsProxyState, opts?: pulumi.CustomResourceOptions): TargetHttpsProxy {
return new TargetHttpsProxy(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:compute/targetHttpsProxy:TargetHttpsProxy';
/**
* Returns true if the given object is an instance of TargetHttpsProxy. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is TargetHttpsProxy {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === TargetHttpsProxy.__pulumiType;
}
/**
* Creation timestamp in RFC3339 text format.
*/
public /*out*/ readonly creationTimestamp!: pulumi.Output<string>;
/**
* An optional description of this resource.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* Name of the resource. Provided by the client when the resource is
* created. The name must be 1-63 characters long, and comply with
* RFC1035. Specifically, the name must be 1-63 characters long and match
* the regular expression `a-z?` which means the
* first character must be a lowercase letter, and all following
* characters must be a dash, lowercase letter, or digit, except the last
* character, which cannot be a dash.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* This field only applies when the forwarding rule that references
* this target proxy has a loadBalancingScheme set to INTERNAL_SELF_MANAGED.
*/
public readonly proxyBind!: pulumi.Output<boolean>;
/**
* The unique identifier for the resource.
*/
public /*out*/ readonly proxyId!: pulumi.Output<number>;
/**
* Specifies the QUIC override policy for this resource. This determines
* whether the load balancer will attempt to negotiate QUIC with clients
* or not. Can specify one of NONE, ENABLE, or DISABLE. If NONE is
* specified, uses the QUIC policy with no user overrides, which is
* equivalent to DISABLE.
* Default value is `NONE`.
* Possible values are `NONE`, `ENABLE`, and `DISABLE`.
*/
public readonly quicOverride!: pulumi.Output<string | undefined>;
/**
* The URI of the created resource.
*/
public /*out*/ readonly selfLink!: pulumi.Output<string>;
/**
* A list of SslCertificate resources that are used to authenticate
* connections between users and the load balancer. At least one SSL
* certificate must be specified.
*/
public readonly sslCertificates!: pulumi.Output<string[]>;
/**
* A reference to the SslPolicy resource that will be associated with
* the TargetHttpsProxy resource. If not set, the TargetHttpsProxy
* resource will not have any SSL policy configured.
*/
public readonly sslPolicy!: pulumi.Output<string | undefined>;
/**
* A reference to the UrlMap resource that defines the mapping from URL
* to the BackendService.
*/
public readonly urlMap!: pulumi.Output<string>;
/**
* Create a TargetHttpsProxy resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: TargetHttpsProxyArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: TargetHttpsProxyArgs | TargetHttpsProxyState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as TargetHttpsProxyState | undefined;
inputs["creationTimestamp"] = state ? state.creationTimestamp : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["proxyBind"] = state ? state.proxyBind : undefined;
inputs["proxyId"] = state ? state.proxyId : undefined;
inputs["quicOverride"] = state ? state.quicOverride : undefined;
inputs["selfLink"] = state ? state.selfLink : undefined;
inputs["sslCertificates"] = state ? state.sslCertificates : undefined;
inputs["sslPolicy"] = state ? state.sslPolicy : undefined;
inputs["urlMap"] = state ? state.urlMap : undefined;
} else {
const args = argsOrState as TargetHttpsProxyArgs | undefined;
if ((!args || args.sslCertificates === undefined) && !opts.urn) {
throw new Error("Missing required property 'sslCertificates'");
}
if ((!args || args.urlMap === undefined) && !opts.urn) {
throw new Error("Missing required property 'urlMap'");
}
inputs["description"] = args ? args.description : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["proxyBind"] = args ? args.proxyBind : undefined;
inputs["quicOverride"] = args ? args.quicOverride : undefined;
inputs["sslCertificates"] = args ? args.sslCertificates : undefined;
inputs["sslPolicy"] = args ? args.sslPolicy : undefined;
inputs["urlMap"] = args ? args.urlMap : undefined;
inputs["creationTimestamp"] = undefined /*out*/;
inputs["proxyId"] = undefined /*out*/;
inputs["selfLink"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(TargetHttpsProxy.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering TargetHttpsProxy resources.
*/
export interface TargetHttpsProxyState {
/**
* Creation timestamp in RFC3339 text format.
*/
creationTimestamp?: pulumi.Input<string>;
/**
* An optional description of this resource.
*/
description?: pulumi.Input<string>;
/**
* Name of the resource. Provided by the client when the resource is
* created. The name must be 1-63 characters long, and comply with
* RFC1035. Specifically, the name must be 1-63 characters long and match
* the regular expression `a-z?` which means the
* first character must be a lowercase letter, and all following
* characters must be a dash, lowercase letter, or digit, except the last
* character, which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* This field only applies when the forwarding rule that references
* this target proxy has a loadBalancingScheme set to INTERNAL_SELF_MANAGED.
*/
proxyBind?: pulumi.Input<boolean>;
/**
* The unique identifier for the resource.
*/
proxyId?: pulumi.Input<number>;
/**
* Specifies the QUIC override policy for this resource. This determines
* whether the load balancer will attempt to negotiate QUIC with clients
* or not. Can specify one of NONE, ENABLE, or DISABLE. If NONE is
* specified, uses the QUIC policy with no user overrides, which is
* equivalent to DISABLE.
* Default value is `NONE`.
* Possible values are `NONE`, `ENABLE`, and `DISABLE`.
*/
quicOverride?: pulumi.Input<string>;
/**
* The URI of the created resource.
*/
selfLink?: pulumi.Input<string>;
/**
* A list of SslCertificate resources that are used to authenticate
* connections between users and the load balancer. At least one SSL
* certificate must be specified.
*/
sslCertificates?: pulumi.Input<pulumi.Input<string>[]>;
/**
* A reference to the SslPolicy resource that will be associated with
* the TargetHttpsProxy resource. If not set, the TargetHttpsProxy
* resource will not have any SSL policy configured.
*/
sslPolicy?: pulumi.Input<string>;
/**
* A reference to the UrlMap resource that defines the mapping from URL
* to the BackendService.
*/
urlMap?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a TargetHttpsProxy resource.
*/
export interface TargetHttpsProxyArgs {
/**
* An optional description of this resource.
*/
description?: pulumi.Input<string>;
/**
* Name of the resource. Provided by the client when the resource is
* created. The name must be 1-63 characters long, and comply with
* RFC1035. Specifically, the name must be 1-63 characters long and match
* the regular expression `a-z?` which means the
* first character must be a lowercase letter, and all following
* characters must be a dash, lowercase letter, or digit, except the last
* character, which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* This field only applies when the forwarding rule that references
* this target proxy has a loadBalancingScheme set to INTERNAL_SELF_MANAGED.
*/
proxyBind?: pulumi.Input<boolean>;
/**
* Specifies the QUIC override policy for this resource. This determines
* whether the load balancer will attempt to negotiate QUIC with clients
* or not. Can specify one of NONE, ENABLE, or DISABLE. If NONE is
* specified, uses the QUIC policy with no user overrides, which is
* equivalent to DISABLE.
* Default value is `NONE`.
* Possible values are `NONE`, `ENABLE`, and `DISABLE`.
*/
quicOverride?: pulumi.Input<string>;
/**
* A list of SslCertificate resources that are used to authenticate
* connections between users and the load balancer. At least one SSL
* certificate must be specified.
*/
sslCertificates: pulumi.Input<pulumi.Input<string>[]>;
/**
* A reference to the SslPolicy resource that will be associated with
* the TargetHttpsProxy resource. If not set, the TargetHttpsProxy
* resource will not have any SSL policy configured.
*/
sslPolicy?: pulumi.Input<string>;
/**
* A reference to the UrlMap resource that defines the mapping from URL
* to the BackendService.
*/
urlMap: pulumi.Input<string>;
} | the_stack |
import {TypedObjNode} from './_Base';
import {Group} from 'three/src/objects/Group';
import {FlagsControllerD} from '../utils/FlagsController';
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
import {BaseNodeType} from '../_Base';
import {HierarchyController} from './utils/HierarchyController';
import {WebGLRenderer} from 'three/src/renderers/WebGLRenderer';
import {Scene} from 'three/src/scenes/Scene';
import {Camera} from 'three/src/cameras/Camera';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {Geometry} from '../../../modules/three/examples/jsm/deprecated/Geometry';
import {Material} from 'three/src/materials/Material';
import {Mesh} from 'three/src/objects/Mesh';
import {RenderHook} from '../../../core/geometry/Material';
import {TypeAssert} from '../../poly/Assert';
import {CameraHelper} from './utils/helpers/CameraHelper';
import {MeshBasicMaterial} from 'three/src/materials/MeshBasicMaterial';
import {MeshDepthMaterial} from 'three/src/materials/MeshDepthMaterial';
import {OrthographicCamera} from 'three/src/cameras/OrthographicCamera';
import {PlaneBufferGeometry} from 'three/src/geometries/PlaneGeometry';
import {WebGLRenderTarget} from 'three/src/renderers/WebGLRenderTarget';
import {Vector2} from 'three/src/math/Vector2';
import {Poly} from '../../Poly';
import {isBooleanTrue} from '../../../core/BooleanValue';
import {TransformController, TransformedParamConfig} from './utils/TransformController';
import {Object3D} from 'three/src/core/Object3D';
import {CoreRenderBlur} from '../../../core/render/Blur';
enum ContactShadowUpdateMode {
ON_RENDER = 'On Every Render',
MANUAL = 'Manual',
}
const UPDATE_MODES: ContactShadowUpdateMode[] = [ContactShadowUpdateMode.ON_RENDER, ContactShadowUpdateMode.MANUAL];
class ContactShadowObjParamConfig extends TransformedParamConfig(NodeParamsConfig) {
shadow = ParamConfig.FOLDER();
/** @param distance from the ground up to which shadows are visible */
dist = ParamConfig.FLOAT(1, {
range: [0, 10],
rangeLocked: [true, false],
});
/** @param size of the plane on which shadows are rendered */
planeSize = ParamConfig.VECTOR2([1, 1]);
/** @param shadow resolution */
shadowRes = ParamConfig.VECTOR2([256, 256]);
/** @param blur amount */
blur = ParamConfig.FLOAT(1, {
range: [0, 10],
rangeLocked: [true, false],
});
/** @param toggle on to add a secondary blur, which may be useful to get rid of artefacts */
tblur2 = ParamConfig.BOOLEAN(1);
/** @param secondary blur amount */
blur2 = ParamConfig.FLOAT(1, {
range: [0, 10],
rangeLocked: [true, false],
visibleIf: {tblur2: 1},
});
/** @param shadow darkness */
darkness = ParamConfig.FLOAT(1);
/** @param shadow opacity */
opacity = ParamConfig.FLOAT(1);
/** @param show helper */
showHelper = ParamConfig.BOOLEAN(0);
/** @param set update mode, which can be to update on every frame, or manually only */
updateMode = ParamConfig.INTEGER(UPDATE_MODES.indexOf(ContactShadowUpdateMode.ON_RENDER), {
callback: (node: BaseNodeType) => {
ContactShadowObjNode.PARAM_CALLBACK_update_updateMode(node as ContactShadowObjNode);
},
menu: {
entries: UPDATE_MODES.map((name, value) => {
return {name, value};
}),
},
});
/** @param click to update shadow, when mode is manual */
update = ParamConfig.BUTTON(null, {
callback: (node: BaseNodeType) => {
ContactShadowObjNode.PARAM_CALLBACK_updateManual(node as ContactShadowObjNode);
},
visibleIf: {updateMode: UPDATE_MODES.indexOf(ContactShadowUpdateMode.MANUAL)},
});
scene = ParamConfig.FOLDER();
include = ParamConfig.STRING('');
exclude = ParamConfig.STRING('');
updateObjectsList = ParamConfig.BUTTON(null, {
callback: (node: BaseNodeType) => {
ContactShadowObjNode.PARAM_CALLBACK_updateObjectsList(node as ContactShadowObjNode);
},
});
printResolveObjectsList = ParamConfig.BUTTON(null, {
callback: (node: BaseNodeType) => {
ContactShadowObjNode.PARAM_CALLBACK_printResolveObjectsList(node as ContactShadowObjNode);
},
});
}
const ParamsConfig = new ContactShadowObjParamConfig();
const PLANE_WIDTH = 1;
const PLANE_HEIGHT = 1;
const CAMERA_HEIGHT = 1;
const DARKNESS = 1;
const DEFAULT_RENDER_TARGET_RES = new Vector2(256, 256);
export class ContactShadowObjNode extends TypedObjNode<Group, ContactShadowObjParamConfig> {
paramsConfig = ParamsConfig;
static type(): Readonly<'contactShadow'> {
return 'contactShadow';
}
readonly hierarchyController: HierarchyController = new HierarchyController(this);
public readonly flags: FlagsControllerD = new FlagsControllerD(this);
private _helper: CameraHelper | undefined;
private _renderTarget = this._createRenderTarget(DEFAULT_RENDER_TARGET_RES);
private _coreRenderBlur: CoreRenderBlur = this._createCoreRenderBlur(DEFAULT_RENDER_TARGET_RES);
private _createRenderTarget(res: Vector2) {
const renderTarget = new WebGLRenderTarget(res.x, res.y);
renderTarget.texture.generateMipmaps = false;
return renderTarget;
}
private _createCoreRenderBlur(res: Vector2) {
return new CoreRenderBlur(res);
}
private _shadowGroup: Group | undefined;
private _plane: Mesh | undefined;
private _planeMaterial: MeshBasicMaterial | undefined;
// private _fillPlaneMaterial: MeshBasicMaterial | undefined;
private _includedObjects: Object3D[] = [];
private _includedAncestors: Object3D[] = [];
private _excludedObjects: Object3D[] = [];
createObject() {
const group = new Group();
this._shadowGroup = new Group();
group.add(this._shadowGroup);
this._shadowGroup.name = 'shadowGroup';
const planeGeometry = new PlaneBufferGeometry(PLANE_WIDTH, PLANE_HEIGHT).rotateX(-Math.PI / 2);
// update uvs
const uvArray = planeGeometry.getAttribute('uv').array as number[];
for (let index of [1, 3, 5, 7]) {
uvArray[index] = 1 - uvArray[index];
}
this._planeMaterial = new MeshBasicMaterial({
map: this._renderTarget.texture,
opacity: 1,
transparent: true,
depthWrite: false,
});
// this._renderTarget.texture.flipY = true;
this._plane = new Mesh(planeGeometry, this._planeMaterial);
// make sure it's rendered after the fillPlane
this._plane.renderOrder = 1;
// the y from the texture is flipped!
// this._plane.scale.y = -1;
this._plane.matrixAutoUpdate = false;
this._shadowGroup.add(this._plane);
// the plane with the color of the ground
// this._fillPlaneMaterial = new MeshBasicMaterial({
// color: 0xffffff,
// opacity: OPACITY,
// transparent: true,
// depthWrite: false,
// });
// const fillPlane = new Mesh(planeGeometry, this._fillPlaneMaterial);
// fillPlane.rotateX(Math.PI);
// this._shadowGroup.add(fillPlane);
this._createDepthCamera(this._shadowGroup);
this._createMaterials();
return group;
}
readonly transformController: TransformController = new TransformController(this);
initializeNode() {
this.hierarchyController.initializeNode();
this.transformController.initializeNode();
this._updateShadowGroupVisibility();
this._updateHelperVisibility();
this.flags.display.onUpdate(() => {
this._updateShadowGroupVisibility();
this._updateHelperVisibility();
});
}
async cook() {
this.transformController.update();
this._updateRenderHook();
this._updateHelperVisibility();
this._updateObjectsList();
if (this._planeMaterial) {
this._planeMaterial.opacity = this.pv.opacity;
}
this._darknessUniform.value = this.pv.darkness;
// update planes size
if (this._plane && this._shadowCamera && this._helper) {
this._plane.scale.x = this.pv.planeSize.x;
this._plane.scale.z = this.pv.planeSize.y;
this._plane.updateMatrix();
this._shadowCamera.left = -this.pv.planeSize.x / 2;
this._shadowCamera.right = this.pv.planeSize.x / 2;
this._shadowCamera.bottom = -this.pv.planeSize.y / 2;
this._shadowCamera.top = this.pv.planeSize.y / 2;
this._shadowCamera.far = this.pv.dist;
this._shadowCamera.updateProjectionMatrix();
this._helper.update();
}
// update renderTargets if needed
if (this._renderTarget.width != this.pv.shadowRes.x || this._renderTarget.height != this.pv.shadowRes.y) {
if (this._planeMaterial) {
this._renderTarget = this._createRenderTarget(this.pv.shadowRes);
this._coreRenderBlur = this._createCoreRenderBlur(this.pv.shadowRes);
this._planeMaterial.map = this._renderTarget.texture;
}
}
this.cookController.endCook();
}
private _shadowCamera: OrthographicCamera | undefined;
private _createDepthCamera(group: Group) {
// the camera to render the depth material from
this._shadowCamera = new OrthographicCamera(
-PLANE_WIDTH / 2,
PLANE_WIDTH / 2,
PLANE_HEIGHT / 2,
-PLANE_HEIGHT / 2,
0,
CAMERA_HEIGHT
);
// this._shadowCamera.rotation.z = Math.PI / 2;
this._shadowCamera.rotation.x = Math.PI / 2; // get the camera to look up
// this._shadowCamera.position.y = 0.1;
group.add(this._shadowCamera);
this._helper = new CameraHelper(this._shadowCamera);
this._helper.visible = false;
this._shadowCamera.add(this._helper);
}
private _depthMaterial: MeshDepthMaterial | undefined;
private _darknessUniform = {value: DARKNESS};
private _createMaterials() {
// like MeshDepthMaterial, but goes from black to transparent
this._depthMaterial = new MeshDepthMaterial();
this._depthMaterial.onBeforeCompile = (shader) => {
shader.uniforms.darkness = this._darknessUniform;
shader.fragmentShader = /* glsl */ `
uniform float darkness;
${shader.fragmentShader.replace(
'gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );',
'gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );'
)}
`;
};
this._depthMaterial.depthTest = false;
this._depthMaterial.depthWrite = false;
}
private _emptyOnBeforeRender = () => {};
private _renderShadow(renderer: WebGLRenderer, scene: Scene) {
if (!this._helper) {
return;
}
if (!this._depthMaterial) {
return;
}
if (!this._shadowCamera) {
return;
}
if (!this._helper) {
return;
}
if (!this._plane) {
return;
}
// save current state
const previousOnBeforeRender = this._plane.onBeforeRender;
const initialBackground = scene.background;
const helperVisible = this._helper.visible;
// prepare scene
scene.background = null;
this._plane.onBeforeRender = this._emptyOnBeforeRender;
this._helper.visible = false;
scene.overrideMaterial = this._depthMaterial;
this._initVisibility(scene);
// render to the render target to get the depths
renderer.setRenderTarget(this._renderTarget);
renderer.render(scene, this._shadowCamera);
this._coreRenderBlur.applyBlur(this._renderTarget, renderer, this.pv.blur, this.pv.blur);
if (isBooleanTrue(this.pv.tblur2)) {
this._coreRenderBlur.applyBlur(this._renderTarget, renderer, this.pv.blur2, this.pv.blur2);
}
// reset and render the normal scene
this._restoreVisibility(scene);
scene.overrideMaterial = null;
this._helper.visible = helperVisible;
renderer.setRenderTarget(null);
scene.background = initialBackground;
this._plane.onBeforeRender = previousOnBeforeRender;
}
private _updateShadowGroupVisibility() {
if (!this._shadowGroup) {
return;
}
if (this.flags.display.active()) {
this._shadowGroup.visible = true;
} else {
this._shadowGroup.visible = false;
}
}
private _updateHelperVisibility() {
if (!this._helper) {
return;
}
if (this.flags.display.active() && isBooleanTrue(this.pv.showHelper)) {
this._helper.visible = true;
} else {
this._helper.visible = false;
}
}
private _updateRenderHook() {
const mode = UPDATE_MODES[this.pv.updateMode];
switch (mode) {
case ContactShadowUpdateMode.ON_RENDER: {
return this._addRenderHook();
}
case ContactShadowUpdateMode.MANUAL: {
return this._removeRenderHook();
}
}
TypeAssert.unreachable(mode);
}
private _addRenderHook() {
if (!this._plane) {
return;
}
if (this._plane.onBeforeRender != this._on_object_before_render_bound) {
this._plane.onBeforeRender = this._on_object_before_render_bound;
}
}
private _emptyRenderHook = () => {};
private _removeRenderHook() {
if (!this._plane) {
return;
}
if (this._plane.onBeforeRender != this._emptyRenderHook) {
this._plane.onBeforeRender = this._emptyRenderHook;
}
}
private _on_object_before_render_bound: RenderHook = this._update.bind(this);
// private _previous_on_before_render: RenderHook | undefined;
private _update(
renderer?: WebGLRenderer,
scene?: Scene,
camera?: Camera,
geometry?: BufferGeometry | Geometry,
material?: Material,
group?: Group | null
) {
if (!renderer || !scene) {
console.log('no renderer or scene');
return;
}
this._renderShadow(renderer, scene);
}
private _updateManual() {
const renderer = Poly.renderersController.firstRenderer();
if (!renderer) {
console.log('no renderer found');
return;
}
const scene = this.scene().threejsScene();
this._renderShadow(renderer, scene);
}
//
//
// ACTIVE
//
//
static PARAM_CALLBACK_update_updateMode(node: ContactShadowObjNode) {
node._updateRenderHook();
}
//
//
// UPDATE
//
//
static PARAM_CALLBACK_updateManual(node: ContactShadowObjNode) {
node._updateManual();
}
//
//
// UPDATE OBJECTS LIST
//
//
static PARAM_CALLBACK_updateObjectsList(node: ContactShadowObjNode) {
node._updateObjectsList();
}
private _updateObjectsList() {
if (this.pv.include != '') {
this._includedObjects = this.scene().objectsByMask(this.pv.include);
} else {
this._includedObjects = [];
}
// we also need to add the parents of this._includedObjects,
// as otherwise those will be hidden, indirectly hidding this._includedObjects
const parentsMap: Map<string, Object3D> = new Map();
for (let object of this._includedObjects) {
object.traverseAncestors((parent) => {
parentsMap.set(parent.uuid, parent);
});
}
this._includedAncestors = [];
parentsMap.forEach((parent, uuid) => {
this._includedAncestors.push(parent);
});
// add excluded
if (this.pv.exclude != '') {
this._excludedObjects = this.scene().objectsByMask(this.pv.exclude);
} else {
this._excludedObjects = [];
}
}
static PARAM_CALLBACK_printResolveObjectsList(node: ContactShadowObjNode) {
node._printResolveObjectsList();
}
private _printResolveObjectsList() {
console.log('included objects:');
console.log(this._includedObjects);
console.log('included parents:');
console.log(this._includedAncestors);
console.log('excluded objects:');
console.log(this._excludedObjects);
}
private _initialVisibilityState: WeakMap<Object3D, boolean> = new WeakMap();
private _initVisibility(scene: Scene) {
// if at least one object is included,
// this means those which are not are to be hidden.
// Therefore, we then have to traverse the whole scene.
// If none is specified in included, we do not need to traverse
if (this._includedObjects.length > 0) {
scene.traverse((object) => {
this._initialVisibilityState.set(object, object.visible);
object.visible = false;
});
} else {
this._storeObjectsVisibility(this._includedObjects);
this._storeObjectsVisibility(this._includedAncestors);
this._storeObjectsVisibility(this._excludedObjects);
}
this._setObjectsVisibility(this._includedObjects, true);
this._setObjectsVisibility(this._includedAncestors, true);
this._setObjectsVisibility(this._excludedObjects, false);
}
private _storeObjectsVisibility(objects: Object3D[]) {
for (let object of objects) {
this._initialVisibilityState.set(object, object.visible);
}
}
private _setObjectsVisibility(objects: Object3D[], visible: boolean) {
for (let object of objects) {
object.visible = visible;
}
}
private _restoreVisibility(scene: Scene) {
if (this._includedObjects.length > 0) {
scene.traverse((object) => {
const state = this._initialVisibilityState.get(object);
if (state) object.visible = state;
});
} else {
this._restoreObjectsVisibility(this._includedObjects);
this._restoreObjectsVisibility(this._includedAncestors);
this._restoreObjectsVisibility(this._excludedObjects);
}
}
private _restoreObjectsVisibility(objects: Object3D[]) {
for (let object of objects) {
const state = this._initialVisibilityState.get(object);
if (state) {
object.visible = state;
}
}
}
} | the_stack |
import { generateSubstepItem } from '../generateSubstepItem'
import {
makeInitialRobotState,
makeContext,
InvariantContext,
RobotState,
EngageMagnetArgs,
DisengageMagnetArgs,
} from '@opentrons/step-generation'
import { THERMOCYCLER_STATE } from '../../constants'
import { LabwareNamesByModuleId, StepArgsAndErrors } from '../types'
import {
SetTemperatureArgs,
DeactivateTemperatureArgs,
} from '../../../../step-generation/lib/types.d'
import { ThermocyclerStateStepArgs } from '../../../../step-generation/src/types'
describe('generateSubstepItem', () => {
const stepId = 'step123'
const tiprackId = 'tiprack1Id'
const pipetteId = 'p300SingleId'
const sourcePlateId = 'sourcePlateId'
const destPlateId = 'destPlateId'
let invariantContext: InvariantContext,
labwareNamesByModuleId: LabwareNamesByModuleId,
robotState: RobotState | null
beforeEach(() => {
invariantContext = makeContext()
labwareNamesByModuleId = {
magnet123: {
nickname: 'mag nickname',
},
tempId: {
nickname: 'temp nickname',
},
thermocyclerModuleId: {
nickname: 'tc nickname',
},
}
robotState = makeInitialRobotState({
invariantContext,
pipetteLocations: { p300SingleId: { mount: 'left' } },
labwareLocations: {
tiprack1Id: { slot: '2' },
sourcePlateId: { slot: '4' },
destPlateId: { slot: '5' },
},
// @ts-expect-error(sa, 2021-6-15): this looks to be copied, because tiprackSetting is nowhere to be found in makeInitialRobotState
tiprackSetting: { tiprack1Id: false },
})
})
it('null is returned when no robotState', () => {
robotState = null
const stepArgsAndErrors = {
stepArgs: {
module: 'aaaa',
commandCreatorFnName: 'deactivateTemperature',
message: 'message',
},
errors: {},
}
const result = generateSubstepItem(
// @ts-expect-error(sa, 2021-6-15): errors should be a boolean, not {}
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toBeNull()
})
;[
{
testName: 'null is returned when no stepArgsAndErrors',
args: null,
},
{
testName: 'null is returned when no stepArgs',
args: {
stepArgs: null,
errors: { field: {} },
},
},
{
testName: 'null is returned when no errors',
args: {
stepArgs: {
module: 'aaaa',
commandCreatorFnName: 'deactivateTemperature',
message: 'message',
},
errors: { field: {} },
},
},
].forEach(({ testName, args }) => {
it(testName, () => {
const result = generateSubstepItem(
// @ts-expect-error(sa, 2021-6-15): errors should be a boolean, not {}
args,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toBeNull()
})
})
it('delay command returns pause substep data', () => {
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
// @ts-expect-error(sa, 2021-6-15): stepArgs missing name and description
stepArgs: {
commandCreatorFnName: 'delay',
message: 'test',
wait: true,
},
}
// @ts-expect-error(sa, 2021-6-15): missing parameters to make valid robot state
const robotState = makeInitialRobotState({ invariantContext })
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: 'pause',
pauseStepArgs: stepArgsAndErrors.stepArgs,
})
})
describe('like substeps', () => {
let sharedArgs: {
pipette: string
sourceLabware: string
destLabware: string
name: string
volume: number
preWetTip: boolean
touchTipAfterAspirate: boolean
touchTipAfterAspirateOffsetMmFromBottom: number
changeTip: string
aspirateFlowRateUlSec: number
aspirateOffsetFromBottomMm: number
touchTipAfterDispense: boolean
touchTipAfterDispenseOffsetMmFromBottom: number
dispenseFlowRateUlSec: number
dispenseOffsetFromBottomMm: number
}
beforeEach(() => {
sharedArgs = {
pipette: pipetteId,
sourceLabware: sourcePlateId,
destLabware: destPlateId,
name: 'testing',
volume: 50,
preWetTip: false,
touchTipAfterAspirate: false,
touchTipAfterAspirateOffsetMmFromBottom: 10,
changeTip: 'once',
aspirateFlowRateUlSec: 5,
aspirateOffsetFromBottomMm: 3,
touchTipAfterDispense: false,
touchTipAfterDispenseOffsetMmFromBottom: 10,
dispenseFlowRateUlSec: 5,
dispenseOffsetFromBottomMm: 10,
}
})
;[
{
testName: 'consolidate command returns substep data',
stepArgs: {
commandCreatorFnName: 'consolidate',
sourceWells: ['A1', 'A2'],
destWell: 'C1',
blowoutLocation: null,
blowoutFlowRateUlSec: 10,
blowoutOffsetFromTopMm: 5,
mixFirstAspirate: null,
mixInDestination: null,
},
expected: {
substepType: 'sourceDest',
multichannel: false,
commandCreatorFnName: 'consolidate',
parentStepId: stepId,
rows: [
{
activeTips: {
pipette: pipetteId,
labware: tiprackId,
well: 'A1',
},
source: { well: 'A1', preIngreds: {}, postIngreds: {} },
dest: undefined,
volume: 50,
},
{
volume: 50,
source: { well: 'A2', preIngreds: {}, postIngreds: {} },
activeTips: {
pipette: pipetteId,
labware: tiprackId,
well: 'A1',
},
dest: {
postIngreds: {
__air__: {
volume: 100,
},
},
preIngreds: {},
well: 'C1',
},
},
],
},
},
{
testName: 'distribute command returns substep data',
stepArgs: {
commandCreatorFnName: 'distribute',
sourceWell: 'A1',
destWells: ['A1', 'A2'],
disposalVolume: null,
disposalLabware: null,
disposalWell: null,
blowoutFlowRateUlSec: 10,
blowoutOffsetFromTopMm: 5,
mixBeforeAspirate: null,
},
expected: {
commandCreatorFnName: 'distribute',
multichannel: false,
parentStepId: stepId,
rows: [
{
activeTips: {
labware: tiprackId,
pipette: pipetteId,
well: 'A1',
},
dest: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {},
well: 'A1',
},
source: {
postIngreds: {},
preIngreds: {},
well: 'A1',
},
volume: 50,
},
{
activeTips: {
labware: tiprackId,
pipette: pipetteId,
well: 'A1',
},
dest: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {},
well: 'A2',
},
source: undefined,
volume: 50,
},
],
substepType: 'sourceDest',
},
},
{
testName: 'transfer command returns substep data',
stepArgs: {
commandCreatorFnName: 'transfer',
sourceWells: ['A1', 'A2'],
destWells: ['A1', 'A2'],
blowoutLocation: null,
blowoutFlowRateUlSec: 10,
blowoutOffsetFromTopMm: 5,
mixBeforeAspirate: null,
mixInDestination: null,
},
expected: {
substepType: 'sourceDest',
multichannel: false,
commandCreatorFnName: 'transfer',
parentStepId: stepId,
rows: [
{
activeTips: {
pipette: pipetteId,
labware: tiprackId,
well: 'A1',
},
source: { well: 'A1', preIngreds: {}, postIngreds: {} },
dest: {
well: 'A1',
preIngreds: {},
postIngreds: {
__air__: {
volume: 50,
},
},
},
volume: 50,
},
{
volume: 50,
source: { well: 'A2', preIngreds: {}, postIngreds: {} },
activeTips: {
pipette: pipetteId,
labware: tiprackId,
well: 'A1',
},
dest: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {},
well: 'A2',
},
},
],
},
},
].forEach(({ testName, stepArgs, expected }) => {
it(testName, () => {
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
// @ts-expect-error(sa, 2021-6-15): stepArgs missing name and description
stepArgs: { ...sharedArgs, ...stepArgs },
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual(expected)
})
})
})
it('mix command returns substep data', () => {
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): stepArgs missing description
stepArgs: {
name: 'testing',
commandCreatorFnName: 'mix',
labware: sourcePlateId,
pipette: pipetteId,
wells: ['A1', 'A2'],
volume: 50,
times: 2,
touchTip: false,
touchTipMmFromBottom: 5,
changeTip: 'always',
blowoutLocation: null,
blowoutFlowRateUlSec: 3,
blowoutOffsetFromTopMm: 3,
aspirateOffsetFromBottomMm: 4,
dispenseOffsetFromBottomMm: 10,
aspirateFlowRateUlSec: 5,
dispenseFlowRateUlSec: 5,
},
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
const expected = {
commandCreatorFnName: 'mix',
multichannel: false,
parentStepId: 'step123',
rows: [
{
activeTips: {
labware: 'tiprack1Id',
pipette: 'p300SingleId',
well: 'A1',
},
dest: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {},
well: 'A1',
},
source: {
postIngreds: {},
preIngreds: {},
well: 'A1',
},
volume: 50,
},
{
activeTips: {
labware: 'tiprack1Id',
pipette: 'p300SingleId',
well: 'A1',
},
dest: {
postIngreds: {
__air__: {
volume: 100,
},
},
preIngreds: {
__air__: {
volume: 50,
},
},
well: 'A1',
},
source: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {
__air__: {
volume: 50,
},
},
well: 'A1',
},
volume: 50,
},
{
activeTips: {
labware: 'tiprack1Id',
pipette: 'p300SingleId',
well: 'B1',
},
dest: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {},
well: 'A2',
},
source: {
postIngreds: {},
preIngreds: {},
well: 'A2',
},
volume: 50,
},
{
activeTips: {
labware: 'tiprack1Id',
pipette: 'p300SingleId',
well: 'B1',
},
dest: {
postIngreds: {
__air__: {
volume: 100,
},
},
preIngreds: {
__air__: {
volume: 50,
},
},
well: 'A2',
},
source: {
postIngreds: {
__air__: {
volume: 50,
},
},
preIngreds: {
__air__: {
volume: 50,
},
},
well: 'A2',
},
volume: 50,
},
],
substepType: 'sourceDest',
}
expect(result).toEqual(expected)
})
it('engageMagnet returns substep data with engage = true', () => {
const engageMagnetArgs: EngageMagnetArgs = {
module: 'magnet123',
commandCreatorFnName: 'engageMagnet',
// @ts-expect-error(sa, 2021-6-15): message should be string or undefined
message: null,
}
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
stepArgs: engageMagnetArgs,
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: 'magnet',
engage: true,
labwareNickname: 'mag nickname',
message: null,
})
})
it('disengageMagnet returns substep data with engage = false', () => {
const disengageMagnetArgs: DisengageMagnetArgs = {
module: 'magnet123',
commandCreatorFnName: 'disengageMagnet',
// @ts-expect-error(sa, 2021-6-15): message cannot be null
message: null,
}
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
stepArgs: disengageMagnetArgs,
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: 'magnet',
engage: false,
labwareNickname: 'mag nickname',
message: null,
})
})
it('setTemperature returns substep data with temperature', () => {
const setTempArgs: SetTemperatureArgs = {
module: 'tempId',
commandCreatorFnName: 'setTemperature',
targetTemperature: 45,
// @ts-expect-error(sa, 2021-6-15): message cannot be null
message: null,
}
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
stepArgs: setTempArgs,
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: 'temperature',
temperature: 45,
labwareNickname: 'temp nickname',
message: null,
})
})
it('setTemperature returns temperature when 0', () => {
const setTempArgs: SetTemperatureArgs = {
module: 'tempId',
commandCreatorFnName: 'setTemperature',
targetTemperature: 0,
// @ts-expect-error(sa, 2021-6-15): message cannot be null
message: null,
}
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
stepArgs: setTempArgs,
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: 'temperature',
temperature: 0,
labwareNickname: 'temp nickname',
message: null,
})
})
it('deactivateTemperature returns substep data with null temp', () => {
const deactivateTempArgs: DeactivateTemperatureArgs = {
module: 'tempId',
commandCreatorFnName: 'deactivateTemperature',
// @ts-expect-error(sa, 2021-6-15): message cannot be null
message: null,
}
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
stepArgs: deactivateTempArgs,
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: 'temperature',
temperature: null,
labwareNickname: 'temp nickname',
message: null,
})
})
it('thermocyclerState returns substep data', () => {
const ThermocyclerStateArgs: ThermocyclerStateStepArgs = {
module: 'thermocyclerModuleId',
commandCreatorFnName: THERMOCYCLER_STATE,
message: 'a message',
blockTargetTemp: 44,
lidTargetTemp: 66,
lidOpen: false,
}
const stepArgsAndErrors: StepArgsAndErrors = {
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
errors: {},
stepArgs: ThermocyclerStateArgs,
}
const result = generateSubstepItem(
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
labwareNamesByModuleId
)
expect(result).toEqual({
substepType: THERMOCYCLER_STATE,
labwareNickname: 'tc nickname',
blockTargetTemp: 44,
lidTargetTemp: 66,
lidOpen: false,
message: 'a message',
})
})
it('null is returned when no matching command', () => {
const stepArgsAndErrors = {
errors: {},
stepArgs: {
commandCreatorFnName: 'nonexistentCommand',
},
}
const result = generateSubstepItem(
// @ts-expect-error(sa, 2021-6-15): errors should be boolean typed
stepArgsAndErrors,
invariantContext,
robotState,
stepId,
{}
)
expect(result).toBeNull()
})
}) | the_stack |
import {
AfterViewInit,
ApplicationRef,
ChangeDetectorRef,
Component,
ComponentRef,
Directive, ElementRef,
EventEmitter,
HostListener,
Injector,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
SimpleChanges,
SkipSelf,
TemplateRef,
Type,
ViewChild,
ViewContainerRef
} from '@angular/core';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { WindowRegistry } from '../window/window-state';
import { WindowComponent } from '../window/window.component';
import { RenderComponentDirective } from '../core/render-component.directive';
import { IN_DIALOG } from '../app/token';
import { OverlayStack, OverlayStackItem, ReactiveChangeDetectionModule, unsubscribe } from '../app';
import { Subscription } from 'rxjs';
import { ButtonComponent } from '../button';
@Component({
template: `
<dui-window>
<dui-window-content class="{{class}}">
<ng-container *ngIf="component"
#renderComponentDirective
[renderComponent]="component" [renderComponentInputs]="componentInputs">
</ng-container>
<ng-container *ngIf="content" [ngTemplateOutlet]="content"></ng-container>
<ng-container *ngIf="container">
<ng-container [ngTemplateOutlet]="container"></ng-container>
</ng-container>
<ng-container *ngIf="!container">
<ng-content></ng-content>
</ng-container>
</dui-window-content>
<div class="dialog-actions" *ngIf="actions">
<ng-container [ngTemplateOutlet]="actions"></ng-container>
</div>
</dui-window>
`,
host: {
'[attr.tabindex]': '1'
},
styleUrls: ['./dialog-wrapper.component.scss']
})
export class DialogWrapperComponent {
@Input() component?: Type<any>;
@Input() componentInputs: { [name: string]: any } = {};
actions?: TemplateRef<any> | undefined;
container?: TemplateRef<any> | undefined;
content?: TemplateRef<any> | undefined;
class: string = '';
@ViewChild(RenderComponentDirective, { static: false }) renderComponentDirective?: RenderComponentDirective;
constructor(
protected cd: ChangeDetectorRef,
) {
}
public setActions(actions: TemplateRef<any> | undefined) {
this.actions = actions;
this.cd.detectChanges();
}
public setDialogContainer(container: TemplateRef<any> | undefined) {
this.container = container;
this.cd.detectChanges();
}
}
@Component({
selector: 'dui-dialog',
template: `
<ng-template #template>
<ng-content></ng-content>
</ng-template>`,
styles: [`:host {
display: none;
}`]
})
export class DialogComponent implements AfterViewInit, OnDestroy, OnChanges {
@Input() title: string = '';
@Input() visible: boolean = false;
@Output() visibleChange = new EventEmitter<boolean>();
@Input() class: string = '';
@Input() noPadding: boolean | '' = false;
@Input() minWidth?: number | string;
@Input() minHeight?: number | string;
@Input() width?: number | string;
@Input() height?: number | string;
@Input() maxWidth?: number | string;
@Input() maxHeight?: number | string;
@Input() center: boolean = false;
@Input() backDropCloses: boolean = false;
@Input() component?: Type<any>;
@Input() componentInputs: { [name: string]: any } = {};
@Output() closed = new EventEmitter<any>();
@Output() open = new EventEmitter<any>();
@ViewChild('template', { static: true }) template?: TemplateRef<any>;
actions?: TemplateRef<any> | undefined;
container?: TemplateRef<any> | undefined;
public overlayRef?: OverlayRef;
public wrapperComponentRef?: ComponentRef<DialogWrapperComponent>;
protected lastOverlayStackItem?: OverlayStackItem;
constructor(
protected applicationRef: ApplicationRef,
protected overlayStack: OverlayStack,
protected viewContainerRef: ViewContainerRef,
protected cd: ChangeDetectorRef,
protected overlay: Overlay,
protected injector: Injector,
protected registry: WindowRegistry,
@Optional() @SkipSelf() protected cdParent?: ChangeDetectorRef,
@Optional() protected window?: WindowComponent,
) {
}
public toPromise(): Promise<any> {
return new Promise((resolve) => {
this.closed.subscribe((v: any) => {
resolve(v);
});
});
}
public setDialogContainer(container: TemplateRef<any> | undefined) {
this.container = container;
if (this.wrapperComponentRef) {
this.wrapperComponentRef.instance.setDialogContainer(container);
}
}
public setActions(actions: TemplateRef<any> | undefined) {
this.actions = actions;
if (this.wrapperComponentRef) {
this.wrapperComponentRef.instance.setActions(actions);
}
}
ngOnChanges(changes: SimpleChanges): void {
if (this.visible) {
this.show();
} else {
this.close(undefined);
}
}
public show() {
if (this.overlayRef) {
return;
}
const window = this.window ? this.window.getClosestNonDialogWindow() : this.registry.getOuterActiveWindow();
const offsetTop = window && window.header ? window.header.getBottomPosition() : 0;
// const document = this.registry.getCurrentViewContainerRef().element.nativeElement.ownerDocument;
//this is necessary for multi-window environments, but doesn't work yet.
// const overlayContainer = new OverlayContainer(document);
//
// const overlay = new Overlay(
// this.injector.get(ScrollStrategyOptions),
// overlayContainer,
// this.injector.get(ComponentFactoryResolver),
// new OverlayPositionBuilder(this.injector.get(ViewportRuler), document, this.injector.get(Platform), overlayContainer),
// this.injector.get(OverlayKeyboardDispatcher),
// this.injector,
// this.injector.get(NgZone),
// document,
// this.injector.get(Directionality),
// );
const overlay = this.overlay;
let positionStrategy = overlay
.position()
.global().centerHorizontally().top(offsetTop + 'px');
if (this.center) {
positionStrategy = overlay
.position()
.global().centerHorizontally().centerVertically();
}
this.overlayRef = overlay.create({
width: this.width || undefined,
height: this.height || undefined,
minWidth: this.minWidth || undefined,
minHeight: this.minHeight || undefined,
maxWidth: this.maxWidth || '90%',
maxHeight: this.maxHeight || '90%',
hasBackdrop: true,
panelClass: [this.class, (this.center ? 'dialog-overlay' : 'dialog-overlay-with-animation'), this.noPadding !== false ? 'dialog-overlay-no-padding' : ''],
scrollStrategy: overlay.scrollStrategies.reposition(),
positionStrategy: positionStrategy,
});
if (this.backDropCloses) {
this.overlayRef!.backdropClick().subscribe(() => {
this.close(undefined);
});
}
const injector = Injector.create({
parent: this.injector,
providers: [
{ provide: DialogComponent, useValue: this },
{ provide: WindowComponent, useValue: window },
{ provide: IN_DIALOG, useValue: true },
],
});
this.open.emit();
const portal = new ComponentPortal(DialogWrapperComponent, this.viewContainerRef, injector);
this.wrapperComponentRef = this.overlayRef!.attach(portal);
this.wrapperComponentRef.instance.component = this.component!;
this.wrapperComponentRef.instance.componentInputs = this.componentInputs;
this.wrapperComponentRef.instance.content = this.template!;
this.wrapperComponentRef.instance.class = this.class!;
if (this.lastOverlayStackItem) this.lastOverlayStackItem.release();
this.lastOverlayStackItem = this.overlayStack.register(this.overlayRef.hostElement);
if (this.actions) {
this.wrapperComponentRef!.instance.setActions(this.actions);
}
if (this.container) {
this.wrapperComponentRef!.instance.setDialogContainer(this.container);
}
this.overlayRef!.updatePosition();
this.visible = true;
this.visibleChange.emit(true);
this.wrapperComponentRef!.location.nativeElement.focus();
this.wrapperComponentRef!.changeDetectorRef.detectChanges();
this.cd.detectChanges();
if (this.cdParent) this.cdParent.detectChanges();
}
protected beforeUnload() {
if (this.lastOverlayStackItem) this.lastOverlayStackItem.release();
if (this.overlayRef) {
this.overlayRef.dispose();
this.overlayRef = undefined;
}
}
ngAfterViewInit() {
}
public close(v?: any) {
this.beforeUnload();
this.visible = false;
this.visibleChange.emit(false);
this.closed.emit(v);
ReactiveChangeDetectionModule.tick();
}
ngOnDestroy(): void {
this.beforeUnload();
}
}
/**
* This directive is necessary if you want to load and render the dialog content
* only when opening the dialog. Without it, it is immediately rendered, which can cause
* performance and injection issues.
*/
@Directive({
'selector': '[dialogContainer]',
})
export class DialogDirective {
constructor(protected dialog: DialogComponent, public template: TemplateRef<any>) {
this.dialog.setDialogContainer(this.template);
}
}
@Component({
selector: 'dui-dialog-actions',
template: '<ng-template #template><ng-content></ng-content></ng-template>'
})
export class DialogActionsComponent implements AfterViewInit, OnDestroy {
@ViewChild('template', { static: true }) template!: TemplateRef<any>;
constructor(protected dialog: DialogComponent) {
}
ngAfterViewInit(): void {
this.dialog.setActions(this.template);
}
ngOnDestroy(): void {
if (this.dialog.actions === this.template) {
this.dialog.setActions(undefined);
}
}
}
@Component({
selector: 'dui-dialog-error',
template: '<ng-content></ng-content>',
styleUrls: ['./dialog-error.component.scss']
})
export class DialogErrorComponent {
}
@Directive({
selector: '[closeDialog]'
})
export class CloseDialogDirective {
@Input() closeDialog: any;
constructor(protected dialog: DialogComponent) {
}
@HostListener('click')
onClick() {
this.dialog.close(this.closeDialog);
}
}
/**
* A directive to open the given dialog on regular left click.
*/
@Directive({
'selector': '[openDialog]',
})
export class OpenDialogDirective implements AfterViewInit, OnChanges, OnDestroy {
@Input() openDialog?: DialogComponent;
@unsubscribe()
openSub?: Subscription;
@unsubscribe()
hiddenSub?: Subscription;
constructor(
protected elementRef: ElementRef,
@Optional() protected button?: ButtonComponent,
) {
}
ngOnDestroy() {
}
ngOnChanges() {
this.link();
}
ngAfterViewInit() {
this.link();
}
protected link() {
if (this.button && this.openDialog) {
this.openSub = this.openDialog.open.subscribe(() => {
if (this.button) this.button.active = true;
});
this.hiddenSub = this.openDialog.closed.subscribe(() => {
if (this.button) this.button.active = false;
});
}
}
@HostListener('click')
onClick() {
if (this.openDialog) this.openDialog.show();
}
} | the_stack |
import { TestBed } from '@angular/core/testing';
import { ObjectFormValidityChangeEvent } from 'app-events/app-events';
import { EventBusGroup, EventBusService } from 'app-events/event-bus.service';
import { importAllAngularServices } from 'tests/unit-test-utils.ajs';
describe('RuleEditorComponent', () => {
importAllAngularServices();
let ctrl = null;
let $scope = null;
let $rootScope = null;
let $timeout = null;
let StateInteractionIdService = null;
let ResponsesService = null;
let PopulateRuleContentIdsService = null;
beforeEach(angular.mock.module('oppia'));
const INTERACTION_SPECS = {
TextInput: {
rule_descriptions: {
StartsWith: 'starts with at least one of' +
' {{x|TranslatableSetOfNormalizedString}}',
Contains: 'contains at least one of' +
' {{x|TranslatableSetOfNormalizedString}}',
Equals: 'is equal to at least one of' +
' {{x|TranslatableSetOfNormalizedString}},' +
' without taking case into account',
FuzzyEquals: 'is equal to at least one of {{x|TranslatableSetOf' +
'NormalizedString}}, misspelled by at most one character'
}
},
AlgebraicExpressionInput: {
rule_descriptions: {
MatchesExactlyWith: 'matches exactly with {{x|AlgebraicExpression}}',
IsEquivalentTo: 'is equivalent to {{x|AlgebraicExpression}}',
ContainsSomeOf: 'contains at least one of the terms present in' +
' {{x|AlgebraicExpression}}',
OmitsSomeOf: 'omits at least one of the terms present in' +
' {{x|AlgebraicExpression}}',
MatchesWithGeneralForm: 'matches the form of {{x|Algebraic' +
'Expression}} with placeholders {{y|SetOfAlgebraicIdentifier}}'
}
},
DummyInteraction1: {
rule_descriptions: {
MatchesExactlyWith: 'matches exactly with' +
' {{x|SetOfTranslatableHtmlContentIds}}'
}
},
DummyInteraction2: {
rule_descriptions: {
MatchesExactlyWith: 'matches exactly with' +
' {{x|ListOfSetsOfTranslatableHtmlContentIds}}'
}
},
DummyInteraction3: {
rule_descriptions: {
MatchesExactlyWith: 'matches exactly with' +
' {{x|TranslatableHtmlContentId}}'
}
},
DummyInteraction4: {
rule_descriptions: {
MatchesExactlyWith: 'matches exactly with {{x|DragAndDropPositiveInt}}'
}
}
};
beforeEach(angular.mock.inject(($injector, $componentController) => {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
$timeout = $injector.get('$timeout');
StateInteractionIdService = $injector
.get('StateInteractionIdService');
ResponsesService = $injector.get('ResponsesService');
PopulateRuleContentIdsService = $injector
.get('PopulateRuleContentIdsService');
ctrl = $componentController('ruleEditor', {
$scope: $scope,
INTERACTION_SPECS: INTERACTION_SPECS
}, {
isEditingRuleInline: () => {
return true;
},
onCancelRuleEdit: () => {},
onSaveRule: () => {}
});
}));
afterEach(() => {
ctrl.$onDestroy();
});
it('should set component properties on initialization', () => {
ctrl.rule = {
type: null
};
StateInteractionIdService.savedMemento = 'TextInput';
expect(ctrl.currentInteractionId).toBe(undefined);
expect(ctrl.editRuleForm).toEqual(undefined);
ctrl.$onInit();
$scope.$apply();
expect(ctrl.currentInteractionId).toBe('TextInput');
expect(ctrl.editRuleForm).toEqual({});
});
it('should set change validity on form valid' +
' change event', () => {
const eventBusGroup = new EventBusGroup(
TestBed.inject(EventBusService));
ctrl.rule = {
type: null
};
expect(ctrl.isInvalid).toBe(undefined);
ctrl.$onInit();
$scope.$apply();
expect(ctrl.isInvalid).toBe(false);
ctrl.modalId = Symbol();
eventBusGroup.emit(new ObjectFormValidityChangeEvent({
value: true, modalId: ctrl.modalId}));
expect(ctrl.isInvalid).toBe(true);
});
it('should change rule type when user selects' +
' new rule type and answer choice is present', () => {
spyOn(ResponsesService, 'getAnswerChoices').and.returnValue(
[
{
val: 'c',
label: '',
},
{
val: 'b',
label: '',
},
{
val: 'a',
label: '',
},
]
);
ctrl.rule = {
type: 'Equals',
inputTypes: {x: 'TranslatableSetOfNormalizedString'},
inputs: {x: {
contentId: null,
normalizedStrSet: []
}}
};
ctrl.currentInteractionId = 'TextInput';
ctrl.onSelectNewRuleType('StartsWith');
$timeout.flush(10);
expect(ctrl.rule).toEqual({
type: 'StartsWith',
inputTypes: {
x: 'TranslatableSetOfNormalizedString'
},
inputs: {
x: {contentId: null, normalizedStrSet: []}
}
});
});
it('should change rule type when user selects' +
' new rule type and answer choice is not present', () => {
spyOn(ResponsesService, 'getAnswerChoices')
.and.returnValue(undefined);
ctrl.rule = {
type: 'Equals',
inputTypes: {x: 'TranslatableSetOfNormalizedString'},
inputs: {x: {
contentId: null,
normalizedStrSet: []
}}
};
ctrl.currentInteractionId = 'TextInput';
ctrl.onSelectNewRuleType('StartsWith');
$timeout.flush(10);
expect(ctrl.rule).toEqual({
type: 'StartsWith',
inputTypes: {
x: 'TranslatableSetOfNormalizedString'
},
inputs: {
x: {contentId: null, normalizedStrSet: []}
}
});
});
it('should change rule type when user selects' +
' new rule type and answer choice is not present', () => {
spyOn(ResponsesService, 'getAnswerChoices')
.and.returnValue(undefined);
ctrl.rule = {
type: 'MatchesExactlyWith',
inputTypes: {x: 'AlgebraicExpression'},
inputs: {x: {
contentId: null,
normalizedStrSet: []
}}
};
ctrl.currentInteractionId = 'AlgebraicExpressionInput';
ctrl.onSelectNewRuleType('MatchesWithGeneralForm');
$timeout.flush(10);
expect(ctrl.rule).toEqual({
type: 'MatchesWithGeneralForm',
inputTypes: {
x: 'AlgebraicExpression',
y: 'SetOfAlgebraicIdentifier'
},
inputs: {
x: {contentId: null, normalizedStrSet: []},
y: []
}
});
});
it('should cancel edit when user clicks cancel button', () => {
spyOn(ctrl, 'onCancelRuleEdit');
ctrl.cancelThisEdit();
expect(ctrl.onCancelRuleEdit).toHaveBeenCalled();
});
it('should save rule when user clicks save button', () => {
spyOn(ctrl, 'onSaveRule');
spyOn(PopulateRuleContentIdsService, 'populateNullRuleContentIds');
ctrl.saveThisRule();
expect(ctrl.onSaveRule).toHaveBeenCalled();
expect(PopulateRuleContentIdsService.populateNullRuleContentIds)
.toHaveBeenCalled();
});
it('should set ruleDescriptionFragments for' +
' SetOfTranslatableHtmlContentIds', () => {
spyOn(ResponsesService, 'getAnswerChoices').and.returnValue(
[
{
val: 'c',
label: '',
}
]
);
ctrl.rule = {
type: 'MatchesExactlyWith'
};
ctrl.currentInteractionId = 'DummyInteraction1';
ctrl.onSelectNewRuleType('MatchesExactlyWith');
$timeout.flush();
expect(ctrl.ruleDescriptionFragments).toEqual([{
text: '',
type: 'noneditable'
}, {
type: 'checkboxes',
varName: 'x'
}, {
text: '',
type: 'noneditable'
}]);
});
it('should set ruleDescriptionFragments for' +
' ListOfSetsOfTranslatableHtmlContentIds', () => {
spyOn(ResponsesService, 'getAnswerChoices').and.returnValue(
[
{
val: 'c',
label: '',
}
]
);
ctrl.rule = {
type: 'MatchesExactlyWith'
};
ctrl.currentInteractionId = 'DummyInteraction2';
ctrl.onSelectNewRuleType('MatchesExactlyWith');
$timeout.flush();
expect(ctrl.ruleDescriptionFragments).toEqual([{
text: '',
type: 'noneditable'
}, {
type: 'dropdown',
varName: 'x'
}, {
text: '',
type: 'noneditable'
}]);
});
it('should set ruleDescriptionFragments for' +
' TranslatableHtmlContentId', () => {
spyOn(ResponsesService, 'getAnswerChoices').and.returnValue(
[
{
val: 'c',
label: '',
}
]
);
ctrl.rule = {
type: 'MatchesExactlyWith'
};
ctrl.currentInteractionId = 'DummyInteraction3';
ctrl.onSelectNewRuleType('MatchesExactlyWith');
$timeout.flush();
expect(ctrl.ruleDescriptionFragments).toEqual([{
text: '',
type: 'noneditable'
}, {
type: 'dragAndDropHtmlStringSelect',
varName: 'x'
}, {
text: '',
type: 'noneditable'
}]);
});
it('should set ruleDescriptionFragments for' +
' DragAndDropPositiveInt', () => {
spyOn(ResponsesService, 'getAnswerChoices').and.returnValue(
[
{
val: 'c',
label: '',
}
]
);
ctrl.rule = {
type: 'MatchesExactlyWith'
};
ctrl.currentInteractionId = 'DummyInteraction4';
ctrl.onSelectNewRuleType('MatchesExactlyWith');
$timeout.flush();
expect(ctrl.ruleDescriptionFragments).toEqual([{
text: '',
type: 'noneditable'
}, {
type: 'dragAndDropPositiveIntSelect',
varName: 'x'
}, {
text: '',
type: 'noneditable'
}]);
});
it('should set ruleDescriptionFragments as noneditable when answer' +
' choices are empty', () => {
spyOn(ResponsesService, 'getAnswerChoices').and.returnValue([]);
ctrl.rule = {
type: 'MatchesExactlyWith'
};
ctrl.currentInteractionId = 'DummyInteraction4';
ctrl.onSelectNewRuleType('MatchesExactlyWith');
$timeout.flush();
expect(ctrl.ruleDescriptionFragments).toEqual([{
text: '',
type: 'noneditable'
}, {
text: ' [Error: No choices available] ',
type: 'noneditable'
}, {
text: '',
type: 'noneditable'
}]);
});
}); | the_stack |
import { Container } from './di.container';
import { IDiEntry, IServiceIdentifier } from './di.shared';
import { ValidatorUtils } from '../utils/validator.utils';
import { ClassParameter } from '../utils/typescript.utils';
import { ArrayUtils } from '../utils/array.utils';
export class DiService {
public static readonly variationStart = '<[';
public static readonly variationEnd = ']>';
// -------------------------------------------------------------------------
// Class vars
// -------------------------------------------------------------------------
private static readonly tmpCtx = 'tmpCtx';
private static contexts: Record<string, IDiEntry<any>[]> = {}; // First level = Context, second level = ServiceId
private static variationsMap: Record<string, any[]> = {};
// -------------------------------------------------------------------------
// Public methods
// -------------------------------------------------------------------------
public static genServiceId(service: IServiceIdentifier, variation?: Record<string, any>) {
let result = '';
if (typeof service === 'string') {
result = service;
} else if (service instanceof Function) {
result = service.name;
}
if (variation) {
if (result.indexOf(this.variationStart) < 0 || result.indexOf(this.variationEnd) < 0) {
let serviceVariations = this.variationsMap[result];
if (!serviceVariations) {
serviceVariations = [];
this.variationsMap[result] = serviceVariations;
}
let currVariationIndex = serviceVariations.findIndex(sv => ValidatorUtils.deepEqual(sv, variation));
if (currVariationIndex < 0) {
currVariationIndex = serviceVariations.length;
serviceVariations.push(variation);
}
result = `${result}${this.variationStart}${currVariationIndex}${this.variationEnd}`;
}
}
return result;
}
/**
* Adds the given entry into the provided context.
* If no context is provided, then the global context will be used.
* @param entry
* @param ctx
*/
public static addEntry(entry: IDiEntry, ctx?: string) {
const currctx = ctx || Container.globalCtx;
const entries = this.getCtx(currctx);
entries.push(entry);
this.contexts[currctx] = entries;
}
/**
* Creates a IDiEntry with the minium required fields
* @param serviceId
* @param clazz
*/
public static createBasicEntry(serviceId: string, clazz?: ClassParameter<any>): IDiEntry {
return <IDiEntry>{
serviceId,
serviceClass: clazz,
isReady: false,
depsClosed: false,
isOnlyTemplate: false
};
}
/**
* Creates or updates the given entry into the provided context.
* If no context is provided, then the global context will be used.
* @param entry
* @param ctx
*/
public static updateEntry(entry: IDiEntry, ctx?: string) {
const currctx = ctx || Container.globalCtx;
const index = this.getIndexOf(entry.serviceId, currctx);
if (index >= 0) {
const entries = this.getCtx(currctx);
entries[index] = entry;
this.contexts[currctx] = entries;
} else {
this.addEntry(entry, currctx);
}
}
/**
* Checks if exists an IDiEntry with the given serviceId in the provided context.
* If no context is provided, then the global context will be used.
* @param serviceId
* @param ctx
*/
public static exists(serviceId: string, ctx?: string): boolean {
return this.getEntry(serviceId, ctx) ? true : false;
}
/**
* Tries to retrieve an IDiEntry with the given serviceId in the provided context.
* If no entry is found, it will return undefined.
* If no context is provided, then the global context will be used.
* @param serviceId
* @param ctx
*/
public static getEntry(serviceId: string, ctx?: string): IDiEntry | undefined {
return this.getCtx(ctx || Container.globalCtx).find(entry => entry.serviceId === serviceId);
}
/**
* Same than `getEntry()` but only returns the entry if it's a template.
* It also ignores any variation in the service id (ex: <[0]>)
* @param serviceId
* @param ctx
*/
public static getTemplateEntry(serviceId: string, ctx?: string): IDiEntry | undefined {
serviceId = serviceId.indexOf(this.variationStart) > 0 ?
serviceId.substring(0, serviceId.indexOf(this.variationStart)) : serviceId;
return this.getCtx(ctx || Container.globalCtx).find(entry => entry.serviceId === serviceId && entry.isOnlyTemplate);
}
/**
* Gets or creates the entry with the given parameters.
* If no context is provided, then the global context will be used.
* @param serviceId
* @param clazz
* @param ctx
*/
public static getEnrySafely(serviceId: string, clazz?: ClassParameter<any>, ctx?: string): IDiEntry {
const entry = this.getEntry(serviceId, ctx);
if (entry) {
if (clazz) { entry.serviceClass = clazz; }
return entry;
} else {
return this.createBasicEntry(serviceId, clazz);
}
}
/**
* Checks the property 'isReady' in the IDiEntry from the provided context.
* If no entry is found, it returns false.
* If no context is provided, then the global context will be used.
* @param serviceId
* @param ctx
*/
public static depIsReady(serviceId: string, ctx?: string): boolean {
const entry = this.getEntry(serviceId, ctx);
return entry ? entry.isReady : false;
}
/**
* Gets or creates the entry with the given serviceId in a temporal context.
* If the class is provided it will try to set it in the result object.
* @param serviceId
* @param clazz
*/
public static getTmpEnrySafely(serviceId: string, clazz?: ClassParameter<any>): IDiEntry {
const entry = this.getEntry(serviceId, this.tmpCtx);
if (entry) {
if (clazz) { entry.serviceClass = clazz; }
return entry;
} else {
return this.createBasicEntry(serviceId, clazz);
}
}
/**
* Updates or creates the entry with the given serviceId in a temporal context.
* If the class is provided it will try to set it in the result object.
* @param serviceId
* @param clazz
*/
public static updateTmpEnry(entry: IDiEntry) {
this.updateEntry(entry, this.tmpCtx);
}
/**
* Removes the entry from the temporal context. Returns true
* if the entry was found.
* @param serviceId
* @param clazz
*/
public static discardTmpEntry(serviceId: string): boolean {
let result = false;
const indx = this.getIndexOf(serviceId, this.tmpCtx);
if (indx >= 0) {
const newCtx = this.getCtx(this.tmpCtx);
newCtx.splice(indx, 1);
this.updateCtx(this.tmpCtx, newCtx);
result = true;
}
return result;
}
/**
* Finds all the IDiEntry that have a depLeft with the given serviceId and
* context. The result object is
* @param serviceId
* @param ctx
*/
public static getAllRelatedDeps(serviceId: string, ctx?: string): Record<string, Record<string, any>> {
const result: Record<string, Record<string, any>> = {};
ctx = ctx || Container.globalCtx;
Object.keys(this.contexts).forEach(matCtx => {
const foundDeps = this.getCtx(matCtx).filter(entry => {
if (entry.depsLeft) {
return entry.depsLeft.find(
depLeft => depLeft.targetServiceId === serviceId &&
(depLeft.targetCtx || matCtx) === ctx
) ? true : false;
} else {
return false;
}
});
if (foundDeps && foundDeps.length > 0) {
result[matCtx] = foundDeps;
}
});
return result;
}
/**
* Overrides the metada field for the given service with the provided metadata
* @param serviceId
* @param metadata
* @param ctx
*/
public static updateMetadata(serviceId: IServiceIdentifier, metadata: any, merge?: boolean, ctx?: string) {
const entry = this.getEnrySafely(this.genServiceId(serviceId), undefined, ctx);
if (merge) {
entry.metadata = { ...(entry.metadata || {}), ...metadata };
} else {
entry.metadata = metadata;
}
this.updateEntry(entry, ctx);
}
/**
* Tries to return the metadata field of the given service, it will return
* undefined if the service doesn't exists or the field has not ben set
* @param serviceId
* @param ctx
*/
public static getMetadata(serviceId: IServiceIdentifier, ctx?: string): any | undefined {
const entry = this.getEntry(this.genServiceId(serviceId), ctx);
if (entry) {
return entry.metadata;
} else {
return undefined;
}
}
/**
* Overrides the metada field for the given service with the provided metadata
* @param serviceId
* @param metadata
* @param ctx
*/
public static updateTmpMetadata(serviceId: IServiceIdentifier, metadata: any, merge?: boolean) {
this.updateMetadata(serviceId, metadata, merge, this.tmpCtx);
}
/**
* Tries to return the metadata field of the given service, it will return
* undefined if the service doesn't exists or the field has not ben set
* @param serviceId
* @param ctx
*/
public static getTmpMetadata(serviceId: IServiceIdentifier): any | undefined {
return this.getMetadata(serviceId, this.tmpCtx);
}
/**
* Returns a list of all the services set as ready
*/
public static getAllReadyEntries() {
return this.getAllEntries().filter(entry => entry.isReady);
}
/**
* Returns a list of all the services set as ready
*/
public static getAllEntries() {
return ArrayUtils.flat(
Object.keys(this.contexts).map(ctx => this.contexts[ctx])
);
}
// -------------------------------------------------------------------------
// Private methods
// -------------------------------------------------------------------------
private static getCtx(ctx: string) {
let result = this.contexts[ctx];
if (!result) { result = []; }
return <IDiEntry[]>result;
}
private static updateCtx(ctx: string, entries: IDiEntry[]) {
this.contexts[ctx] = entries;
}
/**
* Tries to find the index an IDiEntry with the given serviceId in the provided context.
* If no entry is found, it will return -1.
* If no context is provided, then the global context will be used.
* @param serviceId
* @param ctx
*/
private static getIndexOf(serviceId: string, ctx?: string): number {
return this.getCtx(ctx || Container.globalCtx).findIndex(el => el.serviceId === serviceId);
}
} | the_stack |
import { View } from '..';
// Requires
import { ViewHelper } from './view-helper-common';
import { iOSNativeHelper, layout } from '../../../../utils';
import { Trace } from '../../../../trace';
export * from './view-helper-common';
const majorVersion = iOSNativeHelper.MajorVersion;
@NativeClass
class UILayoutViewController extends UIViewController {
public owner: WeakRef<View>;
public static initWithOwner(owner: WeakRef<View>): UILayoutViewController {
const controller = <UILayoutViewController>UILayoutViewController.new();
controller.owner = owner;
return controller;
}
public viewDidLoad(): void {
super.viewDidLoad();
// Unify translucent and opaque bars layout
// this.edgesForExtendedLayout = UIRectEdgeBottom;
this.extendedLayoutIncludesOpaqueBars = true;
}
public viewWillLayoutSubviews(): void {
super.viewWillLayoutSubviews();
const owner = this.owner.get();
if (owner) {
IOSHelper.updateConstraints(this, owner);
}
}
public viewDidLayoutSubviews(): void {
super.viewDidLayoutSubviews();
const owner = this.owner.get();
if (owner) {
if (majorVersion >= 11) {
// Handle nested UILayoutViewController safe area application.
// Currently, UILayoutViewController can be nested only in a TabView.
// The TabView itself is handled by the OS, so we check the TabView's parent (usually a Page, but can be a Layout).
const tabViewItem = owner.parent;
const tabView = tabViewItem && tabViewItem.parent;
let parent = tabView && tabView.parent;
// Handle Angular scenario where TabView is in a ProxyViewContainer
// It is possible to wrap components in ProxyViewContainers indefinitely
// Not using instanceof ProxyViewContainer to avoid circular dependency
// TODO: Try moving UILayoutViewController out of view module
while (parent && !parent.nativeViewProtected) {
parent = parent.parent;
}
if (parent) {
const parentPageInsetsTop = parent.nativeViewProtected.safeAreaInsets.top;
const currentInsetsTop = this.view.safeAreaInsets.top;
const additionalInsetsTop = Math.max(parentPageInsetsTop - currentInsetsTop, 0);
const parentPageInsetsBottom = parent.nativeViewProtected.safeAreaInsets.bottom;
const currentInsetsBottom = this.view.safeAreaInsets.bottom;
const additionalInsetsBottom = Math.max(parentPageInsetsBottom - currentInsetsBottom, 0);
if (additionalInsetsTop > 0 || additionalInsetsBottom > 0) {
const additionalInsets = new UIEdgeInsets({
top: additionalInsetsTop,
left: 0,
bottom: additionalInsetsBottom,
right: 0,
});
this.additionalSafeAreaInsets = additionalInsets;
}
}
}
IOSHelper.layoutView(this, owner);
}
}
public viewWillAppear(animated: boolean): void {
super.viewWillAppear(animated);
const owner = this.owner.get();
if (!owner) {
return;
}
IOSHelper.updateAutoAdjustScrollInsets(this, owner);
if (!owner.parent) {
owner.callLoaded();
}
}
public viewDidDisappear(animated: boolean): void {
super.viewDidDisappear(animated);
const owner = this.owner.get();
if (owner && !owner.parent) {
owner.callUnloaded();
}
}
// Mind implementation for other controllers
public traitCollectionDidChange(previousTraitCollection: UITraitCollection): void {
super.traitCollectionDidChange(previousTraitCollection);
if (majorVersion >= 13) {
const owner = this.owner.get();
if (owner && this.traitCollection.hasDifferentColorAppearanceComparedToTraitCollection && this.traitCollection.hasDifferentColorAppearanceComparedToTraitCollection(previousTraitCollection)) {
owner.notify({
eventName: IOSHelper.traitCollectionColorAppearanceChangedEvent,
object: owner,
});
}
}
}
}
@NativeClass
class UIAdaptivePresentationControllerDelegateImp extends NSObject implements UIAdaptivePresentationControllerDelegate {
public static ObjCProtocols = [UIAdaptivePresentationControllerDelegate];
private owner: WeakRef<View>;
private closedCallback: Function;
public static initWithOwnerAndCallback(owner: WeakRef<View>, whenClosedCallback: Function): UIAdaptivePresentationControllerDelegateImp {
const instance = <UIAdaptivePresentationControllerDelegateImp>super.new();
instance.owner = owner;
instance.closedCallback = whenClosedCallback;
return instance;
}
public presentationControllerDidDismiss(presentationController: UIPresentationController) {
const owner = this.owner.get();
if (owner && typeof this.closedCallback === 'function') {
this.closedCallback();
}
}
}
@NativeClass
class UIPopoverPresentationControllerDelegateImp extends NSObject implements UIPopoverPresentationControllerDelegate {
public static ObjCProtocols = [UIPopoverPresentationControllerDelegate];
private owner: WeakRef<View>;
private closedCallback: Function;
public static initWithOwnerAndCallback(owner: WeakRef<View>, whenClosedCallback: Function): UIPopoverPresentationControllerDelegateImp {
const instance = <UIPopoverPresentationControllerDelegateImp>super.new();
instance.owner = owner;
instance.closedCallback = whenClosedCallback;
return instance;
}
public popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
const owner = this.owner.get();
if (owner && typeof this.closedCallback === 'function') {
this.closedCallback();
}
}
}
export class IOSHelper {
static traitCollectionColorAppearanceChangedEvent = 'traitCollectionColorAppearanceChanged';
static UILayoutViewController = UILayoutViewController;
static UIAdaptivePresentationControllerDelegateImp = UIAdaptivePresentationControllerDelegateImp;
static UIPopoverPresentationControllerDelegateImp = UIPopoverPresentationControllerDelegateImp;
static getParentWithViewController(view: View): View {
while (view && !view.viewController) {
view = view.parent as View;
}
// Note: Might return undefined if no parent with viewController is found
return view;
}
static updateAutoAdjustScrollInsets(controller: UIViewController, owner: View): void {
if (majorVersion <= 10) {
owner._automaticallyAdjustsScrollViewInsets = false;
// This API is deprecated, but has no alternative for <= iOS 10
// Defaults to true and results to appliyng the insets twice together with our logic
// for iOS 11+ we use the contentInsetAdjustmentBehavior property in scrollview
// https://developer.apple.com/documentation/uikit/uiviewcontroller/1621372-automaticallyadjustsscrollviewin
controller.automaticallyAdjustsScrollViewInsets = false;
}
}
static updateConstraints(controller: UIViewController, owner: View): void {
if (majorVersion <= 10) {
const layoutGuide = IOSHelper.initLayoutGuide(controller);
(<any>controller.view).safeAreaLayoutGuide = layoutGuide;
}
}
static initLayoutGuide(controller: UIViewController) {
const rootView = controller.view;
const layoutGuide = UILayoutGuide.new();
rootView.addLayoutGuide(layoutGuide);
NSLayoutConstraint.activateConstraints(<any>[layoutGuide.topAnchor.constraintEqualToAnchor(controller.topLayoutGuide.bottomAnchor), layoutGuide.bottomAnchor.constraintEqualToAnchor(controller.bottomLayoutGuide.topAnchor), layoutGuide.leadingAnchor.constraintEqualToAnchor(rootView.leadingAnchor), layoutGuide.trailingAnchor.constraintEqualToAnchor(rootView.trailingAnchor)]);
return layoutGuide;
}
static layoutView(controller: UIViewController, owner: View): void {
let layoutGuide = controller.view.safeAreaLayoutGuide;
if (!layoutGuide) {
Trace.write(`safeAreaLayoutGuide during layout of ${owner}. Creating fallback constraints, but layout might be wrong.`, Trace.categories.Layout, Trace.messageType.error);
layoutGuide = IOSHelper.initLayoutGuide(controller);
}
const safeArea = layoutGuide.layoutFrame;
let position = IOSHelper.getPositionFromFrame(safeArea);
const safeAreaSize = safeArea.size;
const hasChildViewControllers = controller.childViewControllers.count > 0;
if (hasChildViewControllers) {
const fullscreen = controller.view.frame;
position = IOSHelper.getPositionFromFrame(fullscreen);
}
const safeAreaWidth = layout.round(layout.toDevicePixels(safeAreaSize.width));
const safeAreaHeight = layout.round(layout.toDevicePixels(safeAreaSize.height));
const widthSpec = layout.makeMeasureSpec(safeAreaWidth, layout.EXACTLY);
const heightSpec = layout.makeMeasureSpec(safeAreaHeight, layout.EXACTLY);
ViewHelper.measureChild(null, owner, widthSpec, heightSpec);
ViewHelper.layoutChild(null, owner, position.left, position.top, position.right, position.bottom);
if (owner.parent) {
owner.parent._layoutParent();
}
}
static getPositionFromFrame(frame: CGRect): { left; top; right; bottom } {
const left = layout.round(layout.toDevicePixels(frame.origin.x));
const top = layout.round(layout.toDevicePixels(frame.origin.y));
const right = layout.round(layout.toDevicePixels(frame.origin.x + frame.size.width));
const bottom = layout.round(layout.toDevicePixels(frame.origin.y + frame.size.height));
return { left, right, top, bottom };
}
static getFrameFromPosition(position: { left; top; right; bottom }, insets?: { left; top; right; bottom }): CGRect {
insets = insets || { left: 0, top: 0, right: 0, bottom: 0 };
const left = layout.toDeviceIndependentPixels(position.left + insets.left);
const top = layout.toDeviceIndependentPixels(position.top + insets.top);
const width = layout.toDeviceIndependentPixels(position.right - position.left - insets.left - insets.right);
const height = layout.toDeviceIndependentPixels(position.bottom - position.top - insets.top - insets.bottom);
return CGRectMake(left, top, width, height);
}
static shrinkToSafeArea(view: View, frame: CGRect): CGRect {
const insets = view.getSafeAreaInsets();
if (insets.left || insets.top) {
const position = IOSHelper.getPositionFromFrame(frame);
const adjustedFrame = IOSHelper.getFrameFromPosition(position, insets);
if (Trace.isEnabled()) {
Trace.write(this + ' :shrinkToSafeArea: ' + JSON.stringify(IOSHelper.getPositionFromFrame(adjustedFrame)), Trace.categories.Layout);
}
return adjustedFrame;
}
return null;
}
static expandBeyondSafeArea(view: View, frame: CGRect): CGRect {
const availableSpace = IOSHelper.getAvailableSpaceFromParent(view, frame);
const safeArea = availableSpace.safeArea;
const fullscreen = availableSpace.fullscreen;
const inWindow = availableSpace.inWindow;
const position = IOSHelper.getPositionFromFrame(frame);
const safeAreaPosition = IOSHelper.getPositionFromFrame(safeArea);
const fullscreenPosition = IOSHelper.getPositionFromFrame(fullscreen);
const inWindowPosition = IOSHelper.getPositionFromFrame(inWindow);
const adjustedPosition = position;
if (position.left && inWindowPosition.left <= safeAreaPosition.left) {
adjustedPosition.left = fullscreenPosition.left;
}
if (position.top && inWindowPosition.top <= safeAreaPosition.top) {
adjustedPosition.top = fullscreenPosition.top;
}
if (inWindowPosition.right < fullscreenPosition.right && inWindowPosition.right >= safeAreaPosition.right + fullscreenPosition.left) {
adjustedPosition.right += fullscreenPosition.right - inWindowPosition.right;
}
if (inWindowPosition.bottom < fullscreenPosition.bottom && inWindowPosition.bottom >= safeAreaPosition.bottom + fullscreenPosition.top) {
adjustedPosition.bottom += fullscreenPosition.bottom - inWindowPosition.bottom;
}
const adjustedFrame = CGRectMake(layout.toDeviceIndependentPixels(adjustedPosition.left), layout.toDeviceIndependentPixels(adjustedPosition.top), layout.toDeviceIndependentPixels(adjustedPosition.right - adjustedPosition.left), layout.toDeviceIndependentPixels(adjustedPosition.bottom - adjustedPosition.top));
if (Trace.isEnabled()) {
Trace.write(view + ' :expandBeyondSafeArea: ' + JSON.stringify(IOSHelper.getPositionFromFrame(adjustedFrame)), Trace.categories.Layout);
}
return adjustedFrame;
}
static getAvailableSpaceFromParent(view: View, frame: CGRect): { safeArea: CGRect; fullscreen: CGRect; inWindow: CGRect } {
if (!view) {
return;
}
let scrollView = null;
let viewControllerView = null;
if (view.viewController) {
viewControllerView = view.viewController.view;
} else {
let parent = view.parent as View;
while (parent && !parent.viewController && !(parent.nativeViewProtected instanceof UIScrollView)) {
parent = parent.parent as View;
}
if (parent.nativeViewProtected instanceof UIScrollView) {
scrollView = parent.nativeViewProtected;
} else if (parent.viewController) {
viewControllerView = parent.viewController.view;
}
}
let fullscreen = null;
let safeArea = null;
let controllerInWindow = { x: 0, y: 0 };
if (viewControllerView) {
safeArea = viewControllerView.safeAreaLayoutGuide.layoutFrame;
fullscreen = viewControllerView.frame;
controllerInWindow = viewControllerView.convertPointToView(viewControllerView.bounds.origin, null);
} else if (scrollView) {
const insets = scrollView.safeAreaInsets;
safeArea = CGRectMake(insets.left, insets.top, scrollView.contentSize.width - insets.left - insets.right, scrollView.contentSize.height - insets.top - insets.bottom);
fullscreen = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
}
// We take into account the controller position inside the window.
// for example with a bottomsheet the controller will be "offset"
const locationInWindow = view.getLocationInWindow();
let inWindowLeft = locationInWindow.x - controllerInWindow.x;
let inWindowTop = locationInWindow.y - controllerInWindow.y;
if (scrollView) {
inWindowLeft += scrollView.contentOffset.x;
inWindowTop += scrollView.contentOffset.y;
}
const inWindow = CGRectMake(inWindowLeft, inWindowTop, frame.size.width, frame.size.height);
return {
safeArea: safeArea,
fullscreen: fullscreen,
inWindow: inWindow,
};
}
} | the_stack |
import { assert } from '@canvas-ui/assert'
import { Point, Rect, Size } from '../math'
import { HitTestResult } from './hit-test'
import { PaintingContext } from './painting-context'
import { RenderBox } from './render-box'
import type { RenderContainer } from './render-container'
import { ParentData, RenderObject, Visitor } from './render-object'
import type { RenderPipeline } from './render-pipeline'
export class ViewParentData<ChildType extends RenderObject = RenderObject> extends ParentData {
prevSibling?: ChildType
nextSibling?: ChildType
override detach() {
assert(!this.prevSibling)
assert(!this.nextSibling)
super.detach()
}
}
export class RenderView<ChildType extends RenderObject<ViewParentData<ChildType>> = RenderObject>
extends RenderBox
implements RenderContainer<ChildType> {
protected override setupParentData(child: RenderObject) {
if (!(child.parentData instanceof ViewParentData)) {
child.parentData = new ViewParentData()
}
}
get childCount() {
return this._childCount
}
protected _childCount = 0
get firstChild() {
return this._firstChild
}
protected _firstChild?: ChildType
get lastChild() {
return this._lastChild
}
protected _lastChild?: ChildType
childBefore(child: ChildType) {
assert(child.parent === this)
return child.parentData?.prevSibling
}
childAfter(child: ChildType) {
assert(child.parent === this)
return child.parentData?.nextSibling
}
redepthChildren() {
let child = this._firstChild
while (child) {
this.redepthChild(child)
const childParentData = child.parentData!
child = childParentData.nextSibling
}
}
visitChildren(visitor: Visitor<ChildType>) {
let child = this._firstChild
while (child) {
visitor(child)
child = child.parentData!.nextSibling
}
}
override attach(owner: RenderPipeline) {
super.attach(owner)
let child = this._firstChild
while (child) {
child.attach(owner)
child = child.parentData!.nextSibling
}
}
override detach() {
super.detach()
let child = this._firstChild
while (child) {
child.detach()
child = child.parentData!.nextSibling
}
}
private debugUltimatePrevSiblingOf(child: ChildType, equals: ChildType | undefined) {
let childParentData = child.parentData!
while (childParentData.prevSibling) {
assert(childParentData.prevSibling !== child)
child = childParentData.prevSibling
childParentData = child.parentData!
}
return child === equals
}
private debugUltimateNextSiblingOf(child: ChildType, equals: ChildType | undefined) {
let childParentData = child.parentData!
while (childParentData.nextSibling) {
assert(childParentData.nextSibling !== child)
child = childParentData.nextSibling!
childParentData = child.parentData!
}
return child === equals
}
protected internalInsertAfter(child: ChildType, after?: ChildType) {
const childParentData = child.parentData!
assert(!childParentData.nextSibling)
assert(!childParentData.prevSibling)
this._childCount++
assert(this._childCount > 0)
if (!after) {
// 从头部插入 (_firstChild)
childParentData.nextSibling = this._firstChild
if (this._firstChild) {
const firstChildParentData = this._firstChild.parentData
assert(firstChildParentData)
firstChildParentData.prevSibling = child
}
this._firstChild = child
this._lastChild ??= child
if (this._yogaNode && child.yogaNode) {
assert(!child.yogaNode.getParent(), '子节点的 yogaNode 不能已有 parent')
this._yogaNode.insertChild(child.yogaNode, 0)
}
} else {
assert(this._firstChild)
assert(this._lastChild)
assert(this.debugUltimatePrevSiblingOf(after, this._firstChild))
assert(this.debugUltimateNextSiblingOf(after, this._lastChild))
const afterParentData = after.parentData!
if (!afterParentData.nextSibling) {
// 从尾部插入 (_lastChild)
assert(after === this._lastChild)
childParentData.prevSibling = after
afterParentData.nextSibling = child
this._lastChild = child
if (this._yogaNode && child.yogaNode) {
assert(!child.yogaNode.getParent(), '子节点的 yogaNode 不能已有 parent')
this._yogaNode.insertChild(child.yogaNode, this._childCount - 1)
}
} else {
// 从中间插入
childParentData.nextSibling = afterParentData.nextSibling
childParentData.prevSibling = after
const childPrevSiblingParentData = childParentData.prevSibling!.parentData!
const childNextSiblingParentData = childParentData.nextSibling!.parentData!
childPrevSiblingParentData.nextSibling = child
childNextSiblingParentData.prevSibling = child
assert(afterParentData.nextSibling === child)
if (this._yogaNode && child.yogaNode) {
assert(!child.yogaNode.getParent(), '子节点的 yogaNode 不能已有 parent')
const childIndex = this.findChildIndex(after)
assert(childIndex !== -1, `父节点中没有该子节点 ${child.id}`)
this._yogaNode.insertChild(child.yogaNode, childIndex + 1)
}
}
}
}
insertAfter(child: ChildType, after?: ChildType) {
assert(child as unknown !== this)
assert(after as unknown !== this)
assert(child !== after, '节点不能把自己添加到自己后面')
assert(child !== this._firstChild, '节点已经是 firstChild')
assert(child !== this._lastChild, '节点已经是 lastChild')
this.adoptChild(child)
this.internalInsertAfter(child, after)
}
insertBefore(child: ChildType, before?: ChildType) {
this.insertAfter(child, before?.parentData?.prevSibling)
}
appendChild(child: ChildType) {
this.insertAfter(child, this._lastChild)
}
protected internalRemoveChild(child: ChildType) {
const childParentData = child.parentData!
assert(this.debugUltimatePrevSiblingOf(child, this._firstChild))
assert(this.debugUltimateNextSiblingOf(child, this._lastChild))
assert(this._childCount >= 0)
if (!childParentData.prevSibling) {
// 子节点是 firstChild
assert(this._firstChild === child)
this._firstChild = childParentData.nextSibling
} else {
const childPrevSiblingParentData = childParentData.prevSibling.parentData!
childPrevSiblingParentData.nextSibling = childParentData.nextSibling
}
if (!childParentData.nextSibling) {
// 子节点是 lastChild
assert(this._lastChild === child)
this._lastChild = childParentData.prevSibling
} else {
const childNextSiblingParentData = childParentData.nextSibling.parentData!
childNextSiblingParentData.prevSibling = childParentData.prevSibling
}
childParentData.prevSibling = undefined
childParentData.nextSibling = undefined
this._childCount -= 1
if (this._yogaNode && child.yogaNode) {
assert(child.yogaNode.getParent(), '子节点的 yogaNode 必须有 parent') // todo 检查 parent 的引用是否是 this.yogaNode
this._yogaNode.removeChild(child.yogaNode)
}
}
removeChild(child: ChildType) {
this.internalRemoveChild(child)
this.dropChild(child)
}
removeAllChildren() {
let child = this._firstChild
while (child) {
const childParentData = child.parentData!
const next = childParentData.nextSibling
childParentData.prevSibling = undefined
childParentData.nextSibling = undefined
this.dropChild(child)
child = next
}
this._firstChild = undefined
this._lastChild = undefined
this._childCount = 0
}
get debugChildren() {
const children: ChildType[] = []
if (this._firstChild) {
let child = this._firstChild
// eslint-disable-next-line no-constant-condition
while (true) {
children.push(child)
if (child === this._lastChild) {
break
}
child = child.parentData!.nextSibling!
}
}
return children
}
override performLayout() {
this.updateOffsetAndSize()
let child = this._firstChild
while (child) {
child.layoutAsChild(false, false)
child = child.parentData!.nextSibling
}
}
paint(context: PaintingContext, offset: Point) {
const hasSize = !Size.isZero(this._size)
const { _boxDecorator } = this
if (hasSize) {
_boxDecorator?.paintBackground(context, offset, this._size)
}
const shouldClip = this._viewport.width > 0 && this._viewport.height > 0
if (shouldClip) {
context.pushClipRect(
this.needsCompositing,
offset,
Rect.fromLTWH(0, 0, this._viewport.width, this._viewport.height),
this._paint.bind(this),
)
} else {
this._paint(context, offset)
}
if (hasSize) {
_boxDecorator?.paintBorder(context, offset, this._size)
}
}
paintChildren(
context: PaintingContext,
offset: Point,
viewportOffset: Point,
viewport: Rect,
) {
let child = this._firstChild
const viewportNotEmpty = !Rect.isEmpty(viewport)
while (child) {
child.offstage = viewportNotEmpty && !Rect.overlaps(viewport, child.bounds)
if (!child.offstage) {
context.paintChild(child, Point.add3(child._offset, offset, viewportOffset))
}
child = child.parentData!.nextSibling
}
}
protected _paint(context: PaintingContext, offset: Point) {
this.paintChildren(context, offset, this.viewportOffset, this._viewport)
}
override hitTestChildren(result: HitTestResult, position: Point): boolean {
let child = this._lastChild
const { viewportOffset } = this
while (child) {
const isHit = !child.offstage && result.addWithPaintOffset(
Point.add(child._offset, viewportOffset),
position,
(result, transformed) => {
assert(Point.eq(transformed, Point.add(position, Point.invert(Point.add(child!._offset, viewportOffset)))))
return child!.hitTest(result, transformed)
}
)
if (isHit) {
return true
}
child = child.parentData?.prevSibling
}
return false
}
override hitTestSelf() {
// 如果 RenderView 设置了 Size,则还能命中自己
// 由于在 hitTest 中已经提前检查过 Size.contain 了,我们只需简单判断 Size 不为 zero 即可
return !this.hitTestSelfDisabled && !Size.eq(this._size, Size.zero)
}
protected override allocChildrenYogaNode() {
let child = this._firstChild
let index = 0
while (child) {
this.allocChildYogaNode(child)
if (this._yogaNode && child._yogaNode) {
this._yogaNode.insertChild(child._yogaNode, index)
}
const childParentData = child.parentData!
child = childParentData.nextSibling
index++
}
}
protected override deallocYogaNodeChildren() {
let child = this._firstChild
while (child) {
this.deallocYogaNode(child)
const childParentData = child.parentData!
child = childParentData.nextSibling
}
}
findChildIndex(child: ChildType) {
let ptr = this._firstChild
let i = 0
while (ptr) {
if (ptr === child) {
return i
}
const childParentData = ptr.parentData!
ptr = childParentData.nextSibling
i++
}
return -1
}
} | the_stack |
import Constants from "expo-constants";
import React from "react";
import {
Animated,
Easing,
StyleSheet,
Text,
TouchableWithoutFeedback,
View,
Platform,
} from "react-native";
import { connect } from "react-redux";
import { dispatch } from "../rematch/store";
import { useSafeArea } from "react-native-safe-area-context";
import AudioManager from "../AudioManager";
const Colors = {
darkerGreen: "#000A69",
darkGreen: "rgba(6, 20, 150, 1)",
darkGreenTransparent: "rgba(6, 20, 150, 0)",
green: "#4630eb",
lightGreen: "#5465FF",
white: "white",
transparent: "transparent",
};
const useNativeDriver = Platform.select({ web: false, default: true });
class AnimatedCircle extends React.Component {
static defaultProps = {
renderComponent: (props) => <Animated.View {...props} />,
toValue: 1,
delay: 0,
// speed: 12 * 0.2,
// bounciness: 8,
tension: 3.5 * 4,
friction: 4,
useNativeDriver,
};
animation = new Animated.Value(0);
reset = () => {
this.animation.setValue(0);
};
getAnimation = (props = {}) => {
const { reverse } = props;
let multiplier = reverse ? -1 : 1;
const {
delay,
toValue,
speed,
bounciness,
tension,
friction,
useNativeDriver,
containerAnimation,
} = this.props;
return Animated.spring(this.animation, {
delay,
toValue,
speed,
bounciness,
tension: tension,
friction: friction,
useNativeDriver: containerAnimation ? false : useNativeDriver,
...props,
});
};
getReverseAnimation = (props = {}) =>
this.getAnimation({ toValue: 0, reverse: true, velocity: 10, ...props });
animate = () => {
this.getAnimation().start();
};
get animatedStyle() {
const { innerColor, toColor, containerAnimation } = this.props;
let backgroundColor = innerColor;
if (containerAnimation) {
backgroundColor = containerAnimation.interpolate({
inputRange: [0, 1],
outputRange: [innerColor, toColor || innerColor],
});
}
return {
backgroundColor,
transform: [{ scale: this.animation }],
};
}
render() {
const {
innerColor,
outerColor,
style,
renderComponent,
...props
} = this.props;
const finalProps = {
style: [
{
borderWidth: 10,
borderRadius: circleSize / 2,
width: circleSize,
height: circleSize,
aspectRatio: 1,
position: "absolute",
// minWidth: circleSize,
// maxWidth: circleSize,
// minHeight: circleSize,
// maxHeight: circleSize,
borderColor: outerColor,
backgroundColor: innerColor,
},
this.animatedStyle,
style,
],
...props,
};
return renderComponent(finalProps);
}
}
class AnimatedBadge extends React.Component {
static defaultProps = {
renderComponent: (props) => <Animated.Image {...props} />,
resizeMode: "contain",
};
getReverseAnimation = (props) => this.circle.getReverseAnimation(props);
getAnimation = (toValue) => this.circle.getAnimation(toValue);
animate = () => this.circle.animate();
reset = () => this.circle.reset();
render() {
const { ...props } = this.props;
return <AnimatedCircle ref={(ref) => (this.circle = ref)} {...props} />;
}
}
const circleSize = 64;
const openWidth = circleSize * 5;
class BouncingCircle extends React.Component {
reset = () => {
this.circles.forEach((circle) => circle.reset());
};
getAnimation = () => {
const animations = this.circles.map((circle) => circle.getAnimation());
return Animated.stagger(80, animations);
};
getReverseAnimation = () => {
const animations = this.circles.map((circle, index) => {
let inverseIndex = this.circles.length - index;
let delay = 100 * index;
if (index === this.circles.length - 1) {
delay = 0;
}
return circle.getReverseAnimation({
friction: 10,
delay,
velocity: 6 * inverseIndex,
});
});
return Animated.parallel(animations);
};
animate = () => {
this.getAnimation().start();
};
circleConfig = (index) => {
let config = {
delay: 120 * index,
friction: 3 + index * 5,
tension: 2 + index * 2,
};
if (index === 2) {
config = {
...config,
containerAnimation: this.props.containerAnimation,
toColor: Colors.green,
useNativeDriver: false,
};
}
return config;
};
circles = [];
colors = [
[Colors.lightGreen, Colors.green],
[Colors.darkerGreen, Colors.green],
[Colors.transparent, Colors.darkGreen],
];
_reset = () => {
this.reset();
this.animate();
};
render() {
return (
<View
style={{
width: circleSize,
height: circleSize,
justifyContent: "center",
}}
>
{this.colors.map(([outer, inner], index) => (
<AnimatedCircle
key={"d" + index}
ref={(ref) => this.circles.push(ref)}
outerColor={outer}
innerColor={inner}
{...this.circleConfig(index)}
/>
))}
<AnimatedBadge
source={require("../assets/images/expoBadge.png")}
ref={(ref) => this.circles.push(ref)}
style={{
resizeMode: "contain",
position: "absolute",
width: circleSize,
height: "60%",
borderWidth: 0,
}}
{...this.circleConfig(3)}
/>
</View>
);
}
}
class FirstText extends React.Component {
reset = () => {
this.animation.setValue(0);
};
open = () => {
this.animate();
};
getAnimation = (toValue = 1, delay = 500) =>
Animated.timing(this.animation, {
toValue,
easing: Easing.inOut(Easing.cubic),
duration: 600,
delay,
});
getReverseAnimation = () => this.getAnimation(0);
animate = () => {
this.getAnimation().start();
};
animation = new Animated.Value(0);
get firstTextAnimatedStyle() {
const inputRange = [0.5, 1];
const adjustedOpacity = Animated.add(
this.props.containerAnimation,
this.animation
);
const opacity = this.props.containerAnimation.interpolate({
inputRange: [0.5, 1],
outputRange: [0, 1],
});
const translateX = this.props.containerAnimation.interpolate({
inputRange,
outputRange: [20, 0],
});
const translateY = this.animation.interpolate({
inputRange: [0, 1],
outputRange: [0, -circleSize],
});
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
render() {
return (
<Animated.View
style={[
{
overflow: "hidden",
width: openWidth - circleSize,
height: circleSize * 2,
},
this.firstTextAnimatedStyle,
]}
>
<View
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
{this.props.renderUpperContents()}
</View>
<View
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
{this.props.renderLowerContents()}
</View>
</Animated.View>
);
}
}
class Popup extends React.Component {
// parallel(animations, config?)
async componentDidMount() {
try {
await AudioManager.playAsync("unlock");
} finally {
setTimeout(() => {
this.open();
}, 500);
}
}
reset = () => {
this.circle.reset();
this.firstText.reset();
this.animation.setValue(0);
};
open = () => {
// this.circle.animate();
this.animate();
};
getAnimation = (toValue = 1, delay = 0) =>
Animated.timing(this.animation, {
toValue,
easing: Easing.out(Easing.cubic),
duration: 800,
delay,
});
getReverseAnimation = () => this.getAnimation(0, 2500);
animate = () => {
Animated.sequence([
this.circle.getAnimation(),
this.getAnimation(),
this.firstText.getAnimation(1, 3000),
this.getReverseAnimation(),
this.circle.getReverseAnimation(),
]).start(() => {
dispatch.presentAchievement.set(null);
});
// this.getAnimation().start();
};
circleConfig = (index) => {
let config = {
delay: 120 * index,
friction: 3 + index * 5,
tension: 2 + index * 2,
};
if (index === 2) {
config["toColor"] = "orange";
}
return config;
};
circles = [];
_reset = () => {
this.reset();
this.open();
};
animation = new Animated.Value(0);
get animatedContainerStyle() {
const width = this.animation.interpolate({
inputRange: [0, 1],
outputRange: [circleSize, openWidth],
});
const backgroundColor = this.animation.interpolate({
inputRange: [0, 0.02],
outputRange: [Colors.darkGreenTransparent, Colors.darkGreen],
});
return {
backgroundColor,
borderRadius: circleSize / 2,
height: circleSize,
width,
flexDirection: "row",
alignItems: "flex-start",
};
}
get firstTextAnimatedStyle() {
const inputRange = [0.5, 1];
const opacity = this.animation.interpolate({
inputRange,
outputRange: [0, 1],
});
const translateX = this.animation.interpolate({
inputRange,
outputRange: [20, 0],
});
return {
opacity,
transform: [{ translateX }],
};
}
render() {
return (
<TouchableWithoutFeedback
onPress={() => {
this.props.navigation.navigate("Challenges", { id: this.props.id });
}}
>
<Animated.View style={this.animatedContainerStyle}>
<View
style={[
{
position: "absolute",
top: 0,
bottom: 0,
right: 0,
left: circleSize,
borderTopRightRadius: circleSize / 2,
borderBottomRightRadius: circleSize / 2,
overflow: "hidden",
},
]}
>
<FirstText
renderUpperContents={() => (
<View>
<Text
style={{
color: Colors.white,
marginHorizontal: 8,
fontWeight: "bold",
}}
>
{this.props.name}
</Text>
<View style={{ flexDirection: "row" }}>
<Text
style={{
color: Colors.white,
marginHorizontal: 8,
}}
>
Challenge Complete!{" "}
</Text>
{this.props.score && (
<View
style={{
backgroundColor: "white",
borderRadius: 10,
paddingHorizontal: 4,
}}
>
<Text
style={{ fontWeight: "bold", color: Colors.green }}
>
{this.props.score || 0}x
</Text>
</View>
)}
</View>
</View>
)}
renderLowerContents={() => (
<Text style={{ color: Colors.white, fontWeight: "bold" }}>
Tap for details
</Text>
)}
containerAnimation={this.animation}
ref={(ref) => (this.firstText = ref)}
/>
</View>
<BouncingCircle
containerAnimation={this.animation}
ref={(ref) => (this.circle = ref)}
/>
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
function PopupContainer({ navigation, presentAchievement }) {
const { top } = useSafeArea();
return (
<View
style={[
StyleSheet.absoluteFill,
{ top, padding: 16, alignItems: "center" },
]}
pointerEvents="box-none"
>
{presentAchievement && (
<Popup
navigation={navigation}
id={presentAchievement.id}
name={presentAchievement.name}
score={presentAchievement.score}
/>
)}
</View>
);
}
export default connect(({ presentAchievement }) => ({ presentAchievement }))(
PopupContainer
);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1",
},
}); | the_stack |
/// <reference types="node" />
import * as fs from "fs";
export interface SetupOptions {
EV_KEY: any[];
}
export interface CreateOptions {
name: string;
id: CreateID;
}
export interface CreateID {
bustype: number;
vendor: number;
product: number;
version: number;
ff_effects_max?: number;
absmax?: number[];
absmin?: number[];
absfuzz?: number[];
absflat?: number[];
}
export function setup(
options: SetupOptions,
callback: (err: Error, stream: fs.WriteStream) => void
): void;
export function create(
stream: fs.WriteStream,
options: CreateOptions,
callback: (err: Error) => void
): void;
export function send_event(
stream: fs.WriteStream,
typeParam: number,
code: number,
value: number,
callback: (err: Error) => void
): void;
export function key_event(
stream: fs.WriteStream,
code: number,
callback: (err: Error) => void
): void;
export function emit_combo(
stream: fs.WriteStream,
codes: number[],
callback: (err: Error) => void
): void;
export const BUS_PCI: number;
export const BUS_ISAPNP: number;
export const BUS_USB: number;
export const BUS_HIL: number;
export const BUS_BLUETOOTH: number;
export const BUS_VIRTUAL: number;
export const BUS_ISA: number;
export const BUS_I8042: number;
export const BUS_XTKBD: number;
export const BUS_RS232: number;
export const BUS_GAMEPORT: number;
export const BUS_PARPORT: number;
export const BUS_AMIGA: number;
export const BUS_ADB: number;
export const BUS_I2C: number;
export const BUS_HOST: number;
export const BUS_GSC: number;
export const BUS_ATARI: number;
export const BUS_SPI: number;
export const KEY_RESERVED: number;
export const KEY_ESC: number;
export const KEY_1: number;
export const KEY_2: number;
export const KEY_3: number;
export const KEY_4: number;
export const KEY_5: number;
export const KEY_6: number;
export const KEY_7: number;
export const KEY_8: number;
export const KEY_9: number;
export const KEY_0: number;
export const KEY_MINUS: number;
export const KEY_EQUAL: number;
export const KEY_BACKSPACE: number;
export const KEY_TAB: number;
export const KEY_Q: number;
export const KEY_W: number;
export const KEY_E: number;
export const KEY_R: number;
export const KEY_T: number;
export const KEY_Y: number;
export const KEY_U: number;
export const KEY_I: number;
export const KEY_O: number;
export const KEY_P: number;
export const KEY_LEFTBRACE: number;
export const KEY_RIGHTBRACE: number;
export const KEY_ENTER: number;
export const KEY_LEFTCTRL: number;
export const KEY_A: number;
export const KEY_S: number;
export const KEY_D: number;
export const KEY_F: number;
export const KEY_G: number;
export const KEY_H: number;
export const KEY_J: number;
export const KEY_K: number;
export const KEY_L: number;
export const KEY_SEMICOLON: number;
export const KEY_APOSTROPHE: number;
export const KEY_GRAVE: number;
export const KEY_LEFTSHIFT: number;
export const KEY_BACKSLASH: number;
export const KEY_Z: number;
export const KEY_X: number;
export const KEY_C: number;
export const KEY_V: number;
export const KEY_B: number;
export const KEY_N: number;
export const KEY_M: number;
export const KEY_COMMA: number;
export const KEY_DOT: number;
export const KEY_SLASH: number;
export const KEY_RIGHTSHIFT: number;
export const KEY_KPASTERISK: number;
export const KEY_LEFTALT: number;
export const KEY_SPACE: number;
export const KEY_CAPSLOCK: number;
export const KEY_F1: number;
export const KEY_F2: number;
export const KEY_F3: number;
export const KEY_F4: number;
export const KEY_F5: number;
export const KEY_F6: number;
export const KEY_F7: number;
export const KEY_F8: number;
export const KEY_F9: number;
export const KEY_F10: number;
export const KEY_NUMLOCK: number;
export const KEY_SCROLLLOCK: number;
export const KEY_KP7: number;
export const KEY_KP8: number;
export const KEY_KP9: number;
export const KEY_KPMINUS: number;
export const KEY_KP4: number;
export const KEY_KP5: number;
export const KEY_KP6: number;
export const KEY_KPPLUS: number;
export const KEY_KP1: number;
export const KEY_KP2: number;
export const KEY_KP3: number;
export const KEY_KP0: number;
export const KEY_KPDOT: number;
export const KEY_ZENKAKUHANKAKU: number;
export const KEY_102ND: number;
export const KEY_F11: number;
export const KEY_F12: number;
export const KEY_RO: number;
export const KEY_KATAKANA: number;
export const KEY_HIRAGANA: number;
export const KEY_HENKAN: number;
export const KEY_KATAKANAHIRAGANA: number;
export const KEY_MUHENKAN: number;
export const KEY_KPJPCOMMA: number;
export const KEY_KPENTER: number;
export const KEY_RIGHTCTRL: number;
export const KEY_KPSLASH: number;
export const KEY_SYSRQ: number;
export const KEY_RIGHTALT: number;
export const KEY_LINEFEED: number;
export const KEY_HOME: number;
export const KEY_UP: number;
export const KEY_PAGEUP: number;
export const KEY_LEFT: number;
export const KEY_RIGHT: number;
export const KEY_END: number;
export const KEY_DOWN: number;
export const KEY_PAGEDOWN: number;
export const KEY_INSERT: number;
export const KEY_DELETE: number;
export const KEY_MACRO: number;
export const KEY_MUTE: number;
export const KEY_VOLUMEDOWN: number;
export const KEY_VOLUMEUP: number;
export const KEY_POWER: number;
export const KEY_KPEQUAL: number;
export const KEY_KPPLUSMINUS: number;
export const KEY_PAUSE: number;
export const KEY_SCALE: number;
export const KEY_KPCOMMA: number;
export const KEY_HANGEUL: number;
export const KEY_HANJA: number;
export const KEY_YEN: number;
export const KEY_LEFTMETA: number;
export const KEY_RIGHTMETA: number;
export const KEY_COMPOSE: number;
export const KEY_STOP: number;
export const KEY_AGAIN: number;
export const KEY_PROPS: number;
export const KEY_UNDO: number;
export const KEY_FRONT: number;
export const KEY_COPY: number;
export const KEY_OPEN: number;
export const KEY_PASTE: number;
export const KEY_FIND: number;
export const KEY_CUT: number;
export const KEY_HELP: number;
export const KEY_MENU: number;
export const KEY_CALC: number;
export const KEY_SETUP: number;
export const KEY_SLEEP: number;
export const KEY_WAKEUP: number;
export const KEY_FILE: number;
export const KEY_SENDFILE: number;
export const KEY_DELETEFILE: number;
export const KEY_XFER: number;
export const KEY_PROG1: number;
export const KEY_PROG2: number;
export const KEY_WWW: number;
export const KEY_MSDOS: number;
export const KEY_COFFEE: number;
export const KEY_ROTATE_DISPLAY: number;
export const KEY_CYCLEWINDOWS: number;
export const KEY_MAIL: number;
export const KEY_BOOKMARKS: number;
export const KEY_COMPUTER: number;
export const KEY_BACK: number;
export const KEY_FORWARD: number;
export const KEY_CLOSECD: number;
export const KEY_EJECTCD: number;
export const KEY_EJECTCLOSECD: number;
export const KEY_NEXTSONG: number;
export const KEY_PLAYPAUSE: number;
export const KEY_PREVIOUSSONG: number;
export const KEY_STOPCD: number;
export const KEY_RECORD: number;
export const KEY_REWIND: number;
export const KEY_PHONE: number;
export const KEY_ISO: number;
export const KEY_CONFIG: number;
export const KEY_HOMEPAGE: number;
export const KEY_REFRESH: number;
export const KEY_EXIT: number;
export const KEY_MOVE: number;
export const KEY_EDIT: number;
export const KEY_SCROLLUP: number;
export const KEY_SCROLLDOWN: number;
export const KEY_KPLEFTPAREN: number;
export const KEY_KPRIGHTPAREN: number;
export const KEY_NEW: number;
export const KEY_REDO: number;
export const KEY_F13: number;
export const KEY_F14: number;
export const KEY_F15: number;
export const KEY_F16: number;
export const KEY_F17: number;
export const KEY_F18: number;
export const KEY_F19: number;
export const KEY_F20: number;
export const KEY_F21: number;
export const KEY_F22: number;
export const KEY_F23: number;
export const KEY_F24: number;
export const KEY_PLAYCD: number;
export const KEY_PAUSECD: number;
export const KEY_PROG3: number;
export const KEY_PROG4: number;
export const KEY_DASHBOARD: number;
export const KEY_SUSPEND: number;
export const KEY_CLOSE: number;
export const KEY_PLAY: number;
export const KEY_FASTFORWARD: number;
export const KEY_BASSBOOST: number;
export const KEY_PRINT: number;
export const KEY_HP: number;
export const KEY_CAMERA: number;
export const KEY_SOUND: number;
export const KEY_QUESTION: number;
export const KEY_EMAIL: number;
export const KEY_CHAT: number;
export const KEY_SEARCH: number;
export const KEY_CONNECT: number;
export const KEY_FINANCE: number;
export const KEY_SPORT: number;
export const KEY_SHOP: number;
export const KEY_ALTERASE: number;
export const KEY_CANCEL: number;
export const KEY_BRIGHTNESSDOWN: number;
export const KEY_BRIGHTNESSUP: number;
export const KEY_MEDIA: number;
export const KEY_SWITCHVIDEOMODE: number;
export const KEY_KBDILLUMTOGGLE: number;
export const KEY_KBDILLUMDOWN: number;
export const KEY_KBDILLUMUP: number;
export const KEY_SEND: number;
export const KEY_REPLY: number;
export const KEY_FORWARDMAIL: number;
export const KEY_SAVE: number;
export const KEY_DOCUMENTS: number;
export const KEY_BATTERY: number;
export const KEY_BLUETOOTH: number;
export const KEY_WLAN: number;
export const KEY_UWB: number;
export const KEY_UNKNOWN: number;
export const KEY_VIDEO_NEXT: number;
export const KEY_VIDEO_PREV: number;
export const KEY_BRIGHTNESS_CYCLE: number;
export const KEY_BRIGHTNESS_AUTO: number;
export const KEY_DISPLAY_OFF: number;
export const KEY_WWAN: number;
export const KEY_RFKILL: number;
export const KEY_MICMUTE: number;
export const BTN_MISC: number;
export const BTN_0: number;
export const BTN_1: number;
export const BTN_2: number;
export const BTN_3: number;
export const BTN_4: number;
export const BTN_5: number;
export const BTN_6: number;
export const BTN_7: number;
export const BTN_8: number;
export const BTN_9: number;
export const BTN_MOUSE: number;
export const BTN_LEFT: number;
export const BTN_RIGHT: number;
export const BTN_MIDDLE: number;
export const BTN_SIDE: number;
export const BTN_EXTRA: number;
export const BTN_FORWARD: number;
export const BTN_BACK: number;
export const BTN_TASK: number;
export const BTN_JOYSTICK: number;
export const BTN_TRIGGER: number;
export const BTN_THUMB: number;
export const BTN_THUMB2: number;
export const BTN_TOP: number;
export const BTN_TOP2: number;
export const BTN_PINKIE: number;
export const BTN_BASE: number;
export const BTN_BASE2: number;
export const BTN_BASE3: number;
export const BTN_BASE4: number;
export const BTN_BASE5: number;
export const BTN_BASE6: number;
export const BTN_DEAD: number;
export const BTN_GAMEPAD: number;
export const BTN_SOUTH: number;
export const BTN_EAST: number;
export const BTN_C: number;
export const BTN_NORTH: number;
export const BTN_WEST: number;
export const BTN_Z: number;
export const BTN_TL: number;
export const BTN_TR: number;
export const BTN_TL2: number;
export const BTN_TR2: number;
export const BTN_SELECT: number;
export const BTN_START: number;
export const BTN_MODE: number;
export const BTN_THUMBL: number;
export const BTN_THUMBR: number;
export const BTN_DIGI: number;
export const BTN_TOOL_PEN: number;
export const BTN_TOOL_RUBBER: number;
export const BTN_TOOL_BRUSH: number;
export const BTN_TOOL_PENCIL: number;
export const BTN_TOOL_AIRBRUSH: number;
export const BTN_TOOL_FINGER: number;
export const BTN_TOOL_MOUSE: number;
export const BTN_TOOL_LENS: number;
export const BTN_TOOL_QUINTTAP: number;
export const BTN_TOUCH: number;
export const BTN_STYLUS: number;
export const BTN_STYLUS2: number;
export const BTN_TOOL_DOUBLETAP: number;
export const BTN_TOOL_TRIPLETAP: number;
export const BTN_TOOL_QUADTAP: number;
export const BTN_WHEEL: number;
export const BTN_GEAR_DOWN: number;
export const BTN_GEAR_UP: number;
export const BTN_DPAD_UP: number;
export const BTN_DPAD_DOWN: number;
export const BTN_DPAD_LEFT: number;
export const BTN_DPAD_RIGHT: number;
export const BTN_TRIGGER_HAPPY: number;
export const BTN_TRIGGER_HAPPY1: number;
export const BTN_TRIGGER_HAPPY2: number;
export const BTN_TRIGGER_HAPPY3: number;
export const BTN_TRIGGER_HAPPY4: number;
export const BTN_TRIGGER_HAPPY5: number;
export const BTN_TRIGGER_HAPPY6: number;
export const BTN_TRIGGER_HAPPY7: number;
export const BTN_TRIGGER_HAPPY8: number;
export const BTN_TRIGGER_HAPPY9: number;
export const BTN_TRIGGER_HAPPY10: number;
export const BTN_TRIGGER_HAPPY11: number;
export const BTN_TRIGGER_HAPPY12: number;
export const BTN_TRIGGER_HAPPY13: number;
export const BTN_TRIGGER_HAPPY14: number;
export const BTN_TRIGGER_HAPPY15: number;
export const BTN_TRIGGER_HAPPY16: number;
export const BTN_TRIGGER_HAPPY17: number;
export const BTN_TRIGGER_HAPPY18: number;
export const BTN_TRIGGER_HAPPY19: number;
export const BTN_TRIGGER_HAPPY20: number;
export const BTN_TRIGGER_HAPPY21: number;
export const BTN_TRIGGER_HAPPY22: number;
export const BTN_TRIGGER_HAPPY23: number;
export const BTN_TRIGGER_HAPPY24: number;
export const BTN_TRIGGER_HAPPY25: number;
export const BTN_TRIGGER_HAPPY26: number;
export const BTN_TRIGGER_HAPPY27: number;
export const BTN_TRIGGER_HAPPY28: number;
export const BTN_TRIGGER_HAPPY29: number;
export const BTN_TRIGGER_HAPPY30: number;
export const BTN_TRIGGER_HAPPY31: number;
export const BTN_TRIGGER_HAPPY32: number;
export const BTN_TRIGGER_HAPPY33: number;
export const BTN_TRIGGER_HAPPY34: number;
export const BTN_TRIGGER_HAPPY35: number;
export const BTN_TRIGGER_HAPPY36: number;
export const BTN_TRIGGER_HAPPY37: number;
export const BTN_TRIGGER_HAPPY38: number;
export const BTN_TRIGGER_HAPPY39: number;
export const BTN_TRIGGER_HAPPY40: number;
export const KEY_OK: number;
export const KEY_SELECT: number;
export const KEY_GOTO: number;
export const KEY_CLEAR: number;
export const KEY_POWER2: number;
export const KEY_OPTION: number;
export const KEY_INFO: number;
export const KEY_TIME: number;
export const KEY_VENDOR: number;
export const KEY_ARCHIVE: number;
export const KEY_PROGRAM: number;
export const KEY_CHANNEL: number;
export const KEY_FAVORITES: number;
export const KEY_EPG: number;
export const KEY_PVR: number;
export const KEY_MHP: number;
export const KEY_LANGUAGE: number;
export const KEY_TITLE: number;
export const KEY_SUBTITLE: number;
export const KEY_ANGLE: number;
export const KEY_ZOOM: number;
export const KEY_MODE: number;
export const KEY_KEYBOARD: number;
export const KEY_SCREEN: number;
export const KEY_PC: number;
export const KEY_TV: number;
export const KEY_TV2: number;
export const KEY_VCR: number;
export const KEY_VCR2: number;
export const KEY_SAT: number;
export const KEY_SAT2: number;
export const KEY_CD: number;
export const KEY_TAPE: number;
export const KEY_RADIO: number;
export const KEY_TUNER: number;
export const KEY_PLAYER: number;
export const KEY_TEXT: number;
export const KEY_DVD: number;
export const KEY_AUX: number;
export const KEY_MP3: number;
export const KEY_AUDIO: number;
export const KEY_VIDEO: number;
export const KEY_DIRECTORY: number;
export const KEY_LIST: number;
export const KEY_MEMO: number;
export const KEY_CALENDAR: number;
export const KEY_RED: number;
export const KEY_GREEN: number;
export const KEY_YELLOW: number;
export const KEY_BLUE: number;
export const KEY_CHANNELUP: number;
export const KEY_CHANNELDOWN: number;
export const KEY_FIRST: number;
export const KEY_LAST: number;
export const KEY_AB: number;
export const KEY_NEXT: number;
export const KEY_RESTART: number;
export const KEY_SLOW: number;
export const KEY_SHUFFLE: number;
export const KEY_BREAK: number;
export const KEY_PREVIOUS: number;
export const KEY_DIGITS: number;
export const KEY_TEEN: number;
export const KEY_TWEN: number;
export const KEY_VIDEOPHONE: number;
export const KEY_GAMES: number;
export const KEY_ZOOMIN: number;
export const KEY_ZOOMOUT: number;
export const KEY_ZOOMRESET: number;
export const KEY_WORDPROCESSOR: number;
export const KEY_EDITOR: number;
export const KEY_SPREADSHEET: number;
export const KEY_GRAPHICSEDITOR: number;
export const KEY_PRESENTATION: number;
export const KEY_DATABASE: number;
export const KEY_NEWS: number;
export const KEY_VOICEMAIL: number;
export const KEY_ADDRESSBOOK: number;
export const KEY_MESSENGER: number;
export const KEY_DISPLAYTOGGLE: number;
export const KEY_SPELLCHECK: number;
export const KEY_LOGOFF: number;
export const KEY_DOLLAR: number;
export const KEY_EURO: number;
export const KEY_FRAMEBACK: number;
export const KEY_FRAMEFORWARD: number;
export const KEY_CONTEXT_MENU: number;
export const KEY_MEDIA_REPEAT: number;
export const KEY_10CHANNELSUP: number;
export const KEY_10CHANNELSDOWN: number;
export const KEY_IMAGES: number;
export const KEY_DEL_EOL: number;
export const KEY_DEL_EOS: number;
export const KEY_INS_LINE: number;
export const KEY_DEL_LINE: number;
export const KEY_FN: number;
export const KEY_FN_ESC: number;
export const KEY_FN_F1: number;
export const KEY_FN_F2: number;
export const KEY_FN_F3: number;
export const KEY_FN_F4: number;
export const KEY_FN_F5: number;
export const KEY_FN_F6: number;
export const KEY_FN_F7: number;
export const KEY_FN_F8: number;
export const KEY_FN_F9: number;
export const KEY_FN_F10: number;
export const KEY_FN_F11: number;
export const KEY_FN_F12: number;
export const KEY_FN_1: number;
export const KEY_FN_2: number;
export const KEY_FN_D: number;
export const KEY_FN_E: number;
export const KEY_FN_F: number;
export const KEY_FN_S: number;
export const KEY_FN_B: number;
export const KEY_BRL_DOT1: number;
export const KEY_BRL_DOT2: number;
export const KEY_BRL_DOT3: number;
export const KEY_BRL_DOT4: number;
export const KEY_BRL_DOT5: number;
export const KEY_BRL_DOT6: number;
export const KEY_BRL_DOT7: number;
export const KEY_BRL_DOT8: number;
export const KEY_BRL_DOT9: number;
export const KEY_BRL_DOT10: number;
export const KEY_NUMERIC_0: number;
export const KEY_NUMERIC_1: number;
export const KEY_NUMERIC_2: number;
export const KEY_NUMERIC_3: number;
export const KEY_NUMERIC_4: number;
export const KEY_NUMERIC_5: number;
export const KEY_NUMERIC_6: number;
export const KEY_NUMERIC_7: number;
export const KEY_NUMERIC_8: number;
export const KEY_NUMERIC_9: number;
export const KEY_NUMERIC_STAR: number;
export const KEY_NUMERIC_POUND: number;
export const KEY_NUMERIC_A: number;
export const KEY_NUMERIC_B: number;
export const KEY_NUMERIC_C: number;
export const KEY_NUMERIC_D: number;
export const KEY_CAMERA_FOCUS: number;
export const KEY_WPS_BUTTON: number;
export const KEY_TOUCHPAD_TOGGLE: number;
export const KEY_TOUCHPAD_ON: number;
export const KEY_TOUCHPAD_OFF: number;
export const KEY_CAMERA_ZOOMIN: number;
export const KEY_CAMERA_ZOOMOUT: number;
export const KEY_CAMERA_UP: number;
export const KEY_CAMERA_DOWN: number;
export const KEY_CAMERA_LEFT: number;
export const KEY_CAMERA_RIGHT: number;
export const KEY_ATTENDANT_ON: number;
export const KEY_ATTENDANT_OFF: number;
export const KEY_ATTENDANT_TOGGLE: number;
export const KEY_LIGHTS_TOGGLE: number;
export const KEY_ALS_TOGGLE: number;
export const KEY_BUTTONCONFIG: number;
export const KEY_TASKMANAGER: number;
export const KEY_JOURNAL: number;
export const KEY_CONTROLPANEL: number;
export const KEY_APPSELECT: number;
export const KEY_SCREENSAVER: number;
export const KEY_VOICECOMMAND: number;
export const KEY_ASSISTANT: number;
export const KEY_BRIGHTNESS_MIN: number;
export const KEY_BRIGHTNESS_MAX: number;
export const KEY_KBDINPUTASSIST_PREV: number;
export const KEY_KBDINPUTASSIST_NEXT: number;
export const KEY_KBDINPUTASSIST_PREVGROUP: number;
export const KEY_KBDINPUTASSIST_NEXTGROUP: number;
export const KEY_KBDINPUTASSIST_ACCEPT: number;
export const KEY_KBDINPUTASSIST_CANCEL: number;
export const KEY_RIGHT_UP: number;
export const KEY_RIGHT_DOWN: number;
export const KEY_LEFT_UP: number;
export const KEY_LEFT_DOWN: number;
export const KEY_ROOT_MENU: number;
export const KEY_MEDIA_TOP_MENU: number;
export const KEY_NUMERIC_11: number;
export const KEY_NUMERIC_12: number;
export const KEY_AUDIO_DESC: number;
export const KEY_3D_MODE: number;
export const KEY_NEXT_FAVORITE: number;
export const KEY_STOP_RECORD: number;
export const KEY_PAUSE_RECORD: number;
export const KEY_VOD: number;
export const KEY_UNMUTE: number;
export const KEY_FASTREVERSE: number;
export const KEY_SLOWREVERSE: number;
export const KEY_DATA: number;
export const KEY_ONSCREEN_KEYBOARD: number;
export const KEY_MAX: number;
export const KEY_CNT: number;
export const REL_X: number;
export const REL_Y: number;
export const REL_Z: number;
export const REL_RX: number;
export const REL_RY: number;
export const REL_RZ: number;
export const REL_HWHEEL: number;
export const REL_DIAL: number;
export const REL_WHEEL: number;
export const REL_MISC: number;
export const REL_MAX: number;
export const REL_CNT: number;
export const ABS_X: number;
export const ABS_Y: number;
export const ABS_Z: number;
export const ABS_RX: number;
export const ABS_RY: number;
export const ABS_RZ: number;
export const ABS_THROTTLE: number;
export const ABS_RUDDER: number;
export const ABS_WHEEL: number;
export const ABS_GAS: number;
export const ABS_BRAKE: number;
export const ABS_HAT0X: number;
export const ABS_HAT0Y: number;
export const ABS_HAT1X: number;
export const ABS_HAT1Y: number;
export const ABS_HAT2X: number;
export const ABS_HAT2Y: number;
export const ABS_HAT3X: number;
export const ABS_HAT3Y: number;
export const ABS_PRESSURE: number;
export const ABS_DISTANCE: number;
export const ABS_TILT_X: number;
export const ABS_TILT_Y: number;
export const ABS_TOOL_WIDTH: number;
export const ABS_VOLUME: number;
export const ABS_MISC: number;
export const ABS_MT_SLOT: number;
export const ABS_MT_TOUCH_MAJOR: number;
export const ABS_MT_TOUCH_MINOR: number;
export const ABS_MT_WIDTH_MAJOR: number;
export const ABS_MT_WIDTH_MINOR: number;
export const ABS_MT_ORIENTATION: number;
export const ABS_MT_POSITION_X: number;
export const ABS_MT_POSITION_Y: number;
export const ABS_MT_TOOL_TYPE: number;
export const ABS_MT_BLOB_ID: number;
export const ABS_MT_TRACKING_ID: number;
export const ABS_MT_PRESSURE: number;
export const ABS_MT_DISTANCE: number;
export const ABS_MT_TOOL_X: number;
export const ABS_MT_TOOL_Y: number;
export const ABS_MAX: number;
export const ABS_CNT: number;
export const SW_LID: number;
export const SW_TABLET_MODE: number;
export const SW_HEADPHONE_INSERT: number;
export const SW_RFKILL_ALL: number;
export const SW_MICROPHONE_INSERT: number;
export const SW_DOCK: number;
export const SW_LINEOUT_INSERT: number;
export const SW_JACK_PHYSICAL_INSERT: number;
export const SW_VIDEOOUT_INSERT: number;
export const SW_CAMERA_LENS_COVER: number;
export const SW_KEYPAD_SLIDE: number;
export const SW_FRONT_PROXIMITY: number;
export const SW_ROTATE_LOCK: number;
export const SW_LINEIN_INSERT: number;
export const SW_MUTE_DEVICE: number;
export const SW_PEN_INSERTED: number;
export const SW_MAX: number;
export const SW_CNT: number;
export const MSC_SERIAL: number;
export const MSC_PULSELED: number;
export const MSC_GESTURE: number;
export const MSC_RAW: number;
export const MSC_SCAN: number;
export const MSC_TIMESTAMP: number;
export const MSC_MAX: number;
export const MSC_CNT: number;
export const LED_NUML: number;
export const LED_CAPSL: number;
export const LED_SCROLLL: number;
export const LED_COMPOSE: number;
export const LED_KANA: number;
export const LED_SLEEP: number;
export const LED_SUSPEND: number;
export const LED_MUTE: number;
export const LED_MISC: number;
export const LED_MAIL: number;
export const LED_CHARGING: number;
export const LED_MAX: number;
export const LED_CNT: number;
export const REP_DELAY: number;
export const REP_PERIOD: number;
export const REP_MAX: number;
export const REP_CNT: number;
export const SND_CLICK: number;
export const SND_BELL: number;
export const SND_TONE: number;
export const SND_MAX: number;
export const SND_CNT: number; | the_stack |
export const themeDataBase = {
"lf-active-icon": "#3578E5",
"lf-attachment-footer-background": "#F2F3F5",
"lf-black": "#000000",
"lf-black-alpha-05": "rgba(0, 0, 0, 0.05)",
"lf-black-alpha-10": "rgba(0, 0, 0, 0.1)",
"lf-black-alpha-15": "rgba(0, 0, 0, 0.15)",
"lf-black-alpha-20": "rgba(0, 0, 0, 0.2)",
"lf-black-alpha-30": "rgba(0, 0, 0, 0.3)",
"lf-black-alpha-40": "rgba(0, 0, 0, 0.4)",
"lf-black-alpha-50": "rgba(0, 0, 0, 0.5)",
"lf-black-alpha-60": "rgba(0, 0, 0, 0.6)",
"lf-black-alpha-80": "rgba(0, 0, 0, 0.8)",
"lf-blue-05": "#ECF3FF",
"lf-blue-30": "#AAC9FF",
"lf-blue-40": "#77A7FF",
"lf-blue-60": "#1877F2",
"lf-blue-70": "#2851A3",
"lf-blue-80": "#1D3C78",
"lf-blue-95": "#E7F3FF",
"lf-blue-badge": "#1877F2",
"lf-blue-link": "#1877F2",
"lf-button-icon": "#444950",
"lf-button-text": "#444950",
"lf-comment-background": "#F2F3F5",
"lf-dark-mode-gray-35": "#CCCCCC",
"lf-dark-mode-gray-50": "#828282",
"lf-dark-mode-gray-70": "#4A4A4A",
"lf-dark-mode-gray-80": "#373737",
"lf-dark-mode-gray-90": "#282828",
"lf-dark-mode-gray-100": "#1C1C1C",
"lf-dark-ui-card-border": "#282828",
"lf-dark-ui-cards": "#1C1C1C",
"lf-dark-ui-disabled-icon": "#373737",
"lf-dark-ui-divider": "#282828",
"lf-dark-ui-medium-text": "#828282",
"lf-dark-ui-nav-bar": "#1C1C1C",
"lf-dark-ui-primary-icon": "#828282",
"lf-dark-ui-primary-text": "#CCCCCC",
"lf-dark-ui-secondary-icon": "#4A4A4A",
"lf-dark-ui-secondary-text": "#4A4A4A",
"lf-dark-ui-tab-bar": "#1C1C1C",
"lf-dark-ui-wash": "#000000",
"lf-data-mango": "#f5bb41",
"lf-disabled-icon": "#BEC3C9",
"lf-disabled-text": "#BEC3C9",
"lf-divider-on-wash": "#CCD0D5",
"lf-divider-on-white": "#DADDE1",
"lf-fast": "200ms",
"lf-fb-blue-70": "#4267B2",
"lf-fb-blue-75": "#385898",
"lf-gray-00": "#F5F6F7",
"lf-gray-05": "#F2F3F5",
"lf-gray-10": "#EBEDF0",
"lf-gray-20": "#DADDE1",
"lf-gray-25": "#CCD0D5",
"lf-gray-30": "#BEC3C9",
"lf-gray-45": "#8D949E",
"lf-gray-70": "#606770",
"lf-gray-80": "#444950",
"lf-gray-90": "#303338",
"lf-gray-100": "#1C1E21",
"lf-green-30": "#86DF81",
"lf-green-55": "#00A400",
"lf-green-60": "#008C00",
"lf-green-70": "#006900",
"lf-highlight": "#3578E5",
"lf-highlight-cell-background": "#ECF3FF",
"lf-list-cell-pressed": "rgba(0, 0, 0, 0.05)",
"lf-mobile-wash": "#CCD0D5",
"lf-nav-bar-background": "#4267B2",
"lf-negative": "rgb(224, 36, 94)",
"lf-notification-badge": "rgb(224, 36, 94)",
"lf-placeholder-text": "#8D949E",
"lf-positive": "#00A400",
"lf-primary-button-pressed": "#77A7FF",
"lf-primary-icon": "#1C1E21",
"lf-primary-text": "#1C1E21",
"lf-red-55": "#FA383E",
"lf-secondary-button-pressed": "rgba(0, 0, 0, 0.05)",
"lf-secondary-icon": "#606770",
"lf-secondary-text": "#606770",
"lf-slow": "400ms",
"lf-soft": "cubic-bezier(.08,.52,.52,1)",
"lf-spectrum-aluminum": "#A3CEDF",
"lf-spectrum-aluminum-dark-1": "#8EBFD4",
"lf-spectrum-aluminum-dark-2": "#6CA0B6",
"lf-spectrum-aluminum-dark-3": "#4B8096",
"lf-spectrum-aluminum-tint-15": "#B0D5E5",
"lf-spectrum-aluminum-tint-30": "#BFDDE9",
"lf-spectrum-aluminum-tint-50": "#D1E7F0",
"lf-spectrum-aluminum-tint-70": "#E4F0F6",
"lf-spectrum-aluminum-tint-90": "#F6FAFC",
"lf-spectrum-blue-gray": "#5F6673",
"lf-spectrum-blue-gray-dark-1": "#4F5766",
"lf-spectrum-blue-gray-dark-2": "#303846",
"lf-spectrum-blue-gray-dark-3": "#23272F",
"lf-spectrum-blue-gray-tint-15": "#777D88",
"lf-spectrum-blue-gray-tint-30": "#8F949D",
"lf-spectrum-blue-gray-tint-50": "#AFB3B9",
"lf-spectrum-blue-gray-tint-70": "#CFD1D5",
"lf-spectrum-blue-gray-tint-90": "#EFF0F1",
"lf-spectrum-cherry": "#F35369",
"lf-spectrum-cherry-dark-1": "#E04C60",
"lf-spectrum-cherry-dark-2": "#B73749",
"lf-spectrum-cherry-dark-3": "#9B2B3A",
"lf-spectrum-cherry-tint-15": "#F36B7F",
"lf-spectrum-cherry-tint-30": "#F58796",
"lf-spectrum-cherry-tint-50": "#F8A9B4",
"lf-spectrum-cherry-tint-70": "#FBCCD2",
"lf-spectrum-cherry-tint-90": "#FEEEF0",
"lf-spectrum-grape": "#8C72CB",
"lf-spectrum-grape-dark-1": "#7B64C0",
"lf-spectrum-grape-dark-2": "#6A51B2",
"lf-spectrum-grape-dark-3": "#58409B",
"lf-spectrum-grape-tint-15": "#9D87D2",
"lf-spectrum-grape-tint-30": "#AF9CDA",
"lf-spectrum-grape-tint-50": "#C6B8E5",
"lf-spectrum-grape-tint-70": "#DDD5F0",
"lf-spectrum-grape-tint-90": "#F4F1FA",
"lf-spectrum-lemon": "#FCD872",
"lf-spectrum-lemon-dark-1": "#F5C33B",
"lf-spectrum-lemon-dark-2": "#E1A43B",
"lf-spectrum-lemon-dark-3": "#D18F41",
"lf-spectrum-lemon-tint-15": "#FFE18F",
"lf-spectrum-lemon-tint-30": "#FFE8A8",
"lf-spectrum-lemon-tint-50": "#FFECB5",
"lf-spectrum-lemon-tint-70": "#FEF2D1",
"lf-spectrum-lemon-tint-90": "#FFFBF0",
"lf-spectrum-lime": "#A3CE71",
"lf-spectrum-lime-dark-1": "#89BE4C",
"lf-spectrum-lime-dark-2": "#71A830",
"lf-spectrum-lime-dark-3": "#629824",
"lf-spectrum-lime-tint-15": "#B1D587",
"lf-spectrum-lime-tint-30": "#BEDD9C",
"lf-spectrum-lime-tint-50": "#D1E6B9",
"lf-spectrum-lime-tint-70": "#E4F0D5",
"lf-spectrum-lime-tint-90": "#F6FAF1",
"lf-spectrum-orange": "#F7923B",
"lf-spectrum-orange-dark-1": "#E07A2E",
"lf-spectrum-orange-dark-2": "#CC5D22",
"lf-spectrum-orange-dark-3": "#AC4615",
"lf-spectrum-orange-tint-15": "#F9A159",
"lf-spectrum-orange-tint-30": "#F9B278",
"lf-spectrum-orange-tint-50": "#FBC89F",
"lf-spectrum-orange-tint-70": "#FCDEC5",
"lf-spectrum-orange-tint-90": "#FEF4EC",
"lf-spectrum-pink": "#EC7EBD",
"lf-spectrum-pink-dark-1": "#EC6FB5",
"lf-spectrum-pink-dark-2": "#D4539B",
"lf-spectrum-pink-dark-3": "#B0377B",
"lf-spectrum-pink-tint-15": "#EF92C7",
"lf-spectrum-pink-tint-30": "#F2A5D1",
"lf-spectrum-pink-tint-50": "#F6BFDF",
"lf-spectrum-pink-tint-70": "#F9D9EB",
"lf-spectrum-pink-tint-90": "#FDF3F8",
"lf-spectrum-seafoam": "#54C7EC",
"lf-spectrum-seafoam-dark-1": "#39AFD5",
"lf-spectrum-seafoam-dark-2": "#2088AF",
"lf-spectrum-seafoam-dark-3": "#186D90",
"lf-spectrum-seafoam-tint-15": "#6BCFEF",
"lf-spectrum-seafoam-tint-30": "#84D8F2",
"lf-spectrum-seafoam-tint-50": "#A7E3F6",
"lf-spectrum-seafoam-tint-70": "#CAEEF9",
"lf-spectrum-seafoam-tint-90": "#EEFAFD",
"lf-spectrum-skin-1": "#F1D2B6",
"lf-spectrum-skin-1-dark-1": "#E2BA96",
"lf-spectrum-skin-1-dark-2": "#DDAC82",
"lf-spectrum-skin-1-dark-3": "#D9A170",
"lf-spectrum-skin-1-tint-15": "#F3D9C1",
"lf-spectrum-skin-1-tint-30": "#F6E0CC",
"lf-spectrum-skin-1-tint-50": "#F8E9DB",
"lf-spectrum-skin-1-tint-70": "#FAF2EA",
"lf-spectrum-skin-1-tint-90": "#FEFBF8",
"lf-spectrum-skin-2": "#D7B195",
"lf-spectrum-skin-2-dark-1": "#CFA588",
"lf-spectrum-skin-2-dark-2": "#C2977A",
"lf-spectrum-skin-2-dark-3": "#AF866A",
"lf-spectrum-skin-2-tint-15": "#DEBDA5",
"lf-spectrum-skin-2-tint-30": "#E5C9B5",
"lf-spectrum-skin-2-tint-50": "#ECD8CB",
"lf-spectrum-skin-2-tint-70": "#F3E8E0",
"lf-spectrum-skin-2-tint-90": "#FBF7F5",
"lf-spectrum-skin-3": "#D8A873",
"lf-spectrum-skin-3-dark-1": "#CD9862",
"lf-spectrum-skin-3-dark-2": "#BA8653",
"lf-spectrum-skin-3-dark-3": "#A77A4E",
"lf-spectrum-skin-3-tint-15": "#E0B588",
"lf-spectrum-skin-3-tint-30": "#E5C29E",
"lf-spectrum-skin-3-tint-50": "#ECD4B9",
"lf-spectrum-skin-3-tint-70": "#F4E5D6",
"lf-spectrum-skin-3-tint-90": "#FCF6F1",
"lf-spectrum-skin-4": "#A67B4F",
"lf-spectrum-skin-4-dark-1": "#A07243",
"lf-spectrum-skin-4-dark-2": "#94683D",
"lf-spectrum-skin-4-dark-3": "#815830",
"lf-spectrum-skin-4-tint-15": "#AE8761",
"lf-spectrum-skin-4-tint-30": "#BC9D7D",
"lf-spectrum-skin-4-tint-50": "#D0B9A2",
"lf-spectrum-skin-4-tint-70": "#E2D5C8",
"lf-spectrum-skin-4-tint-90": "#F6F1ED",
"lf-spectrum-skin-5": "#6A4F3B",
"lf-spectrum-skin-5-dark-1": "#624733",
"lf-spectrum-skin-5-dark-2": "#503B2C",
"lf-spectrum-skin-5-dark-3": "#453223",
"lf-spectrum-skin-5-tint-15": "#8A715B",
"lf-spectrum-skin-5-tint-30": "#9F8A79",
"lf-spectrum-skin-5-tint-50": "#BAACA0",
"lf-spectrum-skin-5-tint-70": "#D5CDC6",
"lf-spectrum-skin-5-tint-90": "#F2EFEC",
"lf-spectrum-slate": "#B9CAD2",
"lf-spectrum-slate-dark-1": "#A8BBC3",
"lf-spectrum-slate-dark-2": "#89A1AC",
"lf-spectrum-slate-dark-3": "#688694",
"lf-spectrum-slate-tint-15": "#C4D2D9",
"lf-spectrum-slate-tint-30": "#CEDAE0",
"lf-spectrum-slate-tint-50": "#DCE5E9",
"lf-spectrum-slate-tint-70": "#EAEFF2",
"lf-spectrum-slate-tint-90": "#F8FAFB",
"lf-spectrum-teal": "#6BCEBB",
"lf-spectrum-teal-dark-1": "#4DBBA6",
"lf-spectrum-teal-dark-2": "#31A38D",
"lf-spectrum-teal-dark-3": "#24917D",
"lf-spectrum-teal-tint-15": "#80D4C4",
"lf-spectrum-teal-tint-30": "#97DCCF",
"lf-spectrum-teal-tint-50": "#B4E6DD",
"lf-spectrum-teal-tint-70": "#D2F0EA",
"lf-spectrum-teal-tint-90": "#F0FAF8",
"lf-spectrum-tomato": "#FB724B",
"lf-spectrum-tomato-dark-1": "#EF6632",
"lf-spectrum-tomato-dark-2": "#DB4123",
"lf-spectrum-tomato-dark-3": "#C32D0E",
"lf-spectrum-tomato-tint-15": "#F1765E",
"lf-spectrum-tomato-tint-30": "#F38E7B",
"lf-spectrum-tomato-tint-50": "#F7AFA0",
"lf-spectrum-tomato-tint-70": "#F9CFC7",
"lf-spectrum-tomato-tint-90": "#FDEFED",
"lf-strong": "cubic-bezier(.12,.8,.32,1)",
"lf-tertiary-icon": "#8D949E",
"lf-white": "#FFFFFF",
"lf-white-alpha-05": "rgba(255, 255, 255, 0.05)",
"lf-white-alpha-10": "rgba(255, 255, 255, 0.1)",
"lf-white-alpha-15": "rgba(255, 255, 255, 0.15)",
"lf-white-alpha-20": "rgba(255, 255, 255, 0.2)",
"lf-white-alpha-30": "rgba(255, 255, 255, 0.3)",
"lf-white-alpha-40": "rgba(255, 255, 255, 0.4)",
"lf-white-alpha-50": "rgba(255, 255, 255, 0.5)",
"lf-white-alpha-60": "rgba(255, 255, 255, 0.6)",
"lf-white-alpha-80": "rgba(255, 255, 255, 0.8)",
"lf-white-text": "#FFFFFF",
"lf-www-wash": "#EBEDF0",
"lf-yellow-20": "#FFBA00",
"header-height": "60px",
"lf-animation-enter-exit-in": "cubic-bezier(0.14, 1, 0.34, 1)",
"lf-animation-enter-exit-out": "cubic-bezier(0.45, 0.1, 0.2, 1)",
"lf-animation-swap-shuffle-in": "cubic-bezier(0.14, 1, 0.34, 1)",
"lf-animation-swap-shuffle-out": "cubic-bezier(0.45, 0.1, 0.2, 1)",
"lf-animation-move-in": "cubic-bezier(0.17, 0.17, 0, 1)",
"lf-animation-move-out": "cubic-bezier(0.17, 0.17, 0, 1)",
"lf-animation-expand-collapse-in": "cubic-bezier(0.17, 0.17, 0, 1)",
"lf-animation-expand-collapse-out": "cubic-bezier(0.17, 0.17, 0, 1)",
"lf-animation-passive-move-in": "cubic-bezier(0.5, 0, 0.1, 1)",
"lf-animation-passive-move-out": "cubic-bezier(0.5, 0, 0.1, 1)",
"lf-animation-quick-move-in": "cubic-bezier(0.1, 0.9, 0.2, 1)",
"lf-animation-quick-move-out": "cubic-bezier(0.1, 0.9, 0.2, 1)",
"lf-animation-fade-in": "cubic-bezier(0, 0, 1, 1)",
"lf-animation-fade-out": "cubic-bezier(0, 0, 1, 1)",
"lf-duration-extra-extra-short-in": "100ms",
"lf-duration-extra-extra-short-out": "100ms",
"lf-duration-extra-short-in": "200ms",
"lf-duration-extra-short-out": "150ms",
"lf-duration-short-in": "280ms",
"lf-duration-short-out": "200ms",
"lf-duration-medium-in": "400ms",
"lf-duration-medium-out": "350ms",
"lf-duration-long-in": "500ms",
"lf-duration-long-out": "350ms",
"lf-duration-extra-long-in": "1000ms",
"lf-duration-extra-long-out": "1000ms",
"lf-duration-none": "0ms",
"light-color": "rgba(0,0,0,0.05)",
"light-light-color": "rgba(29,28,29,0.04)",
accent: "#0089ff",
"always-white": "#FFFFFF",
"always-black": "black",
"always-dark-gradient": "linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.6))",
"always-dark-overlay": "rgba(0, 0, 0, 0.4)",
"always-light-overlay": "rgba(255, 255, 255, 0.4)",
"always-gray-40": "#65676B",
"always-gray-75": "#BCC0C4",
"always-gray-95": "#F0F2F5",
"attachment-footer-background": "#F0F2F5",
"base-blue": "#1877F2",
"base-cherry": "#F3425F",
"base-grape": "#9360F7",
"base-lemon": "#F7B928",
"base-lime": "#45BD62",
"base-pink": "#FF66BF",
"base-seafoam": "#54C7EC",
"base-teal": "#2ABBA7",
"base-tomato": "#FB724B",
"blue-link": "#216FDB",
"card-background": "#FFFFFF",
"card-background-flat": "#F7F8FA",
"comment-background": "#F0F2F5",
"comment-footer-background": "#F6F9FA",
"dataviz-primary-1": "rgb(48,200,180)",
"disabled-button-background": "#E4E6EB",
"disabled-icon": "#BCC0C4",
"disabled-text": "#BCC0C4",
divider: "#CED0D4",
"event-date": "#F3425F",
"filter-accent": "invert(39%) sepia(57%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(147.75%) hue-rotate(202deg) brightness(97%) contrast(96%)",
"filter-always-white": "invert(100%)",
"filter-disabled-icon": "invert(80%) sepia(6%) saturate(200%) saturate(120%) hue-rotate(173deg) brightness(98%) contrast(89%)",
"filter-placeholder-icon": "invert(59%) sepia(11%) saturate(200%) saturate(135%) hue-rotate(176deg) brightness(96%) contrast(94%)",
"filter-primary-icon": "invert(8%) sepia(10%) saturate(200%) saturate(200%) saturate(166%) hue-rotate(177deg) brightness(104%) contrast(91%)",
"filter-secondary-icon": "invert(39%) sepia(21%) saturate(200%) saturate(109.5%) hue-rotate(174deg) brightness(94%) contrast(86%)",
"filter-warning-icon": "invert(77%) sepia(29%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(128%) hue-rotate(359deg) brightness(102%) contrast(107%)",
"filter-blue-link-icon": "invert(30%) sepia(98%) saturate(200%) saturate(200%) saturate(200%) saturate(166.5%) hue-rotate(192deg) brightness(91%) contrast(101%)",
"filter-positive": "invert(37%) sepia(61%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(115%) hue-rotate(91deg) brightness(97%) contrast(105%)",
"filter-negative": "invert(25%) sepia(33%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(200%) saturate(110%) hue-rotate(345deg) brightness(132%) contrast(96%)",
"font-family-apple": "system-ui, -apple-system, BlinkMacSystemFont, '.SFNSText-Regular', sans-serif",
"font-family-default": "Helvetica, Arial, sans-serif",
"font-family-segoe": "Segoe UI Historic, Segoe UI, Helvetica, Arial, sans-serif",
"glimmer-spinner-icon": "#65676B",
"hero-banner-background": "#FFFFFF",
"hosted-view-selected-state": "rgba(45, 136, 255, 0.2)",
"highlight-bg": "#E7F3FF",
"hover-overlay": "rgba(29, 161, 242, 0.1)",
"media-hover": "rgba(68, 73, 80, 0.15)",
"media-inner-border": "rgba(0, 0, 0, 0.1)",
"media-outer-border": "#FFFFFF",
"media-pressed": "rgba(68, 73, 80, 0.35)",
"messenger-card-background": "#FFFFFF",
"messenger-reply-background": "#F0F2F5",
"overlay-alpha-80": "rgba(244, 244, 244, 0.8)",
"overlay-on-media": "rgba(0, 0, 0, 0.6)",
"nav-bar-background": "#FFFFFF",
"nav-bar-background-gradient": "linear-gradient(to top, #FFFFFF, rgba(255,255,255.9), rgba(255,255,255,.7), rgba(255,255,255,.4), rgba(255,255,255,0))",
"nav-bar-background-gradient-wash": "linear-gradient(to top, #F0F2F5, rgba(240,242,245.9), rgba(240,242,245,.7), rgba(240,242,245,.4), rgba(240,242,245,0))",
negative: "rgb(224, 36, 94)",
"negative-background": "hsl(350, 87%, 55%, 20%)",
"new-notification-background": "#E7F3FF",
"non-media-pressed": "rgba(29, 161, 242, 0.15)",
"non-media-pressed-on-dark": "rgba(255, 255, 255, 0.3)",
"notification-badge": "rgb(224, 36, 94)",
"placeholder-icon": "#8A8D91",
"placeholder-text": "#8A8D91",
"placeholder-text-on-media": "rgba(255, 255, 255, 0.5)",
"popover-background": "#FFFFFF",
positive: "#31A24C",
"positive-background": "#DEEFE1",
"press-overlay": "rgba(29, 161, 242, 0.2)",
"primary-button-background": "#1877F2",
"primary-button-background-experiment": "#1B74E4",
"primary-button-pressed": "#77A7FF",
"lf-primary-button-disabled": "rgb(176, 213, 255)",
"primary-button-text": "#FFFFFF",
"primary-deemphasized-button-background": "#E7F3FF",
"primary-deemphasized-button-pressed": "rgba(0, 0, 0, 0.05)",
"primary-deemphasized-button-pressed-overlay": "rgba(25, 110, 255, 0.15)",
"primary-deemphasized-button-text": "#1877F2",
"primary-icon": "rgb(15, 20, 25)",
"primary-text": "rgb(15, 20, 25)",
"primary-text-on-media": "#FFFFFF",
"progress-ring-neutral-background": "rgba(190,195,201, 0.2)",
"progress-ring-neutral-foreground": "rgba(0, 0, 0, 0.2)",
"progress-ring-on-media-background": "rgba(255, 255, 255, 0.2)",
"progress-ring-on-media-foreground": "#FFFFFF",
"progress-ring-blue-background": "rgba(24, 119, 242, 0.2)",
"progress-ring-blue-foreground": "hsl(214, 89%, 52%)",
"progress-ring-disabled-background": "rgba(190,195,201, 0.2)",
"progress-ring-disabled-foreground": "#BEC3C9",
"scroll-thumb": "#BCC0C4",
"secondary-button-background": "#E4E6EB",
"secondary-button-background-floating": "#ffffff",
"secondary-button-background-on-dark": "rgba(0, 0, 0, 0.4)",
"secondary-button-pressed": "rgba(0, 0, 0, 0.05)",
"secondary-button-text": "#050505",
"secondary-icon": "rgb(91, 112, 131)",
"secondary-text": "rgb(91, 112, 131)",
"secondary-text-on-media": "rgba(255, 255, 255, 0.9)",
"section-header-text": "#4B4C4F",
"shadow-1": "rgba(0, 0, 0, 0.1)",
"shadow-2": "rgba(0, 0, 0, 0.2)",
"shadow-5": "rgba(0, 0, 0, 0.5)",
"shadow-8": "rgba(0, 0, 0, 0.8)",
"shadow-inset": "rgba(255, 255, 255, 0.5)",
"surface-background": "#FFFFFF",
"text-highlight": "rgba(24, 119, 242, 0.2)",
"toggle-active-background": "#E7F3FF",
"toggle-active-icon": "rgb(24, 119, 242)",
"toggle-active-text": "rgb(24, 119, 242)",
"toggle-button-active-background": "#E7F3FF",
wash: "#E4E6EB",
"web-wash": "#F0F2F5",
warning: "hsl(40, 89%, 52%)",
"dataviz-primary-2": "rgb(134,218,255)",
"dataviz-primary-3": "rgb(95,170,255)",
"dataviz-secondary-1": "rgb(118,62,230)",
"dataviz-secondary-2": "rgb(147,96,247)",
"dataviz-secondary-3": "rgb(219,26,139)",
"dataviz-supplementary-1": "rgb(255,122,105)",
"dataviz-supplementary-2": "rgb(241,168,23)",
"dataviz-supplementary-3": "rgb(49,162,76)",
"dataviz-supplementary-4": "rgb(50,52,54)",
"success-color": "rgb(0, 164, 0)",
"success-disabled-color": "rgb(134, 223, 129)"
}; | the_stack |
'use strict';
import URI from 'vs/base/common/uri';
import {readonly, illegalArgument} from 'vs/base/common/errors';
import {IdGenerator} from 'vs/base/common/idGenerator';
import Event, {Emitter} from 'vs/base/common/event';
import {TPromise} from 'vs/base/common/winjs.base';
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
import {ExtHostDocuments, ExtHostDocumentData} from 'vs/workbench/api/node/extHostDocuments';
import {Selection, Range, Position, EditorOptions, EndOfLine, TextEditorRevealType, TextEditorSelectionChangeKind} from './extHostTypes';
import {ISingleEditOperation} from 'vs/editor/common/editorCommon';
import {IResolvedTextEditorConfiguration, ISelectionChangeEvent} from 'vs/workbench/api/node/mainThreadEditorsTracker';
import * as TypeConverters from './extHostTypeConverters';
import {TextDocument, TextEditorSelectionChangeEvent, TextEditorOptionsChangeEvent, TextEditorOptions, TextEditorViewColumnChangeEvent, ViewColumn} from 'vscode';
import {MainContext, MainThreadEditorsShape, ExtHostEditorsShape, ITextEditorAddData, ITextEditorPositionData} from './extHost.protocol';
export class ExtHostEditors extends ExtHostEditorsShape {
public onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>;
private _onDidChangeTextEditorSelection: Emitter<TextEditorSelectionChangeEvent>;
public onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>;
private _onDidChangeTextEditorOptions: Emitter<TextEditorOptionsChangeEvent>;
public onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>;
private _onDidChangeTextEditorViewColumn: Emitter<TextEditorViewColumnChangeEvent>;
private _editors: { [id: string]: ExtHostTextEditor };
private _proxy: MainThreadEditorsShape;
private _onDidChangeActiveTextEditor: Emitter<vscode.TextEditor>;
private _extHostDocuments: ExtHostDocuments;
private _activeEditorId: string;
private _visibleEditorIds: string[];
constructor(
threadService: IThreadService,
extHostDocuments: ExtHostDocuments
) {
super();
this._onDidChangeTextEditorSelection = new Emitter<TextEditorSelectionChangeEvent>();
this.onDidChangeTextEditorSelection = this._onDidChangeTextEditorSelection.event;
this._onDidChangeTextEditorOptions = new Emitter<TextEditorOptionsChangeEvent>();
this.onDidChangeTextEditorOptions = this._onDidChangeTextEditorOptions.event;
this._onDidChangeTextEditorViewColumn = new Emitter<TextEditorViewColumnChangeEvent>();
this.onDidChangeTextEditorViewColumn = this._onDidChangeTextEditorViewColumn.event;
this._extHostDocuments = extHostDocuments;
this._proxy = threadService.get(MainContext.MainThreadEditors);
this._onDidChangeActiveTextEditor = new Emitter<vscode.TextEditor>();
this._editors = Object.create(null);
this._visibleEditorIds = [];
}
getActiveTextEditor(): vscode.TextEditor {
return this._editors[this._activeEditorId];
}
getVisibleTextEditors(): vscode.TextEditor[] {
return this._visibleEditorIds.map(id => this._editors[id]);
}
get onDidChangeActiveTextEditor(): Event<vscode.TextEditor> {
return this._onDidChangeActiveTextEditor && this._onDidChangeActiveTextEditor.event;
}
showTextDocument(document: TextDocument, column: ViewColumn, preserveFocus: boolean): TPromise<vscode.TextEditor> {
return this._proxy.$tryShowTextDocument(<URI> document.uri, TypeConverters.fromViewColumn(column), preserveFocus).then(id => {
let editor = this._editors[id];
if (editor) {
return editor;
} else {
throw new Error(`Failed to show text document ${document.uri.toString()}, should show in editor #${id}`);
}
});
}
createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
return new TextEditorDecorationType(this._proxy, options);
}
// --- called from main thread
$acceptTextEditorAdd(data: ITextEditorAddData): void {
let document = this._extHostDocuments.getDocumentData(data.document);
let newEditor = new ExtHostTextEditor(this._proxy, data.id, document, data.selections.map(TypeConverters.toSelection), data.options, TypeConverters.toViewColumn(data.editorPosition));
this._editors[data.id] = newEditor;
}
$acceptOptionsChanged(id: string, opts: IResolvedTextEditorConfiguration): void {
let editor = this._editors[id];
editor._acceptOptions(opts);
this._onDidChangeTextEditorOptions.fire({
textEditor: editor,
options: opts
});
}
$acceptSelectionsChanged(id: string, event: ISelectionChangeEvent): void {
const kind = TextEditorSelectionChangeKind.fromValue(event.source);
const selections = event.selections.map(TypeConverters.toSelection);
const textEditor = this._editors[id];
textEditor._acceptSelections(selections);
this._onDidChangeTextEditorSelection.fire({
textEditor,
selections,
kind
});
}
$acceptActiveEditorAndVisibleEditors(id: string, visibleIds: string[]): void {
this._visibleEditorIds = visibleIds;
if (this._activeEditorId === id) {
// nothing to do
return;
}
this._activeEditorId = id;
this._onDidChangeActiveTextEditor.fire(this.getActiveTextEditor());
}
$acceptEditorPositionData(data: ITextEditorPositionData): void {
for (let id in data) {
let textEditor = this._editors[id];
let viewColumn = TypeConverters.toViewColumn(data[id]);
if (textEditor.viewColumn !== viewColumn) {
textEditor._acceptViewColumn(viewColumn);
this._onDidChangeTextEditorViewColumn.fire({ textEditor, viewColumn });
}
}
}
$acceptTextEditorRemove(id: string): void {
// make sure the removed editor is not visible
let newVisibleEditors = this._visibleEditorIds.filter(visibleEditorId => visibleEditorId !== id);
if (this._activeEditorId === id) {
// removing the current active editor
this.$acceptActiveEditorAndVisibleEditors(undefined, newVisibleEditors);
} else {
this.$acceptActiveEditorAndVisibleEditors(this._activeEditorId, newVisibleEditors);
}
let editor = this._editors[id];
editor.dispose();
delete this._editors[id];
}
}
class TextEditorDecorationType implements vscode.TextEditorDecorationType {
private static _Keys = new IdGenerator('TextEditorDecorationType');
private _proxy: MainThreadEditorsShape;
public key: string;
constructor(proxy: MainThreadEditorsShape, options: vscode.DecorationRenderOptions) {
this.key = TextEditorDecorationType._Keys.nextId();
this._proxy = proxy;
this._proxy.$registerTextEditorDecorationType(this.key, <any>options);
}
public dispose(): void {
this._proxy.$removeTextEditorDecorationType(this.key);
}
}
export interface ITextEditOperation {
range: Range;
text: string;
forceMoveMarkers: boolean;
}
export interface IEditData {
documentVersionId: number;
edits: ITextEditOperation[];
setEndOfLine: EndOfLine;
undoStopBefore:boolean;
undoStopAfter:boolean;
}
export class TextEditorEdit {
private _documentVersionId: number;
private _collectedEdits: ITextEditOperation[];
private _setEndOfLine: EndOfLine;
private _undoStopBefore: boolean;
private _undoStopAfter: boolean;
constructor(document: vscode.TextDocument, options:{ undoStopBefore: boolean; undoStopAfter: boolean; }) {
this._documentVersionId = document.version;
this._collectedEdits = [];
this._setEndOfLine = 0;
this._undoStopBefore = options.undoStopBefore;
this._undoStopAfter = options.undoStopAfter;
}
finalize(): IEditData {
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
setEndOfLine: this._setEndOfLine,
undoStopBefore: this._undoStopBefore,
undoStopAfter: this._undoStopAfter
};
}
replace(location: Position | Range | Selection, value: string): void {
let range: Range = null;
if (location instanceof Position) {
range = new Range(location, location);
} else if (location instanceof Range) {
range = location;
} else if (location instanceof Selection) {
range = new Range(location.start, location.end);
} else {
throw new Error('Unrecognized location');
}
this._collectedEdits.push({
range: range,
text: value,
forceMoveMarkers: false
});
}
insert(location: Position, value: string): void {
this._collectedEdits.push({
range: new Range(location, location),
text: value,
forceMoveMarkers: true
});
}
delete(location: Range | Selection): void {
let range: Range = null;
if (location instanceof Range) {
range = location;
} else if (location instanceof Selection) {
range = new Range(location.start, location.end);
} else {
throw new Error('Unrecognized location');
}
this._collectedEdits.push({
range: range,
text: null,
forceMoveMarkers: true
});
}
setEndOfLine(endOfLine:EndOfLine): void {
if (endOfLine !== EndOfLine.LF && endOfLine !== EndOfLine.CRLF) {
throw illegalArgument('endOfLine');
}
this._setEndOfLine = endOfLine;
}
}
function deprecated(name: string, message: string = 'Refer to the documentation for further details.') {
return (target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) => {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.warn(`[Deprecation Warning] method '${name}' is deprecated and should no longer be used. ${message}`);
return originalMethod.apply(this, args);
};
return descriptor;
};
}
class ExtHostTextEditor implements vscode.TextEditor {
private _proxy: MainThreadEditorsShape;
private _id: string;
private _documentData: ExtHostDocumentData;
private _selections: Selection[];
private _options: TextEditorOptions;
private _viewColumn: vscode.ViewColumn;
constructor(proxy: MainThreadEditorsShape, id: string, document: ExtHostDocumentData, selections: Selection[], options: EditorOptions, viewColumn: vscode.ViewColumn) {
this._proxy = proxy;
this._id = id;
this._documentData = document;
this._selections = selections;
this._options = options;
this._viewColumn = viewColumn;
}
dispose() {
this._documentData = null;
}
@deprecated('TextEditor.show') show(column: vscode.ViewColumn) {
this._proxy.$tryShowEditor(this._id, TypeConverters.fromViewColumn(column));
}
@deprecated('TextEditor.hide') hide() {
this._proxy.$tryHideEditor(this._id);
}
// ---- the document
get document(): vscode.TextDocument {
return this._documentData.document;
}
set document(value) {
throw readonly('document');
}
// ---- options
get options(): TextEditorOptions {
return this._options;
}
set options(value: TextEditorOptions) {
this._options = value;
this._runOnProxy(() => {
return this._proxy.$trySetOptions(this._id, this._options);
}, true);
}
_acceptOptions(options: EditorOptions): void {
this._options = options;
}
// ---- view column
get viewColumn(): vscode.ViewColumn {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
_acceptViewColumn(value: vscode.ViewColumn) {
this._viewColumn = value;
}
// ---- selections
get selection(): Selection {
return this._selections && this._selections[0];
}
set selection(value: Selection) {
if (!(value instanceof Selection)) {
throw illegalArgument('selection');
}
this._selections = [value];
this._trySetSelection(true);
}
get selections(): Selection[] {
return this._selections;
}
set selections(value: Selection[]) {
if (!Array.isArray(value) || value.some(a => !(a instanceof Selection))) {
throw illegalArgument('selections');
}
this._selections = value;
this._trySetSelection(true);
}
setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
this._runOnProxy(
() => this._proxy.$trySetDecorations(
this._id,
decorationType.key,
TypeConverters.fromRangeOrRangeWithMessage(ranges)
),
true
);
}
revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
this._runOnProxy(
() => this._proxy.$tryRevealRange(
this._id,
TypeConverters.fromRange(range),
revealType || TextEditorRevealType.Default
),
true
);
}
private _trySetSelection(silent: boolean): TPromise<vscode.TextEditor> {
let selection = this._selections.map(TypeConverters.fromSelection);
return this._runOnProxy(() => this._proxy.$trySetSelections(this._id, selection), silent);
}
_acceptSelections(selections: Selection[]): void {
this._selections = selections;
}
// ---- editing
edit(callback: (edit: TextEditorEdit) => void, options:{ undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Thenable<boolean> {
let edit = new TextEditorEdit(this._documentData.document, options);
callback(edit);
return this._applyEdit(edit);
}
_applyEdit(editBuilder: TextEditorEdit): TPromise<boolean> {
let editData = editBuilder.finalize();
// prepare data for serialization
let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
return {
range: TypeConverters.fromRange(edit.range),
text: edit.text,
forceMoveMarkers: edit.forceMoveMarkers
};
});
return this._proxy.$tryApplyEdits(this._id, editData.documentVersionId, edits, {
setEndOfLine: editData.setEndOfLine,
undoStopBefore: editData.undoStopBefore,
undoStopAfter: editData.undoStopAfter
});
}
// ---- util
private _runOnProxy(callback: () => TPromise<any>, silent: boolean): TPromise<ExtHostTextEditor> {
return callback().then(() => this, err => {
if (!silent) {
return TPromise.wrapError(silent);
}
console.warn(err);
});
}
} | the_stack |
import { from } from 'rxjs';
import { throwError } from 'rxjs/internal/observable/throwError';
import { CacheMissError } from '../src/cache-bridge/cache-miss-error';
import { Cache } from '../src/cache/cache';
import { Client } from '../src/client/client';
import { DataListContainer } from '../src/client/data-list-container';
import { Resource } from '../src/resource/resource';
import { ResourceDescription } from '../src/resource/resource-description';
import { ResourceListContainer } from '../src/resource/resource-list-container';
import { RestCache } from '../src/rest-cache';
describe('RestCache', () => {
let cache: Cache;
let client: Client;
beforeEach(() => {
cache = jasmine.createSpyObj('cache', [
'get',
'getList',
'set',
'setList'
]);
client = jasmine.createSpyObj('client', [
'delete',
'get',
'getList',
'patch',
'post'
]);
});
it('should proxy call to client', () => {
let observable = from([]);
let resourceDescription: ResourceDescription;
let restCache = new RestCache({
client: client
});
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
( <jasmine.Spy> client.delete ).and.returnValue(observable);
expect(restCache.delete({resourceDescription: resourceDescription})).toBe(observable);
});
it('should get resource from client on cache miss', () => {
let data;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
data = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
};
/* Mocking `cache.get` MISS. */
( <jasmine.Spy> cache.get ).and.returnValue(throwError(new CacheMissError()));
/* Mocking `client.get`. */
( <jasmine.Spy> client.get ).and.returnValue(from([data]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.set ).and.returnValue(from([undefined]));
restCache.get({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
}
})
.subscribe(
(resource) => resultList.push(resource),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new Resource({
isFromCache: false,
data: data,
})
]);
/* Check that cache has been used. */
expect(cache.get).toHaveBeenCalledTimes(1);
expect(cache.get).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Client should be called. */
expect(client.get).toHaveBeenCalledTimes(1);
expect(client.get).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs/:blogId',
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that data has been saved in cache. */
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
data: data,
params: {
blogId: 'BLOG_ID_1'
}
}));
});
it('should get resource list from client on cache miss', () => {
let dataListContainer;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
dataListContainer = new DataListContainer({
data: [
{
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
},
{
id: 'BLOG_ID_2',
title: 'BLOG_TITLE_2'
}
],
meta: {
offset: 0,
limit: 10
}
});
/* Mocking `cache.getList` MISS. */
( <jasmine.Spy> cache.getList ).and.returnValue(throwError(new CacheMissError()));
/* Mocking `client.getList`. */
( <jasmine.Spy> client.getList ).and.returnValue(from([dataListContainer]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.setList ).and.returnValue(from([undefined]));
restCache.getList({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
}
})
.subscribe(
(resourceListContainer) => resultList.push(resourceListContainer),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new ResourceListContainer({
isFromCache: false,
data: dataListContainer.data,
meta: dataListContainer.meta
})
]);
/* Check that cache has been used. */
expect(cache.getList).toHaveBeenCalledTimes(1);
expect(cache.getList).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
}
}));
/* Client should be called. */
expect(client.getList).toHaveBeenCalledTimes(1);
expect(client.getList).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs'
}));
/* Check that data has been saved in cache. */
expect(cache.setList).toHaveBeenCalledTimes(1);
expect(cache.setList).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
dataListContainer: dataListContainer,
query: {
offset: 0,
limit: 10
}
}));
});
it('should not get resource from client on cache hit if refresh is false', () => {
let data;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
data = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
};
/* Mocking `cache.get` HIT. */
( <jasmine.Spy> cache.get ).and.returnValue(from([data]));
restCache.get({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
},
refresh: false
})
.subscribe(
(resource) => resultList.push(resource),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new Resource({
isFromCache: true,
data: data,
})
]);
/* Check that cache has been used. */
expect(cache.get).toHaveBeenCalledTimes(1);
expect(cache.get).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that client has not been called. */
expect(client.get).not.toHaveBeenCalled();
/* Check that data has not been saved in cache. */
expect(cache.set).not.toHaveBeenCalled();
});
it('should not get resource list from client on cache hit if refresh is false', () => {
let dataListContainer;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
dataListContainer = new DataListContainer({
data: [
{
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
},
{
id: 'BLOG_ID_2',
title: 'BLOG_TITLE_2'
}
],
meta: {
offset: 0,
limit: 10
}
});
/* Mocking `cache.get` HIT. */
( <jasmine.Spy> cache.getList ).and.returnValue(from([dataListContainer]));
restCache.getList({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
},
refresh: false
})
.subscribe(
(resourceListContainer) => resultList.push(resourceListContainer),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new ResourceListContainer({
isFromCache: true,
data: dataListContainer.data,
meta: dataListContainer.meta
})
]);
/* Check that cache has been used. */
expect(cache.getList).toHaveBeenCalledTimes(1);
expect(cache.getList).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
}
}));
/* Check that client has not been called. */
expect(client.getList).not.toHaveBeenCalled();
/* Check that data has not been saved in cache. */
expect(cache.setList).not.toHaveBeenCalled();
});
it('should get resource from client on cache hit if refresh is true', () => {
let data;
let dataRefreshed;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
data = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
};
dataRefreshed = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1_UPDATE'
};
/* Mocking `cache.get` HIT. */
( <jasmine.Spy> cache.get ).and.returnValue(from([data]));
/* Mocking `client.get`. */
( <jasmine.Spy> client.get ).and.returnValue(from([dataRefreshed]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.set ).and.returnValue(from([undefined]));
restCache.get({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
}
})
.subscribe(
(resource) => resultList.push(resource),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new Resource({
isFromCache: true,
data: data,
}),
new Resource({
isFromCache: false,
data: dataRefreshed,
})
]);
/* Check that cache has been used. */
expect(cache.get).toHaveBeenCalledTimes(1);
expect(cache.get).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that client has been called. */
expect(client.get).toHaveBeenCalledTimes(1);
expect(client.get).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs/:blogId',
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that data has been saved in cache. */
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
data: dataRefreshed,
params: {
blogId: 'BLOG_ID_1'
}
}));
});
it('should get resource list from client on cache hit if refresh is true', () => {
let dataListContainer;
let dataListContainerRefreshed;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
dataListContainer = new DataListContainer({
data: [
{
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
},
{
id: 'BLOG_ID_2',
title: 'BLOG_TITLE_2'
}
],
meta: {
offset: 0,
limit: 10
}
});
dataListContainerRefreshed = new DataListContainer({
data: [
{
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1_UPDATE'
},
{
id: 'BLOG_ID_2',
title: 'BLOG_TITLE_2_UPDATE'
}
],
meta: {
offset: 0,
limit: 10
}
});
/* Mocking `cache.get` HIT. */
( <jasmine.Spy> cache.getList ).and.returnValue(from([dataListContainer]));
/* Mocking `client.getList`. */
( <jasmine.Spy> client.getList ).and.returnValue(from([dataListContainerRefreshed]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.setList ).and.returnValue(from([undefined]));
restCache.getList({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
}
})
.subscribe(
(resourceListContainer) => resultList.push(resourceListContainer),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new ResourceListContainer({
isFromCache: true,
data: dataListContainer.data,
meta: dataListContainer.meta
}),
new ResourceListContainer({
isFromCache: false,
data: dataListContainerRefreshed.data,
meta: dataListContainerRefreshed.meta
})
]);
/* Check that cache has been used. */
expect(cache.getList).toHaveBeenCalledTimes(1);
expect(cache.getList).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
}
}));
/* Check that client has been called. */
expect(client.getList).toHaveBeenCalledTimes(1);
expect(client.getList).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs'
}));
/* Check that data has been saved in cache. */
expect(cache.setList).toHaveBeenCalledTimes(1);
expect(cache.setList).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
dataListContainer: dataListContainerRefreshed,
query: {
offset: 0,
limit: 10
}
}));
});
it('should get resource from client if cache is skipped', () => {
let data;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
data = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
};
/* Mocking `client.get`. */
( <jasmine.Spy> client.get ).and.returnValue(from([data]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.set ).and.returnValue(from([undefined]));
restCache.get({
resourceDescription: resourceDescription,
params: {
blogId: 'BLOG_ID_1'
},
skipCache: true
})
.subscribe(
(resource) => resultList.push(resource),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new Resource({
isFromCache: false,
data: data,
})
]);
/* Check that cache has been used. */
expect(cache.get).not.toHaveBeenCalled();
/* Client should be called. */
expect(client.get).toHaveBeenCalledTimes(1);
expect(client.get).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs/:blogId',
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that data has been saved in cache. */
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
data: data,
params: {
blogId: 'BLOG_ID_1'
}
}));
});
it('should get resource list from client if cache is skipped', () => {
let dataListContainer;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
dataListContainer = new DataListContainer({
data: [
{
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
},
{
id: 'BLOG_ID_2',
title: 'BLOG_TITLE_2'
}
],
meta: {
offset: 0,
limit: 10
}
});
/* Mocking `client.getList`. */
( <jasmine.Spy> client.getList ).and.returnValue(from([dataListContainer]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.setList ).and.returnValue(from([undefined]));
restCache.getList({
resourceDescription: resourceDescription,
query: {
offset: 0,
limit: 10
},
skipCache: true
})
.subscribe(
(resourceListContainer) => resultList.push(resourceListContainer),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new ResourceListContainer({
isFromCache: false,
data: dataListContainer.data,
meta: dataListContainer.meta
})
]);
/* Check that cache has been used. */
expect(cache.getList).not.toHaveBeenCalled();
/* Client should be called. */
expect(client.getList).toHaveBeenCalledTimes(1);
expect(client.getList).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs'
}));
/* Check that data has been saved in cache. */
expect(cache.setList).toHaveBeenCalledTimes(1);
expect(cache.setList).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
dataListContainer: dataListContainer,
query: {
offset: 0,
limit: 10
}
}));
});
it('should update cache when resource is updated', () => {
let data;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
data = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
};
/* Mocking `client.patch`. */
( <jasmine.Spy> client.patch ).and.returnValue(from([data]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.set ).and.returnValue(from([undefined]));
restCache.patch({
resourceDescription: resourceDescription,
data: {
title: 'BLOG_TITLE_1'
},
params: {
blogId: 'BLOG_ID_1'
}
})
.subscribe(
(resource) => resultList.push(resource),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new Resource({
isFromCache: false,
data: data,
})
]);
/* Check that cache has been used. */
expect(cache.get).not.toHaveBeenCalled();
/* Client should be called. */
expect(client.patch).toHaveBeenCalledTimes(1);
expect(client.patch).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs/:blogId',
data: {
title: 'BLOG_TITLE_1'
},
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that data has been saved in cache. */
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
data: data,
params: {
blogId: 'BLOG_ID_1'
}
}));
});
it('should add resource to cache when resource is added', () => {
let data;
let error;
let isComplete;
let resourceDescription: ResourceDescription;
let resultList = [];
let restCache: RestCache;
resourceDescription = new ResourceDescription({path: '/blogs/:blogId'});
restCache = new RestCache({
cache: cache,
client: client
});
data = {
id: 'BLOG_ID_1',
title: 'BLOG_TITLE_1'
};
/* Mocking `client.patch`. */
( <jasmine.Spy> client.post ).and.returnValue(from([data]));
/* Mocking `cache.set`. */
( <jasmine.Spy> cache.set ).and.returnValue(from([undefined]));
restCache.post({
resourceDescription: resourceDescription,
data: {
title: 'BLOG_TITLE_1'
},
params: {
blogId: 'BLOG_ID_1'
}
})
.subscribe(
(resource) => resultList.push(resource),
(_error) => error = _error,
() => isComplete = true
);
expect(error).toBeUndefined();
expect(isComplete).toBe(true);
expect(resultList).toEqual([
new Resource({
isFromCache: false,
data: data,
})
]);
/* Check that cache has been used. */
expect(cache.get).not.toHaveBeenCalled();
/* Client should be called. */
expect(client.post).toHaveBeenCalledTimes(1);
expect(client.post).toHaveBeenCalledWith(jasmine.objectContaining({
path: '/blogs/:blogId',
data: {
title: 'BLOG_TITLE_1'
},
params: {
blogId: 'BLOG_ID_1'
}
}));
/* Check that data has been saved in cache. */
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(jasmine.objectContaining({
resourceDescription: resourceDescription,
data: data,
params: {
blogId: 'BLOG_ID_1'
}
}));
});
}); | the_stack |
import { A } from '@ember/array';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, find, settled } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
//@ts-ignore
import { initialize as injectC3Enhancements } from '@yavin/c3/initializers/inject-c3-enhancements';
//@ts-ignore
import { setupMirage } from 'ember-cli-mirage/test-support';
import { TestContext as Context } from 'ember-test-helpers';
import $ from 'jquery';
import { getTranslation } from '@yavin/c3/utils/chart';
import NaviMetadataService from 'navi-data/services/navi-metadata';
import { Args as ComponentArgs } from '@yavin/c3/components/navi-visualizations/pie-chart';
import { VisualizationModel } from 'navi-core/components/navi-visualizations/table';
import RequestFragment from 'navi-core/models/request';
import NaviFactResponse from '@yavin/client/models/navi-fact-response';
import ColumnFragment from 'navi-core/models/request/column';
const TEMPLATE = hbs`
<NaviVisualizations::PieChart
@model={{this.model}}
@options={{this.options}}
/>`;
interface TestContext extends Context, ComponentArgs {}
let Model: VisualizationModel, Request: RequestFragment, Response: NaviFactResponse;
const RequestJSON = {
table: 'network',
columns: [
{
field: 'totalPageViews',
parameters: {},
type: 'metric',
cid: 'cid_totalPageViews',
source: 'bardOne',
},
{
field: 'uniqueIdentifier',
parameters: {},
type: 'metric',
cid: 'cid_uniqueIdentifier',
source: 'bardOne',
},
{
field: 'age',
parameters: { field: 'desc' },
type: 'dimension',
cid: 'cid_age(field=desc)',
source: 'bardOne',
},
{
field: 'network.dateTime',
parameters: { grain: 'day' },
type: 'timeDimension',
cid: 'cid_network.dateTime(grain=day)',
source: 'bardOne',
},
],
filters: [
{
field: 'network.dateTime',
parameters: { grain: 'day' },
type: 'timeDimension',
operator: 'bet',
values: ['2015-12-14 00:00:00.000', '2015-12-15 00:00:00.000'],
source: 'bardOne',
},
],
sorts: [],
requestVersion: '2.0',
dataSource: 'bardOne',
};
let MetadataService: NaviMetadataService;
module('Integration | Component | pie chart', function (hooks) {
setupRenderingTest(hooks);
setupMirage(hooks);
hooks.beforeEach(async function (this: TestContext) {
injectC3Enhancements();
MetadataService = this.owner.lookup('service:navi-metadata');
await MetadataService.loadMetadata();
Request = this.owner.lookup('service:store').createFragment('request', RequestJSON);
Response = new NaviFactResponse(this.owner.lookup('service:client-injector'), {
rows: [
{
'network.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'age(field=desc)': 'All Other',
uniqueIdentifier: 155191081,
totalPageViews: 310382162,
'revenue(currency=USD)': 200,
'revenue(currency=CAD)': 300,
},
{
'network.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'age(field=desc)': 'Under 13',
uniqueIdentifier: 55191081,
totalPageViews: 2072620639,
'revenue(currency=USD)': 300,
'revenue(currency=CAD)': 256,
},
{
'network.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'age(field=desc)': '13 - 25',
uniqueIdentifier: 55191081,
totalPageViews: 2620639,
'revenue(currency=USD)': 400,
'revenue(currency=CAD)': 5236,
},
{
'network.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'age(field=desc)': '25 - 35',
uniqueIdentifier: 55191081,
totalPageViews: 72620639,
'revenue(currency=USD)': 500,
'revenue(currency=CAD)': 4321,
},
{
'network.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'age(field=desc)': '35 - 45',
uniqueIdentifier: 55191081,
totalPageViews: 72620639,
'revenue(currency=USD)': 600,
'revenue(currency=CAD)': 132,
},
],
});
Model = A([
{
request: Request,
response: Response,
},
]);
this.model = Model;
});
hooks.afterEach(function () {
MetadataService['keg'].reset();
});
test('it renders for a dimension series', async function (assert) {
assert.expect(4);
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_totalPageViews',
dimensions: [
{
name: 'All Other',
values: { 'cid_age(field=desc)': 'All Other' },
},
{
name: 'Under 13',
values: { 'cid_age(field=desc)': 'Under 13' },
},
],
},
},
});
await render(TEMPLATE);
assert.dom('.yavin-c3-chart').isVisible('The pie chart widget component is visible');
assert.dom('.c3-chart-arc').exists({ count: 2 }, 'Two pie slices are present on the chart');
assert
.dom('.chart-series-0 text')
.hasText('13.02%', 'Percentage label shown on slice is formatted properly for `All Other`');
assert
.dom('.chart-series-1 text')
.hasText('86.98%', 'Percentage label shown on slice is formatted properly for `Under 13`');
});
test('it renders for a metric series', async function (assert) {
assert.expect(4);
this.set('options', {
series: {
type: 'metric',
config: {},
},
});
await render(TEMPLATE);
assert.dom('.yavin-c3-chart').isVisible('The pie chart widget component is visible');
assert.dom('.c3-chart-arc').exists({ count: 2 }, 'Two pie slices are present on the chart');
assert
.dom('.chart-series-0 text')
.hasText('66.67%', 'Percentage label shown on slice is formatted properly for `Total Page Views`');
assert
.dom('.chart-series-1 text')
.hasText('33.33%', 'Percentage label shown on slice is formatted properly for `Unique Identifier`');
});
test('metric label', async function (assert) {
assert.expect(7);
this.set('options', {
series: {
type: 'metric',
config: {},
},
});
await render(TEMPLATE);
assert.dom('.c3-title').hasText('', 'The metric label is not visible for a series of type metric');
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_totalPageViews',
dimensions: [
{
name: 'All Other',
values: { 'cid_age(field=desc)': 'All Other' },
},
{
name: 'Under 13',
values: { 'cid_age(field=desc)': 'Under 13' },
},
],
},
},
});
await render(TEMPLATE);
assert.dom('.c3-title').hasText('Total Page Views', 'The metric name is displayed in the metric label correctly');
//Calulate where the metric label should be relative to the pie chart
let chartElm = find('.c3-chart-arcs');
let xTranslate =
getTranslation(chartElm?.getAttribute('transform') as string).x -
(chartElm?.getBoundingClientRect()?.width || 0) / 2 -
50;
let yTranslate: number = ((find('svg')?.getAttribute('height') || 0) as number) / 2;
assert.strictEqual(
Math.round(getTranslation(find('.c3-title')?.getAttribute('transform') as string).x),
Math.round(xTranslate),
'The metric name is in the correct X position on initial render'
);
assert.strictEqual(
Math.round(getTranslation(find('.c3-title')?.getAttribute('transform') as string).y),
Math.round(yTranslate),
'The metric name is in the correct Y position on initial render'
);
/*
* Resize the parent element of the SVG that the pie chart is drawn in
* This effectively moves the pie chart to the left
*/
(find('.pie-chart-widget') as HTMLElement).style.maxWidth = '1000px';
//Rerender with a new metric and new chart position
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_uniqueIdentifier',
dimensions: [
{
name: 'All Other',
values: { 'cid_age(field=desc)': 'All Other' },
},
{
name: 'Under 13',
values: { 'cid_age(field=desc)': 'Under 13' },
},
],
},
},
});
//Recalculate these after the chart is rerendered
chartElm = find('.c3-chart-arcs');
xTranslate =
getTranslation(chartElm?.getAttribute('transform') as string).x -
(chartElm?.getBoundingClientRect().width as number) / 2 -
50;
yTranslate = ($('svg').css('height').replace('px', '') as unknown as number) / 2;
assert.dom('.c3-title').hasText('Unique Identifiers', 'The metric label is updated after the metric is changed');
assert.strictEqual(
Math.round(getTranslation(find('.c3-title')?.getAttribute('transform') as string).x),
Math.round(xTranslate),
'The metric name is in the correct X position after the pie chart moves'
);
assert.strictEqual(
Math.round(getTranslation(find('.c3-title')?.getAttribute('transform') as string).y),
Math.round(yTranslate),
'The metric name is in the correct Y position after the pie chart moves'
);
});
test('metric label - column alias', async function (this: TestContext, assert) {
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_totalPageViews',
dimensions: [
{
name: 'All Other',
values: { 'cid_age(field=desc)': 'All Other' },
},
{
name: 'Under 13',
values: { 'cid_age(field=desc)': 'Under 13' },
},
],
},
},
});
await render(TEMPLATE);
assert.dom('.c3-title').hasText('Total Page Views', 'The metric name is displayed in the metric label correctly');
const metricColumn = this.model.firstObject?.request.columns.firstObject as ColumnFragment;
// set alias
const alias = 'Metric Alias';
metricColumn.set('alias', alias);
await settled();
assert.dom('.c3-title').hasText(alias, 'The metric alias is rendered on update');
// unset alias
metricColumn.set('alias', undefined);
await settled();
assert.dom('.c3-title').hasText('Total Page Views', 'The original metric name is restored on update');
});
test('parameterized metric renders correctly for dimension series', async function (assert) {
const clonedModel = { request: Request, response: Response };
const newColumns = [
...RequestJSON.columns,
{
field: 'revenue',
parameters: { currency: 'USD' },
type: 'metric',
cid: 'cid_revenue(currency=USD)',
source: 'bardOne',
},
];
clonedModel.request = this.owner
.lookup('service:store')
.createFragment('request', { ...RequestJSON, columns: newColumns });
this.set('model', A([clonedModel]));
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_revenue(currency=USD)',
dimensions: [
{
name: 'All Other',
values: { 'cid_age(field=desc)': 'All Other' },
},
{
name: 'Under 13',
values: { 'cid_age(field=desc)': 'Under 13' },
},
],
},
},
});
await render(TEMPLATE);
assert.dom('.c3-title').hasText('Revenue (USD)', 'The metric name is displayed in the metric label correctly');
assert.dom('.yavin-c3-chart').isVisible('The pie chart widget component is visible');
assert.dom('.c3-chart-arc').exists({ count: 2 }, 'Two pie slices are present on the chart');
assert
.dom('.chart-series-0 text')
.hasText('40%', 'Percentage label shown on slice is formatted properly for `All Other`');
assert
.dom('.chart-series-1 text')
.hasText('60%', 'Percentage label shown on slice is formatted properly for `Under 13`');
});
test('renders correctly with multi datasource', async function (assert) {
assert.expect(1);
MetadataService['keg'].reset();
await MetadataService.loadMetadata({ dataSourceName: 'bardTwo' });
const newColumns = [
{
field: 'inventory.dateTime',
type: 'timeDimension',
parameters: { grain: 'day' },
cid: 'cid_inventory.dateTime(grain=day)',
source: 'bardTwo',
},
{
field: 'globallySold',
parameters: {},
type: 'metric',
cid: 'cid_globallySold',
source: 'bardTwo',
},
{
field: 'container',
parameters: { field: 'desc' },
type: 'dimension',
cid: 'cid_container(field=desc)',
source: 'bardTwo',
},
];
const newFilters = [
{
field: 'inventory.dateTime',
parameters: { grain: 'day' },
type: 'timeDimension',
operator: 'bet',
values: ['2015-12-14 00:00:00.000', '2015-12-15 00:00:00.000'],
source: 'bardTwo',
},
];
const bardTwoModel = {
request: this.owner.lookup('service:store').createFragment('request', {
...RequestJSON,
columns: newColumns,
filters: newFilters,
dataSource: 'bardTwo',
}),
response: new NaviFactResponse(this.owner.lookup('service:client-injector'), {
rows: [
{
'inventory.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'container(field=desc)': 'Bag',
globallySold: 155191081,
},
{
'inventory.dateTime(grain=day)': '2015-12-14 00:00:00.000',
'container(field=desc)': 'Bank',
globallySold: 55191081,
},
],
}),
};
this.set('model', A([bardTwoModel]));
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_globallySold',
dimensions: [
{
name: 'Bag',
values: { 'cid_container(field=desc)': 'Bag' },
},
{
name: 'Bank',
values: { 'cid_container(field=desc)': 'Bank' },
},
],
},
},
});
await render(TEMPLATE);
assert
.dom('.c3-title')
.hasText('How many have sold worldwide', 'The metric name is displayed in the metric label correctly');
});
test('parameterized metric renders correctly for metric series', async function (assert) {
assert.expect(4);
const clonedModel = { request: Request, response: Response };
const newColumns = [
{
field: 'network.dateTime',
parameters: { grain: 'day' },
type: 'timeDimension',
cid: 'cid_network.dateTime(grain=day)',
},
{
field: 'revenue',
parameters: { currency: 'USD' },
type: 'metric',
cid: 'cid_revenue(currency=USD)',
},
{
field: 'revenue',
parameters: { currency: 'CAD' },
type: 'metric',
cid: 'cid_revenue(currency=CAD)',
},
];
clonedModel.request = this.owner
.lookup('service:store')
.createFragment('request', { ...RequestJSON, columns: newColumns });
clonedModel.request.columns.forEach((c) => (c.source = Request.dataSource));
this.set('model', A([clonedModel]));
this.set('options', {
series: {
type: 'metric',
config: {},
},
});
await render(TEMPLATE);
assert.dom('.yavin-c3-chart').isVisible('The pie chart widget component is visible');
assert.dom('.c3-chart-arc').exists({ count: 2 }, 'Two pie slices are present on the chart');
assert
.dom('.c3-chart-arc.chart-series-0 text')
.hasText('40%', 'Percentage label shown on slice is formatted properly for `Revenue (USD)`');
assert
.dom('.c3-chart-arc.chart-series-1 text')
.hasText('60%', 'Percentage label shown on slice is formatted properly for `Revenue (CAD)`');
});
test('cleanup tooltip', async function (assert) {
assert.expect(2);
const template = hbs`
{{#if this.shouldRender}}
<NaviVisualizations::PieChart
@model={{this.model}}
@options={{this.options}}
/>
{{/if}}`;
this.set('options', {
series: {
type: 'dimension',
config: {
metricCid: 'cid_totalPageViews',
dimensions: [
{ name: 'All Other', values: { 'cid_age(field=desc)': 'All Other' } },
{ name: 'Under 13', values: { 'cid_age(field=desc)': 'Under 13' } },
],
},
},
});
const owner = this.owner;
type OwnerWithRegistry = typeof owner & {
__registry__: {
registrations: string[];
};
};
const findTooltipComponent = () =>
Object.keys((owner as OwnerWithRegistry).__registry__.registrations).find((r) =>
r.startsWith('component:pie-chart-tooltip-')
);
this.set('model', Model);
this.set('shouldRender', true);
await render(template);
assert.ok(findTooltipComponent(), 'tooltip component is registered when chart is created');
this.set('shouldRender', false);
assert.notOk(findTooltipComponent(), 'tooltip component is unregistered when chart is destroyed');
});
}); | the_stack |
import { t } from 'ttag';
import SimpleSchema from 'simpl-schema';
import './SimpleSchemaExtensions';
import { PersonalProfile, PersonalProfileSchema } from './PersonalProfile';
import { Entrance, EntranceSchema } from './Entrance';
import { Restroom, RestroomSchema } from './Restroom';
import { Staff, StaffSchema } from './Staff';
import { WheelchairPlaces, WheelchairPlacesSchema } from './WheelchairPlaces';
import { Media, MediaSchema } from './Media';
import { Payment, PaymentSchema } from './Payment';
import { AccessibleTablesPrefab, Tables, TablesSchema } from './Tables';
import { Pathways, PathwaysSchema } from './Pathways';
import { Parking, ParkingSchema } from './Parking';
import { Ground, GroundSchema } from './Ground';
import { LocalizedString, LocalizedStringSchema } from './LocalizedString';
import { AnimalPolicySchema, AnimalPolicy } from './AnimalPolicy';
import { SmokingPolicy, smokingPolicies } from './SmokingPolicy';
import { quantityDefinition, Volume, LengthSchema } from './Units';
import { WifiAccessibility, WifiAccessibilitySchema } from './WifiAccessibility';
/**
* Describes the physical (and sometimes human rated) accessibility of a place.
*/
export interface Accessibility {
/// @deprecated
accessibleWith?: PersonalProfile;
/// @deprecated
partiallyAccessibleWith?: PersonalProfile;
/// @deprecated
offersActivitiesForPeopleWith?: PersonalProfile;
// areas?: Array<Area>;
/**
* Information about the service staff.
* `null` indicates there is no staff, `undefined` or missing property indicates unknown.
*/
staff?: Staff | null;
/**
* Information about parking facilities at/around the venue.
* `null` indicates there is no parking, `undefined` or missing property indicates unknown.
*/
parking?: Parking | null;
// QUESTION How is this measured, should be changed to ambient.lighting
/**
* Determines if the venue is well lit (subjectively, by the assessor). Will be replaced by a measurable lumen value in the future.
*/
isWellLit?: boolean;
/**
* Determines if the venue is quiet (subjectively, by the assessor). Will be replaced by a measurable ambient noise level in the future.
*/
isQuiet?: boolean;
// TODO: Causes test error. Fix this!
// ambientNoiseLevel?: Volume; // in dB(A) relative to a reference pressure of 0.00002 Pa
/**
* Object describing the owner's smoking policy.
*/
smokingPolicy?: SmokingPolicy;
/**
* Object describing the owner's policy regarding visitors bringing animals with them.
*/
animalPolicy?: AnimalPolicy;
/**
* `true` if the venue has tactile guide strips on the floor or at the walls, `false` if not. `undefined` or missing property indicates unknown.
*/
hasTactileGuideStrips?: boolean;
/**
* `true` if the venue has induction loops installed in its functional units where this is relevant.
*/
hasInductionLoop?: boolean;
/**
* Describes the Wifi availability and accessibility at the place.
*/
wifi?: WifiAccessibility;
/**
* Object describing the place's ground condition. If there are very different ground conditions, you can create multiple places and nest them.
*/
ground?: Ground | null;
/**
* Describes the accessibility of pathways to the place or inside the place’s boundaries.
*/
pathways?: Pathways | null;
/**
* Describes the accessibility of entrances to the place.
*/
entrances?: ArrayLike<Entrance> | null;
/**
* Describes the accessibility of restrooms in the place.
*/
restrooms?: ArrayLike<Restroom> | null;
/**
* Information about payment at the place.
* `null` indicates there is no payment possible/required,
* `undefined` or missing property indicates unknown.
*/
payment?: Payment | null;
/**
* Information about wheelchair places.
* `null` indicates there are no places, `undefined` or missing property indicates unknown.
*/
wheelchairPlaces?: WheelchairPlaces | null;
/**
* Information about tables.
* `null` indicates there are no tables, `undefined` or missing property indicates unknown.
*/
tables?: Tables | null;
serviceContact?: LocalizedString;
/**
* Information about media.
* `null` indicates there is no media, `undefined` or missing property indicates unknown.
*/
media?: ArrayLike<Media> | null;
/**
* TODO
*/
sitemap?: any; // TODO define type
/**
* TODO
*/
switches?: [any]; // TODO define type
/**
* TODO
*/
vendingMachines?: [any]; // TODO define type
/**
* TODO
*/
powerOutlets?: [any]; // TODO define type
/**
* TODO
*/
beds?: [any]; // TODO define type
/**
* TODO
*/
wardrobe?: any; // TODO define type
/**
* TODO
*/
changingRoom?: any; // TODO define type,
/**
* TODO
*/
stage?: any; // TODO define type,
/**
* TODO
*/
cashRegister?: any; // TODO define type,
/**
* TODO
*/
seats?: any; // TODO define type,
/**
* TODO
*/
services?: any; // TODO define type,,
/**
* TODO
*/
infoDesk?: any; // TODO define type,
/**
* TODO
*/
signage?: any; // TODO define type,
}
export const AccessibilitySchema = new SimpleSchema({
accessibleWith: {
type: PersonalProfileSchema,
optional: true,
accessibility: {
deprecated: true
}
},
partiallyAccessibleWith: {
type: PersonalProfileSchema,
optional: true,
accessibility: {
deprecated: true
}
},
offersActivitiesForPeopleWith: {
type: PersonalProfileSchema,
optional: true,
accessibility: {
deprecated: true
}
},
staff: {
type: StaffSchema,
optional: true,
accessibility: {
question: t`Is there any staff on the premises?`
}
},
wheelchairPlaces: {
type: WheelchairPlacesSchema,
optional: true,
accessibility: {
question: t`Are there any spaces reserved for people in wheelchairs?`
}
},
media: {
type: Array,
optional: true,
accessibility: {
question: t`Is there any media available?`,
questionMore: t`Is there more media available?`,
description: t`e.g. menus, exhibits or presentations`
}
},
'media.$': {
type: MediaSchema
},
payment: {
type: PaymentSchema,
optional: true,
accessibility: {
question: t`Is there any payment possible?`
}
},
parking: {
type: ParkingSchema,
optional: true,
accessibility: {
question: t`Is there parking attached to this place?`
}
},
ground: {
type: GroundSchema,
optional: true,
accessibility: {
question: t`In which condition is the ground you have to traverse to get here?`
}
},
wifi: {
type: WifiAccessibilitySchema,
optional: true,
accessibility: {
question: t`Is there a local wifi?`
}
},
ratingSpacious: {
type: Number,
optional: true,
min: 0,
max: 1,
accessibility: {
deprecated: true,
question: t`How spacious is this place?`,
componentHint: 'StarRating'
}
},
isWellLit: {
type: Boolean,
optional: true,
accessibility: {
question: t`Is the place well lit?`
}
},
isQuiet: {
type: Boolean,
optional: true,
accessibility: {
question: t`Is the place quiet?`
}
},
hasInductionLoop: {
type: Boolean,
optional: true,
accessibility: {
question: t`Does this place have induction loops?`
}
},
// TODO: Causes test error. Fix this!
// ambientNoiseLevel: quantityDefinition(LengthSchema, true, {
// question: t`How loud is the ambient noise here typically (A-Weighted)?`,
// machineData: true
// }),
smokingPolicy: {
type: String,
optional: true,
allowedValues: smokingPolicies.map(s => s.value),
accessibility: {
question: t`Is smoking allowed here?`,
options: smokingPolicies
}
},
hasTactileGuideStrips: {
type: Boolean,
optional: true
},
animalPolicy: {
type: AnimalPolicySchema,
optional: true,
accessibility: {
question: t`What is the animal policy of this place?`
}
},
pathways: {
type: PathwaysSchema,
optional: true
},
entrances: {
type: Array,
optional: true,
label: t`Entrances`,
accessibility: {
questionBlockBegin: t`Would you like to rate the first entrance?`,
questionMore: t`Would you like to rate another entrance?`
}
},
'entrances.$': EntranceSchema,
restrooms: {
type: Array,
optional: true,
label: t`Restrooms`,
accessibility: {
questionBlockBegin: t`Would you like to rate the accessibility of the restroom?`,
questionMore: t`Would you like to rate another restroom?`
}
},
'restrooms.$': RestroomSchema,
tables: {
type: TablesSchema,
optional: true,
accessibility: {
question: t`Are there any tables here?`,
options: [
{
label: t`Accessible table`,
option: AccessibleTablesPrefab
}
]
}
},
sitemap: {
type: Object, // TODO define type
optional: true
},
lifts: {
type: Array,
optional: true
},
'lifts.$': Object, // TODO define type
switches: {
type: Array,
optional: true
},
'switches.$': Object, // TODO define type
vendingMachines: {
type: Array,
optional: true
},
'vendingMachines.$': Object, // TODO define type
powerOutlets: {
type: Array,
optional: true
},
'powerOutlets.$': Object, // TODO define type
beds: {
type: Array,
optional: true
},
'beds.$': Object, // TODO define type
wardrobe: {
type: Object, // TODO define type
optional: true
},
changingRoom: {
type: Object, // TODO define type
optional: true
},
stage: {
type: Object, // TODO define type
optional: true
},
cashRegister: {
type: Object, // TODO define type
optional: true
},
seats: {
type: Object, // TODO define type
optional: true
},
serviceContact: {
type: LocalizedStringSchema,
optional: true,
accessibility: {
question: t`How can the service staff be reached?`
}
},
services: {
type: Object, // TODO define type
optional: true
},
infoDesk: {
type: Object, // TODO define type
optional: true
},
signage: {
type: Object, // TODO define type
optional: true
}
}); | the_stack |
import * as i18n from '../../../../core/i18n/i18n.js';
import * as Platform from '../../../../core/platform/platform.js';
import * as SDK from '../../../../core/sdk/sdk.js';
import * as Formatter from '../../../../models/formatter/formatter.js';
import * as JavaScriptMetaData from '../../../../models/javascript_metadata/javascript_metadata.js';
import * as TextUtils from '../../../../models/text_utils/text_utils.js';
import * as UI from '../../legacy.js';
const UIStrings = {
/**
*@description 0 of suggestions in Java Script Autocomplete
*/
keys: 'Keys',
/**
*@description Text in Java Script Autocomplete
*/
lexicalScopeVariables: 'Lexical scope variables',
/**
*@description Text in Java Script Autocomplete
*/
keywords: 'keywords',
};
const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/object_ui/JavaScriptAutocomplete.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const DEFAULT_TIMEOUT = 500;
let javaScriptAutocompleteInstance: JavaScriptAutocomplete;
export class JavaScriptAutocomplete {
private readonly expressionCache: Map<string, {
date: number,
value: Promise<Array<CompletionGroup>>,
}>;
private constructor() {
this.expressionCache = new Map();
SDK.ConsoleModel.ConsoleModel.instance().addEventListener(
SDK.ConsoleModel.Events.CommandEvaluated, this.clearCache, this);
UI.Context.Context.instance().addFlavorChangeListener(SDK.RuntimeModel.ExecutionContext, this.clearCache, this);
SDK.TargetManager.TargetManager.instance().addModelListener(
SDK.DebuggerModel.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this.clearCache, this);
SDK.TargetManager.TargetManager.instance().addModelListener(
SDK.DebuggerModel.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this.clearCache, this);
}
static instance(): JavaScriptAutocomplete {
if (!javaScriptAutocompleteInstance) {
javaScriptAutocompleteInstance = new JavaScriptAutocomplete();
}
return javaScriptAutocompleteInstance;
}
private clearCache(): void {
this.expressionCache.clear();
}
async completionsForTextInCurrentContext(fullText: string, query: string, force?: boolean):
Promise<UI.SuggestBox.Suggestions> {
const trimmedText = fullText.trim();
const [mapCompletions, expressionCompletions] = await Promise.all(
[this.mapCompletions(trimmedText, query), this.completionsForExpression(trimmedText, query, force)]);
return mapCompletions.concat(expressionCompletions);
}
async argumentsHint(fullText: string): Promise<{
args: Array<Array<string>>,
argumentIndex: number,
}|null|undefined> {
const functionCall = await Formatter.FormatterWorkerPool.formatterWorkerPool().findLastFunctionCall(fullText);
if (!functionCall) {
return null;
}
const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);
if (!executionContext) {
return null;
}
const result = await executionContext.evaluate(
{
expression: functionCall.baseExpression,
objectGroup: 'argumentsHint',
includeCommandLineAPI: true,
silent: true,
returnByValue: false,
generatePreview: false,
throwOnSideEffect: true,
timeout: DEFAULT_TIMEOUT,
allowUnsafeEvalBlockedByCSP: undefined,
disableBreaks: undefined,
replMode: undefined,
},
/* userGesture */ false, /* awaitPromise */ false);
if (!result || 'error' in result || result.exceptionDetails ||
('object' in result && (!result.object || result.object.type !== 'function'))) {
executionContext.runtimeModel.releaseObjectGroup('argumentsHint');
return null;
}
const args = await this.argumentsForFunction(result.object, async () => {
const result = await executionContext.evaluate(
{
expression: functionCall.receiver,
objectGroup: 'argumentsHint',
includeCommandLineAPI: true,
silent: true,
returnByValue: false,
generatePreview: false,
throwOnSideEffect: true,
timeout: DEFAULT_TIMEOUT,
allowUnsafeEvalBlockedByCSP: undefined,
disableBreaks: undefined,
replMode: undefined,
},
/* userGesture */ false, /* awaitPromise */ false);
return (result && !('error' in result) && !result.exceptionDetails && result.object) ? result.object : null;
}, functionCall.functionName);
executionContext.runtimeModel.releaseObjectGroup('argumentsHint');
if (!args.length || (args.length === 1 && (!args[0] || !args[0].length))) {
return null;
}
return {args, argumentIndex: functionCall.argumentIndex};
}
private async argumentsForFunction(
functionObject: SDK.RemoteObject.RemoteObject,
receiverObjGetter: () => Promise<SDK.RemoteObject.RemoteObject|null>,
parsedFunctionName?: string): Promise<string[][]> {
const description = functionObject.description;
if (!description) {
return [];
}
if (!description.endsWith('{ [native code] }')) {
return [await Formatter.FormatterWorkerPool.formatterWorkerPool().argumentsList(description)];
}
// Check if this is a bound function.
if (description === 'function () { [native code] }') {
const properties = await functionObject.getOwnProperties(false);
const internalProperties = properties.internalProperties || [];
const targetProperty = internalProperties.find(property => property.name === '[[TargetFunction]]');
const argsProperty = internalProperties.find(property => property.name === '[[BoundArgs]]');
const thisProperty = internalProperties.find(property => property.name === '[[BoundThis]]');
if (thisProperty && targetProperty && argsProperty && targetProperty.value && thisProperty.value &&
argsProperty.value) {
const thisValue = thisProperty.value;
const originalSignatures =
await this.argumentsForFunction(targetProperty.value, () => Promise.resolve(thisValue));
const boundArgsLength = SDK.RemoteObject.RemoteObject.arrayLength(argsProperty.value);
const clippedArgs = [];
for (const signature of originalSignatures) {
const restIndex = signature.slice(0, boundArgsLength).findIndex(arg => arg.startsWith('...'));
if (restIndex !== -1) {
clippedArgs.push(signature.slice(restIndex));
} else {
clippedArgs.push(signature.slice(boundArgsLength));
}
}
return clippedArgs;
}
}
const javaScriptMetadata = JavaScriptMetaData.JavaScriptMetadata.JavaScriptMetadataImpl.instance();
const descriptionRegexResult = /^function ([^(]*)\(/.exec(description);
const name = descriptionRegexResult && descriptionRegexResult[1] || parsedFunctionName;
if (!name) {
return [];
}
const uniqueSignatures = javaScriptMetadata.signaturesForNativeFunction(name);
if (uniqueSignatures) {
return uniqueSignatures;
}
const receiverObj = await receiverObjGetter();
if (!receiverObj) {
return [];
}
const className = receiverObj.className;
if (className) {
const instanceMethods = javaScriptMetadata.signaturesForInstanceMethod(name, className);
if (instanceMethods) {
return instanceMethods;
}
}
// Check for static methods on a constructor.
if (receiverObj.description && receiverObj.type === 'function' &&
receiverObj.description.endsWith('{ [native code] }')) {
const receiverDescriptionRegexResult = /^function ([^(]*)\(/.exec(receiverObj.description);
if (receiverDescriptionRegexResult) {
const receiverName = receiverDescriptionRegexResult[1];
const staticSignatures = javaScriptMetadata.signaturesForStaticMethod(name, receiverName);
if (staticSignatures) {
return staticSignatures;
}
}
}
let protoNames: string[];
if (receiverObj.type === 'number') {
protoNames = ['Number', 'Object'];
} else if (receiverObj.type === 'string') {
protoNames = ['String', 'Object'];
} else if (receiverObj.type === 'symbol') {
protoNames = ['Symbol', 'Object'];
} else if (receiverObj.type === 'bigint') {
protoNames = ['BigInt', 'Object'];
} else if (receiverObj.type === 'boolean') {
protoNames = ['Boolean', 'Object'];
} else if (receiverObj.type === 'undefined' || receiverObj.subtype === 'null') {
protoNames = [];
} else {
protoNames = await receiverObj.callFunctionJSON(function() {
const result = [];
for (let object: Object = this; object; object = Object.getPrototypeOf(object)) {
if (typeof object === 'object' && object.constructor && object.constructor.name) {
result[result.length] = object.constructor.name;
}
}
return result;
}, []);
}
if (!protoNames) {
return [];
}
for (const proto of protoNames) {
const instanceSignatures = javaScriptMetadata.signaturesForInstanceMethod(name, proto);
if (instanceSignatures) {
return instanceSignatures;
}
}
return [];
}
private async mapCompletions(text: string, query: string): Promise<UI.SuggestBox.Suggestions> {
const mapMatch = text.match(/\.\s*(get|set|delete)\s*\(\s*$/);
const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);
if (!executionContext || !mapMatch) {
return [];
}
const expression =
await Formatter.FormatterWorkerPool.formatterWorkerPool().findLastExpression(text.substring(0, mapMatch.index));
if (!expression) {
return [];
}
const result = await executionContext.evaluate(
{
expression,
objectGroup: 'mapCompletion',
includeCommandLineAPI: true,
silent: true,
returnByValue: false,
generatePreview: false,
throwOnSideEffect: true,
timeout: DEFAULT_TIMEOUT,
allowUnsafeEvalBlockedByCSP: undefined,
disableBreaks: undefined,
replMode: undefined,
},
/* userGesture */ false, /* awaitPromise */ false);
if ('error' in result || Boolean(result.exceptionDetails) || result.object.subtype !== 'map') {
return [];
}
const properties = await result.object.getOwnProperties(false);
const internalProperties = properties.internalProperties || [];
const entriesProperty = internalProperties.find(property => property.name === '[[Entries]]');
if (!entriesProperty || !entriesProperty.value) {
return [];
}
const keysObj = await entriesProperty.value.callFunctionJSON(function() {
const actualThis = (this as {
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
key: any,
}[]);
const result: {
[x: string]: boolean|null,
} = {__proto__: null};
for (let i = 0; i < actualThis.length; i++) {
if (typeof actualThis[i].key === 'string') {
result[actualThis[i].key] = true;
}
}
return result;
}, []);
executionContext.runtimeModel.releaseObjectGroup('mapCompletion');
const rawKeys = Object.keys(keysObj);
const caseSensitivePrefix: UI.SuggestBox.Suggestions = [];
const caseInsensitivePrefix: UI.SuggestBox.Suggestions = [];
const caseSensitiveAnywhere: UI.SuggestBox.Suggestions = [];
const caseInsensitiveAnywhere: UI.SuggestBox.Suggestions = [];
let quoteChar = '"';
if (query.startsWith('\'')) {
quoteChar = '\'';
}
let endChar = ')';
if (mapMatch[0].indexOf('set') !== -1) {
endChar = ', ';
}
const sorter = rawKeys.length < 1000 ? Platform.StringUtilities.naturalOrderComparator : undefined;
const keys = rawKeys.sort(sorter).map(key => quoteChar + key + quoteChar);
for (const key of keys) {
if (key.length < query.length) {
continue;
}
if (query.length && key.toLowerCase().indexOf(query.toLowerCase()) === -1) {
continue;
}
// Substitute actual newlines with newline characters. @see crbug.com/498421
const title = key.split('\n').join('\\n');
const text = title + endChar;
if (key.startsWith(query)) {
caseSensitivePrefix.push(({text: text, title: title, priority: 4} as UI.SuggestBox.Suggestion));
} else if (key.toLowerCase().startsWith(query.toLowerCase())) {
caseInsensitivePrefix.push(({text: text, title: title, priority: 3} as UI.SuggestBox.Suggestion));
} else if (key.indexOf(query) !== -1) {
caseSensitiveAnywhere.push(({text: text, title: title, priority: 2} as UI.SuggestBox.Suggestion));
} else {
caseInsensitiveAnywhere.push(({text: text, title: title, priority: 1} as UI.SuggestBox.Suggestion));
}
}
const suggestions =
caseSensitivePrefix.concat(caseInsensitivePrefix, caseSensitiveAnywhere, caseInsensitiveAnywhere);
if (suggestions.length) {
suggestions[0].subtitle = i18nString(UIStrings.keys);
}
return suggestions;
}
private async completionsForExpression(fullText: string, query: string, force?: boolean):
Promise<UI.SuggestBox.Suggestions> {
const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);
if (!executionContext) {
return [];
}
let expression;
if (fullText.endsWith('?.')) {
expression = await Formatter.FormatterWorkerPool.formatterWorkerPool().findLastExpression(
fullText.substring(0, fullText.length - 2));
} else if (fullText.endsWith('.') || fullText.endsWith('[')) {
expression = await Formatter.FormatterWorkerPool.formatterWorkerPool().findLastExpression(
fullText.substring(0, fullText.length - 1));
}
if (!expression) {
if (fullText.endsWith('.')) {
return [];
}
expression = '';
}
const expressionString = expression;
const dotNotation = fullText.endsWith('.');
const bracketNotation = Boolean(expressionString) && fullText.endsWith('[');
// User is entering float value, do not suggest anything.
if ((expressionString && !isNaN(Number(expressionString))) ||
(!expressionString && query && !isNaN(Number(query)))) {
return [];
}
if (!query && !expressionString && !force) {
return [];
}
const selectedFrame = executionContext.debuggerModel.selectedCallFrame();
let completionGroups: CompletionGroup[]|null;
const TEN_SECONDS = 10000;
let cache = this.expressionCache.get(expressionString);
if (cache && cache.date + TEN_SECONDS > Date.now()) {
completionGroups = await cache.value;
} else if (!expressionString && selectedFrame) {
const value: CompletionGroup[] = [{
items: ['this'],
title: undefined,
}];
const scopeChain = selectedFrame.scopeChain();
const groupPromises = [];
for (const scope of scopeChain) {
groupPromises.push(scope.object()
.getAllProperties(false /* accessorPropertiesOnly */, false /* generatePreview */)
.then(result => ({properties: result.properties, name: scope.name()})));
}
const fullScopes = await Promise.all(groupPromises);
executionContext.runtimeModel.releaseObjectGroup('completion');
for (const scope of fullScopes) {
if (scope.properties) {
value.push({title: scope.name, items: scope.properties.map(property => property.name).sort()});
}
}
cache = {date: Date.now(), value: Promise.resolve(value)};
this.expressionCache.set(expressionString, cache);
completionGroups = await cache.value;
} else {
const resultPromise = executionContext.evaluate(
{
expression: expressionString,
objectGroup: 'completion',
includeCommandLineAPI: true,
silent: true,
returnByValue: false,
generatePreview: false,
throwOnSideEffect: true,
timeout: DEFAULT_TIMEOUT,
allowUnsafeEvalBlockedByCSP: undefined,
disableBreaks: undefined,
replMode: undefined,
},
/* userGesture */ false, /* awaitPromise */ false);
cache = {date: Date.now(), value: resultPromise.then(result => completionsOnGlobal.call(this, result))};
this.expressionCache.set(expressionString, cache);
completionGroups = await cache.value;
}
return this.receivedPropertyNames(completionGroups.slice(0), dotNotation, bracketNotation, expressionString, query);
async function completionsOnGlobal(
this: JavaScriptAutocomplete, result: SDK.RuntimeModel.EvaluationResult): Promise<CompletionGroup[]> {
if ('error' in result || Boolean(result.exceptionDetails) || !result.object) {
return [];
}
if (!executionContext) {
return [];
}
let object: SDK.RemoteObject.RemoteObject = result.object;
while (object && object.type === 'object' && object.subtype === 'proxy') {
const propertiesObject: SDK.RemoteObject.GetPropertiesResult =
await object.getOwnProperties(false /* generatePreview */);
const internalProperties = propertiesObject.internalProperties || [];
const target = internalProperties.find(property => property.name === '[[Target]]');
if (target && target.value) {
object = target.value;
} else {
break;
}
}
if (!object) {
return [];
}
let completions: CompletionGroup[] = [];
if (object.type === 'object' || object.type === 'function') {
completions = (await object.callFunctionJSON(
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(getCompletions as (this: Object, ...arg1: any[]) => Object),
[SDK.RemoteObject.RemoteObject.toCallArgument(object.subtype)]) as CompletionGroup[]) ||
[];
} else if (
object.type === 'string' || object.type === 'number' || object.type === 'boolean' ||
object.type === 'bigint') {
const evaluateResult = await executionContext.evaluate(
{
expression: '(' + getCompletions + ')("' + object.type + '")',
objectGroup: 'completion',
includeCommandLineAPI: false,
silent: true,
returnByValue: true,
generatePreview: false,
allowUnsafeEvalBlockedByCSP: undefined,
disableBreaks: undefined,
replMode: undefined,
throwOnSideEffect: undefined,
timeout: undefined,
},
/* userGesture */ false,
/* awaitPromise */ false);
if (!('error' in evaluateResult) && evaluateResult.object && !evaluateResult.exceptionDetails) {
completions = (evaluateResult.object.value as CompletionGroup[]) || [];
}
}
executionContext.runtimeModel.releaseObjectGroup('completion');
if (!expressionString) {
const globalNames = await executionContext.globalLexicalScopeNames();
if (globalNames) {
// Merge lexical scope names with first completion group on global object: let a and let b should be in the same group.
if (completions.length) {
completions[0].items = completions[0].items.concat(globalNames);
} else {
completions.push({items: globalNames.sort(), title: i18nString(UIStrings.lexicalScopeVariables)});
}
}
}
for (const group of completions) {
for (let i = 0; i < group.items.length; i++) {
group.items[i] = group.items[i].replace(/\n/g, '\\n');
}
group.items.sort(group.items.length < 1000 ? this.itemComparator : undefined);
}
return completions;
function getCompletions(this: Object, type?: string): Object {
let object;
if (type === 'string') {
object = new String('');
} else if (type === 'number') {
object = new Number(0);
}
// Object-wrapped BigInts cannot be constructed via `new BigInt`.
else if (type === 'bigint') {
object = Object(BigInt(0));
} else if (type === 'boolean') {
object = new Boolean(false);
} else {
object = this;
}
const result: CompletionGroup[] = [];
try {
for (let o = object; o; o = Object.getPrototypeOf(o)) {
if ((type === 'array' || type === 'typedarray') && o === object && o.length > 9999) {
continue;
}
const group = ({items: [], title: undefined, __proto__: null} as CompletionGroup);
try {
if (typeof o === 'object' && Object.prototype.hasOwnProperty.call(o, 'constructor') && o.constructor &&
o.constructor.name) {
group.title = o.constructor.name;
}
} catch (ee) {
// we could break upon cross origin check.
}
result[result.length] = group;
const names = Object.getOwnPropertyNames(o);
const isArray = Array.isArray(o);
for (let i = 0; i < names.length && group.items.length < 10000; ++i) {
// Skip array elements indexes.
if (isArray && /^[0-9]/.test(names[i])) {
continue;
}
group.items[group.items.length] = names[i];
}
}
} catch (e) {
}
return result;
}
}
}
private receivedPropertyNames(
propertyGroups: CompletionGroup[]|null, dotNotation: boolean, bracketNotation: boolean, expressionString: string,
query: string): UI.SuggestBox.Suggestions {
if (!propertyGroups) {
return [];
}
const includeCommandLineAPI = (!dotNotation && !bracketNotation);
if (includeCommandLineAPI) {
const commandLineAPI = [
'dir',
'dirxml',
'keys',
'values',
'profile',
'profileEnd',
'monitorEvents',
'unmonitorEvents',
'inspect',
'copy',
'clear',
'getEventListeners',
'debug',
'undebug',
'monitor',
'unmonitor',
'table',
'queryObjects',
'$',
'$$',
'$x',
'$0',
'$_',
];
propertyGroups.push({
items: commandLineAPI,
title: undefined,
});
}
return this.completionsForQuery(dotNotation, bracketNotation, expressionString, query, propertyGroups);
}
private completionsForQuery(
dotNotation: boolean, bracketNotation: boolean, expressionString: string, query: string,
propertyGroups: CompletionGroup[]): UI.SuggestBox.Suggestions {
const quoteUsed = (bracketNotation && query.startsWith('\'')) ? '\'' : '"';
if (!expressionString) {
// See ES2017 spec: https://www.ecma-international.org/ecma-262/8.0/index.html
const keywords = [
// Section 11.6.2.1 Reserved keywords.
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'exports',
'extends',
'finally',
'for',
'function',
'if',
'import',
'in',
'instanceof',
'new',
'return',
'super',
'switch',
'this',
'throw',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
// Section 11.6.2.1's note mentions words treated as reserved in certain cases.
'let',
'static',
// Other keywords not explicitly reserved by spec.
'async',
'of',
];
propertyGroups.push({title: i18nString(UIStrings.keywords), items: keywords.sort()});
}
const allProperties = new Set<string>();
let result: UI.SuggestBox.Suggestion[] = [];
let lastGroupTitle;
const regex = /^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/;
const lowerCaseQuery = query.toLowerCase();
for (const group of propertyGroups) {
const caseSensitivePrefix: UI.SuggestBox.Suggestions = [];
const caseInsensitivePrefix: UI.SuggestBox.Suggestions = [];
const caseSensitiveAnywhere: UI.SuggestBox.Suggestions = [];
const caseInsensitiveAnywhere: UI.SuggestBox.Suggestions = [];
for (let i = 0; i < group.items.length; i++) {
let property: string = group.items[i];
// Assume that all non-ASCII characters are letters and thus can be used as part of identifier.
if (!bracketNotation && !regex.test(property)) {
continue;
}
if (bracketNotation) {
if (!/^[0-9]+$/.test(property)) {
property = quoteUsed + Platform.StringUtilities.escapeCharacters(property, quoteUsed + '\\') + quoteUsed;
}
property += ']';
}
if (allProperties.has(property)) {
continue;
}
if (property.length < query.length) {
continue;
}
const lowerCaseProperty = property.toLowerCase();
if (query.length && lowerCaseProperty.indexOf(lowerCaseQuery) === -1) {
continue;
}
allProperties.add(property);
if (property.startsWith(query)) {
caseSensitivePrefix.push(
({text: property, priority: property === query ? 5 : 4} as UI.SuggestBox.Suggestion));
} else if (lowerCaseProperty.startsWith(lowerCaseQuery)) {
caseInsensitivePrefix.push(({text: property, priority: 3} as UI.SuggestBox.Suggestion));
} else if (property.indexOf(query) !== -1) {
caseSensitiveAnywhere.push(({text: property, priority: 2} as UI.SuggestBox.Suggestion));
} else {
caseInsensitiveAnywhere.push(({text: property, priority: 1} as UI.SuggestBox.Suggestion));
}
}
const structuredGroup =
caseSensitivePrefix.concat(caseInsensitivePrefix, caseSensitiveAnywhere, caseInsensitiveAnywhere);
if (structuredGroup.length && group.title !== lastGroupTitle) {
structuredGroup[0].subtitle = group.title;
lastGroupTitle = group.title;
}
result = result.concat(structuredGroup);
result.forEach(item => {
if (item.text.endsWith(']')) {
item.title = item.text.substring(0, item.text.length - 1);
}
});
}
return result;
}
private itemComparator(a: string, b: string): number {
const aStartsWithUnderscore = a.startsWith('_');
const bStartsWithUnderscore = b.startsWith('_');
if (aStartsWithUnderscore && !bStartsWithUnderscore) {
return 1;
}
if (bStartsWithUnderscore && !aStartsWithUnderscore) {
return -1;
}
return Platform.StringUtilities.naturalOrderComparator(a, b);
}
static async isExpressionComplete(expression: string): Promise<boolean> {
const currentExecutionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);
if (!currentExecutionContext) {
return true;
}
const result =
await currentExecutionContext.runtimeModel.compileScript(expression, '', false, currentExecutionContext.id);
if (!result || !result.exceptionDetails || !result.exceptionDetails.exception) {
return true;
}
const description = result.exceptionDetails.exception.description;
if (description) {
return !description.startsWith('SyntaxError: Unexpected end of input') &&
!description.startsWith('SyntaxError: Unterminated template literal');
}
return false;
}
}
export class JavaScriptAutocompleteConfig {
private readonly editor: UI.TextEditor.TextEditor;
constructor(editor: UI.TextEditor.TextEditor) {
this.editor = editor;
}
static createConfigForEditor(editor: UI.TextEditor.TextEditor): UI.SuggestBox.AutocompleteConfig {
const autocomplete = new JavaScriptAutocompleteConfig(editor);
return {
substituteRangeCallback: autocomplete.substituteRange.bind(autocomplete),
suggestionsCallback: autocomplete.suggestionsCallback.bind(autocomplete),
tooltipCallback: autocomplete.tooltipCallback.bind(autocomplete),
anchorBehavior: undefined,
isWordChar: undefined,
};
}
private substituteRange(lineNumber: number, columnNumber: number): TextUtils.TextRange.TextRange|null {
const token = this.editor.tokenAtTextPosition(lineNumber, columnNumber);
if (token && token.type === 'js-string') {
return new TextUtils.TextRange.TextRange(lineNumber, token.startColumn, lineNumber, columnNumber);
}
const lineText = this.editor.line(lineNumber);
let index;
for (index = columnNumber - 1; index >= 0; index--) {
if (' =:[({;,!+-*/&|^<>.\t\r\n'.indexOf(lineText.charAt(index)) !== -1) {
break;
}
}
return new TextUtils.TextRange.TextRange(lineNumber, index + 1, lineNumber, columnNumber);
}
private async suggestionsCallback(
queryRange: TextUtils.TextRange.TextRange, substituteRange: TextUtils.TextRange.TextRange,
force?: boolean): Promise<UI.SuggestBox.Suggestions> {
const query = this.editor.text(queryRange);
const before =
this.editor.text(new TextUtils.TextRange.TextRange(0, 0, queryRange.startLine, queryRange.startColumn));
const token = this.editor.tokenAtTextPosition(substituteRange.startLine, substituteRange.startColumn);
if (token) {
const excludedTokens = new Set<string>(['js-comment', 'js-string-2', 'js-def']);
const trimmedBefore = before.trim();
if (!trimmedBefore.endsWith('[') && !trimmedBefore.match(/\.\s*(get|set|delete)\s*\(\s*$/)) {
excludedTokens.add('js-string');
}
if (!trimmedBefore.endsWith('.')) {
excludedTokens.add('js-property');
}
if (excludedTokens.has(token.type)) {
return [];
}
}
const queryAndAfter = this.editor.line(queryRange.startLine).substring(queryRange.startColumn);
const words = await JavaScriptAutocomplete.instance().completionsForTextInCurrentContext(before, query, force);
if (!force && queryAndAfter && queryAndAfter !== query &&
words.some(word => queryAndAfter.startsWith(word.text) && query.length !== word.text.length)) {
return [];
}
return words;
}
private async tooltipCallback(lineNumber: number, columnNumber: number): Promise<Element|null> {
const before = this.editor.text(new TextUtils.TextRange.TextRange(0, 0, lineNumber, columnNumber));
const result = await JavaScriptAutocomplete.instance().argumentsHint(before);
if (!result) {
return null;
}
const argumentIndex = result.argumentIndex;
const tooltip = document.createElement('div');
for (const args of result.args) {
const argumentsElement = document.createElement('span');
for (let i = 0; i < args.length; i++) {
if (i === argumentIndex || (i < argumentIndex && args[i].startsWith('...'))) {
argumentsElement.appendChild(UI.Fragment.html`<b>${args[i]}</b>`);
} else {
UI.UIUtils.createTextChild(argumentsElement, args[i]);
}
if (i < args.length - 1) {
UI.UIUtils.createTextChild(argumentsElement, ', ');
}
}
tooltip.appendChild(UI.Fragment.html`<div class='source-code'>\u0192(${argumentsElement})</div>`);
}
return tooltip;
}
}
export interface CompletionGroup {
title?: string;
items: string[];
} | the_stack |
import { fetchAndThrowOnError } from './util';
import * as fsx from 'fs-extra';
import * as path from "path";
import yaml = require('js-yaml');
import * as colors from 'colors';
const CURRENT_EXCEL_RELEASE = 14;
const OLDEST_EXCEL_RELEASE_WITH_CUSTOM_FUNCTIONS = 9;
const CURRENT_OUTLOOK_RELEASE = 10;
const CURRENT_WORD_RELEASE = 3;
const CURRENT_POWERPOINT_RELEASE = 2;
tryCatch(async () => {
// ----
// Clean up Office and Outlook json cross-referencing.
// ----
console.log("\nCleaning up Office json cross-referencing...");
const officeJsonPath = path.resolve("../json/office");
const officeFilename = "office.api.json";
fsx.writeFileSync(
officeJsonPath + '/' + officeFilename,
fsx.readFileSync(officeJsonPath + '/' + officeFilename)
.toString()
.replace(/office\!Office\.Mailbox/g, "outlook!Office.Mailbox")
.replace(/office\!Office\.RoamingSettings/g, "outlook!Office.RoamingSettings"));
console.log("\nCompleted Office json cross-referencing cleanup");
cleanUpJson("outlook");
cleanUpJson("excel");
cleanUpJson("word");
cleanUpJson("powerpoint");
cleanUpJson("onenote");
cleanUpJson("visio");
// ----
// Process Snippets
// ----
console.log("\nRemoving old snippets input files...");
const scriptInputsPath = path.resolve("../script-inputs");
fsx.readdirSync(scriptInputsPath)
.filter(filename => filename.indexOf("snippets") > 0)
.forEach(filename => fsx.removeSync(scriptInputsPath + '/' + filename));
console.log("\nCreating snippets file...");
console.log("\nReading from: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/snippet-extractor-output/snippets.yaml");
fsx.writeFileSync("../script-inputs/script-lab-snippets.yaml", await fetchAndThrowOnError("https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/snippet-extractor-output/snippets.yaml", "text"));
console.log("\nReading from files: " + path.resolve("../../docs/code-snippets"));
const snippetsSourcePath = path.resolve("../../docs/code-snippets");
let localCodeSnippetsString : string = "";
fsx.readdirSync(path.resolve(snippetsSourcePath))
.filter(name => name.endsWith('.yaml') || name.endsWith('.yml'))
.forEach((filename, index) => {
localCodeSnippetsString += fsx.readFileSync(`${snippetsSourcePath}/${filename}`).toString() + "\r\n";
});
fsx.writeFileSync("../script-inputs/local-repo-snippets.yaml", localCodeSnippetsString);
// Parse the YAML into an object/hash set.
let allSnippets: Object = yaml.load(localCodeSnippetsString);
// If a duplicate key exists, merge the Script Lab example(s) into the item with the existing key.
let scriptLabSnippets: Object = yaml.load(fsx.readFileSync(`../script-inputs/script-lab-snippets.yaml`).toString());
for (const key of Object.keys(scriptLabSnippets)) {
if (allSnippets[key]) {
console.log("Combining local and Script Lab snippets for: " + key);
allSnippets[key] = allSnippets[key].concat(scriptLabSnippets[key]);
} else {
allSnippets[key] = scriptLabSnippets[key];
}
}
console.log("\nWriting snippets to: " + path.resolve("../json/snippets.yaml"));
fsx.writeFileSync("../json/snippets.yaml", yaml.safeDump(
allSnippets,
{sortKeys: <any>((a: string, b: string) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
})}
));
console.log("Copying snippets file to subfolders");
const snippetPath = path.resolve("../json/snippets.yaml");
allSnippets = yaml.safeLoad(fsx.readFileSync(snippetPath).toString(), {strict: true});
let commonSnippetKeys = [];
let excelSnippetKeys = [];
let onenoteSnippetKeys = [];
let outlookSnippetKeys = [];
let powerpointSnippetKeys = [];
let visioSnippetKeys = [];
let wordSnippetKeys = [];
let commonText = fsx.readFileSync(path.resolve("../json/office/office.api.json"));
for (const key of Object.keys(allSnippets)) {
if (key.startsWith("Excel")) {
excelSnippetKeys.push(key);
} else if (key.startsWith("OneNote")) {
onenoteSnippetKeys.push(key);
} else if (key.startsWith("PowerPoint")) {
powerpointSnippetKeys.push(key);
} else if (key.startsWith("Visio")) {
visioSnippetKeys.push(key);
} else if (key.startsWith("Word")) {
wordSnippetKeys.push(key);
} else if (key.startsWith("Office")) {
if (commonText.indexOf(key) >= 0) {
commonSnippetKeys.push(key);
} else {
outlookSnippetKeys.push(key);
}
} else {
console.error(colors.red("Unknown snippet key prefix: " + key));
}
}
let commonSnippets = {};
let excelSnippets = {};
let onenoteSnippets = {};
let outlookSnippets = {};
let powerpointSnippets = {};
let visioSnippets = {};
let wordSnippets = {};
commonSnippetKeys.forEach(key => {
commonSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
excelSnippetKeys.forEach(key => {
excelSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
onenoteSnippetKeys.forEach(key => {
onenoteSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
outlookSnippetKeys.forEach(key => {
outlookSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
powerpointSnippetKeys.forEach(key => {
powerpointSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
visioSnippetKeys.forEach(key => {
visioSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
wordSnippetKeys.forEach(key => {
wordSnippets[key] = allSnippets[key];
delete allSnippets[key];
});
writeSnippetFileAndClearYamlIfNew("../json/excel/snippets.yaml", yaml.safeDump(excelSnippets), "excel");
writeSnippetFileAndClearYamlIfNew("../json/excel_online/snippets.yaml", yaml.safeDump(excelSnippets), "excel");
for (let i = CURRENT_EXCEL_RELEASE; i > 0; i--) {
writeSnippetFileAndClearYamlIfNew(`../json/excel_1_${i}/snippets.yaml`, yaml.safeDump(excelSnippets), "excel");
}
writeSnippetFileAndClearYamlIfNew("../json/office/snippets.yaml", yaml.safeDump(commonSnippets), "office");
writeSnippetFileAndClearYamlIfNew("../json/onenote/snippets.yaml", yaml.safeDump(onenoteSnippets), "onenote");
writeSnippetFileAndClearYamlIfNew("../json/outlook/snippets.yaml", yaml.safeDump(outlookSnippets), "outlook");
for (let i = CURRENT_OUTLOOK_RELEASE; i > 0; i--) {
writeSnippetFileAndClearYamlIfNew(`../json/outlook_1_${i}/snippets.yaml`, yaml.safeDump(outlookSnippets), "outlook");
}
writeSnippetFileAndClearYamlIfNew("../json/powerpoint/snippets.yaml", yaml.safeDump(powerpointSnippets), "powerpoint");
for (let i = CURRENT_POWERPOINT_RELEASE; i > 0; i--) {
writeSnippetFileAndClearYamlIfNew(`../json/powerpoint_1_${i}/snippets.yaml`, yaml.safeDump(powerpointSnippets), "powerpoint");
}
writeSnippetFileAndClearYamlIfNew("../json/visio/snippets.yaml", yaml.safeDump(visioSnippets), "visio");
writeSnippetFileAndClearYamlIfNew("../json/word/snippets.yaml", yaml.safeDump(wordSnippets), "word");
for (let i = CURRENT_WORD_RELEASE; i > 0; i--) {
writeSnippetFileAndClearYamlIfNew(`../json/word_1_${i}/snippets.yaml`, yaml.safeDump(wordSnippets), "word");
}
console.log("Moving Custom Functions APIs to correct versions of Excel");
const customFunctionsJson = path.resolve("../json/custom-functions-runtime.api.json");
const officeRuntimeJson = path.resolve("../json/office-runtime.api.json");
fsx.copySync(customFunctionsJson, "../json/excel/custom-functions-runtime.api.json");
for (let i = CURRENT_EXCEL_RELEASE; i >= OLDEST_EXCEL_RELEASE_WITH_CUSTOM_FUNCTIONS; i--) {
fsx.copySync(customFunctionsJson, `../json/excel_1_${i}/custom-functions-runtime.api.json`);
}
fsx.copySync(customFunctionsJson, `../json/excel_online/custom-functions-runtime.api.json`);
console.log("Moving Office Runtime APIs to Common API");
fsx.copySync(officeRuntimeJson, `../json/office/office-runtime.api.json`);
console.log("Cleaning up What's New markdown files.");
let filePath = `../../docs/requirement-set-tables/outlook-preview.md`;
fsx.writeFileSync(filePath, cleanUpOutlookMarkdown(fsx.readFileSync(filePath).toString()));
for (let i = CURRENT_OUTLOOK_RELEASE; i > 0; i--) {
filePath = `../../docs/requirement-set-tables/outlook-1_${i}.md`;
fsx.writeFileSync(filePath, cleanUpOutlookMarkdown(fsx.readFileSync(filePath).toString()));
}
});
function cleanUpJson(host: string) {
console.log(`\nCleaning up ${host} json cross-referencing...`);
const jsonPath = path.resolve(`../json/${host}`);
const fileName = `${host}.api.json`;
console.log(`\nStarting ${host}...`);
let json = fsx.readFileSync(`${jsonPath}/${fileName}`).toString();
let cleanJson;
if (host === "outlook") {
cleanJson = cleanUpOutlookJson(json);
} else {
cleanJson = cleanUpRichApiJson(json);
}
fsx.writeFileSync(`${jsonPath}/${fileName}`, cleanJson);
console.log(`\nCompleted ${host}`);
let currentRelease;
if (host === "outlook") {
currentRelease = CURRENT_OUTLOOK_RELEASE;
} else if (host === "excel") {
currentRelease = CURRENT_EXCEL_RELEASE;
// Handle ExcelApiOnline corner case.
console.log(`\nStarting ${host}_online...`);
json = fsx.readFileSync(`${jsonPath}_online/${fileName}`).toString();
fsx.writeFileSync(`${jsonPath}_online/${fileName}`, cleanUpRichApiJson(json));
console.log(`\nCompleted ${host}_online`);
} else if (host === "word") {
currentRelease = CURRENT_WORD_RELEASE;
} else if (host === "powerpoint") {
currentRelease = CURRENT_POWERPOINT_RELEASE;
} else {
currentRelease = 0;
}
if (currentRelease > 0) {
for (let i = currentRelease; i > 0; i--) {
console.log(`\nStarting ${host}_1_${i}...`);
json = fsx.readFileSync(`${jsonPath}_1_${i}/${fileName}`).toString();
if (host === "outlook") {
cleanJson = cleanUpOutlookJson(json);
} else {
cleanJson = cleanUpRichApiJson(json);
}
fsx.writeFileSync(`${jsonPath}_1_${i}/${fileName}`, cleanJson);
console.log(`Completed ${host}_1_${i}`);
}
}
console.log(`\nCompleted ${host} json cross-referencing cleanup`);
}
function cleanUpOutlookJson(jsonString : string) {
return jsonString.replace(/(\"CommonAPI\.\w+",[\s]+"canonicalReference": ")outlook!/gm, "$1office!");
}
function cleanUpRichApiJson(jsonString : string) {
return jsonString.replace(/(excel|word|visio|onenote|powerpoint)\!OfficeExtension/g, "office!OfficeExtension");
}
function cleanUpOutlookMarkdown(markdownString : string) {
return markdownString.replace(/CommonAPI/gm, "Office");
}
function writeSnippetFileAndClearYamlIfNew(snippetsFilePath: string, snippetsContent: string, keyword: string) {
const yamlRoot = "../yaml";
let existingSnippets = "";
if (fsx.existsSync(snippetsFilePath)) {
existingSnippets = fsx.readFileSync(snippetsFilePath).toString();
}
if (existingSnippets !== snippetsContent) {
fsx.writeFileSync(snippetsFilePath, snippetsContent);
fsx.readdirSync(yamlRoot).forEach((yamlFolder) => {
if (yamlFolder.indexOf(keyword) >= 0) {
console.log(`Removing ${yamlRoot}/${yamlFolder}`);
fsx.removeSync(`${yamlRoot}/${yamlFolder}`);
}
});
}
}
async function tryCatch(call: () => Promise<void>) {
try {
await call();
} catch (e) {
console.error(e);
process.exit(1);
}
} | the_stack |
import { ObjectType, ElemID, InstanceElement, Element, BuiltinTypes, isInstanceElement, ReferenceExpression, ListType } from '@salto-io/adapter-api'
import { extractStandaloneFields } from '../../../src/elements/ducktype/standalone_field_extractor'
const ADAPTER_NAME = 'myAdapter'
describe('Extract standalone fields', () => {
const generateElements = (jsonCode: boolean): Element[] => {
const recipeType = new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'recipe'),
fields: {
name: { refType: BuiltinTypes.STRING },
code: { refType: BuiltinTypes.STRING },
},
})
const connectionType = new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'connection'),
fields: {
name: { refType: BuiltinTypes.STRING },
application: { refType: BuiltinTypes.STRING },
code: { refType: BuiltinTypes.STRING },
},
})
const instances = [
new InstanceElement(
'recipe123',
recipeType,
{
name: 'recipe123',
code: jsonCode ? '{"flat":"a","nested":{"inner":"abc"}}' : { flat: 'a', nested: { inner: 'abc' } },
},
),
new InstanceElement(
'recipe456',
recipeType,
{
name: 'recipe456',
code: jsonCode ? '{"nested":{"inner":"def","other":"ghi"}}' : { nested: { inner: 'def', other: 'ghi' } },
},
),
new InstanceElement(
'conn',
connectionType,
{
name: 'conn',
code: 'ignore',
},
),
]
const typeWithNoInstances = new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'typeWithNoInstances'),
})
return [recipeType, connectionType, ...instances, typeWithNoInstances]
}
const transformationDefaultConfig = {
idFields: ['id'],
}
const transformationConfigByType = {
recipe: {
standaloneFields: [
{ fieldName: 'code', parseJSON: true },
],
},
nonexistentType: {
fieldsToOmit: [
{ fieldName: 'created_at', fieldType: 'string' },
{ fieldName: 'updated_at', fieldType: 'string' },
{ fieldName: 'last_run_at' },
{ fieldName: 'job_succeeded_count' },
{ fieldName: 'job_failed_count' },
],
standaloneFields: [
{ fieldName: 'code', parseJSON: true },
],
},
typeWithNoInstances: {
standaloneFields: [
{ fieldName: 'something' },
],
},
// override existing type with nonexistent standalone field
connection: {
standaloneFields: [
{ fieldName: 'nonexistent' },
],
},
}
describe('extract code fields to their own instances when the value is an object', () => {
let elements: Element[]
let origInstances: InstanceElement[]
let numElements: number
beforeAll(async () => {
elements = generateElements(false)
origInstances = elements.filter(isInstanceElement).map(e => e.clone())
numElements = elements.length
await extractStandaloneFields({
elements,
adapterName: ADAPTER_NAME,
transformationConfigByType,
transformationDefaultConfig,
})
})
it('should add two types and two instances', () => {
expect(elements.length).toEqual(numElements + 4)
})
it('should modify the recipe type', async () => {
const recipeType = elements[0] as ObjectType
expect(await recipeType.fields.code.getType()).toBeInstanceOf(ObjectType)
const codeType = await recipeType.fields.code.getType() as ObjectType
expect(codeType.isEqual(new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'recipe__code'),
fields: {
flat: { refType: BuiltinTypes.STRING },
nested: { refType: new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'recipe__code__nested'),
fields: {
inner: { refType: BuiltinTypes.STRING },
},
}) },
},
}))).toBeTruthy()
})
it('should create new recipe__code instances and reference them', () => {
expect(elements[2]).toBeInstanceOf(InstanceElement)
expect(elements[3]).toBeInstanceOf(InstanceElement)
const recipe123 = elements[2] as InstanceElement
const recipe456 = elements[3] as InstanceElement
expect(elements[6]).toBeInstanceOf(ObjectType)
expect(elements[7]).toBeInstanceOf(ObjectType)
expect(elements[8]).toBeInstanceOf(InstanceElement)
expect(elements[9]).toBeInstanceOf(InstanceElement)
const recipeCode = elements[6] as ObjectType
const recipeCodeNested = elements[7] as ObjectType
const recipe123Code = elements[8] as InstanceElement
const recipe456Code = elements[9] as InstanceElement
expect(Object.keys(recipeCode.fields)).toEqual(['flat', 'nested'])
expect(Object.keys(recipeCodeNested.fields)).toEqual(['inner', 'other'])
expect(recipe123Code.refType.elemID.isEqual(recipeCode.elemID)).toBeTruthy()
expect(recipe456Code.refType.elemID.isEqual(recipeCode.elemID)).toBeTruthy()
const origRecipe123 = origInstances[0]
const origRecipe456 = origInstances[1]
expect(recipe123Code.value).toEqual(origRecipe123.value.code)
expect(recipe456Code.value).toEqual(origRecipe456.value.code)
expect(recipe123.value.code).toBeInstanceOf(ReferenceExpression)
expect(recipe456.value.code).toBeInstanceOf(ReferenceExpression)
expect((recipe123.value.code as ReferenceExpression).elemID.getFullName()).toEqual(
recipe123Code.elemID.getFullName()
)
expect((recipe456.value.code as ReferenceExpression).elemID.getFullName()).toEqual(
recipe456Code.elemID.getFullName()
)
})
it('should not modify the connection type', () => {
const connectionType = elements[1] as ObjectType
expect(connectionType.fields.code.refType.elemID.isEqual(BuiltinTypes.STRING.elemID))
.toBeTruthy()
})
})
describe('extract code fields to their own instances when the value is an array of objects', () => {
let elements: Element[]
let origInstances: InstanceElement[]
let numElements: number
const generateElementsWithList = (): Element[] => {
const recipeType = new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'recipe'),
fields: {
name: { refType: BuiltinTypes.STRING },
code: { refType: new ListType(BuiltinTypes.STRING) },
},
})
const connectionType = new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'connection'),
fields: {
name: { refType: BuiltinTypes.STRING },
application: { refType: BuiltinTypes.STRING },
code: { refType: BuiltinTypes.STRING },
},
})
const instance = new InstanceElement(
'recipe123',
recipeType,
{
name: 'recipe123',
code: [{ flat: 'a', nested: { inner: 'abc' } }, { flat: 'b', nested: { inner: 'abc' } }],
},
)
return [recipeType, connectionType, instance]
}
beforeAll(async () => {
elements = generateElementsWithList()
origInstances = elements.filter(isInstanceElement).map(e => e.clone())
numElements = elements.length
await extractStandaloneFields({
elements,
adapterName: ADAPTER_NAME,
transformationConfigByType,
transformationDefaultConfig,
})
})
it('should add two types and two instances', () => {
expect(elements.length).toEqual(numElements + 4)
})
it('should create new recipe__code instances and reference them', () => {
expect(elements[2]).toBeInstanceOf(InstanceElement)
const recipe123 = elements[2] as InstanceElement
expect(elements[3]).toBeInstanceOf(ObjectType)
expect(elements[4]).toBeInstanceOf(ObjectType)
expect(elements[5]).toBeInstanceOf(InstanceElement)
expect(elements[6]).toBeInstanceOf(InstanceElement)
const recipeCode = elements[3] as ObjectType
const recipe123Code1 = elements[5] as InstanceElement
const recipe123Code2 = elements[6] as InstanceElement
expect(recipe123Code1.refType.elemID.isEqual(recipeCode.elemID)).toBeTruthy()
expect(recipe123Code2.refType.elemID.isEqual(recipeCode.elemID)).toBeTruthy()
const origRecipe123 = origInstances[0]
expect(recipe123Code1.value).toEqual(origRecipe123.value.code[0])
expect(recipe123Code2.value).toEqual(origRecipe123.value.code[1])
expect(recipe123.value.code[0]).toBeInstanceOf(ReferenceExpression)
expect(recipe123.value.code[1]).toBeInstanceOf(ReferenceExpression)
expect((recipe123.value.code[0] as ReferenceExpression).elemID.getFullName()).toEqual(
recipe123Code1.elemID.getFullName()
)
expect((recipe123.value.code[1] as ReferenceExpression).elemID.getFullName()).toEqual(
recipe123Code2.elemID.getFullName()
)
})
it('should not modify the connection type', () => {
const connectionType = elements[1] as ObjectType
expect(connectionType.fields.code.refType.elemID.isEqual(BuiltinTypes.STRING.elemID))
.toBeTruthy()
})
})
describe('extract code fields to their own instances when the value is a serialized json of an object', () => {
let elements: Element[]
let origInstances: InstanceElement[]
let numElements: number
beforeAll(async () => {
elements = generateElements(true)
origInstances = elements.filter(isInstanceElement).map(e => e.clone())
numElements = elements.length
await extractStandaloneFields({
elements,
adapterName: ADAPTER_NAME,
transformationConfigByType,
transformationDefaultConfig,
})
})
it('should add two types and two instances', () => {
expect(elements.length).toEqual(numElements + 4)
})
it('should modify the recipe type', async () => {
const recipeType = elements[0] as ObjectType
expect(await recipeType.fields.code.getType()).toBeInstanceOf(ObjectType)
const codeType = await recipeType.fields.code.getType() as ObjectType
expect(codeType.isEqual(new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'recipe__code'),
fields: {
flat: { refType: BuiltinTypes.STRING },
nested: { refType: new ObjectType({
elemID: new ElemID(ADAPTER_NAME, 'recipe__code__nested'),
fields: {
inner: { refType: BuiltinTypes.STRING },
},
}) },
},
}))).toBeTruthy()
})
it('should create new recipe__code instances and reference them', () => {
expect(elements[2]).toBeInstanceOf(InstanceElement)
expect(elements[3]).toBeInstanceOf(InstanceElement)
const recipe123 = elements[2] as InstanceElement
const recipe456 = elements[3] as InstanceElement
expect(elements[6]).toBeInstanceOf(ObjectType)
expect(elements[7]).toBeInstanceOf(ObjectType)
expect(elements[8]).toBeInstanceOf(InstanceElement)
expect(elements[9]).toBeInstanceOf(InstanceElement)
const recipeCode = elements[6] as ObjectType
const recipeCodeNested = elements[7] as ObjectType
const recipe123Code = elements[8] as InstanceElement
const recipe456Code = elements[9] as InstanceElement
expect(Object.keys(recipeCode.fields)).toEqual(['flat', 'nested'])
expect(Object.keys(recipeCodeNested.fields)).toEqual(['inner', 'other'])
expect(recipe123Code.refType.elemID.isEqual(recipeCode.elemID)).toBeTruthy()
expect(recipe456Code.refType.elemID.isEqual(recipeCode.elemID)).toBeTruthy()
const origRecipe123 = origInstances[0]
const origRecipe456 = origInstances[1]
expect(recipe123Code.value).toEqual(JSON.parse(origRecipe123.value.code))
expect(recipe456Code.value).toEqual(JSON.parse(origRecipe456.value.code))
expect(recipe123.value.code).toBeInstanceOf(ReferenceExpression)
expect(recipe456.value.code).toBeInstanceOf(ReferenceExpression)
expect((recipe123.value.code as ReferenceExpression).elemID.getFullName()).toEqual(
recipe123Code.elemID.getFullName()
)
expect((recipe456.value.code as ReferenceExpression).elemID.getFullName()).toEqual(
recipe456Code.elemID.getFullName()
)
})
it('should not modify the connection type', () => {
const connectionType = elements[1] as ObjectType
expect(connectionType.fields.code.refType.elemID.isEqual(BuiltinTypes.STRING.elemID))
.toBeTruthy()
})
})
describe('keep original code fields when not all values are an object or a serialized object', () => {
let elements: Element[]
let origInstances: InstanceElement[]
let numElements: number
beforeAll(async () => {
elements = generateElements(false)
const recipe456 = elements[3] as InstanceElement
recipe456.value.code = 'invalid'
origInstances = elements.filter(isInstanceElement).map(e => e.clone())
numElements = elements.length
await extractStandaloneFields({
elements,
adapterName: ADAPTER_NAME,
transformationConfigByType,
transformationDefaultConfig,
})
})
it('should not modify elements', () => {
expect(elements.length).toEqual(numElements)
})
it('should not modify the recipe type', () => {
const recipeType = elements[0] as ObjectType
expect(recipeType.fields.code.refType.elemID.isEqual(BuiltinTypes.STRING.elemID)).toBeTruthy()
expect(elements[2]).toEqual(origInstances[0])
expect(elements[3]).toEqual(origInstances[1])
expect(elements[4]).toEqual(origInstances[2])
})
})
describe('keep original code fields when not all values are an object or a serialized object, with {', () => {
let elements: Element[]
let origInstances: InstanceElement[]
let numElements: number
beforeAll(async () => {
elements = generateElements(false)
const recipe456 = elements[3] as InstanceElement
recipe456.value.code = '{invalid'
origInstances = elements.filter(isInstanceElement).map(e => e.clone())
numElements = elements.length
await extractStandaloneFields({
elements,
adapterName: ADAPTER_NAME,
transformationConfigByType,
transformationDefaultConfig,
})
})
it('should not modify elements', () => {
expect(elements.length).toEqual(numElements)
})
it('should not modify the recipe type', () => {
const recipeType = elements[0] as ObjectType
expect(recipeType.fields.code.refType.elemID.isEqual(BuiltinTypes.STRING.elemID)).toBeTruthy()
expect(elements[2]).toEqual(origInstances[0])
expect(elements[3]).toEqual(origInstances[1])
expect(elements[4]).toEqual(origInstances[2])
})
})
}) | the_stack |
import * as utils from '../util/utils'
import { EVENT, RecordMessage } from '../constants'
import { RecordCore, WriteAckCallback } from './record-core'
import { Emitter } from '../util/emitter'
export class List extends Emitter {
public debugId = this.record.getDebugId()
private wrappedFunctions: Map<Function, Function> = new Map()
private originalApplyUpdate: Function
private beforeStructure: any
private hasAddListener: boolean = false
private hasRemoveListener: boolean = false
private hasMoveListener: boolean = false
private subscriptions: utils.RecordSubscribeArguments[] = []
constructor (private record: RecordCore<List>) {
super()
this.originalApplyUpdate = this.record.applyUpdate.bind(this.record)
this.record.applyUpdate = this.applyUpdate.bind(this)
this.record.addReference(this)
this.record.on('discard', () => this.emit('discard', this), this)
this.record.on('delete', () => this.emit('delete', this), this)
this.record.on('error', (...args: any[]) => this.emit('error', ...args), this)
}
get name (): string {
return this.record.name
}
get isReady (): boolean {
return this.record.isReady
}
get version (): number {
return this.record.version as number
}
public whenReady (): Promise<List>
public whenReady (callback: ((list: List) => void)): void
public whenReady (callback?: ((list: List) => void)): void | Promise<List> {
if (callback) {
this.record.whenReady(this, callback)
} else {
return this.record.whenReady(this)
}
}
public discard (): void {
this.destroy()
this.record.removeReference(this)
}
public delete (callback: (error: string | null) => void): void
public delete (): Promise<void>
public delete (callback?: (error: string | null) => void): void | Promise<void> {
this.destroy()
return this.record.delete(callback)
}
/**
* Returns the array of list entries or an
* empty array if the list hasn't been populated yet.
*/
public getEntries (): string[] {
const entries = this.record.get()
if (!(entries instanceof Array)) {
return []
}
return entries as string[]
}
/**
* Returns true if the list is empty
*/
public isEmpty (): boolean {
return this.getEntries().length === 0
}
/**
* Updates the list with a new set of entries
*/
public setEntriesWithAck (entries: string[]): Promise<void>
public setEntriesWithAck (entries: string[], callback: WriteAckCallback): void
public setEntriesWithAck (entries: string[], callback?: WriteAckCallback): Promise<void> | void {
if (!callback) {
return new Promise(( resolve, reject ) => {
this.setEntries(entries, (error: string | null) => {
if (error) {
reject(error)
} else {
resolve()
}
})
})
}
this.setEntries(entries, callback)
}
/**
* Updates the list with a new set of entries
*/
public setEntries (entries: string[], callback?: WriteAckCallback) {
const errorMsg = 'entries must be an array of record names'
let i
if (!(entries instanceof Array)) {
throw new Error(errorMsg)
}
for (i = 0; i < entries.length; i++) {
if (typeof entries[i] !== 'string') {
throw new Error(errorMsg)
}
}
this.beforeChange()
this.record.set({ data: entries, callback })
this.afterChange()
}
/**
* Removes an entry from the list
*
* @param {String} entry
* @param {Number} [index]
*/
public removeEntry (entry: string, index?: number, callback?: WriteAckCallback) {
// @ts-ignore
const currentEntries: string[] = this.record.get()
const hasIndex = this.hasIndex(index)
const entries: string[] = []
let i
for (i = 0; i < currentEntries.length; i++) {
if (currentEntries[i] !== entry || (hasIndex && index !== i)) {
entries.push(currentEntries[i])
}
}
this.beforeChange()
this.record.set({ data: entries, callback })
this.afterChange()
}
/**
* Adds an entry to the list
*
* @param {String} entry
* @param {Number} [index]
*/
public addEntry (entry: string, index?: number, callback?: WriteAckCallback) {
if (typeof entry !== 'string') {
throw new Error('Entry must be a recordName')
}
const hasIndex = this.hasIndex(index)
const entries = this.getEntries()
if (hasIndex) {
entries.splice(index as number, 0, entry)
} else {
entries.push(entry)
}
this.beforeChange()
this.record.set({ data: entries, callback })
this.afterChange()
}
/**
* Proxies the underlying Record's subscribe method. Makes sure
* that no path is provided
*/
public subscribe (callback: (entries: string[]) => void) {
const parameters = utils.normalizeArguments(arguments)
if (parameters.path) {
throw new Error('path is not supported for List.subscribe')
}
// Make sure the callback is invoked with an empty array for new records
const listCallback = function (scope: any, cb: Function) {
cb(scope.getEntries())
}.bind(this, this, parameters.callback)
/**
* Adding a property onto a function directly is terrible practice,
* and we will change this as soon as we have a more seperate approach
* of creating lists that doesn't have records default state.
*
* The reason we are holding a referencing to wrapped array is so that
* on unsubscribe it can provide a reference to the actual method the
* record is subscribed too.
**/
this.wrappedFunctions.set(parameters.callback, listCallback)
parameters.callback = listCallback
this.subscriptions.push(parameters)
this.record.subscribe(parameters, this)
}
/**
* Proxies the underlying Record's unsubscribe method. Makes sure
* that no path is provided
*/
public unsubscribe (callback: (entries: string[]) => void) {
const parameters = utils.normalizeArguments(arguments)
if (parameters.path) {
throw new Error('path is not supported for List.unsubscribe')
}
const listenCallback = this.wrappedFunctions.get(parameters.callback)
parameters.callback = listenCallback as (data: any) => void
this.wrappedFunctions.delete(parameters.callback)
this.subscriptions = this.subscriptions.filter((subscription: any) => {
if (parameters.callback && parameters.callback !== subscription.callback) return true
return false
})
this.record.unsubscribe(parameters, this)
}
/**
* Proxies the underlying Record's _update method. Set's
* data to an empty array if no data is provided.
*/
private applyUpdate (message: RecordMessage) {
if (!(message.parsedData instanceof Array)) {
message.parsedData = []
}
this.beforeChange()
this.originalApplyUpdate(message)
this.afterChange()
}
/**
* Validates that the index provided is within the current set of entries.
*/
private hasIndex (index?: number) {
let hasIndex = false
const entries = this.getEntries()
if (index !== undefined) {
if (isNaN(index)) {
throw new Error('Index must be a number')
}
if (index !== entries.length && (index >= entries.length || index < 0)) {
throw new Error('Index must be within current entries')
}
hasIndex = true
}
return hasIndex
}
/**
* Establishes the current structure of the list, provided the client has attached any
* add / move / remove listener
*
* This will be called before any change to the list, regardsless if the change was triggered
* by an incoming message from the server or by the client
*/
private beforeChange (): void {
this.hasAddListener = this.hasListeners(EVENT.ENTRY_ADDED_EVENT)
this.hasRemoveListener = this.hasListeners(EVENT.ENTRY_REMOVED_EVENT)
this.hasMoveListener = this.hasListeners(EVENT.ENTRY_MOVED_EVENT)
if (this.hasAddListener || this.hasRemoveListener || this.hasMoveListener) {
this.beforeStructure = this.getStructure()
} else {
this.beforeStructure = null
}
}
/**
* Compares the structure of the list after a change to its previous structure and notifies
* any add / move / remove listener. Won't do anything if no listeners are attached.
*/
private afterChange (): void {
if (this.beforeStructure === null) {
return
}
const after = this.getStructure()
const before = this.beforeStructure
let entry
let i
if (this.hasRemoveListener) {
for (entry in before) {
for (i = 0; i < before[entry].length; i++) {
if (after[entry] === undefined || after[entry][i] === undefined) {
this.emit(EVENT.ENTRY_REMOVED_EVENT, entry, before[entry][i])
}
}
}
}
if (this.hasAddListener || this.hasMoveListener) {
for (entry in after) {
if (before[entry] === undefined) {
for (i = 0; i < after[entry].length; i++) {
this.emit(EVENT.ENTRY_ADDED_EVENT, entry, after[entry][i])
}
} else {
for (i = 0; i < after[entry].length; i++) {
if (before[entry][i] !== after[entry][i]) {
if (before[entry][i] === undefined) {
this.emit(EVENT.ENTRY_ADDED_EVENT, entry, after[entry][i])
} else {
this.emit(EVENT.ENTRY_MOVED_EVENT, entry, after[entry][i])
}
}
}
}
}
}
}
/**
* Iterates through the list and creates a map with the entry as a key
* and an array of its position(s) within the list as a value, e.g.
*
* {
* 'recordA': [ 0, 3 ],
* 'recordB': [ 1 ],
* 'recordC': [ 2 ]
* }
*/
private getStructure (): any {
const structure: any = {}
let i
const entries = this.getEntries()
for (i = 0; i < entries.length; i++) {
if (structure[entries[i]] === undefined) {
structure[entries[i]] = [i]
} else {
structure[entries[i]].push(i)
}
}
return structure
}
private destroy () {
for (let i = 0; i < this.subscriptions.length; i++) {
this.record.unsubscribe(this.subscriptions[i], this)
}
this.wrappedFunctions.clear()
this.record.removeContext(this)
}
} | the_stack |
import { LuaArray, tonumber, pairs, LuaObj } from "@wowts/lua";
import { GetTime, TalentId, SpellId } from "@wowts/wow-mock";
import { find } from "@wowts/string";
import { pow } from "@wowts/math";
import { OvaleClass } from "../Ovale";
import { StateModule } from "../engine/state";
import { OvaleAuraClass } from "./Aura";
import { OvalePaperDollClass } from "./PaperDoll";
import { OvaleSpellBookClass } from "./SpellBook";
import { OvaleConditionClass, returnConstant } from "../engine/condition";
import { OvaleFutureClass } from "./Future";
import { OvalePowerClass } from "./Power";
import { AstFunctionNode, NamedParametersOf } from "../engine/ast";
import { CombatLogEvent, SpellPayloadHeader } from "../engine/combat-log-event";
interface CustomAura {
customId: number;
duration: number;
stacks: number;
auraName: string;
}
const customAuras: LuaArray<CustomAura> = {
[SpellId.havoc]: {
customId: -SpellId.havoc,
duration: 10,
stacks: 1,
auraName: "active_havoc",
},
};
const enum DemonId {
WildImp = 55659,
Dreadstalkers = 98035,
Darkglare = 103673,
Doomguard = 11859,
Infernal = 89,
InnerDemonsWildImp = 143622,
DemonicTyrant = 135002,
GrimoireFelguard = 17252,
Vilefiend = 135816,
}
const demonData: LuaArray<{ duration: number }> = {
[DemonId.WildImp]: {
duration: 15,
},
[DemonId.Dreadstalkers]: {
duration: 12,
},
[DemonId.Darkglare]: {
duration: 12,
},
[DemonId.Doomguard]: {
duration: 25,
},
[DemonId.Infernal]: {
duration: 25,
},
[DemonId.InnerDemonsWildImp]: {
duration: 12,
},
[DemonId.DemonicTyrant]: {
duration: 15,
},
[DemonId.GrimoireFelguard]: {
duration: 15,
},
[DemonId.Vilefiend]: {
duration: 15,
},
};
interface Demon {
finish: number;
id: number;
timestamp: number;
}
export class OvaleWarlockClass implements StateModule {
private demonsCount: LuaObj<Demon> = {};
private serial = 1;
constructor(
private ovale: OvaleClass,
private ovaleAura: OvaleAuraClass,
private ovalePaperDoll: OvalePaperDollClass,
private ovaleSpellBook: OvaleSpellBookClass,
private future: OvaleFutureClass,
private power: OvalePowerClass,
private combatLogEvent: CombatLogEvent
) {
ovale.createModule(
"OvaleWarlock",
this.handleInitialize,
this.handleDisable
);
}
public registerConditions(condition: OvaleConditionClass) {
condition.registerCondition("timetoshard", false, this.timeToShard);
condition.registerCondition("demons", false, this.getDemonsCount);
condition.registerCondition("demonduration", false, this.demonDuration);
condition.registerCondition(
"impsspawnedduring",
false,
this.impsSpawnedDuring
);
}
private handleInitialize = () => {
if (this.ovale.playerClass == "WARLOCK") {
this.combatLogEvent.registerEvent(
"SPELL_SUMMON",
this,
this.handleCombatLogEvent
);
this.combatLogEvent.registerEvent(
"SPELL_CAST_SUCCESS",
this,
this.handleCombatLogEvent
);
this.demonsCount = {};
}
};
private handleDisable = () => {
if (this.ovale.playerClass == "WARLOCK") {
this.combatLogEvent.unregisterAllEvents(this);
}
};
private handleCombatLogEvent = (cleuEvent: string) => {
const cleu = this.combatLogEvent;
if (cleu.sourceGUID == this.ovale.playerGUID) {
this.serial = this.serial + 1;
if (cleuEvent == "SPELL_SUMMON") {
const destGUID = cleu.destGUID;
let [, , , , , , , creatureId] = find(
destGUID,
"(%S+)-(%d+)-(%d+)-(%d+)-(%d+)-(%d+)-(%S+)"
);
creatureId = tonumber(creatureId);
const now = GetTime();
for (const [id, v] of pairs(demonData)) {
if (id === creatureId) {
this.demonsCount[destGUID] = {
id: creatureId,
timestamp: now,
finish: now + v.duration,
};
break;
}
}
for (const [k, d] of pairs(this.demonsCount)) {
if (d.finish < now) {
delete this.demonsCount[k];
}
}
this.ovale.needRefresh();
} else if (cleuEvent == "SPELL_CAST_SUCCESS") {
// Implosion removes all the wild imps
const header = cleu.header as SpellPayloadHeader;
const spellId = header.spellId;
if (spellId == SpellId.implosion) {
for (const [k, d] of pairs(this.demonsCount)) {
if (
d.id == DemonId.WildImp ||
d.id == DemonId.InnerDemonsWildImp
) {
delete this.demonsCount[k];
}
}
this.ovale.needRefresh();
}
const aura = customAuras[spellId];
if (aura) {
this.addCustomAura(
aura.customId,
aura.stacks,
aura.duration,
aura.auraName
);
}
}
}
};
cleanState(): void {}
initializeState(): void {}
resetState(): void {}
private impsSpawnedDuring = (
positionalParams: LuaArray<any>,
namedParams: NamedParametersOf<AstFunctionNode>,
atTime: number
) => {
const ms = positionalParams[1];
const delay = (ms || 0) / 1000;
let impsSpawned = 0;
// check for Hand of Guldan
if (this.future.next.currentCast.spellId == SpellId.hand_of_guldan) {
let soulshards = this.power.current.power["soulshards"] || 0;
if (soulshards >= 3) {
soulshards = 3;
}
impsSpawned = impsSpawned + soulshards;
}
// inner demons talent
const talented =
this.ovaleSpellBook.getTalentPoints(TalentId.inner_demons_talent) >
0;
if (talented) {
const value = this.getRemainingDemonDuration(
DemonId.InnerDemonsWildImp,
atTime + delay
);
if (value <= 0) {
impsSpawned = impsSpawned + 1;
}
}
return returnConstant(impsSpawned);
};
private getDemonsCount = (
positionalParams: LuaArray<any>,
namedParams: NamedParametersOf<AstFunctionNode>,
atTime: number
) => {
const creatureId = positionalParams[1];
let count = 0;
for (const [, d] of pairs(this.demonsCount)) {
if (d.finish >= atTime && d.id == creatureId) {
count = count + 1;
}
}
return returnConstant(count);
};
private demonDuration = (
positionalParams: LuaArray<any>,
namedParams: NamedParametersOf<AstFunctionNode>,
atTime: number
) => {
const creatureId = positionalParams[1];
const value = this.getRemainingDemonDuration(creatureId, atTime);
return returnConstant(value);
};
private getRemainingDemonDuration(creatureId: number, atTime: number) {
let max = 0;
for (const [, d] of pairs(this.demonsCount)) {
if (d.finish >= atTime && d.id == creatureId) {
const remaining = d.finish - atTime;
if (remaining > max) {
max = remaining;
}
}
}
return max;
}
private addCustomAura(
customId: number,
stacks: number,
duration: number,
buffName: string
) {
const now = GetTime();
const expire = now + duration;
this.ovaleAura.gainedAuraOnGUID(
this.ovale.playerGUID,
now,
customId,
this.ovale.playerGUID,
"HELPFUL",
false,
undefined,
stacks,
undefined,
duration,
expire,
false,
buffName,
undefined,
undefined,
undefined
);
}
/**
* Based on SimulationCraft function time_to_shard
* Seeks to return the average expected time for the player to generate a single soul shard.
*/
private getTimeToShard(atTime: number) {
let value = 3600;
const tickTime =
2 / this.ovalePaperDoll.getHasteMultiplier("spell", atTime);
const [activeAgonies] = this.ovaleAura.auraCount(
SpellId.agony,
"HARMFUL",
true,
undefined,
atTime,
undefined
);
if (activeAgonies > 0) {
value =
((1 / (0.184 * pow(activeAgonies, -2 / 3))) * tickTime) /
activeAgonies;
if (
this.ovaleSpellBook.isKnownTalent(
TalentId.creeping_death_talent
)
) {
value = value * 0.85;
}
}
return value;
}
private timeToShard = (
positionalParams: LuaArray<any>,
namedParams: NamedParametersOf<AstFunctionNode>,
atTime: number
) => {
const value = this.getTimeToShard(atTime);
return returnConstant(value);
};
} | the_stack |
import * as path from 'path';
import { DisposableObject } from './pure/disposable-object';
import {
Event,
EventEmitter,
ProviderResult,
TreeDataProvider,
TreeItem,
Uri,
window,
env,
} from 'vscode';
import * as fs from 'fs-extra';
import {
DatabaseChangedEvent,
DatabaseItem,
DatabaseManager,
} from './databases';
import {
commandRunner,
commandRunnerWithProgress,
ProgressCallback,
} from './commandRunner';
import {
isLikelyDatabaseRoot,
isLikelyDbLanguageFolder,
showAndLogErrorMessage
} from './helpers';
import { logger } from './logging';
import { clearCacheInDatabase } from './run-queries';
import * as qsClient from './queryserver-client';
import { upgradeDatabaseExplicit } from './upgrades';
import {
importArchiveDatabase,
promptImportInternetDatabase,
promptImportLgtmDatabase,
} from './databaseFetcher';
import { CancellationToken } from 'vscode';
import { asyncFilter } from './pure/helpers-pure';
type ThemableIconPath = { light: string; dark: string } | string;
/**
* Path to icons to display next to currently selected database.
*/
const SELECTED_DATABASE_ICON: ThemableIconPath = {
light: 'media/light/check.svg',
dark: 'media/dark/check.svg',
};
/**
* Path to icon to display next to an invalid database.
*/
const INVALID_DATABASE_ICON: ThemableIconPath = 'media/red-x.svg';
function joinThemableIconPath(
base: string,
iconPath: ThemableIconPath
): ThemableIconPath {
if (typeof iconPath == 'object')
return {
light: path.join(base, iconPath.light),
dark: path.join(base, iconPath.dark),
};
else return path.join(base, iconPath);
}
enum SortOrder {
NameAsc = 'NameAsc',
NameDesc = 'NameDesc',
DateAddedAsc = 'DateAddedAsc',
DateAddedDesc = 'DateAddedDesc',
}
/**
* Tree data provider for the databases view.
*/
class DatabaseTreeDataProvider extends DisposableObject
implements TreeDataProvider<DatabaseItem> {
private _sortOrder = SortOrder.NameAsc;
private readonly _onDidChangeTreeData = this.push(new EventEmitter<DatabaseItem | undefined>());
private currentDatabaseItem: DatabaseItem | undefined;
constructor(
private databaseManager: DatabaseManager,
private readonly extensionPath: string
) {
super();
this.currentDatabaseItem = databaseManager.currentDatabaseItem;
this.push(
this.databaseManager.onDidChangeDatabaseItem(
this.handleDidChangeDatabaseItem
)
);
this.push(
this.databaseManager.onDidChangeCurrentDatabaseItem(
this.handleDidChangeCurrentDatabaseItem
)
);
}
public get onDidChangeTreeData(): Event<DatabaseItem | undefined> {
return this._onDidChangeTreeData.event;
}
private handleDidChangeDatabaseItem = (event: DatabaseChangedEvent): void => {
// Note that events from the database manager are instances of DatabaseChangedEvent
// and events fired by the UI are instances of DatabaseItem
// When event.item is undefined, then the entire tree is refreshed.
// When event.item is a db item, then only that item is refreshed.
this._onDidChangeTreeData.fire(event.item);
};
private handleDidChangeCurrentDatabaseItem = (
event: DatabaseChangedEvent
): void => {
if (this.currentDatabaseItem) {
this._onDidChangeTreeData.fire(this.currentDatabaseItem);
}
this.currentDatabaseItem = event.item;
if (this.currentDatabaseItem) {
this._onDidChangeTreeData.fire(this.currentDatabaseItem);
}
};
public getTreeItem(element: DatabaseItem): TreeItem {
const item = new TreeItem(element.name);
if (element === this.currentDatabaseItem) {
item.iconPath = joinThemableIconPath(
this.extensionPath,
SELECTED_DATABASE_ICON
);
item.contextValue = 'currentDatabase';
} else if (element.error !== undefined) {
item.iconPath = joinThemableIconPath(
this.extensionPath,
INVALID_DATABASE_ICON
);
}
item.tooltip = element.databaseUri.fsPath;
item.description = element.language;
return item;
}
public getChildren(element?: DatabaseItem): ProviderResult<DatabaseItem[]> {
if (element === undefined) {
return this.databaseManager.databaseItems.slice(0).sort((db1, db2) => {
switch (this.sortOrder) {
case SortOrder.NameAsc:
return db1.name.localeCompare(db2.name, env.language);
case SortOrder.NameDesc:
return db2.name.localeCompare(db1.name, env.language);
case SortOrder.DateAddedAsc:
return (db1.dateAdded || 0) - (db2.dateAdded || 0);
case SortOrder.DateAddedDesc:
return (db2.dateAdded || 0) - (db1.dateAdded || 0);
}
});
} else {
return [];
}
}
public getParent(_element: DatabaseItem): ProviderResult<DatabaseItem> {
return null;
}
public getCurrent(): DatabaseItem | undefined {
return this.currentDatabaseItem;
}
public get sortOrder() {
return this._sortOrder;
}
public set sortOrder(newSortOrder: SortOrder) {
this._sortOrder = newSortOrder;
this._onDidChangeTreeData.fire(undefined);
}
}
/** Gets the first element in the given list, if any, or undefined if the list is empty or undefined. */
function getFirst(list: Uri[] | undefined): Uri | undefined {
if (list === undefined || list.length === 0) {
return undefined;
} else {
return list[0];
}
}
/**
* Displays file selection dialog. Expects the user to choose a
* database directory, which should be the parent directory of a
* directory of the form `db-[language]`, for example, `db-cpp`.
*
* XXX: no validation is done other than checking the directory name
* to make sure it really is a database directory.
*/
async function chooseDatabaseDir(byFolder: boolean): Promise<Uri | undefined> {
const chosen = await window.showOpenDialog({
openLabel: byFolder ? 'Choose Database folder' : 'Choose Database archive',
canSelectFiles: !byFolder,
canSelectFolders: byFolder,
canSelectMany: false,
filters: byFolder ? {} : { Archives: ['zip'] },
});
return getFirst(chosen);
}
export class DatabaseUI extends DisposableObject {
private treeDataProvider: DatabaseTreeDataProvider;
public constructor(
private databaseManager: DatabaseManager,
private readonly queryServer: qsClient.QueryServerClient | undefined,
private readonly storagePath: string,
readonly extensionPath: string
) {
super();
this.treeDataProvider = this.push(
new DatabaseTreeDataProvider(databaseManager, extensionPath)
);
this.push(
window.createTreeView('codeQLDatabases', {
treeDataProvider: this.treeDataProvider,
canSelectMany: true,
})
);
}
init() {
void logger.log('Registering database panel commands.');
this.push(
commandRunnerWithProgress(
'codeQL.setCurrentDatabase',
this.handleSetCurrentDatabase,
{
title: 'Importing database from archive',
}
)
);
this.push(
commandRunnerWithProgress(
'codeQL.upgradeCurrentDatabase',
this.handleUpgradeCurrentDatabase,
{
title: 'Upgrading current database',
cancellable: true,
}
)
);
this.push(
commandRunnerWithProgress(
'codeQL.clearCache',
this.handleClearCache,
{
title: 'Clearing Cache',
})
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseFolder',
this.handleChooseDatabaseFolder,
{
title: 'Adding database from folder',
}
)
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseArchive',
this.handleChooseDatabaseArchive,
{
title: 'Adding database from archive',
}
)
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseInternet',
this.handleChooseDatabaseInternet,
{
title: 'Adding database from URL',
}
)
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseLgtm',
this.handleChooseDatabaseLgtm,
{
title: 'Adding database from LGTM',
})
);
this.push(
commandRunner(
'codeQLDatabases.setCurrentDatabase',
this.handleMakeCurrentDatabase
)
);
this.push(
commandRunner(
'codeQLDatabases.sortByName',
this.handleSortByName
)
);
this.push(
commandRunner(
'codeQLDatabases.sortByDateAdded',
this.handleSortByDateAdded
)
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.removeDatabase',
this.handleRemoveDatabase,
{
title: 'Removing database',
cancellable: false
}
)
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.upgradeDatabase',
this.handleUpgradeDatabase,
{
title: 'Upgrading database',
cancellable: true,
}
)
);
this.push(
commandRunner(
'codeQLDatabases.renameDatabase',
this.handleRenameDatabase
)
);
this.push(
commandRunner(
'codeQLDatabases.openDatabaseFolder',
this.handleOpenFolder
)
);
this.push(
commandRunner(
'codeQLDatabases.addDatabaseSource',
this.handleAddSource
)
);
this.push(
commandRunner(
'codeQLDatabases.removeOrphanedDatabases',
this.handleRemoveOrphanedDatabases
)
);
}
private handleMakeCurrentDatabase = async (
databaseItem: DatabaseItem
): Promise<void> => {
await this.databaseManager.setCurrentDatabaseItem(databaseItem);
};
handleChooseDatabaseFolder = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
try {
return await this.chooseAndSetDatabase(true, progress, token);
} catch (e) {
void showAndLogErrorMessage(e.message);
return undefined;
}
};
handleRemoveOrphanedDatabases = async (): Promise<void> => {
void logger.log('Removing orphaned databases from workspace storage.');
let dbDirs = undefined;
if (
!(await fs.pathExists(this.storagePath)) ||
!(await fs.stat(this.storagePath)).isDirectory()
) {
void logger.log('Missing or invalid storage directory. Not trying to remove orphaned databases.');
return;
}
dbDirs =
// read directory
(await fs.readdir(this.storagePath, { withFileTypes: true }))
// remove non-directories
.filter(dirent => dirent.isDirectory())
// get the full path
.map(dirent => path.join(this.storagePath, dirent.name))
// remove databases still in workspace
.filter(dbDir => {
const dbUri = Uri.file(dbDir);
return this.databaseManager.databaseItems.every(item => item.databaseUri.fsPath !== dbUri.fsPath);
});
// remove non-databases
dbDirs = await asyncFilter(dbDirs, isLikelyDatabaseRoot);
if (!dbDirs.length) {
void logger.log('No orphaned databases found.');
return;
}
// delete
const failures = [] as string[];
await Promise.all(
dbDirs.map(async dbDir => {
try {
void logger.log(`Deleting orphaned database '${dbDir}'.`);
await fs.remove(dbDir);
} catch (e) {
failures.push(`${path.basename(dbDir)}`);
}
})
);
if (failures.length) {
const dirname = path.dirname(failures[0]);
void showAndLogErrorMessage(
`Failed to delete unused databases (${failures.join(', ')
}).\nTo delete unused databases, please remove them manually from the storage folder ${dirname}.`
);
}
};
handleChooseDatabaseArchive = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
try {
return await this.chooseAndSetDatabase(false, progress, token);
} catch (e) {
void showAndLogErrorMessage(e.message);
return undefined;
}
};
handleChooseDatabaseInternet = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
return await promptImportInternetDatabase(
this.databaseManager,
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
};
handleChooseDatabaseLgtm = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
return await promptImportLgtmDatabase(
this.databaseManager,
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
};
async tryUpgradeCurrentDatabase(
progress: ProgressCallback,
token: CancellationToken
) {
await this.handleUpgradeCurrentDatabase(progress, token);
}
private handleSortByName = async () => {
if (this.treeDataProvider.sortOrder === SortOrder.NameAsc) {
this.treeDataProvider.sortOrder = SortOrder.NameDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.NameAsc;
}
};
private handleSortByDateAdded = async () => {
if (this.treeDataProvider.sortOrder === SortOrder.DateAddedAsc) {
this.treeDataProvider.sortOrder = SortOrder.DateAddedDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.DateAddedAsc;
}
};
private handleUpgradeCurrentDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
): Promise<void> => {
await this.handleUpgradeDatabase(
progress, token,
this.databaseManager.currentDatabaseItem,
[]
);
};
private handleUpgradeDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
databaseItem: DatabaseItem | undefined,
multiSelect: DatabaseItem[] | undefined,
): Promise<void> => {
if (multiSelect?.length) {
await Promise.all(
multiSelect.map((dbItem) => this.handleUpgradeDatabase(progress, token, dbItem, []))
);
}
if (this.queryServer === undefined) {
throw new Error(
'Received request to upgrade database, but there is no running query server.'
);
}
if (databaseItem === undefined) {
throw new Error(
'Received request to upgrade database, but no database was provided.'
);
}
if (databaseItem.contents === undefined) {
throw new Error(
'Received request to upgrade database, but database contents could not be found.'
);
}
if (databaseItem.contents.dbSchemeUri === undefined) {
throw new Error(
'Received request to upgrade database, but database has no schema.'
);
}
// Search for upgrade scripts in any workspace folders available
await upgradeDatabaseExplicit(
this.queryServer,
databaseItem,
progress,
token
);
};
private handleClearCache = async (
progress: ProgressCallback,
token: CancellationToken,
): Promise<void> => {
if (
this.queryServer !== undefined &&
this.databaseManager.currentDatabaseItem !== undefined
) {
await clearCacheInDatabase(
this.queryServer,
this.databaseManager.currentDatabaseItem,
progress,
token
);
}
};
private handleSetCurrentDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
uri: Uri,
): Promise<void> => {
try {
// Assume user has selected an archive if the file has a .zip extension
if (uri.path.endsWith('.zip')) {
await importArchiveDatabase(
uri.toString(true),
this.databaseManager,
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
} else {
await this.setCurrentDatabase(progress, token, uri);
}
} catch (e) {
// rethrow and let this be handled by default error handling.
throw new Error(
`Could not set database to ${path.basename(uri.fsPath)}. Reason: ${e.message
}`
);
}
};
private handleRemoveDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
if (multiSelect?.length) {
await Promise.all(multiSelect.map((dbItem) =>
this.databaseManager.removeDatabaseItem(progress, token, dbItem)
));
} else {
await this.databaseManager.removeDatabaseItem(progress, token, databaseItem);
}
};
private handleRenameDatabase = async (
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
this.assertSingleDatabase(multiSelect);
const newName = await window.showInputBox({
prompt: 'Choose new database name',
value: databaseItem.name,
});
if (newName) {
await this.databaseManager.renameDatabaseItem(databaseItem, newName);
}
};
private handleOpenFolder = async (
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
if (multiSelect?.length) {
await Promise.all(
multiSelect.map((dbItem) => env.openExternal(dbItem.databaseUri))
);
} else {
await env.openExternal(databaseItem.databaseUri);
}
};
/**
* Adds the source folder of a CodeQL database to the workspace.
* When a database is first added in the "Databases" view, its source folder is added to the workspace.
* If the source folder is removed from the workspace for some reason, we want to be able to re-add it if need be.
*/
private handleAddSource = async (
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
if (multiSelect?.length) {
for (const dbItem of multiSelect) {
await this.databaseManager.addDatabaseSourceArchiveFolder(dbItem);
}
} else {
await this.databaseManager.addDatabaseSourceArchiveFolder(databaseItem);
}
};
/**
* Return the current database directory. If we don't already have a
* current database, ask the user for one, and return that, or
* undefined if they cancel.
*/
public async getDatabaseItem(
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> {
if (this.databaseManager.currentDatabaseItem === undefined) {
await this.chooseAndSetDatabase(false, progress, token);
}
return this.databaseManager.currentDatabaseItem;
}
private async setCurrentDatabase(
progress: ProgressCallback,
token: CancellationToken,
uri: Uri
): Promise<DatabaseItem | undefined> {
let databaseItem = this.databaseManager.findDatabaseItem(uri);
if (databaseItem === undefined) {
databaseItem = await this.databaseManager.openDatabase(progress, token, uri);
}
await this.databaseManager.setCurrentDatabaseItem(databaseItem);
return databaseItem;
}
/**
* Ask the user for a database directory. Returns the chosen database, or `undefined` if the
* operation was canceled.
*/
private async chooseAndSetDatabase(
byFolder: boolean,
progress: ProgressCallback,
token: CancellationToken,
): Promise<DatabaseItem | undefined> {
const uri = await chooseDatabaseDir(byFolder);
if (!uri) {
return undefined;
}
if (byFolder) {
const fixedUri = await this.fixDbUri(uri);
// we are selecting a database folder
return await this.setCurrentDatabase(progress, token, fixedUri);
} else {
// we are selecting a database archive. Must unzip into a workspace-controlled area
// before importing.
return await importArchiveDatabase(
uri.toString(true),
this.databaseManager,
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
}
}
/**
* Perform some heuristics to ensure a proper database location is chosen.
*
* 1. If the selected URI to add is a file, choose the containing directory
* 2. If the selected URI is a directory matching db-*, choose the containing directory
* 3. choose the current directory
*
* @param uri a URI that is a database folder or inside it
*
* @return the actual database folder found by using the heuristics above.
*/
private async fixDbUri(uri: Uri): Promise<Uri> {
let dbPath = uri.fsPath;
if ((await fs.stat(dbPath)).isFile()) {
dbPath = path.dirname(dbPath);
}
if (isLikelyDbLanguageFolder(dbPath)) {
dbPath = path.dirname(dbPath);
}
return Uri.file(dbPath);
}
private assertSingleDatabase(
multiSelect: DatabaseItem[] = [],
message = 'Please select a single database.'
) {
if (multiSelect.length > 1) {
throw new Error(message);
}
}
} | the_stack |
import {
AddonModAssignAssign,
AddonModAssignSubmission,
AddonModAssignPlugin,
AddonModAssignProvider,
AddonModAssign,
} from '@addons/mod/assign/services/assign';
import { AddonModAssignHelper } from '@addons/mod/assign/services/assign-helper';
import { AddonModAssignOffline, AddonModAssignSubmissionsDBRecordFormatted } from '@addons/mod/assign/services/assign-offline';
import { AddonModAssignSubmissionHandler } from '@addons/mod/assign/services/submission-delegate';
import { Injectable, Type } from '@angular/core';
import { CoreFileUploader, CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader';
import { CoreFileEntry, CoreFileHelper } from '@services/file-helper';
import { CoreFileSession } from '@services/file-session';
import { CoreUtils } from '@services/utils/utils';
import { CoreWSFile } from '@services/ws';
import { makeSingleton } from '@singletons';
import { AddonModAssignSubmissionFileComponent } from '../component/file';
import { FileEntry } from '@ionic-native/file/ngx';
/**
* Handler for file submission plugin.
*/
@Injectable( { providedIn: 'root' })
export class AddonModAssignSubmissionFileHandlerService implements AddonModAssignSubmissionHandler {
static readonly FOLDER_NAME = 'submission_file';
name = 'AddonModAssignSubmissionFileHandler';
type = 'file';
/**
* Whether the plugin can be edited in offline for existing submissions. In general, this should return false if the
* plugin uses Moodle filters. The reason is that the app only prefetches filtered data, and the user should edit
* unfiltered data.
*
* @return Boolean or promise resolved with boolean: whether it can be edited in offline.
*/
canEditOffline(): boolean {
// This plugin doesn't use Moodle filters, it can be edited in offline.
return true;
}
/**
* Check if a plugin has no data.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @return Whether the plugin is empty.
*/
isEmpty(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): boolean {
const files = AddonModAssign.getSubmissionPluginAttachments(plugin);
return files.length === 0;
}
/**
* Should clear temporary data for a cancelled submission.
*
* @param assign The assignment.
*/
clearTmpData(assign: AddonModAssignAssign): void {
const files = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id);
// Clear the files in session for this assign.
CoreFileSession.clearFiles(AddonModAssignProvider.COMPONENT, assign.id);
// Now delete the local files from the tmp folder.
CoreFileUploader.clearTmpFiles(files);
}
/**
* This function will be called when the user wants to create a new submission based on the previous one.
* It should add to pluginData the data to send to server based in the data in plugin (previous attempt).
*
* @param assign The assignment.
* @param plugin The plugin object.
* @param pluginData Object where to store the data to send.
* @return If the function is async, it should return a Promise resolved when done.
*/
async copySubmissionData(
assign: AddonModAssignAssign,
plugin: AddonModAssignPlugin,
pluginData: AddonModAssignSubmissionFilePluginData,
): Promise<void> {
// We need to re-upload all the existing files.
const files = AddonModAssign.getSubmissionPluginAttachments(plugin);
// Get the itemId.
pluginData.files_filemanager = await AddonModAssignHelper.uploadFiles(assign.id, files);
}
/**
* Return the Component to use to display the plugin data, either in read or in edit mode.
* It's recommended to return the class of the component, but you can also return an instance of the component.
*
* @return The component (or promise resolved with component) to use, undefined if not found.
*/
getComponent(): Type<unknown> {
return AddonModAssignSubmissionFileComponent;
}
/**
* Delete any stored data for the plugin and submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param offlineData Offline data stored.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
async deleteOfflineData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
offlineData: AddonModAssignSubmissionsDBRecordFormatted,
siteId?: string,
): Promise<void> {
await CoreUtils.ignoreErrors(
AddonModAssignHelper.deleteStoredSubmissionFiles(
assign.id,
AddonModAssignSubmissionFileHandlerService.FOLDER_NAME,
submission.userid,
siteId,
),
);
}
/**
* Get files used by this plugin.
* The files returned by this function will be prefetched when the user prefetches the assign.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return The files (or promise resolved with the files).
*/
getPluginFiles(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
): CoreWSFile[] {
return AddonModAssign.getSubmissionPluginAttachments(plugin);
}
/**
* Get the size of data (in bytes) this plugin will send to copy a previous submission.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @return The size (or promise resolved with size).
*/
async getSizeForCopy(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): Promise<number> {
const files = AddonModAssign.getSubmissionPluginAttachments(plugin);
return CoreFileHelper.getTotalFilesSize(files);
}
/**
* Get the size of data (in bytes) this plugin will send to add or edit a submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @return The size (or promise resolved with size).
*/
async getSizeForEdit(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
): Promise<number> {
// Check if there's any change.
const hasChanged = await this.hasDataChanged(assign, submission, plugin);
if (hasChanged) {
const files = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id);
return CoreFileHelper.getTotalFilesSize(files);
} else {
// Nothing has changed, we won't upload any file.
return 0;
}
}
/**
* Check if the submission data has changed for this plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @return Boolean (or promise resolved with boolean): whether the data has changed.
*/
async hasDataChanged(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
): Promise<boolean> {
const offlineData = await CoreUtils.ignoreErrors(
// Check if there's any offline data.
AddonModAssignOffline.getSubmission(assign.id, submission.userid),
undefined,
);
let numFiles: number;
if (offlineData && offlineData.plugindata && offlineData.plugindata.files_filemanager) {
const offlineDataFiles = <CoreFileUploaderStoreFilesResult>offlineData.plugindata.files_filemanager;
// Has offline data, return the number of files.
numFiles = offlineDataFiles.offline + offlineDataFiles.online.length;
} else {
// No offline data, return the number of online files.
const pluginFiles = AddonModAssign.getSubmissionPluginAttachments(plugin);
numFiles = pluginFiles && pluginFiles.length;
}
const currentFiles = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id);
if (currentFiles.length != numFiles) {
// Number of files has changed.
return true;
}
const files = await this.getSubmissionFilesToSync(assign, submission, offlineData);
// Check if there is any local file added and list has changed.
return CoreFileUploader.areFileListDifferent(currentFiles, files);
}
/**
* Whether or not the handler is enabled on a site level.
*
* @return True or promise resolved with true if enabled.
*/
async isEnabled(): Promise<boolean> {
return true;
}
/**
* Whether or not the handler is enabled for edit on a site level.
*
* @return Whether or not the handler is enabled for edit on a site level.
*/
isEnabledForEdit(): boolean {
return true;
}
/**
* Prepare and add to pluginData the data to send to the server based on the input data.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @param pluginData Object where to store the data to send.
* @param offline Whether the user is editing in offline.
* @param userId User ID. If not defined, site's current user.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
async prepareSubmissionData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: AddonModAssignSubmissionFileData,
pluginData: AddonModAssignSubmissionFilePluginData,
offline = false,
userId?: number,
siteId?: string,
): Promise<void> {
const changed = await this.hasDataChanged(assign, submission, plugin);
if (!changed) {
return;
}
// Data has changed, we need to upload new files and re-upload all the existing files.
const currentFiles = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id);
const error = CoreUtils.hasRepeatedFilenames(currentFiles);
if (error) {
throw error;
}
pluginData.files_filemanager = await AddonModAssignHelper.uploadOrStoreFiles(
assign.id,
AddonModAssignSubmissionFileHandlerService.FOLDER_NAME,
currentFiles,
offline,
userId,
siteId,
);
}
/**
* Prepare and add to pluginData the data to send to the server based on the offline data stored.
* This will be used when performing a synchronization.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param offlineData Offline data stored.
* @param pluginData Object where to store the data to send.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
async prepareSyncData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
offlineData: AddonModAssignSubmissionsDBRecordFormatted,
pluginData: AddonModAssignSubmissionFilePluginData,
siteId?: string,
): Promise<void> {
const files = await this.getSubmissionFilesToSync(assign, submission, offlineData, siteId);
if (files.length == 0) {
return;
}
pluginData.files_filemanager = await AddonModAssignHelper.uploadFiles(assign.id, files, siteId);
}
/**
* Get the file list to be synced.
*
* @param assign The assignment.
* @param submission The submission.
* @param offlineData Offline data stored.
* @param siteId Site ID. If not defined, current site.
* @return File entries when is all resolved.
*/
protected async getSubmissionFilesToSync(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
offlineData?: AddonModAssignSubmissionsDBRecordFormatted,
siteId?: string,
): Promise<CoreFileEntry[]> {
const filesData = <CoreFileUploaderStoreFilesResult>offlineData?.plugindata.files_filemanager;
if (!filesData) {
return [];
}
// Has some data to sync.
let files: CoreFileEntry[] = filesData.online || [];
if (filesData.offline) {
// Has offline files, get them and add them to the list.
const storedFiles = <FileEntry[]> await CoreUtils.ignoreErrors(
AddonModAssignHelper.getStoredSubmissionFiles(
assign.id,
AddonModAssignSubmissionFileHandlerService.FOLDER_NAME,
submission.userid,
siteId,
),
[],
);
files = files.concat(storedFiles);
}
return files;
}
}
export const AddonModAssignSubmissionFileHandler = makeSingleton(AddonModAssignSubmissionFileHandlerService);
// Define if ever used.
export type AddonModAssignSubmissionFileData = Record<string, unknown>;
export type AddonModAssignSubmissionFilePluginData = {
// The id of a draft area containing files for this submission. Or the offline file results.
files_filemanager: number | CoreFileUploaderStoreFilesResult; // eslint-disable-line @typescript-eslint/naming-convention
}; | the_stack |
import WebSocket from 'isomorphic-ws'
import { XrpError, XrpErrorType } from '../shared'
import {
WebSocketReadyState,
RippledMethod,
WebSocketRequest,
SubscribeRequest,
AccountLinesRequest,
GatewayBalancesRequest,
AccountOffersRequest,
RipplePathFindRequest,
WebSocketResponse,
WebSocketFailureResponse,
ResponseStatus,
AccountLinesResponse,
GatewayBalancesResponse,
StatusResponse,
TransactionResponse,
AccountOffersResponse,
RipplePathFindResponse,
SourceCurrency,
} from '../shared/rippled-web-socket-schema'
import IssuedCurrency from '../shared/issued-currency'
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* A network client for interacting with the rippled WebSocket API.
* @see https://xrpl.org/rippled-api.html
*/
export default class WebSocketNetworkClient {
private readonly socket: WebSocket
private accountCallbacks: Map<
string,
(data: TransactionResponse) => void
> = new Map()
private messageCallbacks: Map<
string,
(data: WebSocketResponse) => void
> = new Map()
private waiting: Map<
number | string,
WebSocketResponse | undefined
> = new Map()
private idNumber = 0 // added to web socket request IDs to ensure unique IDs
/**
* Create a new WebSocketNetworkClient.
*
* @param webSocketUrl The URL of the rippled node to query.
* @see https://xrpl.org/monitor-incoming-payments-with-websocket.html
*/
public constructor(
webSocketUrl: string,
private handleErrorMessage: (message: string) => void,
) {
this.socket = new WebSocket(webSocketUrl)
this.messageCallbacks.set('response', (data: WebSocketResponse) => {
const dataStatusResponse = data as StatusResponse
this.waiting.set(dataStatusResponse.id, data)
})
this.messageCallbacks.set('transaction', (data: WebSocketResponse) =>
this.handleTransaction(data as TransactionResponse),
)
this.socket.addEventListener('message', (event) => {
const parsedData = JSON.parse(event.data) as WebSocketResponse
const messageType = parsedData.type
const callback = this.messageCallbacks.get(messageType)
if (callback) {
callback(parsedData)
} else {
this.handleErrorMessage(
`Received unhandlable message: ${event.data as string}`,
)
}
})
this.socket.addEventListener('close', (event: CloseEvent) => {
this.handleErrorMessage(`WebSocket disconnected, ${event.reason}`)
})
this.socket.addEventListener('error', (event: ErrorEvent) => {
this.handleErrorMessage(`WebSocket error: ${event.message}`)
})
}
/**
* Properly handles incoming transactions from the websocket.
*
* @param data The websocket response received from the websocket.
*/
private handleTransaction(data: TransactionResponse) {
const destinationAccount = data.transaction.Destination
const destinationCallback = this.accountCallbacks.get(destinationAccount)
const senderAccount = data.transaction.Account
const senderCallback = this.accountCallbacks.get(senderAccount)
if (destinationCallback) {
destinationCallback(data)
}
if (senderCallback) {
senderCallback(data)
}
if (!destinationCallback && !senderCallback) {
throw new XrpError(
XrpErrorType.Unknown,
`Received a transaction for an account that has not been subscribed to: ${destinationAccount}`,
)
}
}
/**
* Sends an API request over the websocket connection.
* @see https://xrpl.org/monitor-incoming-payments-with-websocket.html
*
* @param request The object to send over the websocket.
* @returns The API response from the websocket.
*/
private async sendApiRequest(
request: WebSocketRequest,
): Promise<WebSocketResponse> {
while (this.socket.readyState === WebSocketReadyState.Connecting) {
await sleep(5)
}
if (this.socket.readyState !== WebSocketReadyState.Open) {
throw new XrpError(XrpErrorType.Unknown, 'Socket is closed/closing')
}
this.socket.send(JSON.stringify(request))
this.waiting.set(request.id, undefined)
let response = this.waiting.get(request.id)
while (response === undefined) {
await sleep(5)
response = this.waiting.get(request.id)
}
this.waiting.delete(request.id)
return response
}
/**
* Subscribes for notification about every validated transaction that affects the given account.
* @see https://xrpl.org/subscribe.html
*
* @param account The account from which to subscribe to incoming transactions, encoded as a classic address.
* @param callback The function called whenever a new transaction is received.
* @returns The response from the websocket confirming the subscription.
*/
public async subscribeToAccount(
account: string,
callback: (data: TransactionResponse) => void,
): Promise<StatusResponse> {
const subscribeRequest: SubscribeRequest = {
id: `monitor_transactions_${account}_${this.idNumber}`,
command: RippledMethod.subscribe,
accounts: [account],
}
this.idNumber++
const response = await this.sendApiRequest(subscribeRequest)
if (response.status !== ResponseStatus.success) {
const errorResponse = response as WebSocketFailureResponse
throw new XrpError(
XrpErrorType.Unknown,
`Subscription request for ${account} failed, ${errorResponse.error_message}`,
)
}
this.accountCallbacks.set(account, callback)
return response as StatusResponse
}
/**
* Unsubscribes from notifications about every validated transaction that affects the given account.
* @see https://xrpl.org/unsubscribe.html
*
* @param account The account from which to unsubscribe from incoming transactions, encoded as a classic address.
* @returns The response from the websocket confirming the unsubscription.
*/
public async unsubscribeFromAccount(
account: string,
): Promise<StatusResponse> {
if (!this.accountCallbacks.has(account)) {
throw new XrpError(
XrpErrorType.InvalidInput,
`Not currently subscribed to ${account}, do not need to unsubscribe`,
)
}
const unsubscribeRequest: SubscribeRequest = {
id: `unsubscribe_transactions_${account}_${this.idNumber}`,
command: RippledMethod.unsubscribe,
accounts: [account],
}
this.idNumber++
const response = await this.sendApiRequest(unsubscribeRequest)
if (response.status !== ResponseStatus.success) {
const errorResponse = response as WebSocketFailureResponse
throw new XrpError(
XrpErrorType.Unknown,
`Unsubscribe request for ${account} failed, ${errorResponse.error_message}`,
)
}
this.accountCallbacks.delete(account)
return response as StatusResponse
}
/**
* Submits an account_lines request to the rippled WebSocket API.
* @see https://xrpl.org/account_lines.html
*
* @param account The XRPL account to query for trust lines.
*/
public async getAccountLines(
account: string,
peerAccount?: string,
): Promise<AccountLinesResponse> {
const accountLinesRequest: AccountLinesRequest = {
id: `${RippledMethod.accountLines}_${account}_${this.idNumber}`,
command: RippledMethod.accountLines,
account,
ledger_index: 'validated',
peer: peerAccount,
}
this.idNumber++
return (await this.sendApiRequest(
accountLinesRequest,
)) as AccountLinesResponse
}
/**
* Submits a gateway_balances request to the rippled WebSocket API.
* @see https://xrpl.org/gateway_balances.html
*
* @param account The XRPL account for which to retrieve issued currency balances.
* @param addressesToExclude (Optional) An array of operational address to exclude from the balances issued.
* @see https://xrpl.org/issuing-and-operational-addresses.html
*/
public async getGatewayBalances(
account: string,
addressesToExclude?: Array<string>,
): Promise<GatewayBalancesResponse> {
const gatewayBalancesRequest: GatewayBalancesRequest = {
id: `${RippledMethod.gatewayBalances}_${account}_${this.idNumber}`,
command: RippledMethod.gatewayBalances,
account,
strict: true,
hotwallet: addressesToExclude,
ledger_index: 'validated',
}
this.idNumber++
const gatewayBalancesResponse = await this.sendApiRequest(
gatewayBalancesRequest,
)
return gatewayBalancesResponse as GatewayBalancesResponse
}
/**
* Submits an account_offers request to the rippled WebSocket API.
* @see https://xrpl.org/account_offers.html
*
* @param account The XRPL account for which to retrieve a list of outstanding offers.
*/
public async getAccountOffers(
account: string,
): Promise<AccountOffersResponse> {
const accountOffersRequest: AccountOffersRequest = {
id: `${RippledMethod.accountOffers}_${account}_${this.idNumber}`,
command: RippledMethod.accountOffers,
account,
}
this.idNumber++
const accountOffersResponse = await this.sendApiRequest(
accountOffersRequest,
)
return accountOffersResponse as AccountOffersResponse
}
/**
* Submits a ripple_path_find request to the rippled WebSocket API.
* @see https://xrpl.org/ripple_path_find.html
*
* @param sourceAccount The XRPL account at the start of the desired path, as a classic address.
* @param destinationAccount The XRPL account at the end of the desired path, as a classic address.
* @param destinationAmount The currency amount that the destination account would receive in a transaction
* (-1 if the path should deliver as much as possible).
* @param sendMax The currency amount that would be spent in the transaction (cannot be used with sourceCurrencies).
* @param sourceCurrencies An array of currencies that the source account might want to spend (cannot be used with sendMax).
*/
public async findRipplePath(
sourceAccount: string,
destinationAccount: string,
destinationAmount: string | IssuedCurrency,
sendMax?: string | IssuedCurrency,
sourceCurrencies?: SourceCurrency[],
): Promise<RipplePathFindResponse> {
if (sendMax && sourceCurrencies) {
throw new XrpError(
XrpErrorType.InvalidInput,
'Cannot provide values for both `sendMax` and `sourceCurrencies`',
)
}
const ripplePathFindRequest: RipplePathFindRequest = {
id: `${RippledMethod.ripplePathFind}_${sourceAccount}_${this.idNumber}`,
command: RippledMethod.ripplePathFind,
source_account: sourceAccount,
destination_account: destinationAccount,
destination_amount: destinationAmount,
send_max: sendMax,
source_currencies: sourceCurrencies,
}
this.idNumber++
const ripplePathFindResponse = await this.sendApiRequest(
ripplePathFindRequest,
)
return ripplePathFindResponse as RipplePathFindResponse
}
/**
* Closes the socket.
*/
public close(): void {
this.socket.close()
}
} | the_stack |
* User storage format:
* {
* type: "matrix|remote",
* id: "user_id|remote_id",
* data: {
* .. matrix-specific info e.g. display name ..
* .. remote specific info e.g. IRC username ..
* }
* }
* Examples:
* {
* type: "matrix",
* id: "@foo:bar",
* data: {
* localpart: "foo", // Required.
* displayName: "Foo Bar" // Optional.
* }
* }
*
* {
* type: "remote",
* id: "foobar@irc.freenode.net",
* data: {
* nickChoices: ["foobar", "foobar_", "foobar__"]
* }
* }
*
* There is also a third type, the "union" type. This binds together a single
* matrix <--> remote pairing. A single remote ID can have many matrix_id and
* vice versa, via mutliple union entries.
*
* {
* type: "union",
* remote_id: "foobar@irc.freenode.net",
* matrix_id: "@foo:bar"
* }
*/
import Datastore from "nedb";
import { BridgeStore } from "./bridge-store";
import { MatrixUser } from "../models/users/matrix";
import { RemoteUser } from "../models/users/remote";
export class UserBridgeStore extends BridgeStore {
/**
* Construct a store suitable for user bridging information.
* @param db The connected NEDB database instance
*/
constructor (db: Datastore) {
super(db);
}
/**
* Retrieve a list of corresponding remote users for the given matrix user ID.
* @param userId The Matrix user ID
* @return Resolves to a list of Remote users.
*/
public async getRemoteUsersFromMatrixId(userId: string) {
const remoteIds = await this.select({
type: "union",
matrix_id: userId
// eslint-disable-next-line camelcase
}, this.convertTo((doc: {remote_id: string}) => {
return doc.remote_id;
}))
return this.select({
type: "remote",
id: { $in: remoteIds }
}, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new RemoteUser(doc.id, doc.data)
));
}
/**
* Retrieve a list of corresponding matrix users for the given remote ID.
* @param remoteId The Remote ID
* @return Resolves to a list of Matrix users.
*/
public async getMatrixUsersFromRemoteId(remoteId: string) {
const matrixUserIds = await this.select({
type: "union",
remote_id: remoteId
// eslint-disable-next-line camelcase
}, this.convertTo((doc: {matrix_id: string}) => {
return doc.matrix_id;
}));
return this.select({
type: "matrix",
id: { $in: matrixUserIds }
}, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new MatrixUser(doc.id, doc.data)
));
}
/**
* Retrieve a MatrixUser based on their user ID localpart. If there is more than
* one match (e.g. same localpart, different domains) then this will return an
* arbitrary matching user.
* @param localpart The user localpart
* @return Resolves to a MatrixUser or null.
*/
public getByMatrixLocalpart(localpart: string) {
return this.selectOne({
type: "matrix",
"data.localpart": localpart
}, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new MatrixUser(doc.id, doc.data)
));
}
/**
* Get a matrix user by their user ID.
* @param userId The user_id
* @return Resolves to the user or null if they
* do not exist. Rejects with an error if there was a problem querying the store.
*/
public getMatrixUser(userId: string) {
return this.selectOne({
type: "matrix",
id: userId
}, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new MatrixUser(doc.id, doc.data)
));
}
/**
* Store a Matrix user. If they already exist, they will be updated. Equivalence
* is determined by their user ID.
* @param matrixUser The matrix user
*/
public setMatrixUser(matrixUser: MatrixUser) {
return this.upsert({
type: "matrix",
id: matrixUser.getId()
}, {
type: "matrix",
id: matrixUser.getId(),
data: matrixUser.serialize()
});
}
/**
* Get a remote user by their remote ID.
* @param id The remote ID
* @return Resolves to the user or null if they
* do not exist. Rejects with an error if there was a problem querying the store.
*/
public getRemoteUser(id: string) {
return this.selectOne({
type: "remote",
id: id
}, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new RemoteUser(doc.id, doc.data)
));
}
/**
* Get remote users by some data about them, previously stored via the set
* method on the Remote user.
* @param dataQuery The keys and matching values the remote users share.
* This should use dot notation for nested types. For example:
* <code> { "topLevel.midLevel.leaf": 42, "otherTopLevel": "foo" } </code>
* @return Resolves to a possibly empty list of
* RemoteUsers. Rejects with an error if there was a problem querying the store.
* @throws If dataQuery isn't an object.
* @example
* remoteUser.set({
* toplevel: "foo",
* nested: {
* bar: {
* baz: 43
* }
* }
* });
* store.setRemoteUser(remoteUser).then(function() {
* store.getByRemoteData({
* "toplevel": "foo",
* "nested.bar.baz": 43
* })
* });
*/
public getByRemoteData(dataQuery: Record<string, unknown>) {
if (typeof dataQuery !== "object") {
throw new Error("Data query must be an object.");
}
const query: Record<string, unknown> = {};
Object.keys(dataQuery).forEach((key: string) => {
query["data." + key] = dataQuery[key];
});
query.type = "remote";
return this.select(query, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new RemoteUser(doc.id, doc.data)
));
}
/**
* Get Matrix users by some data about them, previously stored via the set
* method on the Matrix user.
* @param dataQuery The keys and matching values the remote users share.
* This should use dot notation for nested types. For example:
* <code> { "topLevel.midLevel.leaf": 42, "otherTopLevel": "foo" } </code>
* @return Resolves to a possibly empty list of
* MatrixUsers. Rejects with an error if there was a problem querying the store.
* @throws If dataQuery isn't an object.
* @example
* matrixUser.set({
* toplevel: "foo",
* nested: {
* bar: {
* baz: 43
* }
* }
* });
* store.setMatrixUser(matrixUser).then(function() {
* store.getByMatrixData({
* "toplevel": "foo",
* "nested.bar.baz": 43
* })
* });
*/
public getByMatrixData(dataQuery: Record<string, unknown>) {
if (typeof dataQuery !== "object") {
throw new Error("Data query must be an object.");
}
const query: Record<string, unknown> = {};
Object.keys(dataQuery).forEach((key: string) => {
query["data." + key] = dataQuery[key];
});
query.type = "matrix";
return this.select(query, this.convertTo((doc: {id: string, data: Record<string, unknown>}) =>
new MatrixUser(doc.id, doc.data)
));
}
/**
* Store a Remote user. If they already exist, they will be updated. Equivalence
* is determined by the Remote ID.
* @param remoteUser The remote user
*/
public setRemoteUser(remoteUser: RemoteUser) {
return this.upsert({
type: "remote",
id: remoteUser.getId()
}, {
type: "remote",
id: remoteUser.getId(),
data: remoteUser.serialize()
});
}
/**
* Create a link between a matrix and remote user. If either user does not exist,
* they will be inserted prior to linking. This is done to ensure foreign key
* constraints are satisfied (so you cannot have a mapping to a user ID which
* does not exist).
* @param matrixUser The matrix user
* @param remoteUser The remote user
*/
public async linkUsers(matrixUser: MatrixUser, remoteUser: RemoteUser) {
await this.insertIfNotExists({
type: "remote",
id: remoteUser.getId()
}, {
type: "remote",
id: remoteUser.getId(),
data: remoteUser.serialize()
});
await this.insertIfNotExists({
type: "matrix",
id: matrixUser.getId()
}, {
type: "matrix",
id: matrixUser.getId(),
data: matrixUser.serialize()
});
return this.upsert({
type: "union",
remote_id: remoteUser.getId(),
matrix_id: matrixUser.getId()
}, {
type: "union",
remote_id: remoteUser.getId(),
matrix_id: matrixUser.getId()
});
}
/**
* Delete a link between a matrix user and a remote user.
* @param matrixUser The matrix user
* @param remoteUser The remote user
* @return Resolves to the number of entries removed.
*/
public unlinkUsers(matrixUser: MatrixUser, remoteUser: RemoteUser) {
return this.unlinkUserIds(matrixUser.getId(), remoteUser.getId());
}
/**
* Delete a link between a matrix user ID and a remote user ID.
* @param matrixUserId The matrix user ID
* @param remoteUserId The remote user ID
* @return Resolves to the number of entries removed.
*/
public unlinkUserIds(matrixUserId: string, remoteUserId: string) {
return this.delete({
type: "union",
remote_id: remoteUserId,
matrix_id: matrixUserId
});
}
/**
* Retrieve a list of matrix user IDs linked to this remote ID.
* @param remoteId The remote ID
* @return A list of user IDs.
*/
public getMatrixLinks(remoteId: string): Promise<string[]|null> {
return this.select({
type: "union",
remote_id: remoteId
// eslint-disable-next-line camelcase
}, this.convertTo((doc: {matrix_id: string}) =>
doc.matrix_id
));
}
/**
* Retrieve a list of remote IDs linked to this matrix user ID.
* @param matrixId The matrix user ID
* @return A list of remote IDs.
*/
public getRemoteLinks(matrixId: string): Promise<string[]|null> {
return this.select({
type: "union",
matrix_id: matrixId
// eslint-disable-next-line camelcase
}, this.convertTo((doc: {remote_id: string}) =>
doc.remote_id
));
}
} | the_stack |
import { BehaviorSubject } from "rxjs"
import { gql } from "graphql-tag"
import pull from "lodash/pull"
import remove from "lodash/remove"
import { translateToNewRequest } from "../types/HoppRESTRequest"
import { TeamCollection } from "./TeamCollection"
import { TeamRequest } from "./TeamRequest"
import {
rootCollectionsOfTeam,
getCollectionChildren,
getCollectionRequests,
} from "./utils"
import { apolloClient } from "~/helpers/apollo"
/*
* NOTE: These functions deal with REFERENCES to objects and mutates them, for a simpler implementation.
* Be careful when you play with these.
*
* I am not a fan of mutating references but this is so much simpler compared to mutating clones
* - Andrew
*/
/**
* Finds the parent of a collection and returns the REFERENCE (or null)
*
* @param {TeamCollection[]} tree - The tree to look in
* @param {string} collID - ID of the collection to find the parent of
* @param {TeamCollection} currentParent - (used for recursion, do not set) The parent in the current iteration (undefined if root)
*
* @returns REFERENCE to the collecton or null if not found or the collection is in root
*/
function findParentOfColl(
tree: TeamCollection[],
collID: string,
currentParent?: TeamCollection
): TeamCollection | null {
for (const coll of tree) {
// If the root is parent, return null
if (coll.id === collID) return currentParent || null
// Else run it in children
if (coll.children) {
const result = findParentOfColl(coll.children, collID, coll)
if (result) return result
}
}
return null
}
/**
* Finds and returns a REFERENCE collection in the given tree (or null)
*
* @param {TeamCollection[]} tree - The tree to look in
* @param {string} targetID - The ID of the collection to look for
*
* @returns REFERENCE to the collection or null if not found
*/
function findCollInTree(
tree: TeamCollection[],
targetID: string
): TeamCollection | null {
for (const coll of tree) {
// If the direct child matched, then return that
if (coll.id === targetID) return coll
// Else run it in the children
if (coll.children) {
const result = findCollInTree(coll.children, targetID)
if (result) return result
}
}
// If nothing matched, return null
return null
}
/**
* Finds and returns a REFERENCE to the collection containing a given request ID in tree (or null)
*
* @param {TeamCollection[]} tree - The tree to look in
* @param {string} reqID - The ID of the request to look for
*
* @returns REFERENCE to the collection or null if request not found
*/
function findCollWithReqIDInTree(
tree: TeamCollection[],
reqID: string
): TeamCollection | null {
for (const coll of tree) {
// Check in root collections (if expanded)
if (coll.requests) {
if (coll.requests.find((req) => req.id === reqID)) return coll
}
// Check in children of collections
if (coll.children) {
const result = findCollWithReqIDInTree(coll.children, reqID)
if (result) return result
}
}
// No matches
return null
}
/**
* Finds and returns a REFERENCE to the request with the given ID (or null)
*
* @param {TeamCollection[]} tree - The tree to look in
* @param {string} reqID - The ID of the request to look for
*
* @returns REFERENCE to the request or null if request not found
*/
function findReqInTree(
tree: TeamCollection[],
reqID: string
): TeamRequest | null {
for (const coll of tree) {
// Check in root collections (if expanded)
if (coll.requests) {
const match = coll.requests.find((req) => req.id === reqID)
if (match) return match
}
// Check in children of collections
if (coll.children) {
const match = findReqInTree(coll.children, reqID)
if (match) return match
}
}
// No matches
return null
}
/**
* Updates a collection in the tree with the specified data
*
* @param {TeamCollection[]} tree - The tree to update in (THIS WILL BE MUTATED!)
* @param {Partial<TeamCollection> & Pick<TeamCollection, "id">} updateColl - An object defining all the fields that should be updated (ID is required to find the target collection)
*/
function updateCollInTree(
tree: TeamCollection[],
updateColl: Partial<TeamCollection> & Pick<TeamCollection, "id">
) {
const el = findCollInTree(tree, updateColl.id)
// If no match, stop the operation
if (!el) return
// Update all the specified keys
Object.assign(el, updateColl)
}
/**
* Deletes a collection in the tree
*
* @param {TeamCollection[]} tree - The tree to delete in (THIS WILL BE MUTATED!)
* @param {string} targetID - ID of the collection to delete
*/
function deleteCollInTree(tree: TeamCollection[], targetID: string) {
// Get the parent owning the collection
const parent = findParentOfColl(tree, targetID)
// If we found a parent, update it
if (parent && parent.children) {
parent.children = parent.children.filter((coll) => coll.id !== targetID)
}
// If there is no parent, it could mean:
// 1. The collection with that ID does not exist
// 2. The collection is in root (therefore, no parent)
// Let's look for element, if not exist, then stop
const el = findCollInTree(tree, targetID)
if (!el) return
// Collection exists, so this should be in root, hence removing element
pull(tree, el)
}
/**
* TeamCollectionAdapter provides a reactive collections list for a specific team
*/
export default class TeamCollectionAdapter {
/**
* The reactive list of collections
*
* A new value is emitted when there is a change
* (Use views instead)
*/
collections$: BehaviorSubject<TeamCollection[]>
// Fields for subscriptions, used for destroying once not needed
private teamCollectionAdded$: ZenObservable.Subscription | null
private teamCollectionUpdated$: ZenObservable.Subscription | null
private teamCollectionRemoved$: ZenObservable.Subscription | null
private teamRequestAdded$: ZenObservable.Subscription | null
private teamRequestUpdated$: ZenObservable.Subscription | null
private teamRequestDeleted$: ZenObservable.Subscription | null
/**
* @constructor
*
* @param {string | null} teamID - ID of the team to listen to, or null if none decided and the adapter should stand by
*/
constructor(private teamID: string | null) {
this.collections$ = new BehaviorSubject<TeamCollection[]>([])
this.teamCollectionAdded$ = null
this.teamCollectionUpdated$ = null
this.teamCollectionRemoved$ = null
this.teamRequestAdded$ = null
this.teamRequestDeleted$ = null
this.teamRequestUpdated$ = null
if (this.teamID) this.initialize()
}
/**
* Updates the team the adapter is looking at
*
* @param {string | null} newTeamID - ID of the team to listen to, or null if none decided and the adapter should stand by
*/
changeTeamID(newTeamID: string | null) {
this.collections$.next([])
this.teamID = newTeamID
if (this.teamID) this.initialize()
}
/**
* Unsubscribes from the subscriptions
* NOTE: Once this is called, no new updates to the tree will be detected
*/
unsubscribeSubscriptions() {
this.teamCollectionAdded$?.unsubscribe()
this.teamCollectionUpdated$?.unsubscribe()
this.teamCollectionRemoved$?.unsubscribe()
this.teamRequestAdded$?.unsubscribe()
this.teamRequestDeleted$?.unsubscribe()
this.teamRequestUpdated$?.unsubscribe()
}
/**
* Initializes the adapter
*/
private async initialize() {
await this.loadRootCollections()
this.registerSubscriptions()
}
/**
* Loads the root collections
*/
private async loadRootCollections(): Promise<void> {
const colls = await rootCollectionsOfTeam(apolloClient, this.teamID)
this.collections$.next(colls)
}
/**
* Performs addition of a collection to the tree
*
* @param {TeamCollection} collection - The collection to add to the tree
* @param {string | null} parentCollectionID - The parent of the new collection, pass null if this collection is in root
*/
private addCollection(
collection: TeamCollection,
parentCollectionID: string | null
) {
const tree = this.collections$.value
if (!parentCollectionID) {
tree.push(collection)
} else {
const parentCollection = findCollInTree(tree, parentCollectionID)
if (!parentCollection) return
if (parentCollection.children != null) {
parentCollection.children.push(collection)
} else {
parentCollection.children = [collection]
}
}
this.collections$.next(tree)
}
/**
* Updates an existing collection in tree
*
* @param {Partial<TeamCollection> & Pick<TeamCollection, "id">} collectionUpdate - Object defining the fields that need to be updated (ID is required to find the target)
*/
private updateCollection(
collectionUpdate: Partial<TeamCollection> & Pick<TeamCollection, "id">
) {
const tree = this.collections$.value
updateCollInTree(tree, collectionUpdate)
this.collections$.next(tree)
}
/**
* Removes a collection from the tree
*
* @param {string} collectionID - ID of the collection to remove
*/
private removeCollection(collectionID: string) {
const tree = this.collections$.value
deleteCollInTree(tree, collectionID)
this.collections$.next(tree)
}
/**
* Adds a request to the tree
*
* @param {TeamRequest} request - The request to add to the tree
*/
private addRequest(request: TeamRequest) {
const tree = this.collections$.value
// Check if we have the collection (if not, then not loaded?)
const coll = findCollInTree(tree, request.collectionID)
if (!coll) return // Ignore add request
// Collection is not expanded
if (!coll.requests) return
// Collection is expanded hence append request
coll.requests.push(request)
this.collections$.next(tree)
}
/**
* Removes a request from the tree
*
* @param {string} requestID - ID of the request to remove
*/
private removeRequest(requestID: string) {
const tree = this.collections$.value
// Find request in tree, don't attempt if no collection or no requests (expansion?)
const coll = findCollWithReqIDInTree(tree, requestID)
if (!coll || !coll.requests) return
// Remove the collection
remove(coll.requests, (req) => req.id === requestID)
// Publish new tree
this.collections$.next(tree)
}
/**
* Updates the request in tree
*
* @param {Partial<TeamRequest> & Pick<TeamRequest, 'id'>} requestUpdate - Object defining all the fields to update in request (ID of the request is required)
*/
private updateRequest(
requestUpdate: Partial<TeamRequest> & Pick<TeamRequest, "id">
) {
const tree = this.collections$.value
// Find request, if not present, don't update
const req = findReqInTree(tree, requestUpdate.id)
if (!req) return
Object.assign(req, requestUpdate)
this.collections$.next(tree)
}
/**
* Registers the subscriptions to listen to team collection updates
*/
registerSubscriptions() {
this.teamCollectionAdded$ = apolloClient
.subscribe({
query: gql`
subscription TeamCollectionAdded($teamID: ID!) {
teamCollectionAdded(teamID: $teamID) {
id
title
parent {
id
}
}
}
`,
variables: {
teamID: this.teamID,
},
})
.subscribe(({ data }) => {
this.addCollection(
{
id: data.teamCollectionAdded.id,
children: null,
requests: null,
title: data.teamCollectionAdded.title,
},
data.teamCollectionAdded.parent?.id
)
})
this.teamCollectionUpdated$ = apolloClient
.subscribe({
query: gql`
subscription TeamCollectionUpdated($teamID: ID!) {
teamCollectionUpdated(teamID: $teamID) {
id
title
parent {
id
}
}
}
`,
variables: {
teamID: this.teamID,
},
})
.subscribe(({ data }) => {
this.updateCollection({
id: data.teamCollectionUpdated.id,
title: data.teamCollectionUpdated.title,
})
})
this.teamCollectionRemoved$ = apolloClient
.subscribe({
query: gql`
subscription TeamCollectionRemoved($teamID: ID!) {
teamCollectionRemoved(teamID: $teamID)
}
`,
variables: {
teamID: this.teamID,
},
})
.subscribe(({ data }) => {
this.removeCollection(data.teamCollectionRemoved)
})
this.teamRequestAdded$ = apolloClient
.subscribe({
query: gql`
subscription TeamRequestAdded($teamID: ID!) {
teamRequestAdded(teamID: $teamID) {
id
collectionID
request
title
}
}
`,
variables: {
teamID: this.teamID,
},
})
.subscribe(({ data }) => {
this.addRequest({
id: data.teamRequestAdded.id,
collectionID: data.teamRequestAdded.collectionID,
request: translateToNewRequest(
JSON.parse(data.teamRequestAdded.request)
),
title: data.teamRequestAdded.title,
})
})
this.teamRequestUpdated$ = apolloClient
.subscribe({
query: gql`
subscription TeamRequestUpdated($teamID: ID!) {
teamRequestUpdated(teamID: $teamID) {
id
collectionID
request
title
}
}
`,
variables: {
teamID: this.teamID,
},
})
.subscribe(({ data }) => {
this.updateRequest({
id: data.teamRequestUpdated.id,
collectionID: data.teamRequestUpdated.collectionID,
request: JSON.parse(data.teamRequestUpdated.request),
title: data.teamRequestUpdated.title,
})
})
this.teamRequestDeleted$ = apolloClient
.subscribe({
query: gql`
subscription TeamRequestDeleted($teamID: ID!) {
teamRequestDeleted(teamID: $teamID)
}
`,
variables: {
teamID: this.teamID,
},
})
.subscribe(({ data }) => {
this.removeRequest(data.teamRequestDeleted)
})
}
/**
* Expands a collection on the tree
*
* When a collection is loaded initially in the adapter, children and requests are not loaded (they will be set to null)
* Upon expansion those two fields will be populated
*
* @param {string} collectionID - The ID of the collection to expand
*/
async expandCollection(collectionID: string): Promise<void> {
// TODO: While expanding one collection, block (or queue) the expansion of the other, to avoid race conditions
const tree = this.collections$.value
const collection = findCollInTree(tree, collectionID)
if (!collection) return
if (collection.children != null) return
const collections: TeamCollection[] = (
await getCollectionChildren(apolloClient, collectionID)
).map<TeamCollection>((el) => {
return {
id: el.id,
title: el.title,
children: null,
requests: null,
}
})
const requests: TeamRequest[] = (
await getCollectionRequests(apolloClient, collectionID)
).map<TeamRequest>((el) => {
return {
id: el.id,
collectionID,
title: el.title,
request: translateToNewRequest(JSON.parse(el.request)),
}
})
collection.children = collections
collection.requests = requests
this.collections$.next(tree)
}
} | the_stack |
import { listenStylesheetChange } from '../../Api/app';
import Storage from '../../Api/storage';
import { CustomTheme, Theme } from '../../Typings/theme';
/**
* Detect system theme
* @returns {string}
*/
const detectDefaultTheme = (): string => {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
} else {
return 'light';
}
};
let defaultTheme = detectDefaultTheme();
const updateNativeTheme = (): void => {
defaultTheme = detectDefaultTheme();
updateTheme('*');
};
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
defaultTheme = e.matches ? 'dark' : 'light';
updateTheme('*');
});
let themeJSON: Theme; // user preference theme json
import * as defaultThemeData from './theme.json';
interface DefaultTheme {
[key: string]: Theme;
}
const defaultThemeJSON: DefaultTheme = defaultThemeData;
let currentTheme: string;
/**
* Get style of an element
* @param {string} variable - What style you wanna get?
* @param {string} theme - the current theme
* @returns {string|null} style of the [variable] of the element
*/
const getElementStyle = (variable: string, theme?: string): string | null => {
return themeJSON?.[variable] || defaultThemeJSON[theme ?? currentTheme]?.[variable];
};
/**
* Change style of an element
* @param {HTMLElement} element - Element you want to change the theme style
* @param {string} variable - The style you wanna change
* @param {any} key - CSS key of the style
* @param {string} theme - current theme
* @returns {void}
*/
const changeElementTheme = (element: HTMLElement, variable: string, key: string, theme: string): void => {
if (element) (<any>element.style)[key] = themeJSON?.[variable] || defaultThemeJSON?.[theme]?.[variable]; //eslint-disable-line
};
const getXYCoordinates = (e: MouseEvent): { x: number; y: number } => {
const rect = (e.target as Element).getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top,
};
};
const ALLOWED_STYLES = [
'background',
'color',
'font',
'border',
'text',
'cursor',
'outline',
'--scrollbar',
'--tabs-scrollbar',
'--preview-object',
'--selected-grid',
];
/**
* Change page theme
* @param {string} theme - The current theme
* @returns {Promise<void>}
*/
const changeTheme = async (theme?: string, category?: '*' | 'root' | 'tabbing' | 'favorites' | 'grid'): Promise<void> => {
if (!category) category = '*';
const appearance = await Storage.get('appearance');
if (category === '*' || category === 'root') {
document.body.style.setProperty('--edge-radius', appearance?.frameStyle === 'os' ? '0px' : '10px');
document.body.style.fontSize = appearance?.fontSize ?? '16px';
document.documentElement.style.fontSize = appearance?.fontSize ?? '16px';
document.body.style.fontFamily = appearance?.fontFamily ?? 'system-ui';
document.documentElement.style.fontFamily = appearance?.fontFamily ?? 'system-ui';
document.body.style.setProperty(
'--sidebar-transparency',
appearance?.transparentSidebar ?? true ? appearance?.windowTransparency ?? '0.8' : '1'
);
document.body.style.setProperty(
'--workspace-transparency',
appearance?.transparentWorkspace ?? false ? appearance?.windowTransparency ?? '0.8' : '1'
);
document.body.style.setProperty(
'--topbar-transparency',
appearance?.transparentTopbar ?? false ? appearance?.windowTransparency ?? '0.8' : '1'
);
document.querySelectorAll<HTMLElement>('.sidebar-hover-effect').forEach((obj) => {
obj.style.borderRadius = '6px';
changeElementTheme(obj, 'sidebarBackground', 'background', theme);
if (obj.getAttribute('being-listened') !== 'true') {
obj.setAttribute('being-listened', 'true');
obj.addEventListener('mousemove', (e) => {
const rect = (e.target as Element).getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const elementIsActive = obj.classList.contains('active');
if (elementIsActive) obj.onmouseleave = null;
else {
obj.style.background = `radial-gradient(circle at ${x}px ${y}px, ${getElementStyle('animation.sidebar', currentTheme)} )`;
obj.onmouseleave = () => {
obj.style.background = null;
obj.style.borderImage = null;
};
}
});
}
});
const style = document.querySelector('style#root') ?? document.createElement('style');
style.id = 'root';
let styles = '';
// Generate CSS styles from user theme
for (const key of Object.keys(themeJSON ?? defaultThemeJSON[theme])) {
const value = themeJSON ? themeJSON[key] : defaultThemeJSON[theme]?.[key];
const formalKey = key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
const splittedKey = formalKey.split('.')
const styleKey =splittedKey[splittedKey.length - 1];
if (key.startsWith('hljs')) {
const className = formalKey.split('.').slice(0, -1).join('.').replace('hljs.', 'hljs-');
styles += `.${className} { ${styleKey}: ${value}; }\n`;
} else {
for (const _category of [
'root',
'windowmanager',
'tabs',
'settings',
'favorites',
'grid',
'contextmenu',
'prompt',
'preview',
'properties',
]) {
if (key.startsWith(_category)) {
const usingClassName = formalKey[_category.length] === '.';
const className = formalKey.split('.').slice(1, -1).join('.');
const idName = formalKey.split('#').slice(1).join('#').split('.')[0];
for (const allowed_style of ALLOWED_STYLES) {
if (styleKey.startsWith(allowed_style)) {
if (styleKey.startsWith('--')) {
styles += `:root { ${styleKey}: ${value}; }\n`;
} else {
styles += `${
usingClassName
? className === ''
? _category === 'root'
? ':root'
: '.' + _category
: '.' + className
: '#' + idName
}{ ${styleKey}: ${value}; }\n`;
}
break;
}
}
}
}
}
}
style.innerHTML = styles;
if (!document.head.contains(style)) document.head.appendChild(style);
}
if (category === '*' || category === 'tabbing') {
document.querySelectorAll<HTMLElement>('.tab-hover-effect').forEach((obj) => {
changeElementTheme(obj, 'tabBackground', 'background', theme);
if (obj.getAttribute('being-listened') !== 'true') {
obj.setAttribute('being-listened', 'true');
obj.addEventListener('mousemove', (e) => {
const rect = (e.target as Element).getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
obj.style.background = `radial-gradient(circle at ${x}px ${y}px, ${getElementStyle('animation.tab', currentTheme)} )`;
obj.onmouseleave = () => {
obj.style.background = null;
obj.style.borderImage = null;
};
});
}
});
}
if (category === '*' || category === 'favorites') {
document.querySelectorAll<HTMLElement>('.card-hover-effect').forEach((obj) => {
if (obj.getAttribute('being-listened') !== 'true') {
obj.setAttribute('being-listened', 'true');
obj.addEventListener('mousemove', (e) => {
const { x, y } = getXYCoordinates(e);
obj.style.background = `radial-gradient(circle at ${x}px ${y}px, ${getElementStyle('animation.card', currentTheme)} )`;
obj.onmouseleave = () => {
obj.style.background = null;
obj.style.borderImage = null;
};
});
}
});
}
if (category === '*' || category === 'grid') {
document.querySelectorAll<HTMLElement>('.grid-hover-effect').forEach((obj) => {
changeElementTheme(obj, 'gridBackground', 'background', null);
if (obj.getAttribute('being-listened') !== 'true') {
obj.setAttribute('being-listened', 'true');
obj.addEventListener('mousemove', (e) => {
const { x, y } = getXYCoordinates(e);
obj.style.background = `radial-gradient(circle at ${x}px ${y}px, ${getElementStyle('animation.grid', currentTheme)} )`;
obj.onmouseleave = () => {
obj.style.background = null;
obj.style.borderImage = null;
};
});
}
});
}
return;
};
/**
* Get all installed themes
* @returns {Promise<CustomTheme[]>}
*/
const getInstalledThemes = async (): Promise<CustomTheme[]> => {
const extensions = await Storage.get('extensions');
const themes: CustomTheme[] = [];
if (!extensions?.themes) return themes;
for (const extension of extensions.themes) {
for (const theme of extension.themes) {
themes.push({
name: theme.name,
identifier: extension.identifier + '@' + theme.identifier,
author: extension.author,
version: extension.version,
description: extension.description,
homepage: extension.homepage,
repository: extension.repository,
license: extension.license,
theme: theme.value,
});
}
}
return themes;
};
/**
* Update the entire page theme
* @returns {Promise<void>}
*/
const updateTheme = async (category?: '*' | 'root' | 'tabbing' | 'favorites' | 'grid', customStyleSheet?: JSON): Promise<void> => {
const data = await Storage.get('theme');
if (customStyleSheet) {
themeJSON = customStyleSheet as unknown as Theme;
document.body.dataset.usingCustomTheme = 'true';
listenStylesheetChange((styles) => {
themeJSON = styles as unknown as Theme;
changeTheme(data.theme, '*');
});
}
// If user has no preference theme
if (!data || !Object.keys(data).length || data.theme === 'System Default') {
currentTheme = defaultTheme;
await changeTheme(defaultTheme, category);
} else {
// If user preference is default color theme...
if (Object.keys(defaultThemeJSON).indexOf(data.theme) !== -1) {
if (document.body.dataset.usingCustomTheme !== 'true') themeJSON = null;
currentTheme = data.theme;
await changeTheme(data.theme, category);
} else {
for (const theme of await getInstalledThemes()) {
if (theme.identifier === data.theme) {
if (document.body.dataset.usingCustomTheme !== 'true') themeJSON = theme.theme;
await changeTheme(theme.name, category);
break;
}
}
}
}
return;
};
export { changeTheme, updateTheme, detectDefaultTheme, updateNativeTheme, getElementStyle, getInstalledThemes }; | the_stack |
(() => {
swan.request({
url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址
method: 'GET',
dataType: 'json',
data: {
key: 'value'
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log(res.data);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
const requestTask = swan.request({
url: 'test.php', // 仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json'
},
success(res) {
console.log(res.data);
}
});
// 取消请求任务
requestTask.abort();
})();
(() => {
swan.chooseImage({
success(res) {
swan.uploadFile({
url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址
filePath: res.tempFilePaths[0], // 要上传文件资源的路径
name: 'myfile',
success(res) {
console.log(res.statusCode);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
}
});
})();
(() => {
const uploadTask = swan.uploadFile({
url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url
filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径
name: 'myfile',
success(res) {
console.log(res.statusCode);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
uploadTask.onProgressUpdate(res => {
console.log('上传进度', res.progress);
console.log('已经上传的数据长度', res.totalBytesSent);
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);
});
uploadTask.abort(); // 取消上传任务
})();
(() => {
swan.downloadFile({
url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源
success(res) {
// 下载成功
if (res.statusCode === 200) {
console.log("临时文件路径" + res.tempFilePath);
}
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
const downloadTask = swan.downloadFile({
url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源
success(res) {
console.log(res.tempFilePath);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
downloadTask.onProgressUpdate(res => {
console.log('下载进度', res.progress);
console.log('已经下载的数据长度', res.totalBytesWritten);
console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
});
downloadTask.abort(); // 取消下载任务
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com'
});
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com'
});
swan.onSocketOpen((res) => {
console.log('WebSocket连接已打开!', res.header);
});
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址
});
swan.onSocketError((res) => {
console.log('WebSocket连接打开失败,请检查!');
});
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com'
});
swan.onSocketOpen(() => {
swan.sendSocketMessage({
data: 'baidu'
});
});
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com'
});
swan.onSocketOpen(() => {
swan.sendSocketMessage({
data: 'baidu'
});
});
swan.onSocketMessage((res) => {
console.log('收到服务器内容:', res.data);
});
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com',
success(res) {
swan.closeSocket();
}
});
})();
(() => {
swan.connectSocket({
url: 'wss://example.baidu.com'
});
swan.onSocketClose((res) => {
console.log('WebSocket 已关闭!');
});
swan.onSocketOpen(() => {
swan.closeSocket();
});
})();
(() => {
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.ocrIdCard({
image,
success(res) {
console.log(res.words_result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.ocrBankCard({
image,
success(res) {
console.log(res.result.bank_name);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.ocrDrivingLicense({
image,
success(res) {
console.log(res.words_result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.ocrVehicleLicense({
image,
success(res) {
console.log(res.words_result);
}
});
}
});
})();
(() => {
swan.ai.textReview({
content: '',
success(res) {
console.log(res.result.spam); // 0 表示审核通过
}
});
})();
(() => {
swan.ai.textToAudio({
ctp: '1',
lan: 'zh',
tex: '这是一段测试文字',
success(res) {
console.log(res.filePath);
}
});
})();
(() => {
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.imageAudit({
image,
success(res) {
console.log(res.conclusionType); // 1 为合规
}
});
}
});
})();
(() => {
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.advancedGeneralIdentify({
image,
success(res) {
console.log(res.result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.objectDetectIdentify({
image,
success(res) {
console.log(res.result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.carClassify({
image,
success(res) {
console.log(res.result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.dishClassify({
image,
success(res) {
console.log(res.result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.logoClassify({
image,
success(res) {
console.log(res.result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.animalClassify({
image,
success(res) {
console.log(res.result);
}
});
}
});
swan.chooseImage({
success(res) {
const image = res.tempFilePaths[0];
swan.ai.plantClassify({
image,
success(res) {
console.log(res.result);
}
});
}
});
})();
(() => {
const voiceRecognizer = swan.ai.getVoiceRecognizer();
voiceRecognizer.onStart(() => {
console.log('voice start');
});
voiceRecognizer.onRecognize(res => {
console.log('voice recognize', res);
});
voiceRecognizer.onFinish(res => {
console.log('voice end', res);
});
voiceRecognizer.onError(err => {
console.log('voice error', err);
});
const options = {
mode: 'dnn',
longSpeech: false
};
voiceRecognizer.start(options);
})();
(() => {
swan.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success(res) {
// 成功则返回图片的本地文件路径列表 tempFilePaths
console.log(res.tempFilePaths);
// 文件列表对象
console.log(res.tempFiles);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
swan.previewImage({
current: '', // 当前显示图片的http链接
urls: [], // 需要预览的图片http链接列表
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
swan.getImageInfo({
src: '/xxx/xxx.jpg',
success(res) {
// 成功则返回图片高,宽,本地路径
console.log(res.width);
console.log(res.height);
console.log(res.path);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
swan.saveImageToPhotosAlbum({
filePath: '/xxx/xxx.jpg',
success(res) {
console.log(res);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
const recorderManager = swan.getRecorderManager();
recorderManager.onStart(() => {
// 开始录音事件
console.log('recorder start');
});
recorderManager.onPause(() => {
// 暂停录音事件
console.log('recorder pause');
});
recorderManager.onStop((res) => {
// 停止录音事件
console.log('recorder stop', res);
const { tempFilePath } = res;
});
const options = {
duration: 10000,
sampleRate: 44100,
numberOfChannels: 1,
encodeBitRate: 96000,
format: 'aac'
};
recorderManager.start(options);
})();
(() => {
const backgroundAudioManager = swan.getBackgroundAudioManager();
backgroundAudioManager.title = '此时此刻';
backgroundAudioManager.epname = '此时此刻';
backgroundAudioManager.singer = '许巍';
backgroundAudioManager.coverImgUrl = 'xxx';
backgroundAudioManager.src = 'xxx';
})();
(() => {
const innerAudioContext = swan.createInnerAudioContext();
innerAudioContext.src = 'xxx';
innerAudioContext.autoplay = true;
innerAudioContext.seek({
position: 10
});
innerAudioContext.onPlay((res) => {
console.log('开始播放');
});
})();
(() => {
Page({
data: {
sourceType: ['album', 'camera'],
compressed: false,
maxDuration: 60,
src: ''
},
chooseVideo() {
const self = this;
swan.chooseVideo({
sourceType: this.getData('sourceType'),
compressed: this.getData('compressed'),
maxDuration: this.getData('maxDuration'),
success(res) {
// 成功返回选定视频的临时文件路径
self.setData('src', res.tempFilePath);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
}
});
swan.saveVideoToPhotosAlbum({
filePath: 'bdfile://xxx',
success(res) {
console.log(res);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
const myVideo = swan.createVideoContext('myVideo');
myVideo.play();
})();
(() => {
swan.chooseImage({
count: 1,
success(res) {
const tempFilePaths = res.tempFilePaths;
swan.saveFile({
tempFilePath: tempFilePaths[0],
success(res) {
const savedFilePath = res.savedFilePath;
}
});
}
});
swan.getFileInfo({
filePath: 'bdfile://somefile',
success(res) {
console.log(res.size);
console.log(res.digest);
}
});
swan.getSavedFileList({
success(res) {
const fileList = res.fileList;
}
});
swan.getSavedFileInfo({
filePath: 'bdfile://somefile',
success(res) {
console.log(res.size);
console.log(res.createTime);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
swan.getSavedFileList({
success(res) {
if (res.fileList.length > 0) {
swan.removeSavedFile({
filePath: res.fileList[0].filePath,
success(res) {
console.log(res.filePath);
}
});
}
}
});
})();
(() => {
swan.downloadFile({
url: 'https://smartprogram.baidu.com/xxx.pdf',
success(res) {
const filePath = res.tempFilePath;
swan.openDocument({
filePath,
success(res) {
console.log('打开文档成功');
}
});
}
});
})();
(() => {
swan.setStorage({
key: 'key',
data: 'value'
});
})();
(() => {
try {
swan.setStorageSync('key', 'value');
} catch (e) {
}
swan.getStorage({
key: 'key',
success(res) {
console.log(res.data);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
try {
const result = swan.getStorageSync('key');
} catch (e) {
}
swan.getStorageInfo({
success(res) {
console.log(res.keys);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
try {
const result = swan.getStorageInfoSync();
console.log(result);
} catch (e) {
}
})();
(() => {
swan.removeStorage({
key: 'key',
success(res) {
console.log(res);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
try {
swan.removeStorageSync('key');
} catch (e) {
}
try {
swan.clearStorageSync();
} catch (e) {
}
})();
(() => {
swan.getLocation({
type: 'gcj02',
success(res) {
console.log('纬度:' + res.latitude);
console.log('经度:' + res.longitude);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
swan.getLocation({
type: 'gcj02',
success(res) {
swan.openLocation({
latitude: res.latitude,
longitude: res.longitude,
scale: 18
});
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
let mapContext: swan.MapContext;
Page({
data: {
latitude: '40.042500',
longitude: '116.274040',
},
onReady() {
mapContext = swan.createMapContext('myMap');
},
getCenterLocation() {
mapContext.getCenterLocation({
success(res) {
console.log("经度" + res.longitude);
console.log("纬度" + res.latitude);
}
});
},
moveToLocation() {
mapContext.moveToLocation();
},
translateMarker() {
mapContext.translateMarker({
markerId: 0,
rotate: 90,
autoRotate: true,
duration: 1000,
destination: {
latitude: 23.10229,
longitude: 113.3345211,
},
animationEnd() {
console.log('animation end');
}
});
},
includePoints() {
mapContext.includePoints({
padding: [10],
points: [{
latitude: 23,
longitude: 113.33,
}, {
latitude: 23,
longitude: 113.3345211,
}]
});
},
getRegion() {
mapContext.getRegion({
success(res) {
console.log("西南角的经纬度" + res.southwest);
console.log("东北角的经纬度" + res.northeast);
}
});
}
});
})();
(() => {
Page({
onReady() {
const ctx = this.createCanvasContext('myCanvas');
ctx.setFillStyle('#ff0000');
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fill();
ctx.draw();
}
});
Page({
onReady() {
const ctx = this.createCanvasContext('myCanvas');
}
});
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('#ff0000');
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fill();
ctx.draw();
swan.canvasGetImageData({
canvasId: 'myCanvas',
x: 0,
y: 0,
width: 100,
height: 100,
success(res) {
console.log(res);
}
});
const data = new Uint8ClampedArray([255, 0, 0, 1]);
swan.canvasPutImageData({
canvasId: 'myCanvas',
data,
x: 0,
y: 0,
width: 1,
height: 2,
success(res) {
console.log('success');
}
});
swan.canvasToTempFilePath({
x: 100,
y: 200,
width: 50,
height: 50,
destWidth: 100,
destHeight: 100,
canvasId: 'myCanvas',
success(res) {
console.log(res.tempFilePath);
}
});
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('blue');
ctx.fillRect(30, 30, 150, 75);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('blue');
ctx.setShadow(10, 50, 50, 'red');
ctx.fillRect(30, 30, 150, 75);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// Create linear gradient
const grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, 'blue');
grd.addColorStop(1, 'red');
// Fill with gradient
ctx.setFillStyle(grd);
ctx.fillRect(30, 30, 150, 80);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// Create circular gradient
const grd = ctx.createCircularGradient(75, 50, 50);
grd.addColorStop(0, 'red');
grd.addColorStop(1, 'blue');
// Fill with gradient
ctx.setFillStyle(grd);
ctx.fillRect(30, 30, 150, 80);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// Create circular gradient
const grd = ctx.createLinearGradient(30, 10, 120, 10);
grd.addColorStop(0, 'red');
grd.addColorStop(0.16, 'orange');
grd.addColorStop(0.33, 'yellow');
grd.addColorStop(0.5, 'green');
grd.addColorStop(0.66, 'cyan');
grd.addColorStop(0.83, 'blue');
grd.addColorStop(1, 'purple');
// Fill with gradient
ctx.setFillStyle(grd);
ctx.fillRect(30, 30, 150, 80);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.beginPath();
ctx.moveTo(30, 10);
ctx.lineTo(200, 10);
ctx.stroke();
ctx.beginPath();
ctx.setLineWidth(5);
ctx.moveTo(50, 30);
ctx.lineTo(200, 30);
ctx.stroke();
ctx.beginPath();
ctx.setLineWidth(10);
ctx.moveTo(70, 50);
ctx.lineTo(200, 50);
ctx.stroke();
ctx.beginPath();
ctx.setLineWidth(15);
ctx.moveTo(90, 70);
ctx.lineTo(200, 70);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.beginPath();
ctx.moveTo(30, 10);
ctx.lineTo(200, 10);
ctx.stroke();
ctx.beginPath();
ctx.setLineCap('butt');
ctx.setLineWidth(10);
ctx.moveTo(50, 30);
ctx.lineTo(200, 30);
ctx.stroke();
ctx.beginPath();
ctx.setLineCap('round');
ctx.setLineWidth(10);
ctx.moveTo(70, 50);
ctx.lineTo(200, 50);
ctx.stroke();
ctx.beginPath();
ctx.setLineCap('square');
ctx.setLineWidth(10);
ctx.moveTo(90, 70);
ctx.lineTo(200, 70);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(100, 50);
ctx.lineTo(10, 90);
ctx.stroke();
ctx.beginPath();
ctx.setLineJoin('bevel');
ctx.setLineWidth(10);
ctx.moveTo(50, 10);
ctx.lineTo(140, 50);
ctx.lineTo(50, 90);
ctx.stroke();
ctx.beginPath();
ctx.setLineJoin('round');
ctx.setLineWidth(10);
ctx.moveTo(90, 10);
ctx.lineTo(180, 50);
ctx.lineTo(90, 90);
ctx.stroke();
ctx.beginPath();
ctx.setLineJoin('miter');
ctx.setLineWidth(10);
ctx.moveTo(130, 10);
ctx.lineTo(220, 50);
ctx.lineTo(130, 90);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setLineDash([10, 20], 5);
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.beginPath();
ctx.setLineWidth(10);
ctx.setLineJoin('miter');
ctx.setMiterLimit(1);
ctx.moveTo(10, 10);
ctx.lineTo(100, 50);
ctx.lineTo(10, 90);
ctx.stroke();
ctx.beginPath();
ctx.setLineWidth(10);
ctx.setLineJoin('miter');
ctx.setMiterLimit(2);
ctx.moveTo(50, 10);
ctx.lineTo(140, 50);
ctx.lineTo(50, 90);
ctx.stroke();
ctx.beginPath();
ctx.setLineWidth(10);
ctx.setLineJoin('miter');
ctx.setMiterLimit(3);
ctx.moveTo(90, 10);
ctx.lineTo(180, 50);
ctx.lineTo(90, 90);
ctx.stroke();
ctx.beginPath();
ctx.setLineWidth(10);
ctx.setLineJoin('miter');
ctx.setMiterLimit(4);
ctx.moveTo(130, 10);
ctx.lineTo(220, 50);
ctx.lineTo(130, 90);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.rect(30, 30, 150, 75);
ctx.setFillStyle('blue');
ctx.fill();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('blue');
ctx.fillRect(30, 30, 150, 75);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setStrokeStyle('blue');
ctx.strokeRect(30, 30, 150, 75);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('red');
ctx.fillRect(0, 0, 150, 200);
ctx.setFillStyle('blue');
ctx.fillRect(150, 0, 150, 200);
ctx.clearRect(30, 30, 150, 75);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.moveTo(100, 100);
ctx.lineTo(10, 100);
ctx.lineTo(10, 10);
ctx.fill();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.moveTo(100, 100);
ctx.lineTo(10, 100);
ctx.lineTo(10, 10);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.rect(10, 10, 100, 30);
ctx.setFillStyle('red');
ctx.fill();
ctx.beginPath();
ctx.rect(10, 40, 100, 30);
ctx.setFillStyle('blue');
ctx.fillRect(10, 70, 100, 30);
ctx.rect(10, 100, 100, 30);
ctx.setFillStyle('green');
ctx.fill();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.moveTo(100, 100);
ctx.lineTo(10, 100);
ctx.lineTo(10, 10);
ctx.closePath();
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.moveTo(10, 10);
ctx.lineTo(100, 10);
ctx.moveTo(10, 100);
ctx.lineTo(100, 100);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.moveTo(10, 10);
ctx.rect(10, 10, 100, 50);
ctx.lineTo(110, 60);
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.setFillStyle('blue');
ctx.fill();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.strokeRect(10, 10, 25, 15);
ctx.scale(2, 2);
ctx.strokeRect(10, 10, 25, 15);
ctx.scale(2, 2);
ctx.strokeRect(10, 10, 25, 15);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.strokeRect(100, 10, 150, 100);
ctx.rotate(20 * Math.PI / 180);
ctx.strokeRect(100, 10, 150, 100);
ctx.rotate(20 * Math.PI / 180);
ctx.strokeRect(100, 10, 150, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.strokeRect(10, 10, 150, 100);
ctx.translate(20, 20);
ctx.strokeRect(10, 10, 150, 100);
ctx.translate(20, 20);
ctx.strokeRect(10, 10, 150, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
swan.downloadFile({
url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg',
success(res) {
ctx.save();
ctx.beginPath();
ctx.arc(50, 50, 25, 0, 2 * Math.PI);
ctx.clip();
ctx.drawImage(res.tempFilePath, 25, 25);
ctx.restore();
ctx.draw();
}
});
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFontSize(20);
ctx.fillText('20', 20, 20);
ctx.setFontSize(30);
ctx.fillText('30', 40, 40);
ctx.setFontSize(40);
ctx.fillText('40', 60, 60);
ctx.setFontSize(50);
ctx.fillText('50', 90, 90);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFontSize(20);
ctx.fillText('Hello', 20, 20);
ctx.fillText('World', 100, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setStrokeStyle('red');
ctx.moveTo(150, 20);
ctx.lineTo(150, 170);
ctx.stroke();
ctx.setFontSize(15);
ctx.setTextAlign('left');
ctx.fillText('textAlign=left', 150, 60);
ctx.setTextAlign('center');
ctx.fillText('textAlign=center', 150, 80);
ctx.setTextAlign('right');
ctx.fillText('textAlign=right', 150, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setStrokeStyle('red');
ctx.moveTo(5, 75);
ctx.lineTo(295, 75);
ctx.stroke();
ctx.setFontSize(20);
ctx.setTextBaseline('top');
ctx.fillText('top', 5, 75);
ctx.setTextBaseline('middle');
ctx.fillText('middle', 50, 75);
ctx.setTextBaseline('bottom');
ctx.fillText('bottom', 120, 75);
ctx.setTextBaseline('normal');
ctx.fillText('normal', 200, 75);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
swan.chooseImage({
success(res) {
ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100);
ctx.draw();
}
});
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('red');
ctx.fillRect(10, 10, 150, 100);
ctx.setGlobalAlpha(0.2);
ctx.setFillStyle('blue');
ctx.fillRect(50, 50, 150, 100);
ctx.setFillStyle('yellow');
ctx.fillRect(100, 100, 150, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.font = 'italic bold 20px cursive';
const metrics = ctx.measureText('Hello World');
console.log(metrics.width);
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
const pattern = ctx.createPattern('/path/to/image', 'repeat-x');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 150);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// Draw quadratic curve
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.setStrokeStyle('black');
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// Draw quadratic curve
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(20, 100, 200, 20);
ctx.setStrokeStyle('blue');
ctx.stroke();
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// save the default fill style
ctx.save();
ctx.setFillStyle('blue');
ctx.fillRect(10, 10, 150, 100);
// restore to the previous saved state
ctx.restore();
ctx.fillRect(50, 50, 150, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
// save the default fill style
ctx.save();
ctx.setFillStyle('blue');
ctx.fillRect(10, 10, 150, 100);
// restore to the previous saved state
ctx.restore();
ctx.fillRect(50, 50, 150, 100);
ctx.draw();
})();
(() => {
const ctx = swan.createCanvasContext('myCanvas');
ctx.setFillStyle('blue');
ctx.fillRect(10, 10, 150, 100);
ctx.draw();
ctx.fillRect(30, 30, 150, 100);
ctx.draw();
})();
(() => {
swan.showToast({
title: '我是标题',
icon: 'loading',
duration: 1000,
});
swan.showLoading({
title: '加载中',
mask: 'true'
});
setTimeout(() => {
swan.hideLoading();
}, 2000);
swan.showModal({
title: '提示',
content: '这是一个模态弹窗',
cancelColor: '#999999',
confirmColor: '#0099cc',
success(res) {
if (res.confirm) {
console.log('用户点击了确定');
} else if (res.cancel) {
console.log('用户点击了取消');
}
}
});
swan.showActionSheet({
itemList: ['同意', '一般', '不同意'],
success(res) {
console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`);
}
});
})();
(() => {
swan.setNavigationBarTitle({
title: '我是页面标题'
});
swan.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: '#ff0000',
animation: {
duration: 500,
timingFunc: 'linear'
}
});
})();
(() => {
swan.setTabBarBadge({
index: 0,
text: '文本'
});
swan.removeTabBarBadge({
index: 0
});
swan.showTabBarRedDot({
index: 0
});
swan.hideTabBarRedDot({
index: 0
});
swan.setTabBarStyle({
color: '#FFFFBD',
selectedColor: '#FFFFBD',
backgroundColor: '#FFFFBD',
borderStyle: 'white'
});
swan.setTabBarItem({
index: 0,
text: '文本',
// 图片路径
iconPath: '/images/component_normal.png',
// 选中图片路径
selectedIconPath: '/images/component_selected.png',
});
swan.showTabBar({
success(res) {
console.log(res);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
swan.hideTabBar({
success(res) {
console.log(res);
},
fail(err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
})();
(() => {
swan.navigateTo({
// 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。
url: 'example/xxx?key=value'
});
swan.redirectTo({
// 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。
url: 'example/xxx?key=value'
});
swan.switchTab({
url: '/list',
});
// 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码
// 当前是首页
swan.navigateTo({
url: 'list?key=value'
});
// 当前是列表页
swan.navigateTo({
url: 'detail?key=value'
});
// 在详情页内 navigateBack,将返回首页
swan.navigateBack({
delta: 2
});
swan.reLaunch({
// 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。
url: 'example/xxx?key=value'
});
})();
(() => {
const animation = swan.createAnimation({
transformOrigin: "50% 50%",
duration: 1000,
timingFunction: "ease",
delay: 0
});
Page({
data: {
animationData: {}
},
starttoanimate() {
const animation = swan.createAnimation();
animation.rotate(90).translateY(10).step();
animation.rotate(-90).translateY(-10).step();
this.setData({
animationData: animation.export()
});
}
});
})();
(() => {
swan.pageScrollTo({
scrollTop: 0,
duration: 300
});
})();
(() => {
Page({
onPullDownRefresh() {
// do something
}
});
swan.startPullDownRefresh();
swan.stopPullDownRefresh();
})();
(() => {
swan.createIntersectionObserver({} as any, {
selectAll: true
}).relativeTo('.container')
.observe('.ball', res => {
console.log(res.intersectionRect); // 相交区域
console.log(res.intersectionRect.left); // 相交区域的左边界坐标
console.log(res.intersectionRect.top); // 相交区域的上边界坐标
console.log(res.intersectionRect.width); // 相交区域的宽度
console.log(res.intersectionRect.height); // 相交区域的高度
});
Page({
queryMultipleNodes() {
const query = swan.createSelectorQuery();
query.select('#the-id').boundingClientRect();
query.selectViewport().scrollOffset();
query.exec((res) => {
// res[0].top, // #the-id节点的上边界坐标
// res[1].scrollTop // 显示区域的竖直滚动位置
});
}
});
Component({
// queryMultipleNodes() {
// const query = swan.createSelectorQuery().in(this);
// query.select('#the-id').boundingClientRect((res) => {
// // res.top // 这个组件内 #the-id 节点的上边界坐标
// }).exec();
// }
});
Page({
getRect() {
swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => {
const rect = res as swan.NodesRefRect;
rect.id; // 节点的ID
rect.dataset; // 节点的dataset
rect.left; // 节点的左边界坐标
rect.right; // 节点的右边界坐标
rect.top; // 节点的上边界坐标
rect.bottom; // 节点的下边界坐标
rect.width; // 节点的宽度
rect.height; // 节点的高度
}).exec();
},
getAllRects() {
swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => {
(rects as swan.NodesRefRect[]).forEach((rect) => {
rect.id; // 节点的ID
rect.dataset; // 节点的dataset
rect.left; // 节点的左边界坐标
rect.right; // 节点的右边界坐标
rect.top; // 节点的上边界坐标
rect.bottom; // 节点的下边界坐标
rect.width; // 节点的宽度
rect.height; // 节点的高度
});
}).exec();
}
});
Page({
getScrollOffset() {
swan.createSelectorQuery().selectViewport().scrollOffset((res) => {
res.id; // 节点的ID
res.dataset; // 节点的dataset
res.scrollLeft; // 节点的水平滚动位置
res.scrollTop; // 节点的竖直滚动位置
}).exec();
}
});
Page({
getFields() {
swan.createSelectorQuery().select('#the-id').fields({
dataset: true,
size: true,
scrollOffset: true,
properties: ['scrollX', 'scrollY'],
computedStyle: ['margin', 'backgroundColor']
}, (res) => {
res.dataset; // 节点的dataset
res.width; // 节点的宽度
res.height; // 节点的高度
res.scrollLeft; // 节点的水平滚动位置
res.scrollTop; // 节点的竖直滚动位置
res.scrollX; // 节点 scroll-x 属性的当前值
res.scrollY; // 节点 scroll-y 属性的当前值
// 此处返回指定要返回的样式名
res.margin;
res.backgroundColor;
}).exec();
}
});
})();
(() => {
swan.getSystemInfo({
success(res) {
console.log(res.model);
console.log(res.pixelRatio);
console.log(res.windowWidth);
console.log(res.windowHeight);
console.log(res.language);
console.log(res.version);
console.log(res.platform);
}
});
try {
const res = swan.getSystemInfoSync();
console.log(res.model);
console.log(res.pixelRatio);
console.log(res.windowWidth);
console.log(res.windowHeight);
console.log(res.language);
console.log(res.version);
console.log(res.platform);
} catch (e) {
// Do something when catch error
}
try {
const res = swan.getEnvInfoSync();
console.log(res.appKey);
console.log(res.appName);
console.log(res.lastAppURL);
console.log(res.sdkVersion);
console.log(res.scheme);
} catch (e) {
// Do something when catch error
}
swan.canIUse('view.hover-class');
swan.canIUse('scroll-view.scroll-x');
swan.canIUse('cover-view');
swan.canIUse('button.size.default');
swan.canIUse('button.size.default');
swan.canIUse('request.object.success.data');
swan.canIUse('getSavedFileList');
swan.canIUse('getSavedFileList.object');
swan.canIUse('getSavedFileList.object.success');
})();
(() => {
swan.onMemoryWarning((res) => {
console.log('onMemoryWarningReceive');
});
})();
(() => {
swan.getNetworkType({
success(res) {
console.log(res.networkType);
}
});
swan.onNetworkStatusChange((res) => {
console.log(res.isConnected);
console.log(res.networkType);
});
})();
(() => {
swan.onAccelerometerChange((res) => {
console.log(res.x);
console.log(res.y);
console.log(res.z);
});
swan.startAccelerometer({
interval: 'ui'
});
swan.stopAccelerometer();
})();
(() => {
swan.onCompassChange((res) => {
console.log(res.direction);
});
swan.startCompass();
swan.stopCompass();
})();
(() => {
swan.scanCode({
success(res) {
console.log(res.result);
console.log(res.scanType);
}
});
})();
(() => {
swan.onUserCaptureScreen(() => {
console.log('用户截屏了');
});
})();
(() => {
swan.makePhoneCall({
phoneNumber: '000000' // 仅为示例,并非真实的电话号码
});
})();
(() => {
swan.setClipboardData({
data: 'baidu',
success(res) {
swan.getClipboardData({
success(res) {
console.log(res.data); // baidu
}
});
}
});
swan.getClipboardData({
success(res) {
console.log(res.data);
}
});
})();
(() => {
swan.getExtConfig({
success(res) {
console.log(res.extConfig);
}
});
const data = swan.getExtConfigSync();
console.log(data.extConfig);
})();
(() => {
swan.login({
success(res) {
swan.request({
url: 'https://xxx/xxx', // 开发者服务器地址
data: {
code: res.code
}
});
},
fail(err) {
console.log('login fail', err);
}
});
swan.checkSession({
success(res) {
console.log('登录态有效');
swan.getUserInfo({
success(res) {
console.log('用户名', res.userInfo.nickName);
swan.request({
url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密
data: {
data: res.data,
iv: res.iv
}
});
}
});
},
fail(err) {
console.log('登录态无效');
swan.login({
success(res) {
swan.request({
url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key
data: {
code: res.code
}
});
},
fail(err) {
console.log('登录失败', err);
}
});
}
});
try {
const result = swan.isLoginSync();
console.log('isLoginSync', result);
} catch (e) {
console.log('error', e);
}
})();
(() => {
swan.authorize({
scope: 'scope.userLocation',
success(res) {
// 用户已经同意智能小程序使用定位功能
swan.getLocation();
}
});
})();
(() => {
swan.getSwanId({
success(res) {
console.log(res.data.swanid);
}
});
swan.getUserInfo({
success(res) {
console.log('用户名', res.userInfo.nickName);
}
});
})();
(() => {
swan.openSetting({
success(res) {
console.log(res.authSetting['scope.userInfo']);
console.log(res.authSetting['scope.userLocation']);
}
});
swan.getSetting({
success(res) {
console.log(res.authSetting['scope.userInfo']);
console.log(res.authSetting['scope.userLocation']);
}
});
})();
(() => {
Page({
onShareAppMessage() {
return {
title: '智能小程序示例',
path: '/pages/openShare/openShare?key=value'
};
}
});
swan.openShare({
title: '智能小程序示例',
content: '世界很复杂,百度更懂你',
path: '/pages/openShare/openShare?key=value'
});
})();
(() => {
swan.chooseAddress({
success(res) {
console.log(res.userName);
console.log(res.postalCode);
console.log(res.provinceName);
console.log(res.cityName);
console.log(res.countyName);
console.log(res.detailInfo);
console.log(res.telNumber);
}
});
})();
(() => {
swan.requestPolymerPayment({
orderInfo: {
dealId: "470193086",
appKey: "MMMabc",
totalAmount: "1",
tpOrderId: "3028903626",
dealTitle: "智能小程序Demo支付测试",
signFieldsRange: 1,
rsaSign: '',
bizInfo: ''
},
success(res) {
swan.showToast({
title: '支付成功',
icon: 'success'
});
},
fail(err) {
swan.showToast({
title: JSON.stringify(err)
});
console.log('pay fail', err);
}
});
})();
(() => {
swan.chooseInvoiceTitle({
success(res) {
console.log(res.type);
console.log(res.title);
console.log(res.taxNumber);
console.log(res.companyAddress);
console.log(res.telephone);
console.log(res.bankName);
console.log(res.bankAccount);
}
});
})();
(() => {
swan.navigateToSmartProgram({
appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key
path: '', // 打开的页面路径,如果为空则打开首页
extraData: {
foo: 'baidu'
},
success(res) {
// 打开成功
}
});
swan.navigateBackSmartProgram({
extraData: {
foo: 'baidu'
},
success(res) {
// 返回成功
}
});
})();
(() => {
if (swan.setMetaDescription) {
swan.setMetaDescription({
content: '当前小程序页面描述信息',
success(res) {
console.log('设置成功');
},
fail(res) {
console.log('设置失败');
},
complete(res) {
console.log('设置失败');
}
});
}
if (swan.setMetaKeywords) {
swan.setMetaKeywords({
content: '小程序, 关键字',
success(res) {
console.log('设置成功');
},
fail(res) {
console.log('设置失败');
},
complete(res) {
console.log('设置失败');
}
});
}
if (swan.setDocumentTitle) {
swan.setDocumentTitle({
title: '我是页面标题'
});
}
})();
(() => {
swan.loadSubPackage({
root: 'subpackage',
success(res) {
console.log('下载成功', res);
},
fail(err) {
console.log('下载失败', err);
}
});
})();
(() => {
const updateManager = swan.getUpdateManager();
updateManager.onCheckForUpdate((res) => {
// 请求完新版本信息的回调
console.log(res.hasUpdate);
});
updateManager.onUpdateReady((res) => {
swan.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
});
});
updateManager.onUpdateFailed((res) => {
// 新的版本下载失败
});
})();
(() => {
// 打开调试
swan.setEnableDebug({
enableDebug: true
});
// 关闭调试
swan.setEnableDebug({
enableDebug: false
});
})();
(() => {
swan.reportAnalytics('purchase', {
price: 120,
color: 'red'
});
})(); | the_stack |
import {
DOMWidgetModel, DOMWidgetView, ISerializers
} from '@jupyter-widgets/base';
import {
MODULE_NAME, MODULE_VERSION
} from './version';
import '../style/base.css'
import * as React from "react";
import * as ReactDOM from "react-dom";
import _ from 'lodash';
import {Tabs,Tab} from 'react-bootstrap';
import ChartGalleryComponent from './chartGallery';
import CurrentVisComponent from './currentVis';
import {dispatchLogEvent} from './utils';
import ButtonsBroker from './buttonsBroker';
import WarningBtn from './warningBtn';
import InfoBtn from './infoBtn';
export class LuxModel extends DOMWidgetModel {
defaults() {
return {...super.defaults(),
_model_name: LuxModel.model_name,
_model_module: LuxModel.model_module,
_model_module_version: LuxModel.model_module_version,
_view_name: LuxModel.view_name,
_view_module: LuxModel.view_module,
_view_module_version : LuxModel.model_module_version
};
}
static serializers: ISerializers = {
...DOMWidgetModel.serializers,
// Add any extra serializers here
}
static model_name = 'LuxModel';
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
static view_name = 'LuxWidgetView'; // Set to null if no view
static view_module = MODULE_NAME; // Set to null if no view
static view_module_version = MODULE_VERSION;
}
export class LuxWidgetView extends DOMWidgetView {
initialize(){
let view = this;
interface WidgetProps{
currentVis: object,
recommendations: any[],
intent: string,
selectedIntentIndex: object,
message: string,
longDescription: string,
tabItems: any,
activeTab: any,
showAlert: boolean,
selectedRec: object,
_selectedVisIdxs: object,
deletedIndices: object,
currentVisSelected: number,
openWarning: boolean,
openInfo: boolean,
plottingScale: number
}
class ReactWidget extends React.Component<LuxWidgetView,WidgetProps> {
private chartComponents = Array<any>();
constructor(props:any){
super(props);
for (var i = 0; i < this.props.model.get("recommendations").length; i++) {
this.chartComponents.push(React.createRef<ChartGalleryComponent>());
}
this.state = {
currentVis: props.model.get("current_vis"),
recommendations: props.model.get("recommendations"),
intent: props.model.get("intent"),
selectedIntentIndex: {},
message: props.model.get("message"),
longDescription: this.generateDescription(null),
tabItems: this.generateTabItems(),
activeTab: props.activeTab,
showAlert: false,
selectedRec: {},
_selectedVisIdxs: {},
deletedIndices: {},
currentVisSelected: -2,
openWarning: false,
openInfo: false,
plottingScale: props.model.get("plotting_scale") || 1
}
// This binding is necessary to make `this` work in the callback
this.handleCurrentVisSelect = this.handleCurrentVisSelect.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.exportSelection = this.exportSelection.bind(this);
this.toggleWarningPanel = this.toggleWarningPanel.bind(this);
this.deleteSelection = this.deleteSelection.bind(this);
this.setIntent = this.setIntent.bind(this);
this.closeExportInfo = this.closeExportInfo.bind(this);
this.toggleInfoPanel = this.toggleInfoPanel.bind(this);
}
toggleWarningPanel(e){
if (this.state.openWarning){
dispatchLogEvent("closeWarning",this.state.message);
this.setState({openWarning:false});
} else {
dispatchLogEvent("openWarning",this.state.message);
this.setState({openWarning:true});
}
}
// called to toggle the long description panel
toggleInfoPanel(e){
if (this.state.openInfo) {
dispatchLogEvent("closeInfo",this.state.longDescription);
this.setState({openInfo:false});
} else {
dispatchLogEvent("openInfo",this.state.longDescription);
this.setState({openInfo:true});
}
}
// called to close alert pop up upon export button hit by user
closeExportInfo() {
dispatchLogEvent("closeExportInfo", null);
this.setState({
showAlert:false});
}
// called when the variable is changed in the view.model
onChange(model:any){
this.setState(model.changed);
}
// triggered when component is mounted (i.e., when widget first rendered)
componentDidMount(){
view.listenTo(view.model,"change",this.onChange.bind(this));
}
// triggered after component is updated
// instead of touch (which leads to callback issues), we have to use save_changes
componentDidUpdate(){
view.model.save_changes();
}
// populates the long description
generateDescription(selectedTab) {
// selectedTab starts out as null and is populated on switches of tabs
if (!selectedTab) {
// takes care of init, sets to first longDescription in recommendations list
if (this.props.model.get("recommendations").length > 0) {
selectedTab = this.props.model.get("recommendations")[0].action;
} else {
return "";
}
}
var description = "";
for (var recommendation of this.props.model.get("recommendations")) {
if (recommendation.action === selectedTab) {
description = recommendation.long_description
}
}
return description;
}
handleSelect(selectedTab) {
// The active tab must be set into the state so that
// the Tabs component knows about the change and re-renders.
if (selectedTab){
dispatchLogEvent("switchTab",selectedTab)
}
var description = this.generateDescription(selectedTab);
this.setState({
activeTab: selectedTab,
longDescription: description
});
}
handleCurrentVisSelect = (selectedValue) => {
this.setState({ currentVisSelected: selectedValue }, () => {
if (selectedValue == -1) {
this.onListChanged(-1, null);
} else {
this.onListChanged(-2, null);
}
});
}
onListChanged(tabIdx,selectedLst) {
// Example _selectedVisIdxs : {'Correlation': [0, 2], 'Occurrence': [1]}
var _selectedVisIdxs = {}
this.state.selectedRec[tabIdx] = selectedLst // set selected elements as th selectedRec of this tab
for (var tabID of Object.keys(this.state.selectedRec)){
if (tabID in this.state.recommendations) {
var actionName = this.state.recommendations[tabID]["action"]
if (this.state.selectedRec[tabID].length > 0) {
_selectedVisIdxs[actionName] = this.state.selectedRec[tabID]
}
} else if (this.state.currentVisSelected == -1) {
_selectedVisIdxs["currentVis"] = this.state.currentVis
}
}
this.setState({
_selectedVisIdxs: _selectedVisIdxs
});
}
exportSelection() {
dispatchLogEvent("exportBtnClick",this.state._selectedVisIdxs);
this.setState(
state => ({
showAlert:true
}));
// Expire alert box in 1 minute
setTimeout(()=>{
this.setState(
state => ({
showAlert:false
}));
},60000);
view.model.set('_selectedVisIdxs', this.state._selectedVisIdxs);
view.model.save();
}
/*
* Goes through all selections and removes and clears any selections across recommendation tabs.
* Changing deletedIndices triggers an observer in the backend to update backend data structure.
* Re-renders each tab's chart component, with the updated recommendations.
*/
deleteSelection() {
dispatchLogEvent("deleteBtnClick", this.state._selectedVisIdxs);
var currDeletions = this.state._selectedVisIdxs;
// Deleting from the frontend's visualization data structure
for (var recommendation of this.state.recommendations) {
if (this.state._selectedVisIdxs[recommendation.action]) {
let delCount = 0;
for (var index of this.state._selectedVisIdxs[recommendation.action]) {
recommendation.vspec.splice(index - delCount, 1);
delCount++;
}
}
}
this.setState({
selectedRec: {},
_selectedVisIdxs: {},
deletedIndices: currDeletions
});
// Re-render each tab's components to update deletions on front end
for (var i = 0; i < this.props.model.get("recommendations").length; i++) {
this.chartComponents[i].current.removeDeletedCharts();
}
view.model.set('deletedIndices', currDeletions);
view.model.set('_selectedVisIdxs', {});
view.model.save();
}
/*
* Set selected Vis as intent and re-renders widget to update to new view.
* Shows warning if user tries to select more than one Vis card.
*/
setIntent() {
dispatchLogEvent("intentBtnClick", this.state._selectedVisIdxs);
if (Object.keys(this.state._selectedVisIdxs).length == 1) {
var action = Object.keys(this.state._selectedVisIdxs)[0];
if (this.state._selectedVisIdxs[action].length == 1) {
view.model.set('selectedIntentIndex', this.state._selectedVisIdxs);
view.model.save();
return;
}
}
}
generateTabItems() {
return (
this.props.model.get("recommendations").map((actionResult,tabIdx) =>
<Tab eventKey={actionResult.action} title={actionResult.action} >
<ChartGalleryComponent
// this exists to prevent chart gallery from refreshing while changing tabs
// This is an anti-pattern for React, but is necessary here because our chartgallery is very expensive to initialize
key={'no refresh'}
ref={this.chartComponents[tabIdx]}
title={actionResult.action}
description={actionResult.description}
multiple={true}
maxSelectable={10}
onChange={this.onListChanged.bind(this,tabIdx)}
graphSpec={actionResult.vspec}
currentVisShow={!_.isEmpty(this.props.model.get("current_vis"))}
plottingScale={this.props.model.get("plotting_scale")}
/>
</Tab>
)
)
}
generateNoRecsWarning() {
if (this.state.message!= "") {
return <div id="no-recs-footer" style={{display:"flex"}}>
<div id="no-recs" className = "fa fa-exclamation-triangle"></div>
<div><p className="warnMsgText" dangerouslySetInnerHTML={{__html: this.state.message.replace(/<[^>]+>/g, '')}}></p></div>
</div>
}
}
render() {
var buttonsEnabled = Object.keys(this.state._selectedVisIdxs).length > 0;
var intentEnabled = Object.keys(this.state._selectedVisIdxs).length == 1 && Object.values(this.state._selectedVisIdxs)[0].length == 1;
const height: string = (320 + 160 * (this.state.plottingScale - 1)).toString() + "px";
if (this.state.recommendations.length == 0) {
return (<div id="oneViewWidgetContainer" style={{ flexDirection: 'column' }}>
<div style={{ display: 'flex', flexDirection: 'row', height: height }}>
<CurrentVisComponent intent={this.state.intent} currentVisSpec={this.state.currentVis} numRecommendations={this.state.recommendations.length}
onChange={this.handleCurrentVisSelect}
plottingScale={this.state.plottingScale} />
</div>
<ButtonsBroker buttonsEnabled={buttonsEnabled}
deleteSelection={this.deleteSelection}
exportSelection={this.exportSelection}
setIntent={this.setIntent}
closeExportInfo={this.closeExportInfo}
tabItems={this.state.tabItems}
showAlert={this.state.showAlert}
intentEnabled={intentEnabled}
/>
{this.generateNoRecsWarning()}
</div>);
} else if (this.state.recommendations.length > 0) {
return (<div id="widgetContainer" style={{ flexDirection: 'column' }}>
{/* {attributeShelf}
{filterShelf} */}
<div style={{ display: 'flex', flexDirection: 'row', height: height }}>
<CurrentVisComponent intent={this.state.intent} currentVisSpec={this.state.currentVis} numRecommendations={this.state.recommendations.length}
onChange={this.handleCurrentVisSelect}
plottingScale={this.state.plottingScale} />
<div id="tabBanner">
<p className="title-description" style={{visibility: !_.isEmpty(this.state.currentVis) ? 'visible' : 'hidden' }}>You might be interested in...</p>
<Tabs activeKey={this.state.activeTab} id="tabBannerList" onSelect={this.handleSelect} className={!_.isEmpty(this.state.currentVis) ? "tabBannerPadding" : ""}>
{this.state.tabItems}
</Tabs>
</div>
</div>
<ButtonsBroker buttonsEnabled={buttonsEnabled}
deleteSelection={this.deleteSelection}
exportSelection={this.exportSelection}
setIntent={this.setIntent}
closeExportInfo={this.closeExportInfo}
tabItems={this.state.tabItems}
showAlert={this.state.showAlert}
intentEnabled={intentEnabled}
/>
<InfoBtn message={this.state.longDescription} toggleInfoPanel={this.toggleInfoPanel} openInfo={this.state.openInfo} />
<WarningBtn message={this.state.message} toggleWarningPanel={this.toggleWarningPanel} openWarning={this.state.openWarning} />
</div>);
}
}
}
const $app = document.createElement("div");
const App = React.createElement(ReactWidget,view);
ReactDOM.render(App,$app); // Renders the app
view.el.append($app); //attaches the rendered app to the DOM (both are required for the widget to show)
dispatchLogEvent("initWidget","")
}
} | the_stack |
* @module MarkupTools
*/
// cspell:ignore rtmp stmp
import { Point3d, Vector3d } from "@itwin/core-geometry";
import {
BeButtonEvent, CoordinateLockOverrides, CoreTools, EventHandled, IModelApp, QuantityType, ToolAssistance, ToolAssistanceImage,
ToolAssistanceInputMethod, ToolAssistanceInstruction, ToolAssistanceSection,
} from "@itwin/core-frontend";
import { G, Marker, Element as MarkupElement, SVG } from "@svgdotjs/svg.js";
import { MarkupApp } from "./Markup";
import { MarkupTool } from "./MarkupTool";
/** Base class for tools that place new Markup elements
* @public
*/
export abstract class RedlineTool extends MarkupTool {
protected _minPoints = 1;
protected _nRequiredPoints = 2;
protected readonly _points: Point3d[] = [];
protected onAdded(el: MarkupElement) {
const markup = this.markup;
const undo = markup.undo;
undo.performOperation(this.keyin, () => undo.onAdded(el));
markup.selected.restart(el);
}
protected isComplete(_ev: BeButtonEvent) { return this._points.length >= this._nRequiredPoints; }
protected override setupAndPromptForNextAction(): void {
super.setupAndPromptForNextAction();
this.markup.disablePick();
IModelApp.toolAdmin.setCursor(0 === this._points.length ? IModelApp.viewManager.crossHairCursor : IModelApp.viewManager.dynamicsCursor);
}
protected createMarkup(_svgMarkup: G, _ev: BeButtonEvent, _isDynamics: boolean): void { }
protected clearDynamicsMarkup(_isDynamics: boolean): void { this.markup.svgDynamics!.clear(); }
public override async onRestartTool() { return this.exitTool(); } // Default to single shot and return control to select tool...
public override async onCleanup() { this.clearDynamicsMarkup(false); }
public override async onReinitialize() {
this.clearDynamicsMarkup(false);
return super.onReinitialize();
}
public override async onUndoPreviousStep(): Promise<boolean> {
return (0 === this._points.length) ? false : (this.onReinitialize(), true);
}
public override async onMouseMotion(ev: BeButtonEvent): Promise<void> {
if (undefined === ev.viewport || this._points.length < this._minPoints)
return;
this.clearDynamicsMarkup(true);
this.createMarkup(this.markup.svgDynamics!, ev, true);
}
public override async onDataButtonDown(ev: BeButtonEvent): Promise<EventHandled> {
if (undefined === ev.viewport)
return EventHandled.No;
this._points.push(MarkupApp.convertVpToVb(ev.viewPoint));
if (!this.isComplete(ev)) {
this.setupAndPromptForNextAction();
return EventHandled.No;
}
this.createMarkup(this.markup.svgMarkup!, ev, false);
await this.onReinitialize();
return EventHandled.No;
}
public override async onResetButtonUp(_ev: BeButtonEvent): Promise<EventHandled> {
await this.onReinitialize();
return EventHandled.No;
}
protected provideToolAssistance(mainInstrKey: string, singlePoint: boolean = false): void {
const mainInstruction = ToolAssistance.createInstruction(this.iconSpec, IModelApp.localization.getLocalizedString(mainInstrKey));
const mouseInstructions: ToolAssistanceInstruction[] = [];
const touchInstructions: ToolAssistanceInstruction[] = [];
const acceptMsg = CoreTools.translate("ElementSet.Inputs.AcceptPoint");
const rejectMsg = CoreTools.translate("ElementSet.Inputs.Exit");
if (!ToolAssistance.createTouchCursorInstructions(touchInstructions))
touchInstructions.push(ToolAssistance.createInstruction(singlePoint ? ToolAssistanceImage.OneTouchTap : ToolAssistanceImage.OneTouchDrag, acceptMsg, false, ToolAssistanceInputMethod.Touch));
mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.LeftClick, acceptMsg, false, ToolAssistanceInputMethod.Mouse));
touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.TwoTouchTap, rejectMsg, false, ToolAssistanceInputMethod.Touch));
mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.RightClick, rejectMsg, false, ToolAssistanceInputMethod.Mouse));
const sections: ToolAssistanceSection[] = [];
sections.push(ToolAssistance.createSection(mouseInstructions, ToolAssistance.inputsLabel));
sections.push(ToolAssistance.createSection(touchInstructions, ToolAssistance.inputsLabel));
const instructions = ToolAssistance.createInstructions(mainInstruction, sections);
IModelApp.notifications.setToolAssistance(instructions);
}
}
/** Tool for placing Markup Lines
* @public
*/
export class LineTool extends RedlineTool {
public static override toolId = "Markup.Line";
public static override iconSpec = "icon-line";
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartPoint" : "ElementSet.Prompts.EndPoint")); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const element = svgMarkup.line(start.x, start.y, end.x, end.y);
this.setCurrentStyle(element, false);
if (!isDynamics)
this.onAdded(element);
}
}
/** Tool for placing Markup Rectangles
* @public
*/
export class RectangleTool extends RedlineTool {
public static override toolId = "Markup.Rectangle";
public static override iconSpec = "icon-rectangle";
constructor(protected _cornerRadius?: number) { super(); } // Specify radius to create a rectangle with rounded corners.
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartCorner" : "ElementSet.Prompts.OppositeCorner")); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const vec = start.vectorTo(end);
const width = Math.abs(vec.x);
const height = Math.abs(vec.y);
if (width < 1 || height < 1)
return;
const offset = Point3d.create(vec.x < 0 ? end.x : start.x, vec.y < 0 ? end.y : start.y); // define location by corner points...
const element = svgMarkup.rect(width, height).move(offset.x, offset.y);
this.setCurrentStyle(element, true);
if (undefined !== this._cornerRadius)
element.radius(this._cornerRadius);
if (!isDynamics)
this.onAdded(element);
}
}
/** Tool for placing Markup Polygons
* @public
*/
export class PolygonTool extends RedlineTool {
public static override toolId = "Markup.Polygon";
public static override iconSpec = "icon-polygon";
constructor(protected _numSides?: number) { super(); } // Specify number of polygon sides. Default if undefined is 5.
protected override showPrompt(): void { this.provideToolAssistance(MarkupTool.toolKey + (0 === this._points.length ? "Polygon.Prompts.FirstPoint" : "Polygon.Prompts.NextPoint")); }
protected getPoints(points: number[], center: Point3d, edge: Point3d, numSides: number, inscribe: boolean): boolean {
if (numSides < 3 || numSides > 100)
return false;
let radius = center.distanceXY(edge);
if (radius < 1)
return false;
const delta = (Math.PI * 2.0) / numSides;
const vec = center.vectorTo(edge);
let angle = Vector3d.unitX().planarRadiansTo(vec, Vector3d.unitZ());
if (!inscribe) { const theta = delta * 0.5; angle -= theta; radius /= Math.cos(theta); }
const rtmp = Point3d.create();
const stmp = Point3d.create();
for (let i = 0; i < numSides; i++, angle += delta) {
rtmp.x = radius * Math.cos(angle);
rtmp.y = radius * Math.sin(angle);
rtmp.z = 0.0;
center.plus(rtmp, stmp);
points.push(stmp.x);
points.push(stmp.y);
}
return true;
}
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const center = this._points[0];
const edge = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const pts: number[] = [];
if (!this.getPoints(pts, center, edge, undefined !== this._numSides ? this._numSides : 5, true))
return;
const element = svgMarkup.polygon(pts);
this.setCurrentStyle(element, true);
if (!isDynamics)
this.onAdded(element);
}
}
/** Tool for placing Markup Clouds
* @public
*/
export class CloudTool extends RedlineTool {
public static override toolId = "Markup.Cloud";
public static override iconSpec = "icon-cloud";
protected _cloud?: MarkupElement;
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartCorner" : "ElementSet.Prompts.OppositeCorner")); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const vec = start.vectorTo(end);
const width = Math.abs(vec.x);
const height = Math.abs(vec.y);
if (width < 10 || height < 10)
return;
if (undefined === this._cloud) {
this._cloud = svgMarkup.path(MarkupApp.props.active.cloud.path);
} else if (!isDynamics) {
svgMarkup.add(this._cloud);
}
const offset = Point3d.create(vec.x < 0 ? end.x : start.x, vec.y < 0 ? end.y : start.y); // define location by corner points...
this._cloud.move(offset.x, offset.y);
this._cloud.width(width);
this._cloud.height(height);
this.setCurrentStyle(this._cloud, true);
if (!isDynamics)
this.onAdded(this._cloud);
}
protected override clearDynamicsMarkup(isDynamics: boolean): void {
if (!isDynamics)
super.clearDynamicsMarkup(isDynamics); // For dynamics we don't create a new cloud each frame, we just set the width/height...
}
}
/** Tool for placing Markup Circles
* @public
*/
export class CircleTool extends RedlineTool {
public static override toolId = "Markup.Circle";
public static override iconSpec = "icon-circle";
protected override showPrompt(): void { this.provideToolAssistance(MarkupTool.toolKey + (0 === this._points.length ? "Circle.Prompts.FirstPoint" : "Circle.Prompts.NextPoint")); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const radius = start.distanceXY(end);
if (radius < 1)
return;
const element = svgMarkup.circle(radius * 2.0).center(start.x, start.y);
this.setCurrentStyle(element, true);
if (!isDynamics)
this.onAdded(element);
}
}
/** Tool for placing Markup Ellipses
* @public
*/
export class EllipseTool extends RedlineTool {
public static override toolId = "Markup.Ellipse";
public static override iconSpec = "icon-ellipse";
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartCorner" : "ElementSet.Prompts.OppositeCorner")); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const vec = start.vectorTo(end);
const width = Math.abs(vec.x);
const height = Math.abs(vec.y);
if (width < 1 || height < 1)
return;
const offset = Point3d.create(vec.x < 0 ? end.x : start.x, vec.y < 0 ? end.y : start.y); // define location by corner points...
const element = svgMarkup.ellipse(width, height).move(offset.x, offset.y);
this.setCurrentStyle(element, true);
if (!isDynamics)
this.onAdded(element);
}
}
/** Tool for placing Markup Arrows
* @public
*/
export class ArrowTool extends RedlineTool {
public static override toolId = "Markup.Arrow";
public static override iconSpec = "icon-callout";
/** ctor for ArrowTool
* @param _arrowPos "start", "end", or "both". If undefined = "end".
*/
constructor(protected _arrowPos?: string) { super(); }
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartPoint" : "ElementSet.Prompts.EndPoint")); }
protected getOrCreateArrowMarker(color: string): Marker {
// NOTE: Flashing doesn't currently affect markers, need support for "context-stroke" and "context-fill". For now encode color in name...
const arrowProps = MarkupApp.props.active.arrow;
const arrowLength = arrowProps.length;
const arrowWidth = arrowProps.width;
const arrowMarkerId = `ArrowMarker${arrowLength}x${arrowWidth}-${color}`;
let marker = SVG(`#${arrowMarkerId}`) as Marker;
if (null === marker) {
marker = this.markup.svgMarkup!.marker(arrowLength, arrowWidth).id(arrowMarkerId);
marker.polygon([0, 0, arrowLength, arrowWidth * 0.5, 0, arrowWidth]);
marker.attr("orient", "auto-start-reverse");
marker.attr("overflow", "visible"); // Don't clip the stroke that is being applied to allow the specified start/end to be used directly while hiding the arrow tail fully under the arrow head...
marker.attr("refX", arrowLength);
marker.css({ stroke: color, fill: color });
}
return marker;
}
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const vec = start.vectorTo(end);
if (!vec.normalizeInPlace())
return;
const element = svgMarkup.line(start.x, start.y, end.x, end.y);
this.setCurrentStyle(element, false);
const marker = this.getOrCreateArrowMarker(element.css("stroke"));
const addToStart = ("start" === this._arrowPos || "both" === this._arrowPos);
const addToEnd = ("end" === this._arrowPos || "both" === this._arrowPos);
if (addToStart)
element.marker("start", marker);
if (addToEnd || !addToStart)
element.marker("end", marker);
if (!isDynamics)
this.onAdded(element);
}
}
/** Tool for measuring distances and placing Markups of them
* @public
*/
export class DistanceTool extends ArrowTool {
public static override toolId = "Markup.Distance";
public static override iconSpec = "icon-distance";
protected readonly _startPointWorld = new Point3d();
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartPoint" : "ElementSet.Prompts.EndPoint")); }
protected override setupAndPromptForNextAction(): void { IModelApp.accuSnap.enableSnap(true); IModelApp.toolAdmin.toolState.coordLockOvr = CoordinateLockOverrides.None; super.setupAndPromptForNextAction(); }
protected getFormattedDistance(distance: number): string | undefined {
const formatterSpec = IModelApp.quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length);
if (undefined === formatterSpec)
return undefined;
return IModelApp.quantityFormatter.formatQuantity(distance, formatterSpec);
}
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[1];
const vec = start.vectorTo(end);
if (!vec.normalizeInPlace())
return;
const formatterSpec = IModelApp.quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length);
if (undefined === formatterSpec)
return;
const distanceLine = svgMarkup.line(start.x, start.y, end.x, end.y);
this.setCurrentStyle(distanceLine, false);
const marker = this.getOrCreateArrowMarker(distanceLine.css("stroke"));
distanceLine.marker("start", marker);
distanceLine.marker("end", marker);
const loc = start.interpolate(0.5, end);
const distance = IModelApp.quantityFormatter.formatQuantity(this._startPointWorld.distance(ev.point), formatterSpec);
const text = svgMarkup.plain(distance).addClass(MarkupApp.textClass).attr("text-anchor", "middle").translate(loc.x, loc.y);
this.setCurrentTextStyle(text);
const textWithBg = this.createBoxedText(svgMarkup, text);
if (!isDynamics) {
const markup = this.markup;
const undo = markup.undo;
undo.performOperation(this.keyin, () => { undo.onAdded(distanceLine); undo.onAdded(textWithBg); });
markup.selected.restart(textWithBg); // Select text+box so that user can freely position relative to distance line...
}
}
public override async onDataButtonDown(ev: BeButtonEvent): Promise<EventHandled> {
if (undefined === await IModelApp.quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length)) {
await this.onReinitialize();
return EventHandled.No;
}
if (0 === this._points.length)
this._startPointWorld.setFrom(ev.point);
return super.onDataButtonDown(ev);
}
}
/** Tool for placing Markup freehand sketches
* @public
*/
export class SketchTool extends RedlineTool {
public static override toolId = "Markup.Sketch";
public static override iconSpec = "icon-draw";
protected _minDistSquared = 100;
protected override showPrompt(): void { this.provideToolAssistance(CoreTools.tools + (0 === this._points.length ? "ElementSet.Prompts.StartPoint" : "ElementSet.Prompts.EndPoint")); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (this._points.length < (isDynamics ? this._nRequiredPoints - 1 : this._nRequiredPoints))
return;
const pts: number[] = [];
const evPt = MarkupApp.convertVpToVb(ev.viewPoint);
this._points.forEach((pt) => { pts.push(pt.x); pts.push(pt.y); });
if (isDynamics && !evPt.isAlmostEqualXY(this._points[this._points.length - 1])) { pts.push(evPt.x); pts.push(evPt.y); }
const isClosed = (this._points.length > 2 && (this._points[0].distanceSquaredXY(isDynamics ? evPt : this._points[this._points.length - 1]) < this._minDistSquared * 2));
const element = isClosed ? svgMarkup.polygon(pts) : svgMarkup.polyline(pts);
this.setCurrentStyle(element, isClosed);
if (!isDynamics)
this.onAdded(element);
}
public override async onMouseMotion(ev: BeButtonEvent): Promise<void> {
const evPt = MarkupApp.convertVpToVb(ev.viewPoint);
if (undefined !== ev.viewport && this._points.length > 0 && evPt.distanceSquaredXY(this._points[this._points.length - 1]) > this._minDistSquared)
this._points.push(evPt);
return super.onMouseMotion(ev);
}
}
/** Tool for placing SVG symbols on a Markup
* @public
*/
export class SymbolTool extends RedlineTool {
public static override toolId = "Markup.Symbol";
public static override iconSpec = "icon-symbol";
protected _symbol?: MarkupElement;
constructor(protected _symbolData?: string, protected _applyCurrentStyle?: boolean) { super(); }
public override async onInstall(): Promise<boolean> { if (undefined === this._symbolData) return false; return super.onInstall(); }
protected override showPrompt(): void { this.provideToolAssistance(0 === this._points.length ? (`${MarkupTool.toolKey}Symbol.Prompts.FirstPoint`) : `${CoreTools.tools}ElementSet.Prompts.OppositeCorner`, true); }
protected override createMarkup(svgMarkup: G, ev: BeButtonEvent, isDynamics: boolean): void {
if (undefined === this._symbolData)
return;
if (this._points.length < this._minPoints)
return;
const start = this._points[0];
const end = isDynamics ? MarkupApp.convertVpToVb(ev.viewPoint) : this._points[this._points.length - 1];
const vec = start.vectorTo(end);
const width = Math.abs(vec.x);
const height = Math.abs(vec.y);
if ((width < 10 || height < 10) && (isDynamics || this._points.length !== this._minPoints))
return;
if (undefined === this._symbol) {
const symbol = svgMarkup.group().svg(this._symbolData); // creating group instead of using symbol because of inability to flash/hilite multi-color symbol instance...
if (0 === symbol.children().length) {
symbol.remove();
this._symbolData = undefined;
}
try { symbol.flatten(symbol); } catch { }
this._symbol = symbol;
} else if (!isDynamics) {
svgMarkup.add(this._symbol);
}
const offset = Point3d.create(vec.x < 0 ? end.x : start.x, vec.y < 0 ? end.y : start.y); // define location by corner points...
if (!isDynamics && this._points.length === this._minPoints)
this._symbol.size(ev.viewport!.viewRect.width * 0.1).center(offset.x, offset.y);
else if (!ev.isShiftKey)
this._symbol.size(width).move(offset.x, offset.y);
else
this._symbol.size(width, height).move(offset.x, offset.y);
if (this._applyCurrentStyle) {
const active = MarkupApp.props.active; // Apply color and transparency only; using active stroke-width, etc. for pre-defined symbols is likely undesirable...
this._symbol.forElementsOfGroup((child) => {
const css = window.getComputedStyle(child.node);
const toValue = (val: string | null, newVal: string) => (!val || val === "none") ? "none" : newVal;
child.css({ "fill": toValue(css.fill, active.element.fill), "stroke": toValue(css.stroke, active.element.stroke), "fill-opacity": active.element["fill-opacity"], "stroke-opacity": active.element["stroke-opacity"] });
});
}
if (!isDynamics)
this.onAdded(this._symbol);
}
public override async onDataButtonUp(ev: BeButtonEvent): Promise<EventHandled> {
if (undefined === ev.viewport || this._points.length !== this._minPoints)
return EventHandled.No;
this.createMarkup(this.markup.svgMarkup!, ev, false);
await this.onReinitialize();
return EventHandled.No;
}
public override async onResetButtonUp(_ev: BeButtonEvent): Promise<EventHandled> {
await this.onReinitialize();
return EventHandled.No;
}
protected override clearDynamicsMarkup(isDynamics: boolean): void {
if (!isDynamics)
super.clearDynamicsMarkup(isDynamics); // For dynamics we don't create a new symbol each frame, we just set the width/height...
}
} | the_stack |
import { expect } from "chai";
import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend";
import {
ContentSpecificationTypes, Field, KeySet, NestedContentField, RelationshipDirection, RelationshipMeaning, Ruleset, RuleTypes,
} from "@itwin/presentation-common";
import { Presentation } from "@itwin/presentation-frontend";
import { initialize, terminate } from "../IntegrationTests";
import { getFieldByLabel } from "../Utils";
describe("Learning Snippets", () => {
describe("Content", () => {
let imodel: IModelConnection;
beforeEach(async () => {
await initialize();
imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim");
});
afterEach(async () => {
await imodel.close();
await terminate();
});
describe("Customization", () => {
describe("DefaultPropertyCategoryOverride", () => {
it("uses `requiredSchemas` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.DefaultPropertyCategoryOverride.RequiredSchemas.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, there are two default
// property category overrides:
// - For iModels containing BisCore version 1.0.1 and older, the default property category should be "Custom Category OLD".
// - For iModels containing BisCore version 1.0.2 and newer, the default property category should be "Custom Category NEW".
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
}],
}, {
ruleType: RuleTypes.DefaultPropertyCategoryOverride,
requiredSchemas: [{ name: "BisCore", maxVersion: "1.0.2" }],
specification: {
id: "default",
label: "Custom Category OLD",
},
}, {
ruleType: RuleTypes.DefaultPropertyCategoryOverride,
requiredSchemas: [{ name: "BisCore", minVersion: "1.0.2" }],
specification: {
id: "default",
label: "Custom Category NEW",
},
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// The iModel uses BisCore older than 1.0.2 - we should use the "OLD" default category
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
const defaultCategory = content.descriptor.categories.find((category) => category.name === "default");
expect(defaultCategory).to.containSubset({
label: "Custom Category OLD",
});
});
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.DefaultPropertyCategoryOverride.Priority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, there are two default
// property category overrides of different priorities. The high priority rule should take precedence.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
}],
}, {
ruleType: RuleTypes.DefaultPropertyCategoryOverride,
priority: 0,
specification: {
id: "default",
label: "Low Priority",
},
}, {
ruleType: RuleTypes.DefaultPropertyCategoryOverride,
priority: 9999,
specification: {
id: "default",
label: "High Priority",
},
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// The iModel uses BisCore older than 1.0.2 - we should use the "OLD" default category
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
const defaultCategory = content.descriptor.categories.find((category) => category.name === "default");
expect(defaultCategory).to.containSubset({
label: "High Priority",
});
});
it("uses `specification` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.DefaultPropertyCategoryOverride.Specification.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, there's a default property
// category override to place properties into.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
}],
}, {
ruleType: RuleTypes.DefaultPropertyCategoryOverride,
specification: {
id: "default",
label: "Test Category",
},
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the default property category is correctly set up
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
const defaultCategory = content.descriptor.categories.find((category) => category.name === "default");
expect(defaultCategory).to.containSubset({
label: "Test Category",
});
content.descriptor.fields.forEach((field) => {
expect(field.category).to.eq(defaultCategory);
});
});
});
describe("PropertyCategorySpecification", () => {
it("allows referencing by `id`", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Id.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The rule contains a custom
// category specification that is referenced by properties override, putting all properties into the
// "Custom" category.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyCategories: [{
id: "custom-category",
label: "Custom",
}],
propertyOverrides: [{
name: "*",
categoryId: "custom-category",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the field is assigned a category with correct label
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields.length).to.be.greaterThan(0);
content.descriptor.fields.forEach((field) => {
expect(field.category).to.containSubset({
label: "Custom",
});
});
});
it("uses `label` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Label.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// it puts all properties into a custom category with "Custom Category" label.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyCategories: [{
id: "custom-category",
label: "Custom Category",
}],
propertyOverrides: [{
name: "*",
categoryId: "custom-category",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the field is assigned a category with correct label
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields.length).to.be.greaterThan(0);
content.descriptor.fields.forEach((field) => {
expect(field.category).to.containSubset({
label: "Custom Category",
});
});
});
it("uses `description` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Description.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, it puts
// all properties into a custom category with a description.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyCategories: [{
id: "custom-category",
label: "Custom Category",
description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
}],
propertyOverrides: [{
name: "*",
categoryId: "custom-category",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Description.Result
// Ensure category description is assigned
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.categories).to.containSubset([{
label: "Custom Category",
description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `parentId` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.ParentId.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, it
// puts all properties into a custom category with "Nested Category" label which in turn is put into "Root Category".
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyCategories: [{
id: "root-category",
label: "Root Category",
}, {
id: "nested-category",
parentId: "root-category",
label: "Nested Category",
}],
propertyOverrides: [{
name: "*",
categoryId: "nested-category",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure categories' hierarchy was set up correctly
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields.length).to.be.greaterThan(0);
content.descriptor.fields.forEach((field) => {
expect(field.category).to.containSubset({
label: "Nested Category",
parent: {
label: "Root Category",
},
});
});
});
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Priority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content
// is customized to put `CodeValue` property into "Category A" category and `UserLabel` property into
// "Category B" category. Both categories are assigned custom priorities.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "CodeValue",
categoryId: "category-a",
}, {
name: "UserLabel",
categoryId: "category-b",
}],
propertyCategories: [{
id: "category-a",
label: "Category A",
priority: 1,
}, {
id: "category-b",
label: "Category B",
priority: 2,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Priority.Result
// Ensure that correct category priorities are assigned
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Code",
category: {
label: "Category A",
priority: 1,
},
}]);
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
category: {
label: "Category B",
priority: 2,
},
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `autoExpand` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.AutoExpand.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content
// is customized to put all properties into a custom category which has the `autoExpand` flag.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "*",
categoryId: "custom-category",
}],
propertyCategories: [{
id: "custom-category",
label: "Custom Category",
autoExpand: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.AutoExpand.Result
// Ensure that categories have the `expand` flag
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.categories).to.containSubset([{
label: "Custom Category",
expand: true,
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `renderer` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Renderer.Ruleset
// There's a content rule for returning content of given instance. The produced content
// is customized to put all properties into a custom category which uses a custom "my-category-renderer"
// renderer.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "*",
categoryId: "custom-category",
}],
propertyCategories: [{
id: "custom-category",
label: "Custom Category",
renderer: {
rendererName: "my-category-renderer",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertyCategorySpecification.Renderer.Result
// Ensure that categories have the `expand` flag
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.categories).to.containSubset([{
label: "Custom Category",
renderer: {
name: "my-category-renderer",
},
}]);
// __PUBLISH_EXTRACT_END__
});
});
describe("PropertySpecification", () => {
it("uses `overridesPriority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.OverridesPriority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property has a couple of property overrides which set renderer, editor and label. The label is
// overriden by both specifications and the one with higher `overridesPriority` takes precedence.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
overridesPriority: 1,
labelOverride: "A",
renderer: {
rendererName: "my-renderer",
},
}, {
name: "UserLabel",
overridesPriority: 2,
labelOverride: "B",
editor: {
editorName: "my-editor",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field is assigned attributes from both specifications
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "B",
renderer: {
name: "my-renderer",
},
editor: {
name: "my-editor",
},
}]);
});
it("uses `labelOverride` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.LabelOverride.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property has a label override that relabels it to "Custom Label".
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
labelOverride: "Custom Label",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field is assigned attributes from both specifications
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Custom Label",
}]);
});
it("uses `categoryId` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.CategoryId.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property is placed into a custom category by assigning it a `categoryId`.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyCategories: [{
id: "custom-category",
label: "Custom Category",
}],
propertyOverrides: [{
name: "UserLabel",
categoryId: "custom-category",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field has the correct category
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
category: {
label: "Custom Category",
},
}]);
});
it("uses `isDisplayed` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.IsDisplayed.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// the `LastMod` property, which is hidden using a custom attribute in ECSchema, is force-displayed
// using a property override.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "LastMod",
isDisplayed: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `LastMod` is there
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Last Modified",
}]);
});
it("uses `doNotHideOtherPropertiesOnDisplayOverride` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.DoNotHideOtherPropertiesOnDisplayOverride.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// the `UserLabel` property is set to be displayed with `doNotHideOtherPropertiesOnDisplayOverride` flag,
// which ensures other properties are also kept displayed.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
isDisplayed: true,
doNotHideOtherPropertiesOnDisplayOverride: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` property is not the only property in content
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
}]).and.to.have.lengthOf(4);
});
it("uses `renderer` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.Renderer.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// it assigns the `UserLabel` property a custom "my-renderer" renderer.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
renderer: {
rendererName: "my-renderer",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.Renderer.Result
// Ensure the `UserLabel` field is assigned the "my-renderer" renderer
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
renderer: {
name: "my-renderer",
},
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `editor` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.Editor.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition,
// it assigns the `UserLabel` property a custom "my-editor" editor.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
editor: {
editorName: "my-editor",
},
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.Editor.Result
// Ensure the `UserLabel` field is assigned the "my-editor" editor
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
editor: {
name: "my-editor",
},
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `isReadOnly` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.IsReadOnly.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property is made read-only.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
isReadOnly: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.IsReadOnly.Result
// Ensure the `UserLabel` field is read-only.
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
isReadonly: true,
}]);
// __PUBLISH_EXTRACT_END__
});
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.PropertySpecification.Priority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. In addition, the `UserLabel`
// property's priority is set to 9999.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
propertyOverrides: [{
name: "UserLabel",
priority: 9999,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the `UserLabel` field's priority is 9999, which makes it appear higher in the property grid.
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "User Label",
priority: 9999,
}]);
});
});
describe("CalculatedPropertiesSpecification", () => {
it("uses `label` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.CalculatedPropertiesSpecification.Label.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content is customized to
// additionally have a calculated "My Calculated Property" property.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
calculatedProperties: [{
label: "My Calculated Property",
value: `123`,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the custom property was created
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "My Calculated Property",
}]);
});
it("uses `value` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.CalculatedPropertiesSpecification.Value.Ruleset
// There's a content rule for returning content of given `bis.GeometricElement3d` instance. The produced content is
// customized to additionally have a calculated "Element Volume" property whose value is calculated based on
// element's `BBoxHigh` and `BBoxLow` property values.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
calculatedProperties: [{
label: "Element Volume",
value: "(this.BBoxHigh.x - this.BBoxLow.x) * (this.BBoxHigh.y - this.BBoxLow.y) * (this.BBoxHigh.z - this.BBoxLow.z)",
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the custom property was created and has a value
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "generic.PhysicalObject", id: "0x74" }]),
descriptor: {},
}))!;
const field = getFieldByLabel(content.descriptor.fields, "Element Volume");
expect(content.contentSet).to.have.lengthOf(1).and.to.containSubset([{
values: {
[field.name]: "3.449493952966681",
},
}]);
});
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.CalculatedPropertiesSpecification.Priority.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content is customized to
// additionally have a "My Calculated Property" property with priority set to `9999`. This should make the property
// appear at the top in the UI, since generally properties have a priority of `1000`.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
calculatedProperties: [{
label: "My Calculated Property",
value: `123`,
priority: 9999,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the custom property has correct priority
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "My Calculated Property",
priority: 9999,
}]);
});
});
describe("RelatedPropertiesSpecification", () => {
it("uses `propertiesSource` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.PropertiesSource.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content is customized to
// additionally include properties of parent element by following the `bis.ElementOwnsChildElements` relationship
// in backwards direction.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ElementOwnsChildElements" },
direction: RelationshipDirection.Backward,
}],
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the custom property was created
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x12" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Element",
nestedFields: [{
label: "Model",
}, {
label: "Code",
}, {
label: "User Label",
}],
}]);
});
it("uses `instanceFilter` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.InstanceFilter.Ruleset
// There's a content rule for returning content of given instance. The produced content is customized to
// additionally include properties of child elements by following the `bis.ElementOwnsChildElements` relationship
// in forward direction, but only of children whose `CodeValue` starts with a "Bis" substring.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ElementOwnsChildElements" },
direction: RelationshipDirection.Forward,
}],
instanceFilter: `this.CodeValue ~ "Bis%"`,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the custom property was created
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
const childElementField = getFieldByLabel(content.descriptor.fields, "Element") as NestedContentField;
const childElementCodeField = getFieldByLabel(childElementField.nestedFields, "Code");
expect(content.contentSet[0].values[childElementField.name]).to.have.lengthOf(2).and.to.containSubset([{
primaryKeys: [{ id: "0xe" }],
values: {
[childElementCodeField.name]: "BisCore.RealityDataSources",
},
}, {
primaryKeys: [{ id: "0x10" }],
values: {
[childElementCodeField.name]: "BisCore.DictionaryModel",
},
}]);
});
it("uses `handleTargetClassPolymorphically` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.HandleTargetClassPolymorphically.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content is customized to
// additionally include properties of parent element by following the `bis.ElementOwnsChildElements` relationship
// in backwards direction. Setting `handleTargetClassPolymorphically` to `true` makes sure that the concrete target class is
// determined and all its properties are loaded.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ElementOwnsChildElements" },
direction: RelationshipDirection.Backward,
}],
handleTargetClassPolymorphically: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the custom property was created
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x12" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Subject",
nestedFields: [{
label: "Model",
}, {
label: "Code",
}, {
label: "User Label",
}, {
label: "Description",
}],
}]);
});
it("uses `relationshipMeaning` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.RelationshipMeaning.Ruleset
// There's a content rule for returning content of given `bis.PhysicalModel` instance. The produced content is customized to
// additionally include properties of modeled element by following the `bis.ModelModelsElement` relationship.
// Setting `relationshipMeaning` to `SameInstance` makes sure that all related properties are placed into a category
// nested under the default category.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ModelModelsElement" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "PhysicalPartition" },
}],
relationshipMeaning: RelationshipMeaning.SameInstance,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that all related properties are placed into a category nested under the default category
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:PhysicalModel", id: "0x1c" }]),
descriptor: {},
}))!;
const defaultCategory = content.descriptor.categories[0];
expect(content.descriptor.fields).to.containSubset([{
label: "Physical Partition",
category: defaultCategory,
nestedFields: [{
label: "Model",
category: {
parent: defaultCategory,
},
}, {
label: "Code",
category: {
parent: defaultCategory,
},
}, {
label: "User Label",
category: {
parent: defaultCategory,
},
}, {
label: "Description",
category: {
parent: defaultCategory,
},
}],
}]);
});
it("uses `properties` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.Properties.Ruleset
// There's a content rule for returning content of given `bis.PhysicalModel` instance. The produced content is customized to
// additionally include specific properties of modeled Element by following the `bis.ModelModelsElement` relationship.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ModelModelsElement" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "PhysicalPartition" },
}],
properties: ["UserLabel", "Description"],
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure that the two related properties are picked up
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:PhysicalModel", id: "0x1c" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Physical Partition",
nestedFields: [{
label: "User Label",
}, {
label: "Description",
}],
}]);
});
it("uses `autoExpand` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.AutoExpand.Ruleset
// There's a content rule for returning content of given `bis.Subject` instance. The produced content is customized to
// additionally include all properties of child subjects by following the `bis.SubjectOwnsSubjects` relationship and that
// the properties should be automatically expanded.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "SubjectOwnsSubjects" },
direction: RelationshipDirection.Forward,
}],
autoExpand: true,
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure the field has `autoExpand` attribute set to `true`
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Subject",
autoExpand: true,
nestedFields: [{
label: "Model",
}, {
label: "Code",
}, {
label: "User Label",
}, {
label: "Description",
}],
}]);
});
it("uses `skipIfDuplicate` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.SkipIfDuplicate.Ruleset
// There's a content rule for returning content of given `bis.PhysicalModel` instance. There are also two specifications
// requesting to load related properties:
// - the one specified through a content modifier requests all properties of the target class and has `skipIfDuplicate` flag.
// - the one specified through the content specification requests only `UserLabel` property.
// The specification at content specification level takes precedence and loads the `UserLabel` property. The other is completely
// ignored due to `skipIfDuplicate` attribute being set to `true`.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ModelModelsElement" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "PhysicalPartition" },
}],
properties: ["UserLabel"],
}],
}],
}, {
ruleType: RuleTypes.ContentModifier,
class: { schemaName: "BisCore", className: "Model" },
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ModelModelsElement" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "PhysicalPartition" },
}],
skipIfDuplicate: true,
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure only one related property is loaded
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:PhysicalModel", id: "0x1c" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Physical Partition",
nestedFields: (nestedFields: Field[]) => {
return nestedFields.length === 1
&& nestedFields[0].label === "User Label";
},
}]);
});
it("uses `nestedRelatedProperties` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Content.Customization.RelatedPropertiesSpecification.NestedRelatedProperties.Ruleset
// There's a content rule for returning content of given `bis.PhysicalModel` instance. There's also a related properties
// specification that loads modeled element properties and properties of `bis.LinkElement` related to the modeled element.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.Content,
specifications: [{
specType: ContentSpecificationTypes.SelectedNodeInstances,
relatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ModelModelsElement" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "PhysicalPartition" },
}],
nestedRelatedProperties: [{
propertiesSource: [{
relationship: { schemaName: "BisCore", className: "ElementHasLinks" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "RepositoryLink" },
}],
}],
}],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// Ensure properties of physical partition and repository link are loaded
const content = (await Presentation.presentation.getContent({
imodel,
rulesetOrId: ruleset,
keys: new KeySet([{ className: "BisCore:PhysicalModel", id: "0x1c" }]),
descriptor: {},
}))!;
expect(content.descriptor.fields).to.containSubset([{
label: "Physical Partition",
nestedFields: [{
label: "Repository Link",
nestedFields: [{
label: "URL",
}],
}],
}]);
});
});
});
});
});
function printRuleset(ruleset: Ruleset) {
if (process.env.PRINT_RULESETS) {
// eslint-disable-next-line no-console
console.log(JSON.stringify(ruleset, undefined, 2));
}
} | the_stack |
import Tooltip from 'rc-tooltip'
import * as React from 'react'
import {
DragElementWrapper,
DropTarget,
DropTargetCollector,
DropTargetConnector,
DropTargetMonitor,
DropTargetSpec,
} from 'react-dnd'
import { MeteorCall } from '../../lib/api/methods'
import { PubSub } from '../../lib/api/pubsub'
import { StatusResponse } from '../../lib/api/systemStatus'
import { GENESIS_SYSTEM_VERSION, getCoreSystem, ICoreSystem } from '../../lib/collections/CoreSystem'
import { RundownLayoutBase, RundownLayouts } from '../../lib/collections/RundownLayouts'
import { RundownPlaylists } from '../../lib/collections/RundownPlaylists'
import { RundownId, Rundowns } from '../../lib/collections/Rundowns'
import { getAllowConfigure, getHelpMode } from '../lib/localStorage'
import { NotificationCenter, Notification, NoticeLevel } from '../lib/notifications/notifications'
import { Studios } from '../../lib/collections/Studios'
import { ShowStyleBases } from '../../lib/collections/ShowStyleBases'
import { ShowStyleVariants } from '../../lib/collections/ShowStyleVariants'
import { unprotectString } from '../../lib/lib'
import { MeteorReactComponent } from '../lib/MeteorReactComponent'
import { Translated, translateWithTracker } from '../lib/ReactMeteorData/react-meteor-data'
import { Spinner } from '../lib/Spinner'
import { isRundownDragObject, RundownListDragDropTypes } from './RundownList/DragAndDropTypes'
import { GettingStarted } from './RundownList/GettingStarted'
import { RegisterHelp } from './RundownList/RegisterHelp'
import { RundownDropZone } from './RundownList/RundownDropZone'
import { RundownListFooter } from './RundownList/RundownListFooter'
import RundownPlaylistDragLayer from './RundownList/RundownPlaylistDragLayer'
import { RundownPlaylistUi } from './RundownList/RundownPlaylistUi'
import { doUserAction, UserAction } from '../lib/userAction'
export enum ToolTipStep {
TOOLTIP_START_HERE = 'TOOLTIP_START_HERE',
TOOLTIP_RUN_MIGRATIONS = 'TOOLTIP_RUN_MIGRATIONS',
TOOLTIP_EXTRAS = 'TOOLTIP_EXTRAS',
}
interface IRundownsListProps {
coreSystem: ICoreSystem
rundownPlaylists: Array<RundownPlaylistUi>
rundownLayouts: Array<RundownLayoutBase>
}
interface IRundownsListState {
systemStatus?: StatusResponse
subsReady: boolean
}
interface IRundownsListDropTargetProps {
connectDropTarget: DragElementWrapper<RundownPlaylistUi>
activateDropZone: boolean
}
const dropTargetSpec: DropTargetSpec<IRundownsListProps> = {
canDrop: (props: IRundownsListProps, monitor: DropTargetMonitor) => {
/* We only accept rundowns from playlists with more than one rundown,
since there's no point in replacing a single rundown playlist with a new
single rundown playlist
*/
const item = monitor.getItem()
if (isRundownDragObject(item)) {
const { id } = item
const playlist = props.rundownPlaylists.find(
(playlist) => playlist.rundowns.findIndex((rundown) => rundown._id === id) > -1
)
return playlist?.rundowns !== undefined && playlist.rundowns.length > 1
}
console.debug('RundownList Not accepting drop of ', item)
return false
},
// hover: (props, monitor) => {
// console.debug('Rundown list hover', monitor.getItem())
// }
}
const dropTargetCollector: DropTargetCollector<IRundownsListDropTargetProps, IRundownsListProps> = function (
connect: DropTargetConnector,
monitor: DropTargetMonitor,
props: IRundownsListProps
): IRundownsListDropTargetProps {
const activateDropZone = monitor.canDrop() && monitor.isOver()
return {
connectDropTarget: connect.dropTarget(),
activateDropZone,
}
}
export const RundownList = translateWithTracker(() => {
const studios = Studios.find().fetch()
const showStyleBases = ShowStyleBases.find().fetch()
const showStyleVariants = ShowStyleVariants.find().fetch()
const rundownLayouts = RundownLayouts.find({
$or: [{ exposeAsStandalone: true }, { exposeAsShelf: true }],
}).fetch()
return {
coreSystem: getCoreSystem(),
rundownPlaylists: RundownPlaylists.find({}, { sort: { created: -1 } })
.fetch()
.map((playlist: RundownPlaylistUi) => {
playlist.rundowns = playlist.getRundowns()
const airStatuses: string[] = []
const statuses: string[] = []
playlist.unsyncedRundowns = []
playlist.showStyles = []
for (const rundown of playlist.rundowns) {
airStatuses.push(String(rundown.airStatus))
statuses.push(String(rundown.status))
if (rundown.orphaned) {
playlist.unsyncedRundowns.push(rundown)
}
const showStyleBase = showStyleBases.find((style) => style._id === rundown.showStyleBaseId)
if (showStyleBase) {
const showStyleVariant = showStyleVariants.find((variant) => variant._id === rundown.showStyleVariantId)
playlist.showStyles.push({
id: showStyleBase._id,
baseName: showStyleBase.name || undefined,
variantName: (showStyleVariant && showStyleVariant.name) || undefined,
})
}
}
playlist.rundownAirStatus = airStatuses.join(', ')
playlist.rundownStatus = statuses.join(', ')
playlist.studioName = studios.find((s) => s._id === playlist.studioId)?.name || ''
return playlist
}),
rundownLayouts,
}
})(
DropTarget(
RundownListDragDropTypes.RUNDOWN,
dropTargetSpec,
dropTargetCollector
)(
class RundownList extends MeteorReactComponent<
Translated<IRundownsListProps> & IRundownsListDropTargetProps,
IRundownsListState
> {
// private _subscriptions: Array<Meteor.SubscriptionHandle> = []
constructor(props: Translated<IRundownsListProps> & IRundownsListDropTargetProps) {
super(props)
this.state = {
subsReady: false,
}
}
tooltipStep() {
let gotPlaylists = false
for (const playlist of this.props.rundownPlaylists) {
if (playlist.unsyncedRundowns.length > -1) {
gotPlaylists = true
break
}
}
if (this.props.coreSystem?.version === GENESIS_SYSTEM_VERSION && gotPlaylists === true) {
return getAllowConfigure() ? ToolTipStep.TOOLTIP_RUN_MIGRATIONS : ToolTipStep.TOOLTIP_START_HERE
} else {
return ToolTipStep.TOOLTIP_EXTRAS
}
}
componentDidMount() {
const { t } = this.props
// Subscribe to data:
this.subscribe(PubSub.rundownPlaylists, {})
this.subscribe(PubSub.studios, {})
this.subscribe(PubSub.rundownLayouts, {})
this.autorun(() => {
const showStyleBaseIds: Set<string> = new Set()
const showStyleVariantIds: Set<string> = new Set()
const playlistIds: Set<string> = new Set(
RundownPlaylists.find()
.fetch()
.map((i) => unprotectString(i._id))
)
for (const rundown of Rundowns.find().fetch()) {
showStyleBaseIds.add(unprotectString(rundown.showStyleBaseId))
showStyleVariantIds.add(unprotectString(rundown.showStyleVariantId))
}
this.subscribe(PubSub.showStyleBases, {
_id: { $in: Array.from(showStyleBaseIds) },
})
this.subscribe(PubSub.showStyleVariants, {
_id: { $in: Array.from(showStyleVariantIds) },
})
this.subscribe(PubSub.rundowns, {
playlistId: { $in: Array.from(playlistIds) },
})
})
this.autorun(() => {
let subsReady = this.subscriptionsReady()
if (subsReady !== this.state.subsReady && !this.state.subsReady) {
this.setState({
subsReady: subsReady,
})
}
})
MeteorCall.systemStatus
.getSystemStatus()
.then((systemStatus: StatusResponse) => {
this.setState({ systemStatus })
})
.catch(() => {
NotificationCenter.push(
new Notification(
'systemStatus_failed',
NoticeLevel.CRITICAL,
t('Could not get system status. Please consult system administrator.'),
'RundownList'
)
)
})
}
private handleRundownDrop(rundownId: RundownId) {
const { t } = this.props
doUserAction(t, 'drag&drop in dropzone', UserAction.RUNDOWN_ORDER_MOVE, (e) =>
MeteorCall.userAction.moveRundown(e, rundownId, null, [rundownId])
)
}
renderRundownPlaylists(list: RundownPlaylistUi[]) {
const { t, rundownLayouts } = this.props
if (list.length < 1) {
return <p>{t('There are no rundowns ingested into Sofie.')}</p>
}
return (
<ul className="rundown-playlists">
{list.map((playlist) => (
<RundownPlaylistUi
key={unprotectString(playlist._id)}
playlist={playlist}
rundownLayouts={rundownLayouts}
/>
))}
</ul>
)
}
render() {
const { t, rundownPlaylists, activateDropZone, connectDropTarget } = this.props
const step = this.tooltipStep()
const showGettingStarted =
this.props.coreSystem?.version === GENESIS_SYSTEM_VERSION && rundownPlaylists.length === 0
const handleDropZoneDrop = (id: RundownId) => {
this.handleRundownDrop(id)
}
return (
<React.Fragment>
{this.props.coreSystem ? <RegisterHelp step={step} /> : null}
{showGettingStarted === true ? <GettingStarted step={step} /> : null}
{connectDropTarget(
<section className="mtl gutter has-statusbar">
<header className="mvs">
<h1>{t('Rundowns')}</h1>
</header>
{this.state.subsReady ? (
<section className="mod mvl rundown-list">
<header className="rundown-list__header">
<span className="rundown-list-item__name">
<Tooltip
overlay={t('Click on a rundown to control your studio')}
visible={getHelpMode()}
placement="top"
>
<span>{t('Rundown')}</span>
</Tooltip>
</span>
{/* <span className="rundown-list-item__problems">{t('Problems')}</span> */}
<span>{t('Show Style')}</span>
<span>{t('On Air Start Time')}</span>
<span>{t('Duration')}</span>
<span>{t('Last Updated')}</span>
{this.props.rundownLayouts.some((l) => l.exposeAsShelf || l.exposeAsStandalone) && (
<span>{t('Shelf Layout')}</span>
)}
</header>
{this.renderRundownPlaylists(rundownPlaylists)}
<footer>
{<RundownDropZone activated={activateDropZone} rundownDropHandler={handleDropZoneDrop} />}
</footer>
<RundownPlaylistDragLayer />
</section>
) : (
<Spinner />
)}
</section>
)}
{this.state.systemStatus ? <RundownListFooter systemStatus={this.state.systemStatus} /> : null}
</React.Fragment>
)
}
}
)
) | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/cr_elements/cr_tabs/cr_tabs.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import './history_deletion_dialog.js';
import './passwords_deletion_dialog.js';
import './installed_app_checkbox.js';
import '../controls/settings_checkbox.js';
import '../icons.js';
import '../settings_shared_css.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js';
import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js';
import {IronPagesElement} from 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {PrefControlMixinInterface} from '../controls/pref_control_mixin.js';
import {SettingsCheckboxElement} from '../controls/settings_checkbox.js';
import {DropdownMenuOptionList} from '../controls/settings_dropdown_menu.js';
import {SettingsDropdownMenuElement} from '../controls/settings_dropdown_menu.js';
import {loadTimeData} from '../i18n_setup.js';
import {StatusAction, SyncBrowserProxy, SyncBrowserProxyImpl, SyncStatus} from '../people_page/sync_browser_proxy.js';
import {routes} from '../route.js';
import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js';
import {ClearBrowsingDataBrowserProxy, ClearBrowsingDataBrowserProxyImpl, InstalledApp} from './clear_browsing_data_browser_proxy.js';
/**
* InstalledAppsDialogActions enum.
* These values are persisted to logs and should not be renumbered or
* re-used.
* See tools/metrics/histograms/enums.xml.
*/
enum InstalledAppsDialogActions {
CLOSE = 0,
CANCEL_BUTTON = 1,
CLEAR_BUTTON = 2,
}
/**
* @param dialog the dialog to close
* @param isLast whether this is the last CBD-related dialog
*/
function closeDialog(dialog: CrDialogElement, isLast: boolean) {
// If this is not the last dialog, then stop the 'close' event from
// propagating so that other (following) dialogs don't get closed as well.
if (!isLast) {
dialog.addEventListener('close', e => {
e.stopPropagation();
}, {once: true});
}
dialog.close();
}
/**
* @param oldDialog the dialog to close
* @param newDialog the dialog to open
*/
function replaceDialog(oldDialog: CrDialogElement, newDialog: CrDialogElement) {
closeDialog(oldDialog, false);
if (!newDialog.open) {
newDialog.showModal();
}
}
type UpdateSyncStateEvent = {
signedIn: boolean,
syncConsented: boolean,
syncingHistory: boolean,
shouldShowCookieException: boolean,
isNonGoogleDse: boolean,
nonGoogleSearchHistoryString: string,
};
interface SettingsClearBrowsingDataDialogElement {
$: {
clearBrowsingDataDialog: CrDialogElement,
installedAppsDialog: CrDialogElement,
tabs: IronPagesElement,
};
}
const SettingsClearBrowsingDataDialogElementBase =
RouteObserverMixin(WebUIListenerMixin(I18nMixin(PolymerElement))) as {
new (): PolymerElement & WebUIListenerMixinInterface &
I18nMixinInterface & RouteObserverMixinInterface
};
class SettingsClearBrowsingDataDialogElement extends
SettingsClearBrowsingDataDialogElementBase {
static get is() {
return 'settings-clear-browsing-data-dialog';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* The current sync status, supplied by SyncBrowserProxy.
*/
syncStatus: Object,
/**
* Results of browsing data counters, keyed by the suffix of
* the corresponding data type deletion preference, as reported
* by the C++ side.
*/
counters_: {
type: Object,
// Will be filled as results are reported.
value() {
return {};
}
},
/**
* List of options for the dropdown menu.
*/
clearFromOptions_: {
readOnly: true,
type: Array,
value: [
{value: 0, name: loadTimeData.getString('clearPeriodHour')},
{value: 1, name: loadTimeData.getString('clearPeriod24Hours')},
{value: 2, name: loadTimeData.getString('clearPeriod7Days')},
{value: 3, name: loadTimeData.getString('clearPeriod4Weeks')},
{value: 4, name: loadTimeData.getString('clearPeriodEverything')},
],
},
clearingInProgress_: {
type: Boolean,
value: false,
},
clearingDataAlertString_: {
type: String,
value: '',
},
clearButtonDisabled_: {
type: Boolean,
value: false,
},
isSupervised_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('isSupervised');
},
},
showHistoryDeletionDialog_: {
type: Boolean,
value: false,
},
showPasswordsDeletionDialogLater_: {
type: Boolean,
value: false,
},
showPasswordsDeletionDialog_: {
type: Boolean,
value: false,
},
isSignedIn_: {
type: Boolean,
value: false,
},
isSyncConsented_: {
type: Boolean,
value: false,
},
isSyncingHistory_: {
type: Boolean,
value: false,
},
shouldShowCookieException_: {
type: Boolean,
value: false,
},
isSyncPaused_: {
type: Boolean,
value: false,
computed: 'computeIsSyncPaused_(syncStatus)',
},
hasPassphraseError_: {
type: Boolean,
value: false,
computed: 'computeHasPassphraseError_(syncStatus)',
},
hasOtherSyncError_: {
type: Boolean,
value: false,
computed:
'computeHasOtherError_(syncStatus, isSyncPaused_, hasPassphraseError_)',
},
tabsNames_: {
type: Array,
value: () =>
[loadTimeData.getString('basicPageTitle'),
loadTimeData.getString('advancedPageTitle'),
],
},
/**
* Installed apps that might be cleared if the user clears browsing data
* for the selected time period.
*/
installedApps_: {
type: Array,
value: () => [],
},
installedAppsFlagEnabled_: {
type: Boolean,
value: () => loadTimeData.getBoolean('installedAppsInCbd'),
},
searchHistoryLinkFlagEnabled_: {
type: Boolean,
value: () => loadTimeData.getBoolean('searchHistoryLink'),
},
googleSearchHistoryString_: {
type: String,
computed: 'computeGoogleSearchHistoryString_(isNonGoogleDse_)',
},
isNonGoogleDse_: {
type: Boolean,
value: false,
},
nonGoogleSearchHistoryString_: String,
};
}
// TODO(dpapad): make |syncStatus| private.
syncStatus: SyncStatus|undefined;
private counters_: {[k: string]: string};
private clearFromOptions_: DropdownMenuOptionList;
private clearingInProgress_: boolean;
private clearingDataAlertString_: string;
private clearButtonDisabled_: boolean;
private isSupervised_: boolean;
private showHistoryDeletionDialog_: boolean;
private showPasswordsDeletionDialogLater_: boolean;
private showPasswordsDeletionDialog_: boolean;
private isSignedIn_: boolean;
private isSyncConsented_: boolean;
private isSyncingHistory_: boolean;
private shouldShowCookieException_: boolean;
private isSyncPaused_: boolean;
private hasPassphraseError_: boolean;
private hasOtherSyncError_: boolean;
private tabsNames_: Array<string>;
private installedApps_: Array<InstalledApp>;
private installedAppsFlagEnabled_: boolean;
private searchHistoryLinkFlagEnabled_: boolean;
private googleSearchHistoryString_: string;
private isNonGoogleDse_: boolean;
private nonGoogleSearchHistoryString_: string;
private browserProxy_: ClearBrowsingDataBrowserProxy =
ClearBrowsingDataBrowserProxyImpl.getInstance();
private syncBrowserProxy_: SyncBrowserProxy =
SyncBrowserProxyImpl.getInstance();
ready() {
super.ready();
this.syncBrowserProxy_.getSyncStatus().then(
this.handleSyncStatus_.bind(this));
this.addWebUIListener(
'sync-status-changed', this.handleSyncStatus_.bind(this));
this.addWebUIListener(
'update-sync-state', this.updateSyncState_.bind(this));
this.addWebUIListener(
'update-counter-text', this.updateCounterText_.bind(this));
this.addEventListener(
'settings-boolean-control-change', this.updateClearButtonState_);
}
connectedCallback() {
super.connectedCallback();
this.browserProxy_.initialize().then(() => {
this.$.clearBrowsingDataDialog.showModal();
});
}
/**
* Handler for when the sync state is pushed from the browser.
*/
private handleSyncStatus_(syncStatus: SyncStatus) {
this.syncStatus = syncStatus;
}
/**
* @return Whether either clearing is in progress or no data type is selected.
*/
private isClearButtonDisabled_(
clearingInProgress: boolean, clearButtonDisabled: boolean): boolean {
return clearingInProgress || clearButtonDisabled;
}
/**
* Disables the Clear Data button if no data type is selected.
*/
private updateClearButtonState_() {
// on-select-item-changed gets called with undefined during a tab change.
// https://github.com/PolymerElements/iron-selector/issues/95
const tab = this.$.tabs.selectedItem;
if (!tab) {
return;
}
this.clearButtonDisabled_ =
this.getSelectedDataTypes_(tab as HTMLElement).length === 0;
}
/**
* Record visits to the CBD dialog.
*
* RouteObserverMixin
*/
currentRouteChanged(currentRoute: Route) {
if (currentRoute === routes.CLEAR_BROWSER_DATA) {
chrome.metricsPrivate.recordUserAction('ClearBrowsingData_DialogCreated');
}
}
/**
* Updates the history description to show the relevant information
* depending on sync and signin state.
*/
private updateSyncState_(event: UpdateSyncStateEvent) {
this.isSignedIn_ = event.signedIn;
this.isSyncConsented_ = event.syncConsented;
this.isSyncingHistory_ = event.syncingHistory;
this.shouldShowCookieException_ = event.shouldShowCookieException;
this.$.clearBrowsingDataDialog.classList.add('fully-rendered');
this.isNonGoogleDse_ = event.isNonGoogleDse;
this.nonGoogleSearchHistoryString_ = event.nonGoogleSearchHistoryString;
}
/** Choose a label for the history checkbox. */
private browsingCheckboxLabel_(
isSyncConsented: boolean, isSyncingHistory: boolean,
hasSyncError: boolean, historySummary: string,
historySummarySignedIn: string, historySummarySignedInNoLink: string,
historySummarySynced: string): string {
if (this.searchHistoryLinkFlagEnabled_) {
return isSyncingHistory ? historySummarySignedInNoLink : historySummary;
} else if (isSyncingHistory && !hasSyncError) {
return historySummarySynced;
} else if (isSyncConsented && !this.isSyncPaused_) {
return historySummarySignedIn;
}
return historySummary;
}
/** Choose a label for the cookie checkbox. */
private cookiesCheckboxLabel_(
shouldShowCookieException: boolean, cookiesSummary: string,
cookiesSummarySignedIn: string): string {
if (shouldShowCookieException) {
return cookiesSummarySignedIn;
}
return cookiesSummary;
}
/**
* Updates the text of a browsing data counter corresponding to the given
* preference.
* @param prefName Browsing data type deletion preference.
* @param text The text with which to update the counter
*/
private updateCounterText_(prefName: string, text: string) {
// Data type deletion preferences are named "browser.clear_data.<datatype>".
// Strip the common prefix, i.e. use only "<datatype>".
const matches = prefName.match(/^browser\.clear_data\.(\w+)$/)!;
this.set('counters_.' + assert(matches[1]), text);
}
/**
* @return A list of selected data types.
*/
private getSelectedDataTypes_(tab: HTMLElement): Array<string> {
const checkboxes = tab.querySelectorAll('settings-checkbox');
const dataTypes: Array<string> = [];
checkboxes.forEach((checkbox) => {
if (checkbox.checked && !checkbox.hidden) {
dataTypes.push(checkbox.pref!.key);
}
});
return dataTypes;
}
/**
* Gets a list of top 5 installed apps that have been launched
* within the time period selected. This is used to warn the user
* that data for these apps will be cleared as well, and offers
* them the option to exclude deletion of this data.
*/
private async getInstalledApps_() {
const tab = this.$.tabs.selectedItem as HTMLElement;
const timePeriod = tab.querySelector<SettingsDropdownMenuElement>(
'.time-range-select')!.pref!.value;
this.installedApps_ = await this.browserProxy_.getInstalledApps(timePeriod);
}
private shouldShowInstalledApps_(): boolean {
if (!this.installedAppsFlagEnabled_) {
return false;
}
const haveInstalledApps = this.installedApps_.length > 0;
chrome.send('metricsHandler:recordBooleanHistogram', [
'History.ClearBrowsingData.InstalledAppsDialogShown', haveInstalledApps
]);
return haveInstalledApps;
}
/** Logs interactions with the installed app dialog to UMA. */
private recordInstalledAppsInteractions_() {
if (this.installedApps_.length === 0) {
return;
}
const uncheckedAppCount =
this.installedApps_.filter(app => !app.isChecked).length;
chrome.metricsPrivate.recordBoolean(
'History.ClearBrowsingData.InstalledAppExcluded', !!uncheckedAppCount);
chrome.metricsPrivate.recordCount(
'History.ClearBrowsingData.InstalledDeselectedNum', uncheckedAppCount);
chrome.metricsPrivate.recordPercentage(
'History.ClearBrowsingData.InstalledDeselectedPercent',
Math.round(100 * uncheckedAppCount / this.installedApps_.length));
}
/** Clears browsing data and maybe shows a history notice. */
private async clearBrowsingData_() {
this.clearingInProgress_ = true;
this.clearingDataAlertString_ = loadTimeData.getString('clearingData');
const tab = this.$.tabs.selectedItem as HTMLElement;
const dataTypes = this.getSelectedDataTypes_(tab);
const timePeriod = (tab.querySelector('.time-range-select') as unknown as
PrefControlMixinInterface)
.pref!.value;
if (tab.id === 'basic-tab') {
chrome.metricsPrivate.recordUserAction('ClearBrowsingData_BasicTab');
} else {
chrome.metricsPrivate.recordUserAction('ClearBrowsingData_AdvancedTab');
}
this.shadowRoot!
.querySelectorAll<SettingsCheckboxElement>(
'settings-checkbox[no-set-pref]')
.forEach(checkbox => checkbox.sendPrefChange());
const {showHistoryNotice, showPasswordsNotice} =
await this.browserProxy_.clearBrowsingData(
dataTypes, timePeriod, this.installedApps_);
this.clearingInProgress_ = false;
IronA11yAnnouncer.requestAvailability();
this.dispatchEvent(new CustomEvent('iron-announce', {
bubbles: true,
composed: true,
detail: {text: loadTimeData.getString('clearedData')}
}));
this.showHistoryDeletionDialog_ = showHistoryNotice;
// If both the history notice and the passwords notice should be shown, show
// the history notice first, and then show the passwords notice once the
// history notice gets closed.
this.showPasswordsDeletionDialog_ =
showPasswordsNotice && !showHistoryNotice;
this.showPasswordsDeletionDialogLater_ =
showPasswordsNotice && showHistoryNotice;
// Close the clear browsing data or installed apps dialog if they are open.
const isLastDialog = !showHistoryNotice && !showPasswordsNotice;
if (this.$.clearBrowsingDataDialog.open) {
closeDialog(this.$.clearBrowsingDataDialog, isLastDialog);
}
if (this.$.installedAppsDialog.open) {
closeDialog(this.$.installedAppsDialog, isLastDialog);
}
}
private onCancelTap_() {
this.$.clearBrowsingDataDialog.cancel();
}
/**
* Handles the closing of the notice about other forms of browsing history.
*/
private onHistoryDeletionDialogClose_(e: Event) {
this.showHistoryDeletionDialog_ = false;
if (this.showPasswordsDeletionDialogLater_) {
// Stop the close event from propagating further and also automatically
// closing other dialogs.
e.stopPropagation();
this.showPasswordsDeletionDialogLater_ = false;
this.showPasswordsDeletionDialog_ = true;
}
}
/**
* Handles the closing of the notice about incomplete passwords deletion.
*/
private onPasswordsDeletionDialogClose_() {
this.showPasswordsDeletionDialog_ = false;
}
/**
* Records an action when the user changes between the basic and advanced tab.
*/
private recordTabChange_(event: CustomEvent<{value: number}>) {
if (event.detail.value === 0) {
chrome.metricsPrivate.recordUserAction(
'ClearBrowsingData_SwitchTo_BasicTab');
} else {
chrome.metricsPrivate.recordUserAction(
'ClearBrowsingData_SwitchTo_AdvancedTab');
}
}
// <if expr="not chromeos">
/** Called when the user clicks the link in the footer. */
private onSyncDescriptionLinkClicked_(e: Event) {
if ((e.target as HTMLElement).tagName === 'A') {
e.preventDefault();
if (!this.syncStatus!.hasError) {
chrome.metricsPrivate.recordUserAction('ClearBrowsingData_Sync_Pause');
this.syncBrowserProxy_.pauseSync();
} else if (this.isSyncPaused_) {
chrome.metricsPrivate.recordUserAction('ClearBrowsingData_Sync_SignIn');
this.syncBrowserProxy_.startSignIn();
} else {
if (this.hasPassphraseError_) {
chrome.metricsPrivate.recordUserAction(
'ClearBrowsingData_Sync_NavigateToPassphrase');
} else {
chrome.metricsPrivate.recordUserAction(
'ClearBrowsingData_Sync_NavigateToError');
}
// In any other error case, navigate to the sync page.
Router.getInstance().navigateTo(routes.SYNC);
}
}
}
// </if>
private computeIsSyncPaused_(): boolean {
return !!this.syncStatus!.hasError &&
!this.syncStatus!.hasUnrecoverableError &&
this.syncStatus!.statusAction === StatusAction.REAUTHENTICATE;
}
private computeHasPassphraseError_(): boolean {
return !!this.syncStatus!.hasError &&
this.syncStatus!.statusAction === StatusAction.ENTER_PASSPHRASE;
}
private computeHasOtherError_(): boolean {
return this.syncStatus !== undefined && !!this.syncStatus!.hasError &&
!this.isSyncPaused_ && !this.hasPassphraseError_;
}
private computeGoogleSearchHistoryString_(isNonGoogleDse: boolean): string {
return isNonGoogleDse ?
this.i18nAdvanced('clearGoogleSearchHistoryNonGoogleDse') :
this.i18nAdvanced('clearGoogleSearchHistoryGoogleDse');
}
private shouldShowGoogleSearchHistoryLabel_(isSignedIn: boolean): boolean {
return this.searchHistoryLinkFlagEnabled_ && isSignedIn;
}
private shouldShowNonGoogleSearchHistoryLabel_(isNonGoogleDse: boolean):
boolean {
return this.searchHistoryLinkFlagEnabled_ && isNonGoogleDse;
}
private shouldShowFooter_(): boolean {
let showFooter = false;
// <if expr="not chromeos">
showFooter = !!this.syncStatus && !!this.syncStatus!.signedIn;
// </if>
return showFooter;
}
private async onClearBrowsingDataClick_() {
await this.getInstalledApps_();
if (this.shouldShowInstalledApps_()) {
replaceDialog(this.$.clearBrowsingDataDialog, this.$.installedAppsDialog);
} else {
await this.clearBrowsingData_();
}
}
private hideInstalledApps_() {
chrome.metricsPrivate.recordEnumerationValue(
'History.ClearBrowsingData.InstalledAppsDialogAction',
InstalledAppsDialogActions.CLOSE,
Object.keys(InstalledAppsDialogActions).length);
replaceDialog(this.$.installedAppsDialog, this.$.clearBrowsingDataDialog);
}
private onCancelInstalledApps_() {
chrome.metricsPrivate.recordEnumerationValue(
'History.ClearBrowsingData.InstalledAppsDialogAction',
InstalledAppsDialogActions.CANCEL_BUTTON,
Object.keys(InstalledAppsDialogActions).length);
replaceDialog(this.$.installedAppsDialog, this.$.clearBrowsingDataDialog);
}
/** Handles the tap confirm button in installed apps. */
private async onInstalledAppsConfirmClick_() {
chrome.metricsPrivate.recordEnumerationValue(
'History.ClearBrowsingData.InstalledAppsDialogAction',
InstalledAppsDialogActions.CLEAR_BUTTON,
Object.keys(InstalledAppsDialogActions).length);
this.recordInstalledAppsInteractions_();
await this.clearBrowsingData_();
}
}
customElements.define(
SettingsClearBrowsingDataDialogElement.is,
SettingsClearBrowsingDataDialogElement); | the_stack |
import Vue, {VueConstructor, PropType} from 'vue'
import {withKnobs, object} from '@storybook/addon-knobs'
import * as uiv from 'uiv'
import {RundeckVcr, Cassette} from '@rundeck/client/dist/util/RundeckVcr'
Vue.use(uiv)
import LogViewer from './logViewer.vue'
import { ExecutionLog } from '../../utilities/ExecutionLogConsumer'
import fetchMock from 'fetch-mock'
import { RootStore } from '../../stores/RootStore'
const rootStore = new RootStore(window._rundeck.rundeckClient)
export default {
title: 'ExecutionViewer',
decorators: [withKnobs]
}
function playback<T>(component: T, fixture: string): () => Promise<T> {
return async () => {
fetchMock.reset()
const cassette = await Cassette.Load(fixture)
const vcr = new RundeckVcr(fetchMock)
vcr.play(cassette)
return component
}
}
export const darkTheme = () => (Vue.extend({
components: { LogViewer: playback(LogViewer, '/fixtures/ExecAnsiColorOutput.json') },
template: '<LogViewer :useUserSettings="false" :config="settings" executionId="912" style="height: 100%;" />',
mounted: function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
settings: {
default: {
theme: 'dark',
ansiColor: false
}
}
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient),
})
}))
// export const loading = () => (Vue.extend({
// components: { LogViewer },
// template: '<LogViewer :useUserSettings="false" executionId="1" style="height: 100%;" />',
// mounted: function() {
// const el = this.$el as any
// el.parentNode.style.height = '100vh'
// },
// props: {},
// provide: () => ({
// executionLogViewerFactory: function(){
// return Promise.resolve(new class {
// completed = false
// execCompleted = false
// size = 100
// async init(){ return Promise.resolve()}
// getEnrichedOutput() {
// return {
// id: '1',
// offset: '50',
// completed: false,
// execCompleted: true,
// hasFailedNodes: false,
// execState: "completed",
// lastModified: "foo",
// execDuration: 100,
// percentLoaded: 100,
// totalSize: 100,
// retryBackoff: 50000,
// clusterExec: false,
// compacted: false,
// entries: []
// }
// }
// })
// }
// })
// }))
export const basicOutput = () => (Vue.extend({
components: {
LogViewer
},
template: '<LogViewer @hook:destroyed="this.cleanup" @hook:beforeCreate="this.setup" v-if="shouldDisplay" :useUserSettings="false" executionId="900" style="height: 100%;" />',
created: function() {
console.log('Created')
},
mounted: async function() {
console.log('Mounted!!!')
const el = this.$el as any
el.parentNode.style.height = '100vh'
fetchMock.reset()
const cassette = await Cassette.Load('/fixtures/ExecBasicOutput.json')
this.vcr = new RundeckVcr(fetchMock)
this.vcr.play(cassette)
this.shouldDisplay = true
},
data() {
return ({
shouldDisplay: false,
vcr: undefined as undefined | RundeckVcr
})
},
methods: {
cleanUp(): void {
console.log('Cleanup hook')
rootStore.executionOutputStore.executionOutputsById.clear()
},
setup(): void {
console.log('Setup hook')
rootStore.executionOutputStore.executionOutputsById.clear()
this.vcr!.rewind()
}
},
provide() { return ({
rootStore: rootStore,
executionLogViewerFactory: function(){
return Promise.resolve(new ExecutionLog('900'))
}
})}
}))
export const htmlOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecHtmlOutput.json')
},
template: '<LogViewer :useUserSettings="false" executionId="907" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient)
})
}))
export const ansiColorOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecAnsiColorOutput.json')
},
template: '<LogViewer :useUserSettings="false" executionId="912" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient)
})
}))
export const largeOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecLargeOutput.json')
},
template: '<LogViewer :useUserSettings="false" executionId="7" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient)
})
}))
export const runningOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecRunningOutput.json')
},
template: '<LogViewer :useUserSettings="false" executionId="900" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient)
})
}))
export const failedOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecFailedOutput.json')
},
template: '<LogViewer :useUserSettings="false" executionId="880" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient),
})
}))
export const gutterOverflow = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecBasicOutput.json')
},
template: '<LogViewer :useUserSettings="false" :config="config" executionId="900" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
props: {
config: { default: {
timestamps: true
}}
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient),
executionLogViewerFactory: function(){
return Promise.resolve(new ExecutionLog('900'))
}
})
}))
export const userSettings = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecBasicOutput.json')
},
template: '<LogViewer executionId="900" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100vh'
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient),
executionLogViewerFactory: function(){
return Promise.resolve(new ExecutionLog('900'))
}
})
}))
export const filtered = () => (Vue.extend({
components: {
LogViewer
},
template: '<LogViewer @hook:destroyed="this.cleanup" @hook:beforeCreate="this.setup" v-if="shouldDisplay" :useUserSettings="false" executionId="880" style="height: 100%;" node="xubuntu" stepCtx="3/1" />',
created: function() {
console.log('Created')
},
mounted: async function() {
console.log('Mounted!!!')
const el = this.$el as any
el.parentNode.style.height = '100vh'
fetchMock.reset()
const cassette = await Cassette.Load('/fixtures/ExecFailedOutput.json')
this.vcr = new RundeckVcr(fetchMock)
this.vcr.play(cassette)
this.shouldDisplay = true
},
data() {
return ({
shouldDisplay: false,
vcr: undefined as undefined | RundeckVcr
})
},
methods: {
cleanUp(): void {
console.log('Cleanup hook')
rootStore.executionOutputStore.executionOutputsById.clear()
},
setup(): void {
console.log('Setup hook')
rootStore.executionOutputStore.executionOutputsById.clear()
this.vcr!.rewind()
}
},
provide() { return ({
rootStore: rootStore,
executionLogViewerFactory: function(){
return Promise.resolve(new ExecutionLog('880'))
}
})}
}))
export const missingOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecMissingOutput.json')
},
template: '<LogViewer executionId="1033" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100%'
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient),
executionLogViewerFactory: function(){
return Promise.resolve(new ExecutionLog('1033'))
}
})
}))
export const oversizeOutput = () => (Vue.extend({
components: {
LogViewer: playback(LogViewer, '/fixtures/ExecOverSize.json')
},
template: '<LogViewer executionId="900" style="height: 100%;" />',
mounted: async function() {
const el = this.$el as any
el.parentNode.style.height = '100%'
},
provide: () => ({
rootStore: new RootStore(window._rundeck.rundeckClient),
executionLogViewerFactory: function(){
return Promise.resolve(new ExecutionLog('900'))
}
})
})) | the_stack |
import * as _ from 'underscore'
import * as jQuery from 'jquery'
// Initial Setup
// -------------
declare global {
interface Window {
Backbone : any
}
function attachEvent( a, b );
function detachEvent( a, b );
}
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
const previousBackbone = window.Backbone;
// Create a local reference to a common array method we'll want to use later.
const slice = Array.prototype.slice;
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
const exported = {
$ : jQuery,
history : null,
VERSION : '1.2.3',
View, History, Router, noConflict
}
export default exported;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
function noConflict() {
window.Backbone = previousBackbone;
return this;
};
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
export function View(options) {
this.cid = _.uniqueId('view');
options || (options = {});
_.extend(this, _.pick(options, viewOptions));
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be preferred to global lookups where possible.
$: function (selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () { },
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function () {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function () {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function (element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof exported.$ ? element : exported.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save',
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function (events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function () {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function () {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = exported.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
export function Router(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
}
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () { },
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function (route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
exported.history.route(route, function (fragment) {
var args = router._extractParameters(route, fragment);
if (router.execute(callback, args, name) !== false) {
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
exported.history.trigger('route', router, name, args);
}
});
return this;
},
// Execute a route handler with the provided parameters. This is an
// excellent place to do pre-route setup or post-route cleanup.
execute: function (callback, args, name) {
if (callback) callback.apply(this, args);
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function (fragment, options) {
exported.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function () {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function (route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function (match, optional) {
return optional ? match : '([^/?]+)';
})
.replace(splatParam, '([^?]*?)');
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function (route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function (param, i) {
// Don't decode the search params.
if (i === params.length - 1) return param || null;
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
export function History() {
this.handlers = [];
this.checkUrl = _.bind(this.checkUrl, this);
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for stripping urls of hash.
var pathStripper = /#.*$/;
// Has the history handling already been started?
(History as any).started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Are we at the app root?
atRoot: function () {
var path = this.location.pathname.replace(/[^\/]$/, '$&/');
return path === this.root && !this.getSearch();
},
// Does the pathname match the root?
matchRoot: function () {
var path = this.decodeFragment(this.location.pathname);
var root = path.slice(0, this.root.length - 1) + '/';
return root === this.root;
},
// Unicode characters in `location.pathname` are percent encoded so they're
// decoded for comparison. `%25` should not be decoded since it may be part
// of an encoded parameter.
decodeFragment: function (fragment) {
return decodeURI(fragment.replace(/%25/g, '%2525'));
},
// In IE6, the hash fragment and search params are incorrect if the
// fragment contains `?`.
getSearch: function () {
var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
return match ? match[0] : '';
},
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function (window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the pathname and search params, without the root.
getPath: function () {
var path = this.decodeFragment(
this.location.pathname + this.getSearch()
).slice(this.root.length - 1);
return path.charAt(0) === '/' ? path.slice(1) : path;
},
// Get the cross-browser normalized URL fragment from the path or hash.
getFragment: function (fragment) {
if (fragment == null) {
if (this._usePushState || !this._wantsHashChange) {
fragment = this.getPath();
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function (options) {
if ((History as any).started) throw new Error('Backbone.history has already been started');
(History as any).started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({ root: '/' }, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._hasHashChange = 'onhashchange' in window && ((document as any).documentMode === void 0 || (document as any).documentMode > 7);
this._useHashChange = this._wantsHashChange && this._hasHashChange;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.history && this.history.pushState);
this._usePushState = this._wantsPushState && this._hasPushState;
this.fragment = this.getFragment();
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
// Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) {
// If we've started off with a route from a `pushState`-enabled
// browser, but we're currently in a browser that doesn't support it...
if (!this._hasPushState && !this.atRoot()) {
var root = this.root.slice(0, -1) || '/';
this.location.replace(root + '#' + this.getPath());
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._hasPushState && this.atRoot()) {
this.navigate(this.getHash(), { replace: true });
}
}
// Proxy an iframe to handle location events if the browser doesn't
// support the `hashchange` event, HTML5 history, or the user wants
// `hashChange` but not `pushState`.
if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
this.iframe = document.createElement('iframe');
this.iframe.src = 'javascript:0';
this.iframe.style.display = 'none';
this.iframe.tabIndex = -1;
var body = document.body;
// Using `appendChild` will throw on IE < 9 if the document is not ready.
var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
iWindow.document.open();
iWindow.document.close();
iWindow.location.hash = '#' + this.fragment;
}
// Add a cross-platform `addEventListener` shim for older browsers.
var addEventListener = window.addEventListener || function (eventName, listener) {
return attachEvent('on' + eventName, listener);
};
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._usePushState) {
addEventListener('popstate', this.checkUrl, false);
} else if (this._useHashChange && !this.iframe) {
addEventListener('hashchange', this.checkUrl, false);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function () {
// Add a cross-platform `removeEventListener` shim for older browsers.
var removeEventListener = window.removeEventListener || function (eventName, listener) {
return detachEvent('on' + eventName, listener);
};
// Remove window listeners.
if (this._usePushState) {
removeEventListener('popstate', this.checkUrl, false);
} else if (this._useHashChange && !this.iframe) {
removeEventListener('hashchange', this.checkUrl, false);
}
// Clean up the iframe if necessary.
if (this.iframe) {
document.body.removeChild(this.iframe);
this.iframe = null;
}
// Some environments will throw when clearing an undefined interval.
if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
(History as any).started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function (route, callback) {
this.handlers.unshift({ route: route, callback: callback });
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function (e) {
var current = this.getFragment();
// If the user pressed the back button, the iframe's hash will have
// changed and we should use that for comparison.
if (current === this.fragment && this.iframe) {
current = this.getHash(this.iframe.contentWindow);
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl();
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function (fragment) {
// If the root doesn't match, no routes can match either.
if (!this.matchRoot()) return false;
fragment = this.fragment = this.getFragment(fragment);
return _.some(this.handlers, function (handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function (fragment, options) {
if (!(History as any).started) return false;
if (!options || options === true) options = { trigger: !!options };
// Normalize the fragment.
fragment = this.getFragment(fragment || '');
// Don't include a trailing slash on the root.
var root = this.root;
if (fragment === '' || fragment.charAt(0) === '?') {
root = root.slice(0, -1) || '/';
}
var url = root + fragment;
// Strip the hash and decode for matching.
fragment = this.decodeFragment(fragment.replace(pathStripper, ''));
if (this.fragment === fragment) return;
this.fragment = fragment;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._usePushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) {
var iWindow = this.iframe.contentWindow;
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if (!options.replace) {
iWindow.document.open();
iWindow.document.close();
}
this._updateHash(iWindow.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) return this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function (location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
exported.history = new History; | the_stack |
import * as assert from 'assert';
import { VSBufferReadableStream, newWriteableBufferStream, VSBuffer, streamToBuffer, bufferToStream, readableToBuffer, VSBufferReadable } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter } from 'vs/base/common/event';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { basename } from 'vs/base/common/resources';
import { consumeReadable, consumeStream, isReadable, isReadableStream } from 'vs/base/common/stream';
import { URI } from 'vs/base/common/uri';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IUntitledFileWorkingCopyModel, IUntitledFileWorkingCopyModelContentChangedEvent, IUntitledFileWorkingCopyModelFactory, UntitledFileWorkingCopy } from 'vs/workbench/services/workingCopy/common/untitledFileWorkingCopy';
import { TestServiceAccessor, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
export class TestUntitledFileWorkingCopyModel extends Disposable implements IUntitledFileWorkingCopyModel {
private readonly _onDidChangeContent = this._register(new Emitter<IUntitledFileWorkingCopyModelContentChangedEvent>());
readonly onDidChangeContent = this._onDidChangeContent.event;
private readonly _onWillDispose = this._register(new Emitter<void>());
readonly onWillDispose = this._onWillDispose.event;
constructor(readonly resource: URI, public contents: string) {
super();
}
fireContentChangeEvent(event: IUntitledFileWorkingCopyModelContentChangedEvent): void {
this._onDidChangeContent.fire(event);
}
updateContents(newContents: string): void {
this.doUpdate(newContents);
}
private throwOnSnapshot = false;
setThrowOnSnapshot(): void {
this.throwOnSnapshot = true;
}
async snapshot(token: CancellationToken): Promise<VSBufferReadableStream> {
if (this.throwOnSnapshot) {
throw new Error('Fail');
}
const stream = newWriteableBufferStream();
stream.end(VSBuffer.fromString(this.contents));
return stream;
}
async update(contents: VSBufferReadableStream, token: CancellationToken): Promise<void> {
this.doUpdate((await streamToBuffer(contents)).toString());
}
private doUpdate(newContents: string): void {
this.contents = newContents;
this.versionId++;
this._onDidChangeContent.fire({ isInitial: newContents.length === 0 });
}
versionId = 0;
pushedStackElement = false;
pushStackElement(): void {
this.pushedStackElement = true;
}
override dispose(): void {
this._onWillDispose.fire();
super.dispose();
}
}
export class TestUntitledFileWorkingCopyModelFactory implements IUntitledFileWorkingCopyModelFactory<TestUntitledFileWorkingCopyModel> {
async createModel(resource: URI, contents: VSBufferReadableStream, token: CancellationToken): Promise<TestUntitledFileWorkingCopyModel> {
return new TestUntitledFileWorkingCopyModel(resource, (await streamToBuffer(contents)).toString());
}
}
suite('UntitledFileWorkingCopy', () => {
const factory = new TestUntitledFileWorkingCopyModelFactory();
let disposables: DisposableStore;
const resource = URI.from({ scheme: Schemas.untitled, path: 'Untitled-1' });
let instantiationService: IInstantiationService;
let accessor: TestServiceAccessor;
let workingCopy: UntitledFileWorkingCopy<TestUntitledFileWorkingCopyModel>;
function createWorkingCopy(uri: URI = resource, hasAssociatedFilePath = false, initialValue = '') {
return new UntitledFileWorkingCopy<TestUntitledFileWorkingCopyModel>(
'testUntitledWorkingCopyType',
uri,
basename(uri),
hasAssociatedFilePath,
initialValue.length > 0 ? { value: bufferToStream(VSBuffer.fromString(initialValue)) } : undefined,
factory,
async workingCopy => { await workingCopy.revert(); return true; },
accessor.workingCopyService,
accessor.workingCopyBackupService,
accessor.logService
);
}
setup(() => {
disposables = new DisposableStore();
instantiationService = workbenchInstantiationService(undefined, disposables);
accessor = instantiationService.createInstance(TestServiceAccessor);
workingCopy = createWorkingCopy();
});
teardown(() => {
workingCopy.dispose();
disposables.dispose();
});
test('registers with working copy service', async () => {
assert.strictEqual(accessor.workingCopyService.workingCopies.length, 1);
workingCopy.dispose();
assert.strictEqual(accessor.workingCopyService.workingCopies.length, 0);
});
test('dirty', async () => {
assert.strictEqual(workingCopy.isDirty(), false);
let changeDirtyCounter = 0;
workingCopy.onDidChangeDirty(() => {
changeDirtyCounter++;
});
let contentChangeCounter = 0;
workingCopy.onDidChangeContent(() => {
contentChangeCounter++;
});
await workingCopy.resolve();
assert.strictEqual(workingCopy.isResolved(), true);
// Dirty from: Model content change
workingCopy.model?.updateContents('hello dirty');
assert.strictEqual(contentChangeCounter, 1);
assert.strictEqual(workingCopy.isDirty(), true);
assert.strictEqual(changeDirtyCounter, 1);
await workingCopy.save();
assert.strictEqual(workingCopy.isDirty(), false);
assert.strictEqual(changeDirtyCounter, 2);
});
test('dirty - cleared when content event signals isEmpty', async () => {
assert.strictEqual(workingCopy.isDirty(), false);
await workingCopy.resolve();
workingCopy.model?.updateContents('hello dirty');
assert.strictEqual(workingCopy.isDirty(), true);
workingCopy.model?.fireContentChangeEvent({ isInitial: true });
assert.strictEqual(workingCopy.isDirty(), false);
});
test('dirty - not cleared when content event signals isEmpty when associated resource', async () => {
workingCopy.dispose();
workingCopy = createWorkingCopy(resource, true);
await workingCopy.resolve();
workingCopy.model?.updateContents('hello dirty');
assert.strictEqual(workingCopy.isDirty(), true);
workingCopy.model?.fireContentChangeEvent({ isInitial: true });
assert.strictEqual(workingCopy.isDirty(), true);
});
test('revert', async () => {
let revertCounter = 0;
workingCopy.onDidRevert(() => {
revertCounter++;
});
let disposeCounter = 0;
workingCopy.onWillDispose(() => {
disposeCounter++;
});
await workingCopy.resolve();
workingCopy.model?.updateContents('hello dirty');
assert.strictEqual(workingCopy.isDirty(), true);
await workingCopy.revert();
assert.strictEqual(revertCounter, 1);
assert.strictEqual(disposeCounter, 1);
assert.strictEqual(workingCopy.isDirty(), false);
});
test('dispose', async () => {
let disposeCounter = 0;
workingCopy.onWillDispose(() => {
disposeCounter++;
});
await workingCopy.resolve();
workingCopy.dispose();
assert.strictEqual(disposeCounter, 1);
});
test('backup', async () => {
assert.strictEqual((await workingCopy.backup(CancellationToken.None)).content, undefined);
await workingCopy.resolve();
workingCopy.model?.updateContents('Hello Backup');
const backup = await workingCopy.backup(CancellationToken.None);
let backupContents: string | undefined = undefined;
if (isReadableStream(backup.content)) {
backupContents = (await consumeStream(backup.content, chunks => VSBuffer.concat(chunks))).toString();
} else if (backup.content) {
backupContents = consumeReadable(backup.content, chunks => VSBuffer.concat(chunks)).toString();
}
assert.strictEqual(backupContents, 'Hello Backup');
});
test('resolve - without contents', async () => {
assert.strictEqual(workingCopy.isResolved(), false);
assert.strictEqual(workingCopy.hasAssociatedFilePath, false);
assert.strictEqual(workingCopy.model, undefined);
await workingCopy.resolve();
assert.strictEqual(workingCopy.isResolved(), true);
assert.ok(workingCopy.model);
});
test('resolve - with initial contents', async () => {
workingCopy.dispose();
workingCopy = createWorkingCopy(resource, false, 'Hello Initial');
let contentChangeCounter = 0;
workingCopy.onDidChangeContent(() => {
contentChangeCounter++;
});
assert.strictEqual(workingCopy.isDirty(), true);
await workingCopy.resolve();
assert.strictEqual(workingCopy.isDirty(), true);
assert.strictEqual(workingCopy.model?.contents, 'Hello Initial');
assert.strictEqual(contentChangeCounter, 1);
workingCopy.model.updateContents('Changed contents');
await workingCopy.resolve(); // second resolve should be ignored
assert.strictEqual(workingCopy.model?.contents, 'Changed contents');
});
test('backup - with initial contents uses those even if unresolved', async () => {
workingCopy.dispose();
workingCopy = createWorkingCopy(resource, false, 'Hello Initial');
assert.strictEqual(workingCopy.isDirty(), true);
const backup = (await workingCopy.backup(CancellationToken.None)).content;
if (isReadableStream(backup)) {
const value = await streamToBuffer(backup as VSBufferReadableStream);
assert.strictEqual(value.toString(), 'Hello Initial');
} else if (isReadable(backup)) {
const value = readableToBuffer(backup as VSBufferReadable);
assert.strictEqual(value.toString(), 'Hello Initial');
} else {
assert.fail('Missing untitled backup');
}
});
test('resolve - with associated resource', async () => {
workingCopy.dispose();
workingCopy = createWorkingCopy(resource, true);
await workingCopy.resolve();
assert.strictEqual(workingCopy.isDirty(), true);
assert.strictEqual(workingCopy.hasAssociatedFilePath, true);
});
test('resolve - with backup', async () => {
await workingCopy.resolve();
workingCopy.model?.updateContents('Hello Backup');
const backup = await workingCopy.backup(CancellationToken.None);
await accessor.workingCopyBackupService.backup(workingCopy, backup.content, undefined, backup.meta);
assert.strictEqual(accessor.workingCopyBackupService.hasBackupSync(workingCopy), true);
workingCopy.dispose();
workingCopy = createWorkingCopy();
let contentChangeCounter = 0;
workingCopy.onDidChangeContent(() => {
contentChangeCounter++;
});
await workingCopy.resolve();
assert.strictEqual(workingCopy.isDirty(), true);
assert.strictEqual(workingCopy.model?.contents, 'Hello Backup');
assert.strictEqual(contentChangeCounter, 1);
});
}); | the_stack |
import { Portal, TemplatePortal } from '@angular/cdk/portal';
import {
AfterViewInit,
Component,
ComponentFactory,
ComponentFactoryResolver,
ComponentRef,
OnDestroy,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import moment from 'moment';
import { Observable, of } from 'rxjs';
import { filter, first, map, publishReplay, refCount, switchMap } from 'rxjs/operators';
import { EndpointsService } from '../../../../core/src/core/endpoints.service';
import { ConfirmationDialogConfig } from '../../../../core/src/shared/components/confirmation-dialog.config';
import { PreviewableComponent } from '../../../../core/src/shared/previewable-component';
import { SnackBarService } from '../../../../core/src/shared/services/snackbar.service';
import { StratosCatalogEntity } from '../../../../store/src/entity-catalog/entity-catalog-entity/entity-catalog-entity';
import { entityDeleted } from '../../../../store/src/operators';
import { IFavoriteMetadata, UserFavorite } from '../../../../store/src/types/user-favorites.types';
import { KUBERNETES_ENDPOINT_TYPE } from '../kubernetes-entity-factory';
import { KubernetesEndpointService } from '../services/kubernetes-endpoint.service';
import { KubeResourceActionBuilders } from '../store/action-builders/kube-resource.action-builder';
import { BasicKubeAPIResource, KubeAPIResource, KubeResourceEntityDefinition, KubeStatus } from '../store/kube.types';
import { ConfirmationDialogService } from './../../../../core/src/shared/components/confirmation-dialog.service';
import { SidePanelService } from './../../../../core/src/shared/services/side-panel.service';
import { entityCatalog } from './../../../../store/src/entity-catalog/entity-catalog';
import { UserFavoriteManager } from './../../../../store/src/user-favorite-manager';
export interface KubernetesResourceViewerComponentConfig {
resource: BasicKubeAPIResource;
}
export interface KubernetesResourceViewerConfig {
title: string;
analysis?: any;
resource$: Observable<BasicKubeAPIResource>;
resourceKind: string;
component?: any;
definition?: any;
}
interface KubernetesResourceViewerResource {
raw: any;
jsonView: KubeAPIResource;
age: string;
creationTimestamp: string;
labels: { name: string, value: string, }[];
annotations: { name: string, value: string, }[];
kind: string;
apiVersion: string;
}
@Component({
selector: 'app-kubernetes-resource-viewer',
templateUrl: './kubernetes-resource-viewer.component.html',
styleUrls: ['./kubernetes-resource-viewer.component.scss']
})
export class KubernetesResourceViewerComponent implements PreviewableComponent, OnDestroy, AfterViewInit {
constructor(
private endpointsService: EndpointsService,
private kubeEndpointService: KubernetesEndpointService,
private resolver: ComponentFactoryResolver,
private userFavoriteManager: UserFavoriteManager,
private viewContainerRef: ViewContainerRef,
private confirmDialog: ConfirmationDialogService,
private sidePanelService: SidePanelService,
private snackBarService: SnackBarService,
) { }
public title: string;
public resource$: Observable<KubernetesResourceViewerResource>;
public hasPodMetrics$: Observable<boolean>;
public podRouterLink$: Observable<string[]>;
private analysis;
public alerts;
public favorite: UserFavorite<IFavoriteMetadata>;
// Custom component
@ViewChild('customComponent', { read: ViewContainerRef, static: false }) customComponentContainer;
componentRef: ComponentRef<PreviewableComponent>;
component: any;
data: any; // TODO: Typing
@ViewChild('header', { static: false }) templatePortalContent: TemplateRef<unknown>;
headerContent: Portal<any>;
ngOnDestroy() {
this.removeCustomComponent();
}
removeCustomComponent() {
if (this.customComponentContainer) {
this.customComponentContainer.clear();
}
if (this.componentRef) {
this.componentRef.destroy();
}
}
createCustomComponent() {
this.removeCustomComponent();
if (this.component && this.customComponentContainer) {
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(this.component);
this.componentRef = this.customComponentContainer.createComponent(factory);
this.componentRef.instance.setProps(this.data);
}
}
ngAfterViewInit() {
this.createCustomComponent();
setTimeout(() => this.headerContent = new TemplatePortal(this.templatePortalContent, this.viewContainerRef), 0);
}
setProps(props: KubernetesResourceViewerConfig) {
this.title = props.title;
this.analysis = props.analysis;
this.component = props.component;
this.resource$ = props.resource$.pipe(
filter(item => !!item),
map((item: (KubeAPIResource | KubeStatus)) => {
const resource: KubernetesResourceViewerResource = {} as KubernetesResourceViewerResource;
const newItem = {} as any;
resource.raw = item;
Object.keys(item || []).forEach(k => {
if (k !== 'endpointId' && k !== 'releaseTitle' && k !== 'expandedStatus' && k !== '_metadata') {
newItem[k] = item[k];
}
});
resource.jsonView = newItem;
/* tslint:disable-next-line:no-string-literal */
const fallback = item['_metadata'] || {};
const ts = item.metadata ? item.metadata.creationTimestamp : fallback.creationTimestamp;
resource.age = moment(ts).fromNow(true);
resource.creationTimestamp = ts;
if (item.metadata && item.metadata.labels) {
resource.labels = [];
Object.keys(item.metadata.labels || []).forEach(labelName => {
resource.labels.push({
name: labelName,
value: item.metadata.labels[labelName]
});
});
}
if (item.metadata && item.metadata.annotations) {
resource.annotations = [];
Object.keys(item.metadata.annotations || []).forEach(labelName => {
resource.annotations.push({
name: labelName,
value: item.metadata.annotations[labelName]
});
});
}
/* tslint:disable-next-line:no-string-literal */
resource.kind = item['kind'] || fallback.kind || props.resourceKind;
/* tslint:disable-next-line:no-string-literal */
resource.apiVersion = item['apiVersion'] || fallback.apiVersion || this.getVersionFromSelfLink(item.metadata['selfLink']);
this.component = props.component;
this.data = {
endpointId: this.getEndpointId(item),
resource: item,
definition: props.definition
};
this.createCustomComponent();
setTimeout(() => this.setFavorite(props.definition, item), 0);
// Apply analysis if there is one - if this is a k8s resource (i.e. not a container)
if (item.metadata) {
this.applyAnalysis(resource);
}
return resource;
}),
publishReplay(1),
refCount()
);
this.hasPodMetrics$ = props.resourceKind === 'pod' ?
this.resource$.pipe(
switchMap(resource => this.endpointsService.hasMetrics(this.getEndpointId(resource.raw))),
first(),
) :
of(false);
this.podRouterLink$ = this.hasPodMetrics$.pipe(
filter(hasPodMetrics => hasPodMetrics),
switchMap(() => this.resource$),
map(pod => {
return [
`/kubernetes`,
this.getEndpointId(pod.raw),
`pods`,
pod.raw.metadata.namespace,
pod.raw.metadata.name
];
})
);
this.createCustomComponent();
}
private getVersionFromSelfLink(url: string): string {
if (!url) {
return;
}
const parts = url.split('/');
return `${parts[1]}/${parts[2]}`;
}
private getEndpointId(res): string {
return this.kubeEndpointService?.kubeGuid || res.endpointId || res.metadata?.kubeId;
}
private applyAnalysis(resource) {
let id = (resource.kind || 'pod').toLowerCase();
id = `${id}/${resource.raw.metadata.namespace}/${resource.raw.metadata.name}`;
if (this.analysis && this.analysis.alerts[id]) {
this.alerts = this.analysis.alerts[id];
} else {
this.alerts = null;
}
}
private setFavorite(defn: KubeResourceEntityDefinition, item: any) {
if (defn) {
const entityDefn = entityCatalog.getEntity(KUBERNETES_ENDPOINT_TYPE, defn.type);
const canFav = this.userFavoriteManager.canFavoriteEntityType(entityDefn);
if (canFav) {
this.favorite = this.userFavoriteManager.getFavorite(item, defn.type, KUBERNETES_ENDPOINT_TYPE);
}
}
}
// Warn about deletion and then delete the resource if confirmed
public deleteWarn() {
// Namespace vs Pod definition in different places
const defn = (this.data.definition?.definition || this.data.definition) as KubeResourceEntityDefinition;
this.sidePanelService.hide();
const confirmation = new ConfirmationDialogConfig(
`Delete ${defn.label}`,
`Are you sure you want to delete "${this.data.resource.metadata.name}" ?`,
'Delete',
true,
);
this.confirmDialog.openWithCancel(confirmation,
() => {
const catalogEntity = entityCatalog.getEntityFromKey(entityCatalog.getEntityKey(KUBERNETES_ENDPOINT_TYPE, defn.type)) as
StratosCatalogEntity<IFavoriteMetadata, any, KubeResourceActionBuilders>;
catalogEntity.api.deleteResource(
this.data.resource,
this.data.endpointId,
this.data.resource.metadata.name,
this.data.resource.metadata.namespace
).pipe(
entityDeleted(),
first()
).subscribe((result) => {
const msg = result.error ? `Could not delete reosource: ${result.error}` : `Deleted resource '${this.data.resource.metadata.name}'`;
this.snackBarService.show(msg);
}
);
},
() => {
this.sidePanelService.open();
}
);
}
} | the_stack |
import * as fs from "fs-extra";
import * as path from "path";
import * as commander from "commander";
import * as object from "./common/object";
import * as utils from "./common/utils";
import * as nodeUtils from "./common/nodeUtils";
import * as dbft from "./format/dragonBonesFormat";
import * as spft from "./format/spineFormat";
import * as l2ft from "./format/live2DFormat";
import fromSpine from "./action/fromSpine";
import fromLive2D from "./action/fromLive2D";
import format from "./action/formatFormat";
import * as helper from "./helper/helperRemote";
function execute(): void {
const commands = commander
.version("0.1.0")
.option("-i, --input [path]", "Input path")
.option("-o, --output [path]", "Output path")
.option("-t, --type [type]", "Convert from type [spine, live2d]", /^(spine|live2d)$/i, "none")
.option("-f, --filter [keyword]", "Filter")
.option("-d, --delete", "Delete raw files after convert complete.")
.parse(process.argv);
const input = path.resolve(path.normalize(commands["input"] as string || process.cwd()));
const output = "output" in commands ? path.resolve(path.normalize(commands["output"])) : input;
const type = commands["type"] as string || "";
const filter = commands["filter"] as string || "";
const deleteRaw = commands["delete"] as boolean || false;
// let loadTextureAtlasToData = false;
// let megreTextureAtlasToData = false;
switch (type) {
case "spine": {
const files = nodeUtils.filterFileList(input, /\.(json)$/i);
for (const file of files) {
if (filter && file.indexOf(filter) < 0) {
continue;
}
const fileString = fs.readFileSync(file, "utf-8");
if (!spft.isSpineString(fileString)) {
continue;
}
const fileName = path.basename(file, ".json");
const textureAtlasFile = path.join(path.dirname(file), fileName + ".atlas");
let textureAtlasString = "";
if (fs.existsSync(textureAtlasFile)) {
textureAtlasString = fs.readFileSync(textureAtlasFile, "utf-8");
}
const spine = new spft.Spine();
object.copyObjectFrom(JSON.parse(fileString), spine, spft.copyConfig);
const result = fromSpine({ name: fileName, data: spine, textureAtlas: textureAtlasString });
const outputFile = (output ? file.replace(input, output) : file).replace(".json", "_ske.json");
format(result);
const textureAtlases = result.textureAtlas.concat(); // TODO
result.textureAtlas.length = 0;
object.compress(result, dbft.compressConfig);
if (!fs.existsSync(path.dirname(outputFile))) {
fs.mkdirsSync(path.dirname(outputFile));
}
fs.writeFileSync(
outputFile,
JSON.stringify(result)
);
console.log(outputFile);
if (deleteRaw) {
fs.removeSync(file);
fs.removeSync(textureAtlasFile);
}
let index = 0;
for (const textureAtlas of textureAtlases) {
const pageName = `_tex${textureAtlases.length > 1 ? "_" + index++ : ""}`;
const outputFile = (output ? file.replace(input, output) : file).replace(".json", pageName + ".json");
const textureAtlasImage = path.join(path.dirname(file), textureAtlas.imagePath);
textureAtlas.imagePath = path.basename(outputFile).replace(".json", ".png");
const imageOutputFile = path.join(path.dirname(outputFile), textureAtlas.imagePath);
if (!fs.existsSync(path.dirname(imageOutputFile))) {
fs.mkdirsSync(path.dirname(imageOutputFile));
}
object.compress(textureAtlas, dbft.compressConfig);
if (!fs.existsSync(path.dirname(outputFile))) {
fs.mkdirsSync(path.dirname(outputFile));
}
fs.writeFileSync(
outputFile,
JSON.stringify(textureAtlas)
);
if (deleteRaw) {
fs.moveSync(textureAtlasImage, imageOutputFile);
}
else {
fs.copySync(textureAtlasImage, imageOutputFile);
}
let hasRotated = false;
for (const texture of textureAtlas.SubTexture) {
if (texture.rotated) {
hasRotated = true;
}
}
if (hasRotated) {
const helperInput = {
type: "modify_spine_textureatlas",
data: {
file: imageOutputFile,
config: textureAtlas,
texture: fs.readFileSync(imageOutputFile, "base64")
}
};
helper.addInput(helperInput);
}
console.log(outputFile);
console.log(imageOutputFile);
}
}
break;
}
case "live2d": {
const files = nodeUtils.filterFileList(input, /\.(model.json)$/i);
for (const file of files) {
if (filter && file.indexOf(filter) < 0) {
continue;
}
// Parse config.
const dirURL = path.dirname(file);
const fileName = path.basename(file, ".model.json");
const fileString = fs.readFileSync(file, "utf-8");
const modelConfig = JSON.parse(fileString) as l2ft.ModelConfig;
const modelURL = path.join(dirURL, modelConfig.model);
const deleteFiles = [file];
modelConfig.name = modelConfig.name || fileName;
// Parse model.
if (fs.existsSync(modelURL)) {
const fileBuffer = fs.readFileSync(modelURL);
const model = l2ft.parseModel(fileBuffer.buffer as ArrayBuffer);
if (!model) {
console.log("Model parse error.", modelURL);
continue;
}
modelConfig.modelImpl = model;
deleteFiles.push(modelURL);
}
else {
console.log("File does not exist.", modelURL);
continue;
}
for (let i = 0, l = modelConfig.textures.length; i < l; ++i) { // Parse textures.
const textureURI = modelConfig.textures[i] as string;
const textureURL = path.join(dirURL, textureURI);
if (fs.existsSync(textureURL)) {
const texture = { file: textureURI, width: 0, height: 0 };
const textureAtlasBuffer = fs.readFileSync(textureURL);
modelConfig.textures[i] = texture;
if (textureAtlasBuffer.toString('ascii', 12, 16) === "CgBI") {
texture.width = textureAtlasBuffer.readUInt32BE(32);
texture.height = textureAtlasBuffer.readUInt32BE(36);
}
else {
texture.width = textureAtlasBuffer.readUInt32BE(16);
texture.height = textureAtlasBuffer.readUInt32BE(20);
}
}
else {
console.log("File does not exist.", textureURL);
}
}
if (modelConfig.motions) { // Parse animation.
for (const k in modelConfig.motions) {
const motionConfigs = modelConfig.motions[k];
for (const motionConfig of motionConfigs) {
const motionURL = path.join(dirURL, motionConfig.file);
if (fs.existsSync(motionURL)) {
motionConfig.motion = l2ft.parseMotion(fs.readFileSync(motionURL, "utf-8"));
deleteFiles.push(motionURL);
}
else {
console.log("File does not exist.", motionURL);
}
}
}
}
if (modelConfig.expressions) {
for (const k in modelConfig.expressions) {
const expressionConfig = modelConfig.expressions[k];
const expressionURL = path.join(dirURL, expressionConfig.file);
if (fs.existsSync(expressionURL)) {
expressionConfig.expression = JSON.parse(utils.formatJSONString(fs.readFileSync(expressionURL, "utf-8")));
deleteFiles.push(expressionURL);
}
else {
console.log("File does not exist.", expressionURL);
}
}
}
const result = fromLive2D(modelConfig);
if (result === null) {
continue;
}
const outputDirURL = dirURL.replace(input, output);
const outputURL = path.join(outputDirURL, fileName + "_ske.json");
format(result);
console.log(outputURL);
if (!fs.existsSync(outputDirURL)) {
fs.mkdirsSync(outputDirURL);
}
if (outputDirURL !== dirURL) {
for (const textureAtlas of result.textureAtlas) {
const rawImageURL = path.join(dirURL, textureAtlas.imagePath);
const outputImageURL = path.join(outputDirURL, textureAtlas.imagePath);
console.log(outputImageURL);
if (!fs.existsSync(path.dirname(outputImageURL))) {
fs.mkdirsSync(path.dirname(outputImageURL));
}
if (deleteRaw) {
fs.moveSync(rawImageURL, outputImageURL);
}
else {
fs.copySync(rawImageURL, outputImageURL);
}
}
}
object.compress(result, dbft.compressConfig);
fs.writeFileSync(
outputURL,
JSON.stringify(result)
);
if (deleteRaw) {
for (const file of deleteFiles) {
fs.unlinkSync(file);
}
}
}
break;
}
case "cocos":
// loadTextureAtlasToData = true;
// megreTextureAtlasToData = true;
// break;
default:
console.log(`Unknown type: ${type}`);
return;
}
console.log("Convert complete.");
if (helper.hasInput()) {
helper.start();
console.log("Waitting for helper.");
}
}
execute(); | the_stack |
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { HefengConfig } from 'life-helper-config'
import { COMMON_SERVER_ERROR } from 'src/common/errors.constant'
import { request } from 'src/common/http'
import { INVALID_LOCATION } from './hefeng-error.constant'
import {
AirDailyForecastItem,
AirNow,
CityInfo,
DailyForecastItem,
HefengResponse,
HourlyForecastItem,
LivingIndexItem,
RainSurvey,
WarningCity,
WarningNowItem,
WeatherNow,
} from './hefeng-http.model'
/**
* 和风天气 - HTTP 请求服务
*
* ### 功能说明
*
* ```markdown
* 1. 封装对 [和风天气](https://dev.qweather.com/docs/api/) API 的请求。
* 2. 仅将请求参数封装为函数,不对数据本身做任何处理,不做缓存处理。
* 3. 仅返回响应数据中的有效数据部分,不是将整个响应都返回的。
* 4. 只将用得到的参数进行封装为方法的入参,其余部分写死在请求参数中。
* ```
*
* ### 注意事项
*
* ```markdown
* 1. 各个请求的 `请求参数` 以及函数的格式几乎完全一致,可以封装成 `type -> apiInfo` 的形式去请求接口,只需要一个函数就够了,
* 而不是每一个对应的 API 都使用了一个函数(当前文件的方案),但千万不要这么做。
* 2. 上述做法的缺点是都写在一个函数内,里面需要有各种冗余的判断,会被限制住,处理差异性参数非常麻烦。
* 3. 当前版本就是从上述的版本改过来的,不要再重蹈覆辙了(宁可每个方法都有很多重复的代码),这样一劳永逸。
* ```
*/
@Injectable()
export class HefengHttpService {
/** 日志工具 */
private readonly logger = new Logger(HefengHttpService.name)
/**
* 由于使用了无效的 `location` 数据,而返回的 `code`
*
* @see
* [错误状态码](https://dev.qweather.com/docs/start/status-code/)
*
*
* @description
*
* ### 状态码说明
*
* ```markdown
* 1. `code` 指的是响应数据中的 `code` 字段,而不是响应状态码。
* 2. `204` 含义:请求成功,但你查询的地区暂时没有你需要的数据。
* 3. `400` 含义:请求错误,可能包含错误的请求参数或缺少必选的请求参数。(实测使用地名进行城市查询,没找到也会报这个错,因此把它也加上)
* 4. `404` 含义:查询的数据或地区不存在。
* ```
*/
private readonly invalidLocationCodes = ['204', '400', '404']
/**
* 查询和风天气中的城市信息
*
* @param location 位置,详情见下方说明
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/geo/city-lookup/)
*
* @description
*
* ### `location` 支持的形式:
*
* ```markdown
* 1. 查询地区的名称,支持模糊搜索。例如 `西安`。
* 2. 以英文逗号分隔的经度,纬度坐标(十进制),例如 `116.41,39.92`。
* 3. 和风天气内部定义的 `LocationID`。
* 4. 行政区划编码 `Adcode`。
* ```
*/
async searchCity(location: string): Promise<CityInfo[]> {
const { key } = HefengConfig.basic
const response = await request<HefengResponse>({
url: 'https://geoapi.qweather.com/v2/city/lookup',
params: {
key,
location,
/** 搜索范围: 中国城市范围 */
range: 'cn',
/** 返回结果的数量 */
number: 10,
/** 语言: 中文 */
lang: 'zh',
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.location
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 城市信息查询, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 热门城市查询
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/geo/top-city/)
*/
async getTopCity(): Promise<CityInfo[]> {
const { key } = HefengConfig.basic
const response = await request<HefengResponse>({
url: 'https://geoapi.qweather.com/v2/city/top',
params: {
key,
/** 搜索范围 */
range: 'cn',
/** 返回结果的数量,取值范围 1-20 */
number: 20,
/** 语言: 中文 */
lang: 'zh',
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.topCityList
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 热门城市查询, 响应 code => \`${response.data.code}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取实时天气数据
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/weather/weather-now/)
*/
async getWeatherNow(location: string): Promise<WeatherNow> {
const { key, baseURL } = HefengConfig.basic
const response = await request<HefengResponse>({
baseURL,
url: '/weather/now',
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.now as WeatherNow
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 实时天气, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取逐天天气预报
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
* @param days 天数
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/weather/weather-daily-forecast/)
*/
async getDailyForecast(location: string, days: 3 | 7 | 10 | 15): Promise<DailyForecastItem[]> {
/**
* 说明:
* 1. 3 天和 7 天使用开发版。
* 2. 10 天 和 15 天使用商业版。
*/
const { key, baseURL } = [10, 15].includes(days) ? HefengConfig.pro : HefengConfig.basic
const response = await request<HefengResponse>({
baseURL,
url: `/weather/${days}d`,
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.daily as DailyForecastItem[]
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 逐天天气预报, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取逐小时天气预报
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
* @param hours 小时数
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/weather/weather-hourly-forecast/)
*/
async getHourlyForecast(location: string, hours: 24 | 72 | 168): Promise<HourlyForecastItem[]> {
const { key, baseURL } = hours === 24 ? HefengConfig.basic : HefengConfig.pro
const response = await request<HefengResponse>({
baseURL,
url: `/weather/${hours}h`,
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.hourly as HourlyForecastItem[]
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 逐小时天气预报, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取天气生活指数
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/indices/)
*/
async getLivingIndex(location: string): Promise<LivingIndexItem[]> {
const { key, baseURL } = HefengConfig.basic
const response = await request<HefengResponse>({
baseURL,
url: '/indices/1d',
params: {
key,
location,
type: 0,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.daily as LivingIndexItem[]
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 天气生活指数, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取实时空气质量
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/air/air-now/)
*/
async getAirNow(location: string): Promise<AirNow> {
const { key, baseURL } = HefengConfig.basic
const response = await request<HefengResponse>({
baseURL,
url: '/air/now',
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.now as AirNow
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 实时空气质量, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取空气质量预报
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/air/air-daily-forecast/)
*/
async getAirDailyForecast(location: string): Promise<AirDailyForecastItem[]> {
const { key, baseURL } = HefengConfig.pro
const response = await request<HefengResponse>({
baseURL,
url: '/air/5d',
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.daily as AirDailyForecastItem[]
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 空气质量预报, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取分钟级降水
*
* @param location 需要查询地区的以英文逗号分隔的 `经度,纬度` 坐标(十进制)
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/grid-weather/minutely/)
*
*
* @description
*
* ### 注意事项
*
* ```markdown
* 1. 当前接口的 `location` 参数不支持使用 `LocationID`。
* ```
*/
async getMinutelyRain(location: string): Promise<RainSurvey> {
const { key, baseURL } = HefengConfig.pro
const response = await request<HefengResponse>({
baseURL,
url: '/minutely/5m',
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 分钟级降水, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取天气预警城市列表
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/warning/weather-warning-city-list/)
*/
async getWarningCityList(): Promise<WarningCity[]> {
const { key } = HefengConfig.basic
const response = await request<HefengResponse>({
url: 'https://devapi.qweather.com/v7/warning/list',
params: {
key,
range: 'cn',
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.warningLocList
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 天气预警城市列表, 响应 code => \`${response.data.code}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
/**
* 获取天气灾害预警
*
* @param location 需要查询地区的 `LocationID` 或以英文逗号分隔的 `经度,纬度` 坐标(十进制)
*
* @see
* [API 开发文档](https://dev.qweather.com/docs/api/warning/weather-warning/)
*/
async getWarningNow(location: string): Promise<WarningNowItem[]> {
const { key, baseURL } = HefengConfig.basic
const response = await request<HefengResponse>({
baseURL,
url: '/warning/now',
params: {
key,
location,
},
})
if (response.data.code === '200') {
// `code` 为 `200` 表示请求成功
return response.data.warning
} else {
// 失败情况
this.logger.error(`[接口请求错误] 和风天气 - 天气灾害预警, 响应 code => \`${response.data.code}\`, location => \`${location}\` `)
if (this.invalidLocationCodes.includes(response.data.code)) {
throw new HttpException(INVALID_LOCATION, HttpStatus.BAD_REQUEST)
} else {
throw new HttpException(COMMON_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
} | the_stack |
import { Component, Input, Output, Pipe, PipeTransform, ViewChild, EventEmitter, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Validators, FormGroup, FormArray, FormBuilder } from '@angular/forms';
import { ModalDirective, ModalOptions } from 'ngx-bootstrap';
import { SnmpDeviceService } from '../snmpdevice/snmpdevicecfg.service';
import { MeasurementService } from '../measurement/measurementcfg.service';
import { MeasFilterService } from '../measfilter/measfiltercfg.service';
import { MeasGroupService } from '../measgroup/measgroupcfg.service';
import { IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts } from '../common/multiselect-dropdown';
import { SpinnerComponent } from '../common/spinner';
import { Subscription } from "rxjs";
import { CustomFilterService } from './customfilter.service';
@Component({
selector: 'test-filter-modal',
templateUrl: './testingfilter.html',
styleUrls: ['./filter-modal-styles.css'],
providers: [SnmpDeviceService, MeasGroupService, MeasurementService, MeasFilterService, SpinnerComponent, CustomFilterService],
})
export class TestFilterModal implements OnInit {
@ViewChild('childModal') public childModal: ModalDirective;
@Input() formValues: any;
@Input() titleName: any;
@Input() systemInfo: any;
@Output() public validationClicked: EventEmitter<any> = new EventEmitter();
@Input() showValidation: boolean;
@Input() textValidation: string;
//EMITERS
public validationClick(myId?: string): void {
this.childModal.hide();
this.validationClicked.emit();
}
public mode : string;
public builder : any;
//CONSTRUCTOR
constructor(builder: FormBuilder, public measurementService: MeasurementService, public customFilterService: CustomFilterService, public measGroupService: MeasGroupService, public measFilterService: MeasFilterService, public snmpDeviceService: SnmpDeviceService) {
this.builder = builder;
}
//INIT
ngOnInit() {
}
createStaticForm() {
this.filterForm = this.builder.group({
ID: [this.filterForm ? this.filterForm.value.ID : '', Validators.required],
RelatedDev: [this.filterForm ? this.filterForm.value.RelatedDev : ''],
RelatedMeas: [this.filterForm ? this.filterForm.value.RelatedMeas : ''],
Items: this.builder.array([]),
Description: [this.filterForm ? this.filterForm.value.Description : '']
});
console.log(this.filterForm);
}
clearConfig() {
// this.loadFromDevice = true;
this.formValues = null;
this.measOnMeasGroup = [];
this.measGroups = [];
this.selectedOID = "";
this.selectedMeas = null;
}
clearItems() {
this.checkedResults = [];
this.isConnected = false;
}
clearQuery() {
this.alertHandler = {};
this.queryResult = null;
}
//SHOW MODAL FUNCTION: SPLITTED INTO NEW AND EDIT
newCustomFilter(formValues? : any) {
//Reset forms!
this.showNewFilterForm = false;
this.mode = "new";
this.clearQuery();
this.clearItems();
this.clearConfig();
this.unsubscribeRequest();
if (formValues) {
//Get Related Device INFO:
this.formValues = formValues;
this.loadDeviceValues(this.formValues);
this.pingDevice(this.formValues);
this.createStaticForm();
} else{
this.initGetDevices();
}
this.childModal.show();
}
editCustomFilter(_formValues : any, editForm? : any, alertMessage? : any) {
this.mode = "edit";
//reset var values
this.clearQuery();
this.clearItems();
this.clearConfig();
//secure forms
this.showNewFilterForm = false;
this.formValues = _formValues || null;
this.unsubscribeRequest();
//Get Related Device INFO:
this.loadDeviceValues(this.formValues);
this.pingDevice(this.formValues);
this.filterForm = {};
this.filterForm.value = editForm;
this.createStaticForm();
//Fill with items:
this.fillFilterValues(editForm.Items);
this.oldID = editForm.ID;
this.selectedMeas = editForm.RelatedMeas;
this.getMeasByIdforModal(this.selectedMeas);
this.childModal.show();
}
fillFilterValues(items) {
for (let item of items) {
this.addFilterValue(item.TagID, item.Alias);
}
}
clearSelected() {
this.filterForm.controls.Items = this.builder.array([]);
}
//Forms:
filterForm: any
newFilterForm: any;
itemForm: any;
//Bool controllers
all: boolean = true;
showNewFilterForm: boolean = false;
showItemForm: boolean = false;
//Selector Data:
private mySettings: IMultiSelectSettings = {
singleSelect: true,
};
snmpdevs: IMultiSelectOption[] = [];
measGroups: IMultiSelectOption[] = [];
//SELECTED DATA:
selectedMeas: any;
// selectedMeasGroup: any;
selectedOID: any;
customFilterValues: any;
//Data
checkedResults: Array<any> = [];
queryResult: any;
dataArray : any = [];
filter : any = null;
//snmpdevs: any;
oidValue: any;
filterText: string = "";
//Measurements on selected MeasGroup
measOnMeasGroup: Array<string> = [];
test: any;
//Sysinfo
alertHandler: any = {};
isRequesting: boolean;
isConnected: boolean;
myObservable: Subscription;
oldID : string;
public editForm : any;
//FILTERFORM
//ADD
addFilterValue(selectedTag: string, customAlias: string): void {
// add address to the list
this.checkedResults.push(selectedTag);
const control = <FormArray>this.filterForm.controls['Items'];
control.push(this.builder.group({
TagID: [selectedTag.toString(), Validators.required],
Alias: [customAlias || '']
})
);
}
//REMOVE
removeFilterValue(i: number) {
// remove address from the list
const control = <FormArray>this.filterForm.controls['Items'];
control.removeAt(i);
}
//SELECTORS
//MeasGroup Selector
selectMeasGroup(measGroup: string): void {
this.queryResult = null;
this.selectedOID = null;
this.getMeasGroupByIdForModal(measGroup);
this.selectedMeas = "";
}
loadDeviceValues (formValues) : void {
this.measGroups = [];
if (formValues.MeasurementGroups) {
for (let entry of formValues.MeasurementGroups) {
this.measGroups.push({ 'id': entry, 'name': entry });
}
this.measOnMeasGroup = [];
this.selectedOID = "";
}
}
//Device Selector
selectDevice(id: string): void {
this.unsubscribeRequest();
// this.resetVars();
this.isConnected = false;
this.snmpDeviceService.getDevicesById(id)
.subscribe(
data => {
this.clearConfig();
if (data.MeasurementGroups) {
for (let entry of data.MeasurementGroups) {
this.measGroups.push({ 'id': entry, 'name': entry });
}
//clearItems
this.clearQuery()
}
this.formValues = data;
this.pingDevice(this.formValues);
},
err => console.error(err),
() => console.log('DONE')
);
}
//Select Measurement -> Load OID
selectMeasOID(id: string) {
if (this.selectedMeas !== id) {
this.clearQuery();
this.selectedMeas = id;
this.getMeasByIdforModal(id);
}
}
//Select ALL Options
selectAllOptions(checkAll: boolean): void {
for (let entry of this.queryResult.QueryResult) {
if (checkAll) {
if (this.checkedResults.indexOf(entry.Value) == -1)
this.selectOption(entry.Value);
} else {
let test = this.checkedResults.indexOf(entry.Value);
if (test > -1) {
this.removeFilterValue(test);
this.checkedResults.splice(test, 1);
}
entry.checked = false;
}
}
if (this.queryResult.QueryResult.length === this.checkedResults.length) {
this.all = false;
} else {
this.all = !this.all
}
}
//SHOW ITEMS FORM
showItemFormPanel(): void {
this.showItemForm = true;
this.itemForm = this.builder.group({
TagID: ['', Validators.required],
Alias: ['']
});
}
showNewFilterFormPanel(): void {
this.showNewFilterForm = true;
this.newFilterForm = this.builder.group({
id: ['', Validators.required],
IDMeasurementCfg: [''],
FType: ['CustomFilter'],
FilterName: [''],
EnableAlias: ['false'],
Description: ['']
});
}
addCustomItem(tagID: string): void {
//Check if it already exist
if ((this.checkedResults && this.checkedResults.indexOf(tagID) > -1) == false) {
if (this.selectOption(this.itemForm.controls['TagID'].value) == false) {
this.addFilterValue(this.itemForm.controls['TagID'].value, this.itemForm.controls['Alias'].value);
this.showItemForm = false;
}
} else {
alert("Tag ID: " + tagID + " already exists")
}
}
onChange(event){
let tmpArray = this.dataArray.filter((item: any) => {
return item['Value'].match(event);
});
this.queryResult.QueryResult = tmpArray;
}
//QUERYRESULT PANEL
sendQuery() {
this.filter = null;
this.isRequesting = true;
this.snmpDeviceService.sendQuery(this.formValues, 'walk', this.selectedOID, true)
.subscribe(data => {
this.queryResult = data;
for (let res of this.queryResult.QueryResult) {
res.Value = res.Value.toString();
res.checked = false;
let a = this.checkedResults.indexOf(res.Value)
if (a > -1){
res.checked = true;
}
}
this.queryResult.OID = this.selectedOID;
this.isRequesting = false;
this.dataArray = this.queryResult.QueryResult;
},
err => {
console.error(err);
},
() => { console.log("DONE") }
);
}
removeOption(id: any): void {
if (this.queryResult) {
this.selectOption(id);
} else {
if (this.checkedResults.indexOf(id) != -1) {
let index = this.checkedResults.indexOf(id);
this.checkedResults.splice(index, 1);
this.removeFilterValue(index);
}
}
}
selectOption(id: any): boolean {
//Check if there is some OID
let ifexist: boolean = false;
let tmpValue = id;
//Look for every queryResult value:
if (this.queryResult) {
for (let entry of this.queryResult.QueryResult) {
//if matches, changes the checked status
if (entry.Value === tmpValue) {
//Change the check status
entry.checked = !entry.checked;
//When selected:
if (entry.checked === true) {
//Push the first ocrurante to avoid duplicating entries with the same value
if (this.checkedResults.indexOf(tmpValue) == -1) {
ifexist = true;
this.addFilterValue(tmpValue, null);
}
//When non selected:
} else {
//Delete at first occurance
if (this.checkedResults.indexOf(tmpValue) != -1) {
let index = this.checkedResults.indexOf(tmpValue);
this.checkedResults.splice(index, 1);
this.removeFilterValue(index);
}
}
}
//Must check if the value is custom value => It is not on the queryResult array and its added on checkedResults array
if (ifexist == false && (this.checkedResults.indexOf(tmpValue) != -1)) {
let index = this.checkedResults.indexOf(tmpValue);
this.checkedResults.splice(index, 1);
this.removeFilterValue(index);
}
}
//Change titles if all are un/selected
if (this.queryResult.QueryResult.length === this.checkedResults.length) {
this.all = false;
} else if (this.checkedResults.length == 0) {
this.all = !this.all;
} else {
this.all != this.all;
}
}
return ifexist;
}
//PROVIDERS FOR MODAL
initGetDevices() {
this.isRequesting = false;
this.alertHandler = {};
this.unsubscribeRequest();
this.clearItems();
this.snmpDeviceService.getDevices(null)
.subscribe(
data => {
this.snmpdevs = [];
for (let entry of data) {
this.snmpdevs.push({ 'id': entry.ID, 'name': entry.ID });
}
this.createStaticForm();
},
err => console.error(err),
() => console.log('DONE')
);
}
getMeasGroupByIdForModal(id: string) {
this.myObservable = this.measGroupService.getMeasGroupById(id)
.subscribe(
data => {
this.measOnMeasGroup = data.Measurements;
},
err => console.error(err),
() => console.log('DONE')
);
}
getMeasByIdforModal(id: string) {
this.myObservable = this.measurementService.getMeasById(id)
.subscribe(
data => {
this.selectedOID = data.IndexOID || null;
},
err => console.error(err),
() => console.log('DONE')
);
}
addCustomFilter() {
console.log(this.formValues);
this.filterForm.controls['RelatedDev'].patchValue(this.formValues.ID);
this.filterForm.controls['RelatedMeas'].patchValue(this.selectedMeas);
if (this.mode === "new") {
this.customFilterService.addCustomFilter(this.filterForm.value)
.subscribe(data => {
this.showNewFilterForm = true;
this.showNewFilterFormPanel();
this.customFilterValues = data;
this.alertHandler = {
msg: 'Your custom filter' + data['ID'] + ' was added succesfully. You can assign it to a new Measurement Filter', type: 'success', closable: true
};
},
err => {
console.error(err),
this.alertHandler = { msg: 'Something went wrong... ' + err['_body'], type: 'danger', closable: true };
},
() => { console.log("DONE"); }
);
} else {
if (this.filterForm.valid) {
var r = true;
if (this.filterForm.value.ID != this.oldID) {
r = confirm("Changing CustomFilter ID from " + this.oldID + " to " + this.filterForm.value.ID + ". Proceed?");
}
if (r == true) {
this.customFilterService.editCustomFilter(this.filterForm.value, this.oldID)
.subscribe(data => {
this.validationClick();
},
err => console.error(err),
() => { }
);
}
}
}
}
saveMeasFilter() {
if (this.newFilterForm.valid) {
this.measFilterService.addMeasFilter(this.newFilterForm.value)
.subscribe(data => {
this.validationClick();
},
err => console.error(err),
() => { console.log("DONE")}
);
}
}
pingDevice(formValues) {
this.alertHandler = {};
this.isRequesting = true;
this.myObservable = this.snmpDeviceService.pingDevice(formValues,true)
.subscribe(data => {
this.alertHandler = { msg: 'Test succesfull ' + data['SysDescr'], type: 'success', closable: true };
this.isConnected = true;
this.isRequesting = false
},
err => {
this.alertHandler = { msg: 'Test failed! ' + err['_body'], type: 'danger', closable: true };
this.isConnected = false;
this.isRequesting = false
},
() => {
console.log("OK");
}
);
}
unsubscribeRequest() {
if (this.myObservable) this.myObservable.unsubscribe();
}
ngOnDestroy() {
console.log("UNSUBSCRIBING");
if (this.myObservable) this.myObservable.unsubscribe();
}
} | the_stack |
import {
isObject,
isPromise,
isBoolean,
RefTyped,
wrap,
unwrap,
NO_OP,
} from "../utils";
import { ref, Ref, watch, computed, reactive, UnwrapRef } from "../api";
type ValidatorFunc<T, TContext = any> = (
model: T,
ctx: TContext
) => boolean | Promise<boolean>;
type ValidatorObject<TValidator extends ValidatorFunc<any>> = {
$validator: TValidator;
$message: RefTyped<string>;
};
type Validator<T> = ValidatorFunc<T> | ValidatorObject<ValidatorFunc<T>>;
interface ValidationValue<T> {
$value: UnwrapRef<T>;
$dirty: boolean;
$errors: Array<any>;
$anyInvalid: boolean;
$touch(): void;
$reset(): void;
}
interface ValidatorResult {
$error: any;
$invalid: boolean;
}
interface ValidationGroupResult {
$anyDirty: boolean;
$errors: Array<any>;
$anyInvalid: boolean;
$touch(): void;
$reset(): void;
}
interface ValidatorResultPromise {
$pending: boolean;
$promise: Promise<boolean> | null;
}
interface ValidatorResultMessage {
$message: string;
}
/* Input */
type ValidationInputType<T, TValue> = Record<
Exclude<keyof T, "$value">,
Validator<UnwrapRef<TValue>>
> & { $value: TValue };
type ValidationInput<T> = T extends { $value: infer TValue }
? ValidationInputType<T, TValue>
: { [K in keyof T]: ValidationInput<T[K]> };
type UseValidation<T> = { [K in keyof T]: ValidationInput<T[K]> };
/* /Input */
/* Output */
type ValidatorOutput<T, TValue> = T extends (
value?: TValue,
ctx?: any
) => boolean
? ReturnType<T> extends Promise<boolean>
? ValidatorResultPromise & ValidatorResult
: ValidatorResult
: T extends { $validator: Function }
? ValidatorOutput<T["$validator"], TValue> &
(T extends { $message: infer TM } ? { $message: TM } : {})
: T extends (...args: any) => infer TReturn
? TReturn extends Promise<any>
? ValidatorResultPromise & ValidatorResult
: ValidatorResult
: never;
type NonDollarSign<T> = T extends `$${infer _}` ? never : T;
type ToObjectOutput<T extends Record<string, any>> = T extends {
$value: infer V;
}
? UnwrapRef<V>
: {
[K in NonDollarSign<keyof T>]: ToObjectOutput<T[K]>;
};
type Validation<T extends Record<string, any>> = T extends {
$value: infer TV;
}
? {
[K in keyof Omit<T, "$value">]: K extends `$${infer _}`
? UnwrapRef<T[K]>
: ValidatorOutput<T[K], TV>;
} & {
$value: UnwrapRef<TV>;
} & {
toObject(): UnwrapRef<TV>;
} & ValidationValue<TV> & { b: 1 }
: {
[K in keyof T]: K extends `$${infer _}`
? UnwrapRef<T[K]>
: Validation<T[K]>;
} &
(NonDollarSign<keyof T> extends string
? ValidationGroupResult & { toObject(): ToObjectOutput<T> }
: {});
/* /Output */
function isValidation(v: any): v is ValidationInputType<any, any> {
return typeof v.$value !== "undefined";
}
function isValidatorObject(v: any): v is ValidatorObject<any> {
return isObject(v);
}
const buildValidationFunction = (
r: Ref<any>,
f: ValidatorFunc<any>,
m: Ref<string | undefined>,
handlers: Array<Function>
) => {
const $promise: Ref<Promise<boolean> | null> = ref(null);
const $pending = ref(false);
const $error = ref<Error | string | true>();
const $invalid = ref(false);
let context: any = undefined;
const onChange = (r: any) => {
const p = async () => {
try {
$pending.value = true;
const result = f(r, context);
if (isPromise(result)) {
$invalid.value = !(await result);
} else {
$invalid.value = !result;
}
// @ts-ignore
$error.value = $invalid.value ? m.value || true : undefined;
} catch (e) {
$invalid.value = true;
throw e;
} finally {
$pending.value = false;
}
};
$promise.value = p().catch((x) => {
$error.value = unwrap(x);
$invalid.value = true;
return x;
});
};
handlers.push((ctx: any) => {
context = ctx;
watch(
() => {
try {
// keep track on the external dependencies
f(r.value, context);
} catch (e) {
// ignore error
}
return r.value;
},
onChange,
{ deep: true, immediate: true }
);
});
function $touch() {
onChange(r.value);
}
return {
$promise,
$pending,
$invalid,
$error,
$touch,
};
};
const buildValidationValue = (
r: Ref<any>,
v: Validator<any>,
handlers: Array<Function>
): ValidatorResult & ValidatorResultPromise & ValidatorResultMessage => {
const { $message, $validator, ...$rest } = isValidatorObject(v)
? v
: { $validator: v, $message: undefined };
const {
$pending,
$promise,
$invalid,
$error,
$touch,
} = buildValidationFunction(r, $validator, ref($message), handlers);
return {
$pending,
$error,
$promise,
$invalid,
$message,
$touch,
...$rest,
} as any;
};
const buildValidation = <T>(
o: ValidationInput<T>,
handlers: Array<Function>
): Record<string, Validation<any>> => {
const r: Record<string, Validation<any>> = {};
const $value: any | undefined = isValidation(o) ? wrap(o.$value) : undefined;
for (const k of Object.keys(o)) {
if (k[0] === "$") {
if (k === "$value") {
r[k] = $value;
const $dirty = ref(false);
let dirtyWatch = NO_OP;
const createDirtyWatcher = () => {
dirtyWatch();
dirtyWatch = watch(
$value,
() => {
$dirty.value = true;
dirtyWatch();
},
{ immediate: false, deep: true }
);
};
createDirtyWatcher();
(r as any)["$dirty"] = $dirty;
(r as any)["$reset"] = () => {
$dirty.value = false
createDirtyWatcher();
};
(r as any)["$touch"] = () => ($dirty.value = true);
// @ts-ignore
r.toObject = () => unwrap($value);
continue;
} else {
r[k] = (o as any)[k];
continue;
}
}
if ($value) {
const validation = buildValidationValue(
$value,
(o as Record<string, any>)[k],
handlers
);
// @ts-expect-error no valid type
r[k] = validation;
} else {
const validation = buildValidation(
(o as Record<string, any>)[k],
handlers
);
let $anyDirty: Ref<boolean> | undefined = undefined;
let $errors: Readonly<Ref<Readonly<Array<any>>>>;
let $anyInvalid: Ref<boolean>;
let toObject: () => Record<string, any> = NO_OP as any;
if (isValidation(validation)) {
const validations = Object.keys(validation)
.filter((x) => x[0] !== "$")
.map((x) => (validation[x] as any) as ValidatorResult);
$errors = computed(() =>
validations
.map((x) => x.$error)
.map((x) => unwrap(x))
.filter((x) => x !== undefined)
);
// $anyDirty = computed(() => validations.some(x => !!x));
$anyInvalid = computed(() =>
validations.some((x) => {
return !!unwrap(x.$invalid);
})
);
toObject = () => {
return Object.keys(validation)
.filter((x) => x[0] !== "$")
.reduce((p, c) => {
//@ts-ignore
p[c] = validation[c].toObject();
return p;
}, {});
};
} else {
const validations = Object.keys(validation).map(
(x) => (validation[x] as any) as ValidationGroupResult
);
$errors = computed(() => {
return validations
.map((x) => unwrap(x.$errors))
.filter((x) => x !== undefined)
.filter((x) => {
return x.some(Boolean);
});
});
$anyDirty = computed(() => {
return validations.some((x) => {
return (
unwrap(x.$anyDirty) ||
(isBoolean(unwrap((x as any).$dirty)) &&
unwrap((x as any).$dirty))
);
});
});
$anyInvalid = computed(() =>
validations.some((x) => {
return !!unwrap(x.$anyInvalid);
})
);
toObject = () => {
return Object.keys(validation)
.filter((x) => x[0] !== "$")
.reduce((p, c) => {
//@ts-ignore
p[c] = validation[c].toObject();
return p;
}, {});
};
}
r[k] = {
toObject,
...validation,
$errors,
$anyInvalid,
} as any;
if ($anyDirty) {
(r[k] as any).$anyDirty = $anyDirty;
const keys = Object.keys(r[k]).filter(
(x) => x[0] !== "$" && isObject(r[k][x])
);
r[k].$touch = () => {
// r[k].
keys.forEach((m) => {
const touch = r[k][m].$touch;
if (touch) {
touch();
}
});
};
r[k].$reset = () => {
keys.forEach((m) => {
const reset = r[k][m].$reset;
if (reset) {
reset();
}
});
};
}
}
}
return r;
};
export function useValidation<T extends UseValidation<E>, E = any>(
input: E
): Validation<E> & ValidationGroupResult & { toObject(): ToObjectOutput<E> } {
const handlers: Array<Function> = [];
const validation = buildValidation({ input }, handlers);
// convert to reactive, this will make it annoying to deconstruct, but
// allows to use it directly on the render template without `.value`
// https://github.com/vuejs/vue-next/pull/738
// @ts-expect-error TODO check this error
const validationInput = reactive(validation.input);
// set the context, this will allow to use this object as the second
// argument when calling validators
handlers.forEach((x) => x(validationInput));
return validationInput as any;
} | the_stack |
* This module provides the APIs to Silabs Simplicity Studio's Jetty server.
*
*/
// dirty flag reporting interval
const DIRTY_FLAG_REPORT_INTERVAL_MS = 1000
const UC_COMPONENT_STATE_REPORTING_INTERVAL_ID = 6000
import axios, { AxiosPromise, AxiosResponse } from 'axios'
import * as env from '../util/env'
import * as querySession from '../db/query-session.js'
const wsServer = require('../server/ws-server.js')
const dbEnum = require('../../src-shared/db-enum.js')
import * as ucTypes from '../../src-shared/types/uc-component-types'
import * as dbMappingTypes from '../types/db-mapping-types'
import * as http from 'http-status-codes'
import zcl from './zcl.js'
import * as sqlite from 'sqlite3'
const localhost = 'http://localhost:'
const op_tree = '/rest/clic/components/all/project/'
const op_add = '/rest/clic/component/add/project/'
const op_remove = '/rest/clic/component/remove/project/'
let dirtyFlagStatusId: NodeJS.Timeout
let ucComponentStateReportId: NodeJS.Timeout
let studioHttpPort: number
function projectPath(db: env.dbType, sessionId: number) {
return querySession.getSessionKeyValue(
db,
sessionId,
dbEnum.sessionKey.ideProjectPath
)
}
/**
* Boolean deciding whether Studio integration logic should be enabled
* @param {*} db
* @param {*} sessionId
* @returns - Promise to studio project path
*/
async function integrationEnabled(db: env.dbType, sessionId: number) {
let path: string = await querySession.getSessionKeyValue(
db,
sessionId,
dbEnum.sessionKey.ideProjectPath
)
return typeof path !== 'undefined'
}
/**
* Extract project name from the Studio project path
* @param {} db
* @param {*} sessionId
* @returns '' if retrival failed
*/
function projectName(studioProjectPath: string) {
const prefix = '_2F'
if (studioProjectPath && studioProjectPath.includes(prefix)) {
return studioProjectPath.substr(
studioProjectPath.lastIndexOf(prefix) + prefix.length
)
} else {
return ''
}
}
/**
* Send HTTP GET request to Studio Jetty server for project information.
* @param {} db
* @param {*} sessionId
* @returns - HTTP RESP with project info in JSON form
*/
async function getProjectInfo(
db: env.dbType,
sessionId: number
): Promise<{
data: string[]
status?: http.StatusCodes
}> {
let studioProjectPath = await projectPath(db, sessionId)
if (studioProjectPath) {
let name = await projectName(studioProjectPath)
let path = localhost + studioHttpPort + op_tree + studioProjectPath
env.logInfo(`StudioUC(${name}): GET: ${path}`)
return axios
.get(path)
.then((resp) => {
env.logInfo(`StudioUC(${name}): RESP: ${resp.status}`)
return resp
})
.catch((err) => {
env.logError(`StudioUC(${name}): ERR: ${err}`)
return { data: [] }
})
} else {
env.logError(
`StudioUC(): Invalid Studio path project. Failed to retrieve project info.`
)
return { data: [] }
}
}
/**
* Send HTTP Post to update UC component state in Studio
* @param {*} project
* @param {*} componentIds
* @param {*} add
* @param {*} db
* @param {*} sessionId
* @param {*} side
* @return {*} - [{id, status, data }]
* id - string,
* status - boolean. true if HTTP REQ status code is OK,
* data - HTTP response data field
*/
async function updateComponentByClusterIdAndComponentId(
db: env.dbType,
sessionId: number,
componentIds: string[],
clusterId: number,
add: boolean,
side: string
) {
if (!integrationEnabled(db, sessionId)) {
env.logInfo(
`StudioUC(): Failed to update component due to invalid Studio project path.`
)
return Promise.resolve({ componentIds: [], added: add })
}
// retrieve components to enable
let promises = []
if (clusterId) {
let ids = zcl
.getComponentIdsByCluster(db, sessionId, clusterId, side)
.then((response: ucTypes.UcComponentIds) =>
Promise.resolve(response.componentIds)
)
promises.push(ids)
}
// enabling components via Studio
return (
Promise.all(promises)
.then((ids) => ids.flat())
.then((ids) => ids.concat(componentIds))
// enabling components via Studio jetty server.
.then((ids) => updateComponentByComponentIds(db, sessionId, ids, add))
.catch((err) => {
env.logInfo(err)
return err
})
)
}
/**
* Send HTTP Post to update UC component state in Studio
* @param {*} project - local Studio project path
* @param {*} componentIds - a list of component Ids
* @param {*} add - true if adding component, false if removing.
* @return {*} - [{id, status, data }]
* id - string,
* status - boolean. true if HTTP REQ status code is OK,
* data - HTTP response data field
*/
async function updateComponentByComponentIds(
db: env.dbType,
sessionId: number,
componentIds: string[],
add: boolean
) {
componentIds = componentIds.filter((x) => x)
let promises: Promise<
AxiosResponse | ucTypes.UcComponentUpdateResponseWrapper
>[] = []
let project = await projectPath(db, sessionId)
let name = await projectName(project)
if (Object.keys(componentIds).length) {
promises = componentIds.map((componentId) =>
httpPostComponentUpdate(project, componentId, add)
)
}
return Promise.all(promises).then((responses) =>
responses.map((resp, index) => {
return {
projectName: name,
id: componentIds[index],
status: resp.status,
data: resp.data,
}
})
)
}
function httpPostComponentUpdate(
project: string,
componentId: string,
add: boolean
) {
let operation = add ? op_add : op_remove
let operationText = add ? 'add' : 'remove'
return axios
.post(localhost + studioHttpPort + operation + project, {
componentId: componentId,
})
.then((res) => {
// @ts-ignore
res.componentId = componentId
return res
})
.catch((err) => {
let resp = err.response
// This is the weirdest API in the world:
// if the component is added, but something else goes wrong, it actualy
// returns error, but puts componentAdded flag into the error response.
// Same with component removed.
if (
(add && resp?.data?.componentAdded) ||
(!add && resp?.data?.componentRemoved)
) {
// Pretend it was all good.
resp.componentId = componentId
return resp
} else {
// Actual fail.
return {
status: http.StatusCodes.NOT_FOUND,
id: componentId,
data: `StudioUC(${projectName(
project
)}): Failed to ${operationText} component(${componentId})`,
}
}
})
}
/**
* Start the dirty flag reporting interval.
*
*/
function initIdeIntegration(db: env.dbType, studioPort: number) {
studioHttpPort = studioPort
dirtyFlagStatusId = setInterval(() => {
sendDirtyFlagStatus(db)
}, DIRTY_FLAG_REPORT_INTERVAL_MS)
ucComponentStateReportId = setInterval(() => {
sendUcComponentStateReport(db)
}, UC_COMPONENT_STATE_REPORTING_INTERVAL_ID)
}
/**
* Clears up the reporting interval.
*/
function deinit() {
if (dirtyFlagStatusId) clearInterval(dirtyFlagStatusId)
if (ucComponentStateReportId) clearInterval(ucComponentStateReportId)
}
async function sendUcComponentStateReport(db: env.dbType) {
let sessions = await querySession.getAllSessions(db)
for (const session of sessions) {
let socket = wsServer.clientSocket(session.sessionKey)
let studioIntegration = await integrationEnabled(db, session.sessionId)
if (socket && studioIntegration) {
getProjectInfo(db, session.sessionId).then((resp) => {
if (resp.status == http.StatusCodes.OK)
wsServer.sendWebSocketMessage(socket, {
category: dbEnum.wsCategory.ucComponentStateReport,
payload: resp.data,
})
})
}
}
}
function sendDirtyFlagStatus(db: env.dbType) {
// TODO: delegate type declaration to actual function
querySession
.getAllSessions(db)
.then((sessions: dbMappingTypes.SessionType[]) => {
sessions.forEach((session) => {
let socket = wsServer.clientSocket(session.sessionKey)
if (socket) {
querySession
.getSessionDirtyFlag(db, session.sessionId)
.then((flag) => {
wsServer.sendWebSocketMessage(socket, {
category: dbEnum.wsCategory.dirtyFlag,
payload: flag,
})
})
.catch((err) => {
env.logWarning('Could not query dirty status.')
})
}
})
})
}
/**
* Notify front-end that current session failed to load.
* @param {} err
*/
function sendSessionCreationErrorStatus(db: env.dbType, err: string) {
// TODO: delegate type declaration to actual function
querySession
.getAllSessions(db)
.then((sessions: dbMappingTypes.SessionType[]) =>
sessions.forEach((session) => {
let socket = wsServer.clientSocket(session.sessionKey)
if (socket) {
wsServer.sendWebSocketMessage(socket, {
category: dbEnum.wsCategory.sessionCreationError,
payload: err,
})
}
})
)
}
/**
* Notify front-end that current session failed to load.
* @param {*} err
*/
function sendComponentUpdateStatus(
db: env.dbType,
sessionId: number,
data: any
) {
querySession
.getAllSessions(db)
.then((sessions: dbMappingTypes.SessionType[]) =>
sessions.forEach((session) => {
if (session.sessionId == sessionId) {
let socket = wsServer.clientSocket(session.sessionKey)
if (socket) {
wsServer.sendWebSocketMessage(socket, {
category: dbEnum.wsCategory.componentUpdateStatus,
payload: data,
})
}
}
})
)
}
exports.getProjectInfo = getProjectInfo
exports.updateComponentByComponentIds = updateComponentByComponentIds
exports.updateComponentByClusterIdAndComponentId =
updateComponentByClusterIdAndComponentId
exports.projectName = projectName
exports.integrationEnabled = integrationEnabled
exports.initIdeIntegration = initIdeIntegration
exports.deinit = deinit
exports.sendSessionCreationErrorStatus = sendSessionCreationErrorStatus
exports.sendComponentUpdateStatus = sendComponentUpdateStatus | the_stack |
import { Signer, TypedDataSigner } from '@ethersproject/abstract-signer';
import { BigNumber } from '@ethersproject/bignumber';
import { hexDataLength, hexDataSlice } from '@ethersproject/bytes';
import type { BaseProvider } from '@ethersproject/providers';
import type { ContractTransaction } from '@ethersproject/contracts';
import getUnixTime from 'date-fns/getUnixTime';
import { v4 } from 'uuid';
import warning from 'tiny-warning';
import invariant from 'tiny-invariant';
import padEnd from 'lodash/padEnd';
import padStart from 'lodash/padStart';
import {
ERC1155__factory,
ERC20__factory,
ERC721__factory,
} from '../../contracts';
import { NULL_ADDRESS } from '../../utils/eth';
import { UnexpectedAssetTypeError } from '../error';
import type {
ECSignature,
ERC721OrderStruct,
ERC721OrderStructSerialized,
ERC1155OrderStruct,
ERC1155OrderStructSerialized,
NftOrderV4,
OrderStructOptionsCommon,
OrderStructOptionsCommonStrict,
SignedNftOrderV4,
SignedNftOrderV4Serialized,
SwappableAssetV4,
UserFacingERC20AssetDataSerializedV4,
UserFacingERC721AssetDataSerializedV4,
UserFacingERC1155AssetDataSerializedV4,
ApprovalOverrides,
} from './types';
import { ApprovalStatus, TransactionOverrides } from '../common/types';
import {
ERC721ORDER_STRUCT_NAME,
ERC721ORDER_STRUCT_ABI,
ERC1155ORDER_STRUCT_NAME,
ERC1155ORDER_STRUCT_ABI,
FEE_ABI,
PROPERTY_ABI,
ETH_ADDRESS_AS_ERC20,
} from './constants';
export const signOrderWithEoaWallet = async (
order: NftOrderV4,
signer: TypedDataSigner,
chainId: number,
exchangeContractAddress: string
) => {
if ((order as ERC1155OrderStruct).erc1155Token) {
const domain = {
chainId: chainId,
verifyingContract: exchangeContractAddress,
name: 'ZeroEx',
version: '1.0.0',
};
const types = {
[ERC1155ORDER_STRUCT_NAME]: ERC1155ORDER_STRUCT_ABI,
Fee: FEE_ABI,
Property: PROPERTY_ABI,
};
const value = order;
const rawSignatureFromEoaWallet = await signer._signTypedData(
domain,
types,
value
);
return rawSignatureFromEoaWallet;
}
if ((order as ERC721OrderStruct).erc721Token) {
const domain = {
chainId: chainId,
verifyingContract: exchangeContractAddress,
name: 'ZeroEx',
version: '1.0.0',
};
const types = {
[ERC721ORDER_STRUCT_NAME]: ERC721ORDER_STRUCT_ABI,
Fee: FEE_ABI,
Property: PROPERTY_ABI,
};
const value = order;
const rawSignatureFromEoaWallet = await signer._signTypedData(
domain,
types,
value
);
return rawSignatureFromEoaWallet;
}
warning(!order, 'Unknown order type');
throw new Error(`Unknown order type`);
};
/**
*
* @param walletAddress Owner of the asset
* @param exchangeProxyAddressForAsset Exchange Proxy address specific to the ERC type (e.g. use the 0x ERC721 Proxy if you're using a 721 asset). This is the address that will need approval & does the spending/swap.
* @param asset
* @param provider
* @returns
*/
export const getApprovalStatus = async (
walletAddress: string,
exchangeProxyAddressForAsset: string,
asset: SwappableAssetV4,
provider: BaseProvider
): Promise<ApprovalStatus> => {
switch (asset.type) {
case 'ERC20':
// ETH (ERC20 representation) requires no approvals, we can shortcut here
if (asset.tokenAddress.toLowerCase() === ETH_ADDRESS_AS_ERC20) {
return {
contractApproved: true,
};
}
const erc20 = ERC20__factory.connect(asset.tokenAddress, provider);
const erc20AllowanceBigNumber: BigNumber = await erc20.allowance(
walletAddress,
exchangeProxyAddressForAsset
);
// Weird issue with BigNumber and approvals...need to look into it, adding buffer.
const MAX_APPROVAL_WITH_BUFFER = BigNumber.from(
MAX_APPROVAL.toString()
).sub('100000000000000000');
const approvedForMax = erc20AllowanceBigNumber.gte(
MAX_APPROVAL_WITH_BUFFER
);
return {
contractApproved: approvedForMax,
};
case 'ERC721':
const erc721 = ERC721__factory.connect(asset.tokenAddress, provider);
const erc721ApprovalForAllPromise = erc721.isApprovedForAll(
walletAddress,
exchangeProxyAddressForAsset
);
const erc721ApprovedAddressForIdPromise = erc721.getApproved(
asset.tokenId
);
const [erc721ApprovalForAll, erc721ApprovedAddressForId] =
await Promise.all([
erc721ApprovalForAllPromise,
erc721ApprovedAddressForIdPromise,
]);
const tokenIdApproved =
erc721ApprovedAddressForId.toLowerCase() ===
exchangeProxyAddressForAsset.toLowerCase();
return {
contractApproved: erc721ApprovalForAll ?? false,
tokenIdApproved: tokenIdApproved,
};
case 'ERC1155':
const erc1155 = ERC1155__factory.connect(asset.tokenAddress, provider);
const erc1155ApprovalForAll = await erc1155.isApprovedForAll(
walletAddress,
exchangeProxyAddressForAsset
);
return {
contractApproved: erc1155ApprovalForAll ?? false,
};
default:
throw new UnexpectedAssetTypeError((asset as any).type);
}
};
// Some arbitrarily high number.
// TODO(johnrjj) - Support custom ERC20 approval amounts
export const MAX_APPROVAL = BigNumber.from(2).pow(118);
/**
* @param exchangeProxyAddressForAsset Exchange Proxy address specific to the ERC type (e.g. use the 0x ERC721 Proxy if you're using a 721 asset). This is the address that will need approval & does the spending/swap.
* @param asset
* @param signer Signer, must be a signer not a provider, as signed transactions are needed to approve
* @param approve Optional, can specify to unapprove asset when set to false
* @returns
*/
export const approveAsset = async (
exchangeProxyAddressForAsset: string,
asset: SwappableAssetV4,
signer: Signer,
txOverrides: Partial<TransactionOverrides> = {},
approvalOrderrides?: Partial<ApprovalOverrides>
): Promise<ContractTransaction> => {
const approve = approvalOrderrides?.approve ?? true;
switch (asset.type) {
case 'ERC20':
const erc20 = ERC20__factory.connect(asset.tokenAddress, signer);
const erc20ApprovalTxPromise = erc20.approve(
exchangeProxyAddressForAsset,
approve ? MAX_APPROVAL.toString() : 0,
{
...txOverrides,
}
);
return erc20ApprovalTxPromise;
case 'ERC721':
const erc721 = ERC721__factory.connect(asset.tokenAddress, signer);
// If consumer prefers only to approve the tokenId, only approve tokenId
if (approvalOrderrides?.approvalOnlyTokenIdIfErc721) {
const erc721ApprovalForOnlyTokenId = erc721.approve(
exchangeProxyAddressForAsset,
asset.tokenId,
{
...txOverrides,
}
);
return erc721ApprovalForOnlyTokenId;
}
// Otherwise default to approving entire contract
const erc721ApprovalForAllPromise = erc721.setApprovalForAll(
exchangeProxyAddressForAsset,
approve,
{
...txOverrides,
}
);
return erc721ApprovalForAllPromise;
case 'ERC1155':
const erc1155 = ERC1155__factory.connect(asset.tokenAddress, signer);
// ERC1155s can only approval all
const erc1155ApprovalForAll = await erc1155.setApprovalForAll(
exchangeProxyAddressForAsset,
approve,
{
...txOverrides,
}
);
return erc1155ApprovalForAll;
default:
throw new UnexpectedAssetTypeError((asset as any).type);
}
};
// Parse a hex signature returned by an RPC call into an `ECSignature`.
export function parseRawSignature(rawSignature: string): ECSignature {
const hexSize = hexDataLength(rawSignature);
// if (hexUtils.size(rpcSig) !== 65) {
// throw new Error(`Invalid RPC signature length: "${rpcSig}"`);
// }
if (hexSize !== 65) {
throw new Error(
`Invalid signature length, expected 65, got ${hexSize}.\n"Raw signature: ${rawSignature}"`
);
}
// Some providers encode V as 0,1 instead of 27,28.
const VALID_V_VALUES = [0, 1, 27, 28];
// Some providers return the signature packed as V,R,S and others R,S,V.
// Try to guess which encoding it is (with a slight preference for R,S,V).
// let v = parseInt(rpcSig.slice(-2), 16);
let v = parseInt(rawSignature.slice(-2), 16);
if (VALID_V_VALUES.includes(v)) {
// Format is R,S,V
v = v >= 27 ? v : v + 27;
return {
// r: hexDataSlice.slice(rpcSig, 0, 32),
// s: hexUtils.slice(rpcSig, 32, 64),
r: hexDataSlice(rawSignature, 0, 32),
s: hexDataSlice(rawSignature, 32, 64),
v,
};
}
// Format should be V,R,S
// v = parseInt(rpcSig.slice(2, 4), 16);
v = parseInt(rawSignature.slice(2, 4), 16);
if (!VALID_V_VALUES.includes(v)) {
throw new Error(
`Cannot determine RPC signature layout from V value: "${rawSignature}"`
);
}
v = v >= 27 ? v : v + 27;
return {
v,
r: hexDataSlice(rawSignature, 1, 33),
s: hexDataSlice(rawSignature, 33, 65),
};
}
export const INFINITE_EXPIRATION_TIMESTAMP_SEC = BigNumber.from(2524604400);
export const generateErc721Order = (
nft: UserFacingERC721AssetDataSerializedV4,
erc20: UserFacingERC20AssetDataSerializedV4,
orderData: Partial<OrderStructOptionsCommon> & OrderStructOptionsCommonStrict
): ERC721OrderStructSerialized => {
let expiry = INFINITE_EXPIRATION_TIMESTAMP_SEC.toString();
if (orderData.expiry) {
// If number is provided, assume given as unix timestamp
if (typeof orderData.expiry === 'number') {
expiry = orderData.expiry.toString();
} else {
// If date is provided, convert to unix timestamp
expiry = getUnixTime(orderData.expiry).toString();
}
}
const erc721Order: ERC721OrderStructSerialized = {
erc721Token: nft.tokenAddress.toLowerCase(),
erc721TokenId: nft.tokenId,
direction: parseInt(orderData.direction.toString()), // KLUDGE(johnrjj) - There's some footgun here when only doing orderData.direction.toString(), need to parseInt it
erc20Token: erc20.tokenAddress.toLowerCase(),
erc20TokenAmount: erc20.amount,
maker: orderData.maker.toLowerCase(),
// Defaults not required...
erc721TokenProperties:
orderData.tokenProperties?.map((property) => ({
propertyData: property.propertyData,
propertyValidator: property.propertyValidator,
})) ?? [],
fees:
orderData.fees?.map((x) => {
return {
amount: x.amount.toString(),
recipient: x.recipient.toLowerCase(),
feeData: x.feeData?.toString() ?? '0x',
};
}) ?? [],
expiry: expiry,
nonce:
orderData.nonce?.toString() ??
generateRandomV4OrderNonce(orderData.appId),
taker: orderData.taker?.toLowerCase() ?? NULL_ADDRESS,
};
return erc721Order;
};
export const generateErc1155Order = (
nft: UserFacingERC1155AssetDataSerializedV4,
erc20: UserFacingERC20AssetDataSerializedV4,
orderData: Partial<OrderStructOptionsCommon> & OrderStructOptionsCommonStrict
): ERC1155OrderStructSerialized => {
let expiry = INFINITE_EXPIRATION_TIMESTAMP_SEC.toString();
if (orderData.expiry) {
// If number is provided, assume given as unix timestamp
if (typeof orderData.expiry === 'number') {
expiry = orderData.expiry.toString();
} else {
// If date is provided, convert to unix timestamp
expiry = getUnixTime(orderData.expiry).toString();
}
}
const erc1155Order: ERC1155OrderStructSerialized = {
erc1155Token: nft.tokenAddress.toLowerCase(),
erc1155TokenId: nft.tokenId,
erc1155TokenAmount: nft.amount ?? '1',
direction: parseInt(orderData.direction.toString(10)), // KLUDGE(johnrjj) - There's some footgun here when only doing orderData.direction.toString(), need to parseInt it
erc20Token: erc20.tokenAddress.toLowerCase(),
erc20TokenAmount: erc20.amount,
maker: orderData.maker.toLowerCase(),
// Defaults not required...
erc1155TokenProperties:
orderData.tokenProperties?.map((property) => ({
propertyData: property.propertyData.toString(),
propertyValidator: property.propertyValidator,
})) ?? [],
fees:
orderData.fees?.map((fee) => {
return {
amount: fee.amount.toString(),
recipient: fee.recipient.toLowerCase(),
feeData: fee.feeData?.toString() ?? '0x',
};
}) ?? [],
expiry: expiry,
nonce:
orderData.nonce?.toString() ??
generateRandomV4OrderNonce(orderData.appId),
taker: orderData.taker?.toLowerCase() ?? NULL_ADDRESS,
};
return erc1155Order;
};
// Number of digits in base 10 128bit nonce
// floor(log_10(2^128 - 1)) + 1
export const ONE_TWENTY_EIGHT_BIT_LENGTH = 39;
// Max nonce digit length in base 10
// floor(log_10(2^256 - 1)) + 1
export const TWO_FIFTY_SIX_BIT_LENGTH = 78;
const checkIfStringContainsOnlyNumbers = (val: string) => {
const onlyNumbers = /^\d+$/.test(val);
return onlyNumbers;
};
export const RESERVED_APP_ID_PREFIX = '1001';
const RESERVED_APP_ID_PREFIX_DIGITS = RESERVED_APP_ID_PREFIX.length;
export const DEFAULT_APP_ID = '314159';
export const verifyAppIdOrThrow = (appId: string) => {
const isCorrectLength =
appId.length <= ONE_TWENTY_EIGHT_BIT_LENGTH - RESERVED_APP_ID_PREFIX_DIGITS;
const hasOnlyNumbers = checkIfStringContainsOnlyNumbers(appId);
invariant(isCorrectLength, 'appId must be 39 digits or less');
invariant(
hasOnlyNumbers,
'appId must be numeric only (no alpha or special characters, only numbers)'
);
};
/**
* Generates a 256bit nonce.
* The format:
* First 128bits: ${SDK_PREFIX}${APP_ID}000000 (right padded zeroes to fill)
* Second 128bits: ${RANDOM_GENERATED_128BIT_ORDER_HASH}
* @returns 128bit nonce as string (0x orders can handle up to 256 bit nonce)
*/
export const generateRandomV4OrderNonce = (
appId: string = DEFAULT_APP_ID
): string => {
if (appId) {
verifyAppIdOrThrow(appId);
}
const order128 = padStart(
generateRandom128BitNumber(),
ONE_TWENTY_EIGHT_BIT_LENGTH,
'0'
);
const appId128 = padEnd(
`${RESERVED_APP_ID_PREFIX}${appId}`,
ONE_TWENTY_EIGHT_BIT_LENGTH,
'0'
);
const final256BitNonce = `${appId128}${order128}`;
invariant(
final256BitNonce.length <= TWO_FIFTY_SIX_BIT_LENGTH,
'Invalid nonce size'
);
return final256BitNonce;
};
// uuids are 128bits
export const generateRandom128BitNumber = (base = 10): string => {
const hex = '0x' + v4().replace(/-/g, '');
const value = BigInt(hex);
const valueBase10String = value.toString(base); // don't convert this to a number, will lose precision
return valueBase10String;
};
export const serializeNftOrder = (
signedOrder: SignedNftOrderV4
): SignedNftOrderV4Serialized => {
if ('erc721Token' in signedOrder) {
return {
...signedOrder,
direction: parseInt(signedOrder.direction.toString()),
expiry: signedOrder.expiry.toString(),
nonce: signedOrder.nonce.toString(),
erc20TokenAmount: signedOrder.erc20TokenAmount.toString(),
fees: signedOrder.fees.map((fee) => ({
...fee,
amount: fee.amount.toString(),
feeData: fee.feeData.toString(),
})),
erc721TokenId: signedOrder.erc721TokenId.toString(),
};
} else if ('erc1155Token' in signedOrder) {
return {
...signedOrder,
direction: parseInt(signedOrder.direction.toString()),
expiry: signedOrder.expiry.toString(),
nonce: signedOrder.nonce.toString(),
erc20TokenAmount: signedOrder.erc20TokenAmount.toString(),
fees: signedOrder.fees.map((fee) => ({
...fee,
amount: fee.amount.toString(),
feeData: fee.feeData.toString(),
})),
erc1155TokenAmount: signedOrder.erc1155TokenAmount.toString(),
erc1155TokenId: signedOrder.erc1155TokenId.toString(),
};
} else {
console.log(
'unknown order format type (not erc721 and not erc1155',
signedOrder
);
throw new Error('Unknown asset type');
}
}; | the_stack |
import { fetcher, IndexedFormula, NamedNode, sym } from 'rdflib'
import { ACLbyCombination, readACL } from './acl'
import * as widgets from '../widgets'
import * as ns from '../ns'
import { AccessController } from './access-controller'
import { AgentMapMap, ComboList, PartialAgentTriple } from './types'
import { AddAgentButtons } from './add-agent-buttons'
import * as debug from '../debug'
import { LiveStore } from 'pane-registry'
const ACL = ns.acl
const COLLOQUIAL = {
13: 'Owners',
9: 'Owners (write locked)',
5: 'Editors',
3: 'Posters',
2: 'Submitters',
1: 'Viewers'
}
const RECOMMENDED = {
13: true,
5: true,
3: true,
2: true,
1: true
}
const EXPLANATION = {
13: 'can read, write, and control sharing.',
9: 'can read and control sharing, currently write-locked.',
5: 'can read and change information',
3: 'can add new information, and read but not change existing information',
2: 'can add new information but not read any',
1: 'can read but not change information'
}
/**
* Type for the options parameter of [[AccessGroups]]
*/
export interface AccessGroupsOptions {
defaults?: boolean
}
/**
* Renders the table of Owners, Editors, Posters, Submitters, Viewers
* for https://github.com/solid/userguide/blob/main/views/sharing/userguide.md
*/
export class AccessGroups {
private readonly defaults: boolean
public byCombo: ComboList
public aclMap: AgentMapMap
private readonly addAgentButton: AddAgentButtons
private readonly rootElement: HTMLElement
private _store: LiveStore
constructor (
private doc: NamedNode,
private aclDoc: NamedNode,
public controller: AccessController,
store: IndexedFormula,
private options: AccessGroupsOptions = {}
) {
this.defaults = options.defaults || false
fetcher(store, {})
// The store will already have an updater at this point:
// store.updater = new UpdateManager(store)
this._store = store as LiveStore // TODO hacky, find a better solution
this.aclMap = readACL(doc, aclDoc, store, this.defaults)
this.byCombo = ACLbyCombination(this.aclMap)
this.addAgentButton = new AddAgentButtons(this)
this.rootElement = this.controller.dom.createElement('div')
this.rootElement.classList.add(this.controller.classes.accessGroupList)
}
public get store () {
return this._store
}
public set store (store) {
this._store = store
this.aclMap = readACL(this.doc, this.aclDoc, store, this.defaults)
this.byCombo = ACLbyCombination(this.aclMap)
}
public render (): HTMLElement {
this.rootElement.innerHTML = ''
this.renderGroups().forEach(group => this.rootElement.appendChild(group))
if (this.controller.isEditable) {
this.rootElement.appendChild(this.addAgentButton.render())
}
return this.rootElement
}
private renderGroups (): HTMLElement[] {
const groupElements: HTMLElement[] = []
for (let comboIndex = 15; comboIndex > 0; comboIndex--) {
const combo = kToCombo(comboIndex)
if ((this.controller.isEditable && RECOMMENDED[comboIndex]) || this.byCombo[combo]) {
groupElements.push(this.renderGroup(comboIndex, combo))
}
}
return groupElements
}
private renderGroup (comboIndex: number, combo: string): HTMLElement {
const groupRow = this.controller.dom.createElement('div')
groupRow.classList.add(this.controller.classes.accessGroupListItem)
widgets.makeDropTarget(groupRow, (uris) => this.handleDroppedUris(uris, combo)
.then(() => this.controller.render())
.catch(error => this.controller.renderStatus(error)))
const groupColumns = this.renderGroupElements(comboIndex, combo)
groupColumns.forEach(column => groupRow.appendChild(column))
return groupRow
}
private renderGroupElements (comboIndex, combo): HTMLElement[] {
const groupNameColumn = this.controller.dom.createElement('div')
groupNameColumn.classList.add(this.controller.classes.group)
groupNameColumn.classList.toggle(this.controller.classes[`group-${comboIndex}`], this.controller.isEditable)
groupNameColumn.innerText = COLLOQUIAL[comboIndex] || ktToList(comboIndex)
const groupAgentsColumn = this.controller.dom.createElement('div')
groupAgentsColumn.classList.add(this.controller.classes.group)
groupAgentsColumn.classList.toggle(this.controller.classes[`group-${comboIndex}`], this.controller.isEditable)
const groupAgentsTable = groupAgentsColumn.appendChild(this.controller.dom.createElement('table'))
const combos = this.byCombo[combo] || []
combos
.map(([pred, obj]) => this.renderAgent(groupAgentsTable, combo, pred, obj))
.forEach(agentElement => groupAgentsTable.appendChild(agentElement))
const groupDescriptionElement = this.controller.dom.createElement('div')
groupDescriptionElement.classList.add(this.controller.classes.group)
groupDescriptionElement.classList.toggle(this.controller.classes[`group-${comboIndex}`], this.controller.isEditable)
groupDescriptionElement.innerText = EXPLANATION[comboIndex] || 'Unusual combination'
return [groupNameColumn, groupAgentsColumn, groupDescriptionElement]
}
private renderAgent (groupAgentsTable, combo, pred, obj): HTMLElement {
const personRow = widgets.personTR(this.controller.dom, ACL(pred), sym(obj), this.controller.isEditable
? {
deleteFunction: () => this.deleteAgent(combo, pred, obj)
.then(() => groupAgentsTable.removeChild(personRow))
.catch(error => this.controller.renderStatus(error))
}
: {})
return personRow
}
private async deleteAgent (combo, pred, obj): Promise<void> {
const combos = this.byCombo[combo] || []
const comboToRemove = combos.find(([comboPred, comboObj]) => comboPred === pred && comboObj === obj)
if (comboToRemove) {
combos.splice(combos.indexOf(comboToRemove), 1)
}
await this.controller.save()
}
public async addNewURI (uri: string): Promise<void> {
await this.handleDroppedUri(uri, kToCombo(1))
await this.controller.save()
}
private async handleDroppedUris (uris: string[], combo: string): Promise<void> {
try {
await Promise.all(uris.map(uri => this.handleDroppedUri(uri, combo)))
await this.controller.save()
} catch (error) {
return Promise.reject(error)
}
}
private async handleDroppedUri (uri: string, combo: string, secondAttempt: boolean = false): Promise<void> {
const agent = findAgent(uri, this.store) // eg 'agent', 'origin', agentClass'
const thing = sym(uri)
if (!agent && !secondAttempt) {
debug.log(` Not obvious: looking up dropped thing ${thing}`)
try {
await this._store.fetcher.load(thing.doc())
} catch (error) {
const message = `Ignore error looking up dropped thing: ${error}`
debug.error(message)
return Promise.reject(new Error(message))
}
return this.handleDroppedUri(uri, combo, true)
} else if (!agent) {
const error = ` Error: Drop fails to drop appropriate thing! ${uri}`
debug.error(error)
return Promise.reject(new Error(error))
}
this.setACLCombo(combo, uri, agent, this.controller.subject)
}
private setACLCombo (combo: string, uri: string, res: PartialAgentTriple, subject: NamedNode): void {
if (!(combo in this.byCombo)) {
this.byCombo[combo] = []
}
this.removeAgentFromCombos(uri) // Combos are mutually distinct
this.byCombo[combo].push([res.pred, res.obj.uri])
debug.log(`ACL: setting access to ${subject} by ${res.pred}: ${res.obj}`)
}
private removeAgentFromCombos (uri: string): void {
for (let k = 0; k < 16; k++) {
const combos = this.byCombo[kToCombo(k)]
if (combos) {
for (let i = 0; i < combos.length; i++) {
while (i < combos.length && combos[i][1] === uri) {
combos.splice(i, 1)
}
}
}
}
}
}
function kToCombo (k: number): string {
const y = ['Read', 'Append', 'Write', 'Control']
const combo: string[] = []
for (let i = 0; i < 4; i++) {
if (k & (1 << i)) {
combo.push('http://www.w3.org/ns/auth/acl#' + y[i])
}
}
combo.sort()
return combo.join('\n')
}
function ktToList (k: number): string {
let list = ''
const y = ['Read', 'Append', 'Write', 'Control']
for (let i = 0; i < 4; i++) {
if (k & (1 << i)) {
list += y[i]
}
}
return list
}
function findAgent (uri, kb): PartialAgentTriple | null {
const obj = sym(uri)
const types = kb.findTypeURIs(obj)
for (const ty in types) {
debug.log(' drop object type includes: ' + ty)
}
// An Origin URI is one like https://fred.github.io eith no trailing slash
if (uri.startsWith('http') && uri.split('/').length === 3) {
// there is no third slash
return { pred: 'origin', obj: obj } // The only way to know an origin alas
}
// @@ This is an almighty kludge needed because drag and drop adds extra slashes to origins
if (
uri.startsWith('http') &&
uri.split('/').length === 4 &&
uri.endsWith('/')
) {
// there IS third slash
debug.log('Assuming final slash on dragged origin URI was unintended!')
return { pred: 'origin', obj: sym(uri.slice(0, -1)) } // Fix a URI where the drag and drop system has added a spurious slash
}
if (ns.vcard('WebID').uri in types) return { pred: 'agent', obj: obj }
if (ns.vcard('Group').uri in types) {
return { pred: 'agentGroup', obj: obj } // @@ note vcard membership not RDFs
}
if (
obj.sameTerm(ns.foaf('Agent')) ||
obj.sameTerm(ns.acl('AuthenticatedAgent')) || // AuthenticatedAgent
obj.sameTerm(ns.rdf('Resource')) ||
obj.sameTerm(ns.owl('Thing'))
) {
return { pred: 'agentClass', obj: obj }
}
if (
ns.vcard('Individual').uri in types ||
ns.foaf('Person').uri in types ||
ns.foaf('Agent').uri in types
) {
const pref = kb.any(obj, ns.foaf('preferredURI'))
if (pref) return { pred: 'agent', obj: sym(pref) }
return { pred: 'agent', obj: obj }
}
if (ns.solid('AppProvider').uri in types) {
return { pred: 'origin', obj: obj }
}
if (ns.solid('AppProviderClass').uri in types) {
return { pred: 'originClass', obj: obj }
}
debug.log(' Triage fails for ' + uri)
return null
} | the_stack |
import {
Component, Input, OnChanges, ViewChild, ElementRef, SimpleChanges, OnInit
} from '@angular/core';
import * as d3 from 'd3';
import {
DayPercentage
} from 'app/entities/desktop/desktop.model';
export interface MarginObject {
top: number;
bottom: number;
right: number;
left: number;
}
@Component({
selector: 'app-simple-line-graph',
templateUrl: './simple-line-graph.component.html',
styleUrls: ['./simple-line-graph.component.scss']
})
export class SimpleLineGraphComponent implements OnChanges, OnInit {
constructor(
private chart: ElementRef
) { }
@ViewChild('svg', { static: true }) svg: ElementRef;
@Input() data: DayPercentage[] = [];
@Input() width = 900;
@Input() height = 156; // we want a 116px height on the ticks, this minus margins
private locked: string = null; // store a reference to the element being activated
private transitionDuration = 500; // transition speed
get margin(): MarginObject {
return { right: 20, left: 20, top: 20, bottom: 20 };
}
//////// X AXIS ITEMS ////////
// maps all of our x data points
get xData(): number[] {
return this.data.map(d => d.daysAgo);
}
// determines how wide the graph should be to hold our data
// in its respective area;
get rangeX(): [number, number] {
const min = this.margin.left;
const max = this.width - this.margin.right;
return [max, min]; // we want to plot our data backwards, so we reverse [min, max]
}
// determines the min and max values of the x axis
get domainX(): [number, number] {
const min = Math.min(...this.xData);
const max = Math.max(...this.xData);
return [min, max];
}
get xScale(): d3.Scale.TimeScale {
return d3.scaleTime()
.range(this.rangeX)
.domain(this.domainX);
}
//////// Y AXIS ITEMS ////////
get rangeY(): [number, number] {
const min = this.margin.top;
const max = this.height - this.margin.bottom;
return [max, min];
}
get domainY(): [number, number] {
const min = 0;
const max = 100; // since this based on a percentage we are doing 0 to 100;
return [min, max];
}
get yScale(): d3.Scale.LinearScale {
return d3.scaleLinear()
.range(this.rangeY)
.domain(this.domainY);
}
//////// SELECTIONS ////////
get containerSelection(): d3.Selection<HTMLElement> {
return d3.select('app-simple-line-graph');
}
get labelContainerSelection(): d3.Selection<HTMLElement> {
return d3.select('.label-container');
}
get svgSelection(): d3.Selection<SVGElement> {
return d3.select(this.svg.nativeElement);
}
get axisYSelection(): d3.Selection<SVGElement> {
return this.svgSelection.select('.y-axis');
}
// returns a function that when passed our data, will return an svg path as a string
get createPath(): d3.Path {
return d3.line()
.x(d => this.xScale(d.daysAgo))
.y(d => this.yScale(d.percentage));
}
get viewBox(): string {
return `0 0 ${this.width} ${this.height}`;
}
ngOnInit(): void {
if (this.data && this.data.length > 0) {
this.renderChart();
}
}
ngOnChanges(changes: SimpleChanges) {
if (changes.data && !changes.data.firstChange) {
this.renderChart();
}
}
////////////////// RENDER FUNCTIONS ////////////////////
private renderChart(): void {
this.AllUnlockDeactivate();
this.resizeChart();
this.renderGrid();
this.renderLine();
this.renderPoints();
this.renderTooltips();
this.renderRings();
this.renderLabelButtons();
this.relock();
// reset the standard transition speed to 500 since it could be zero
this.transitionDuration = 500;
}
private renderLine(): void {
// create the line using path function
const line: d3.Geo.Path = this.createPath(this.data);
const theLine = this.svgSelection.selectAll('.line').data([this.data], d => d.daysAgo);
theLine.exit().remove();
theLine.enter().append('path').attr('class', 'line').merge(theLine)
.transition().duration(this.transitionDuration)
.attr('d', line);
}
private renderPoints(): void {
const points = this.svgSelection.selectAll('circle.point')
.data(this.data, d => d.daysAgo);
points.exit().remove();
points.enter().append('circle')
.attr('class', (_d, i) => `point elem-${i}`)
.merge(points)
.transition().duration(this.transitionDuration)
.attr('percent', (d => d.percentage))
.attr('cx', d => this.xScale(d.daysAgo))
.attr('cy', d => this.yScale(d.percentage))
.attr('r', 4);
}
private renderRings(): void {
const rings = this.svgSelection.selectAll('circle.ring')
.data(this.data, d => d.daysAgo);
rings.exit().remove();
rings.enter().append('circle')
.attr('class', (_d, i) => `ring elem-${i}`)
.merge(rings)
.transition().duration(this.transitionDuration)
.attr('cx', d => this.xScale(d.daysAgo))
.attr('cy', d => this.yScale(d.percentage))
.attr('r', 10);
}
private renderTooltips(): void {
// these numbers are specific to its container
const localWidth = this.width - this.margin.right - this.margin.left - 34;
const thisRange = [localWidth, -this.margin.right];
const thisScale: d3.Scale.LinearScale = d3.scaleLinear()
.domain(this.domainX)
.range(thisRange);
const tooltips = this.containerSelection.selectAll('div.graph-tooltip')
.data(this.data, d => d.daysAgo);
tooltips.exit().remove();
tooltips.enter().append('div')
.attr('class', (_d, i: number) => `graph-tooltip elem-${i}`)
.merge(tooltips)
.text(d => `Checked in ${Math.round(d.percentage)}%`)
.style('left', (d, i: number) => {
const left = thisScale(d.daysAgo);
if (i === 0) { return `${localWidth + this.margin.right}px`; }
return `${left}px`;
})
.style('top', d => `${this.yScale(d.percentage) - 10}px`);
}
private renderLabelButtons(): void {
// these numbers are specific to its container
const thisRange = [this.width - 48, 53];
const thisScale: d3.Scale.LinearScale = d3.scaleLinear()
.domain(this.domainX)
.range(thisRange);
const labels = this.labelContainerSelection.selectAll('.graph-button')
.data(this.data, d => d.daysAgo);
labels.exit().remove();
labels.enter().append('button')
.call(parent => {
parent.append('div')
.attr('class', (_d, i: number) => `inner elem-${i}`);
})
.attr('class', (_d, i: number) => `graph-button elem-${i}`)
.merge(labels)
.transition().duration(this.transitionDuration)
.style('left', d => {
if (this.xData.length > 7) {
return `${this.xScale(d.daysAgo) - 30}px`;
} else {
return `${thisScale(d.daysAgo) - 30}px`;
}
})
.call(parent => {
parent.select('.inner')
.text(p => this.formatLabels(p.daysAgo));
});
// add all listeners
this.containerSelection.selectAll('.graph-button')
// add class to rotate labels when more than comfortable to fit in space
.classed('turnt', () => this.xData.length > 7)
.on('mouseenter', e => this.handleHover(e))
.on('mouseout', () => this.AllDeactivate())
// focus styles
.on('focus', e => this.handleHover(e))
.on('focusout', () => this.AllDeactivate())
.on('click', e => this.handleClick(e));
}
private formatLabels(daysAgo: number): string {
switch (daysAgo) {
case 0:
return '24 hrs ago';
break;
default:
return `${daysAgo + 1} days ago`;
}
}
private renderGrid(): void {
// create the X axis grid lines
const xGrid = d3.axisTop()
.ticks(this.data.length)
.tickFormat('')
.tickSize(this.height - (this.margin.bottom + this.margin.top))
.tickSizeOuter(0)
.scale(this.xScale);
// Render the X grid lines
const grid = this.svgSelection.selectAll('.grid').data([this.data]);
grid.exit().remove();
grid.enter().append('g').attr('class', 'grid')
.attr('transform', `translate(0, ${this.height - this.margin.bottom})`)
.merge(grid).transition().duration(this.transitionDuration)
.call(xGrid);
// create the Y axis
const yAxis = d3.axisRight(this.yScale).tickFormat(d => d + '%').ticks(1);
// render the Y axis
const y = this.svgSelection.selectAll('.y-axis').data([this.data]);
y.exit().remove();
y.enter().append('g').attr('class', 'y-axis')
.attr('transform', `translate(${this.margin.left}, 0)`)
.merge(y).transition().duration(this.transitionDuration)
.call(yAxis);
// create the X axis
const xAxis = d3.axisBottom().ticks(this.data.length)
.tickSizeInner(10).tickSizeOuter(0).tickFormat('')
.scale(this.xScale);
// render the X axis
const x = this.svgSelection.selectAll('.x-axis').data([this.data]);
x.exit().remove();
x.enter().append('g').attr('class', 'x-axis')
.attr('transform', `translate(0, ${this.height - this.margin.bottom})`)
.merge(x).transition().duration(this.transitionDuration)
.call(xAxis);
// remove zero from bottom of chart on X axis
this.svgSelection.selectAll('.tick')
.filter(tick => tick === 0)
.remove();
}
private handleHover(e: MouseEvent): void {
const num = this.getHoveredElement(e);
d3.selectAll(`.elem-${num}`).classed('active', true);
}
private handleClick(e: MouseEvent): void {
const num = this.getHoveredElement(e);
const isAlreadyLocked = d3.selectAll(`.elem-${num}`).classed('lock');
if (isAlreadyLocked) {
d3.selectAll(`.elem-${num}`).classed('lock', false);
this.locked = null;
} else {
d3.selectAll('.lock').classed('lock', false);
d3.selectAll(`.elem-${num}`).classed('lock', true);
this.locked = num;
}
}
private getHoveredElement(e: MouseEvent): string {
const classes = d3.select(e.target).attr('class');
const match = classes.match(/elem-([0-9]{1,2})/g)[0];
const num = match.split('-')[1];
return num;
}
private relock(): void {
if (this.locked) {
d3.selectAll(`.elem-${this.locked}`).classed('lock', true);
}
}
private AllDeactivate(): void {
d3.selectAll('.active').classed('active', false);
}
private allUnlock(): void {
d3.selectAll('.lock').classed('lock', false);
}
private AllUnlockDeactivate(): void {
this.allUnlock();
this.AllDeactivate();
}
onResize(): void {
this.transitionDuration = 0; // turn off transitions for resize events;
this.renderChart();
}
private resizeChart(): void {
this.width = this.chart.nativeElement.getBoundingClientRect().width;
}
} | the_stack |
import {TypedSopNode} from './_Base';
import {
AttribClassMenuEntries,
AttribTypeMenuEntries,
AttribClass,
AttribType,
ATTRIBUTE_CLASSES,
ATTRIBUTE_TYPES,
} from '../../../core/geometry/Constant';
import {CoreAttribute} from '../../../core/geometry/Attribute';
import {CoreObject} from '../../../core/geometry/Object';
import {CoreGroup} from '../../../core/geometry/Group';
import {TypeAssert} from '../../poly/Assert';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {PolyDictionary} from '../../../types/GlobalTypes';
import {Vector2} from 'three/src/math/Vector2';
import {Vector3} from 'three/src/math/Vector3';
import {Vector4} from 'three/src/math/Vector4';
type VectorComponent = 'x' | 'y' | 'z' | 'w';
const COMPONENT_NAMES: Array<VectorComponent> = ['x', 'y', 'z', 'w'];
type ValueArrayByName = PolyDictionary<number[]>;
import {AttribCreateSopOperation} from '../../operations/sop/AttribCreate';
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
const DEFAULT = AttribCreateSopOperation.DEFAULT_PARAMS;
class AttribCreateSopParamsConfig extends NodeParamsConfig {
/** @param the group this applies to */
group = ParamConfig.STRING(DEFAULT.group);
/** @param the attribute class (geometry or object) */
class = ParamConfig.INTEGER(DEFAULT.class, {
menu: {
entries: AttribClassMenuEntries,
},
});
/** @param the attribute type (numeric or string) */
type = ParamConfig.INTEGER(DEFAULT.type, {
menu: {
entries: AttribTypeMenuEntries,
},
});
/** @param the attribute name */
name = ParamConfig.STRING(DEFAULT.name);
/** @param the attribute size (1 for float, 2 for vector2, 3 for vector3, 4 for vector4) */
size = ParamConfig.INTEGER(DEFAULT.size, {
range: [1, 4],
rangeLocked: [true, true],
visibleIf: {type: AttribType.NUMERIC},
});
/** @param the value for a float attribute */
value1 = ParamConfig.FLOAT(DEFAULT.value1, {
visibleIf: {type: AttribType.NUMERIC, size: 1},
expression: {forEntities: true},
});
/** @param the value for a vector2 */
value2 = ParamConfig.VECTOR2(DEFAULT.value2, {
visibleIf: {type: AttribType.NUMERIC, size: 2},
expression: {forEntities: true},
});
/** @param the value for a vector3 */
value3 = ParamConfig.VECTOR3(DEFAULT.value3, {
visibleIf: {type: AttribType.NUMERIC, size: 3},
expression: {forEntities: true},
});
/** @param the value for a vector4 */
value4 = ParamConfig.VECTOR4(DEFAULT.value4, {
visibleIf: {type: AttribType.NUMERIC, size: 4},
expression: {forEntities: true},
});
/** @param the value for a string attribute */
string = ParamConfig.STRING(DEFAULT.string, {
visibleIf: {type: AttribType.STRING},
expression: {forEntities: true},
});
}
const ParamsConfig = new AttribCreateSopParamsConfig();
export class AttribCreateSopNode extends TypedSopNode<AttribCreateSopParamsConfig> {
paramsConfig = ParamsConfig;
static type() {
return 'attribCreate';
}
private _x_arrays_by_geometry_uuid: ValueArrayByName = {};
private _y_arrays_by_geometry_uuid: ValueArrayByName = {};
private _z_arrays_by_geometry_uuid: ValueArrayByName = {};
private _w_arrays_by_geometry_uuid: ValueArrayByName = {};
initializeNode() {
this.io.inputs.setCount(1);
this.io.inputs.initInputsClonedState(AttribCreateSopOperation.INPUT_CLONED_STATE);
this.scene().dispatchController.onAddListener(() => {
this.params.onParamsCreated('params_label', () => {
this.params.label.init([this.p.name]);
});
});
}
private _operation: AttribCreateSopOperation | undefined;
cook(input_contents: CoreGroup[]) {
// cannot yet convert to an operation, as expressions may be used in this node
// but we can still use one when no expression is required
if (this._is_using_expression()) {
if (this.pv.name && this.pv.name.trim() != '') {
this._add_attribute(ATTRIBUTE_CLASSES[this.pv.class], input_contents[0]);
} else {
this.states.error.set('attribute name is not valid');
}
} else {
this._operation = this._operation || new AttribCreateSopOperation(this.scene(), this.states);
const core_group = this._operation.cook(input_contents, this.pv);
this.setCoreGroup(core_group);
}
}
private async _add_attribute(attrib_class: AttribClass, core_group: CoreGroup) {
const attrib_type = ATTRIBUTE_TYPES[this.pv.type];
switch (attrib_class) {
case AttribClass.VERTEX:
await this.add_point_attribute(attrib_type, core_group);
return this.setCoreGroup(core_group);
case AttribClass.OBJECT:
await this.add_object_attribute(attrib_type, core_group);
return this.setCoreGroup(core_group);
}
TypeAssert.unreachable(attrib_class);
}
async add_point_attribute(attrib_type: AttribType, core_group: CoreGroup) {
const core_objects = core_group.coreObjects();
switch (attrib_type) {
case AttribType.NUMERIC: {
for (let i = 0; i < core_objects.length; i++) {
await this.add_numeric_attribute_to_points(core_objects[i]);
}
return;
}
case AttribType.STRING: {
for (let i = 0; i < core_objects.length; i++) {
await this.add_string_attribute_to_points(core_objects[i]);
}
return;
}
}
TypeAssert.unreachable(attrib_type);
}
async add_object_attribute(attrib_type: AttribType, core_group: CoreGroup) {
const core_objects = core_group.coreObjectsFromGroup(this.pv.group);
switch (attrib_type) {
case AttribType.NUMERIC:
await this.add_numeric_attribute_to_object(core_objects);
return;
case AttribType.STRING:
await this.add_string_attribute_to_object(core_objects);
return;
}
TypeAssert.unreachable(attrib_type);
}
async add_numeric_attribute_to_points(core_object: CoreObject) {
const core_geometry = core_object.coreGeometry();
if (!core_geometry) {
return;
}
const points = core_object.pointsFromGroup(this.pv.group);
const param = [this.p.value1, this.p.value2, this.p.value3, this.p.value4][this.pv.size - 1];
if (param.hasExpression()) {
if (!core_geometry.hasAttrib(this.pv.name)) {
core_geometry.addNumericAttrib(this.pv.name, this.pv.size, param.value);
}
const geometry = core_geometry.geometry();
const array = geometry.getAttribute(this.pv.name).array as number[];
if (this.pv.size == 1) {
if (this.p.value1.expressionController) {
await this.p.value1.expressionController.compute_expression_for_points(points, (point, value) => {
array[point.index() * this.pv.size + 0] = value;
});
}
} else {
const vparam = [this.p.value2, this.p.value3, this.p.value4][this.pv.size - 2];
let params = vparam.components;
const tmp_arrays = new Array(params.length);
let component_param;
const arrays_by_geometry_uuid = [
this._x_arrays_by_geometry_uuid,
this._y_arrays_by_geometry_uuid,
this._z_arrays_by_geometry_uuid,
this._w_arrays_by_geometry_uuid,
];
for (let i = 0; i < params.length; i++) {
component_param = params[i];
if (component_param.hasExpression() && component_param.expressionController) {
tmp_arrays[i] = this._init_array_if_required(
geometry,
arrays_by_geometry_uuid[i],
points.length
);
await component_param.expressionController.compute_expression_for_points(
points,
(point, value) => {
// array[point.index()*this.pv.size+i] = value
tmp_arrays[i][point.index()] = value;
}
);
} else {
const value = component_param.value;
for (let point of points) {
array[point.index() * this.pv.size + i] = value;
}
}
}
// commit the tmp values
for (let j = 0; j < tmp_arrays.length; j++) {
const tmp_array = tmp_arrays[j];
if (tmp_array) {
for (let i = 0; i < tmp_array.length; i++) {
array[i * this.pv.size + j] = tmp_array[i];
}
}
}
}
} else {
// no need to do work here, as this will be done in the operation
}
}
async add_numeric_attribute_to_object(core_objects: CoreObject[]) {
const param = [this.p.value1, this.p.value2, this.p.value3, this.p.value4][this.pv.size - 1];
if (param.hasExpression()) {
if (this.pv.size == 1) {
if (this.p.value1.expressionController) {
await this.p.value1.expressionController.compute_expression_for_objects(
core_objects,
(core_object, value) => {
core_object.setAttribValue(this.pv.name, value);
}
);
}
} else {
const vparam = [this.p.value2, this.p.value3, this.p.value4][this.pv.size - 2];
let params = vparam.components;
let values_by_core_object_index: PolyDictionary<Vector2 | Vector3 | Vector4> = {};
// for (let component_param of params) {
// values.push(component_param.value);
// }
const init_vector = this._vector_by_attrib_size(this.pv.size);
if (init_vector) {
for (let core_object of core_objects) {
values_by_core_object_index[core_object.index()] = init_vector;
}
for (let component_index = 0; component_index < params.length; component_index++) {
const component_param = params[component_index];
const component_name = COMPONENT_NAMES[component_index];
if (component_param.hasExpression() && component_param.expressionController) {
await component_param.expressionController.compute_expression_for_objects(
core_objects,
(core_object, value) => {
const vector = values_by_core_object_index[core_object.index()] as Vector4;
vector[component_name] = value;
}
);
} else {
for (let core_object of core_objects) {
const vector = values_by_core_object_index[core_object.index()] as Vector4;
vector[component_name] = component_param.value;
}
}
}
for (let i = 0; i < core_objects.length; i++) {
const core_object = core_objects[i];
const value = values_by_core_object_index[core_object.index()];
core_object.setAttribValue(this.pv.name, value);
}
}
}
} else {
// no need to do work here, as this will be done in the operation
}
}
private _vector_by_attrib_size(size: number) {
switch (size) {
case 2:
return new Vector2(0, 0);
case 3:
return new Vector3(0, 0, 0);
case 4:
return new Vector4(0, 0, 0, 0);
}
}
// private _convert_object_numeric_value(value: Vector4) {
// let converted_value;
// switch (this.pv.size) {
// case 1: {
// converted_value = value.x;
// break;
// }
// case 2: {
// converted_value = new Vector2(value.x, value.y);
// break;
// }
// case 3: {
// converted_value = new Vector3(value.x, value.y, value.z);
// break;
// }
// case 4: {
// converted_value = new Vector4(value.x, value.y, value.z, value.w);
// break;
// }
// }
// return converted_value;
// }
async add_string_attribute_to_points(core_object: CoreObject) {
const points = core_object.pointsFromGroup(this.pv.group);
const param = this.p.string;
const string_values: string[] = new Array(points.length);
if (param.hasExpression() && param.expressionController) {
await param.expressionController.compute_expression_for_points(points, (point, value) => {
string_values[point.index()] = value;
});
} else {
// no need to do work here, as this will be done in the operation
}
const index_data = CoreAttribute.arrayToIndexedArrays(string_values);
const geometry = core_object.coreGeometry();
if (geometry) {
geometry.setIndexedAttribute(this.pv.name, index_data['values'], index_data['indices']);
}
}
async add_string_attribute_to_object(core_objects: CoreObject[]) {
const param = this.p.string;
if (param.hasExpression() && param.expressionController) {
await param.expressionController.compute_expression_for_objects(core_objects, (core_object, value) => {
core_object.setAttribValue(this.pv.name, value);
});
} else {
// no need to do work here, as this will be done in the operation
}
// this.context().set_entity(object);
// const core_object = new CoreObject(object);
// this.param('string').eval(val => {
// core_object.addAttribute(this.pv.name, val);
// });
}
private _init_array_if_required(
geometry: BufferGeometry,
arrays_by_geometry_uuid: ValueArrayByName,
points_count: number
) {
const uuid = geometry.uuid;
const current_array = arrays_by_geometry_uuid[uuid];
if (current_array) {
// only create new array if we need more point, or as soon as the length is different?
if (current_array.length < points_count) {
arrays_by_geometry_uuid[uuid] = new Array(points_count);
}
} else {
arrays_by_geometry_uuid[uuid] = new Array(points_count);
}
return arrays_by_geometry_uuid[uuid];
}
//
//
// CHECK IF EXPRESSION IS BEING USED, TO ALLOW EASY SWITCH TO OPERATION
//
//
private _is_using_expression(): boolean {
const attrib_type = ATTRIBUTE_TYPES[this.pv.type];
switch (attrib_type) {
case AttribType.NUMERIC:
const param = [this.p.value1, this.p.value2, this.p.value3, this.p.value4][this.pv.size - 1];
return param.hasExpression();
case AttribType.STRING:
return this.p.string.hasExpression();
}
}
//
//
// API UTILS
//
//
setType(type: AttribType) {
this.p.type.set(ATTRIBUTE_TYPES.indexOf(type));
}
} | the_stack |
import * as React from 'react';
import PropTypes from 'prop-types';
import { isEqual, find } from 'lodash';
import ReactSelect, { components as Components, createFilter } from 'react-select';
import CreatableSelect from 'react-select/creatable';
import Icon from './Icon';
export const CONTROL_CLASS = 'common-select-control';
type Option = { [key: string]: any };
const MultiValueRemove = (props) => (
<Components.MultiValueRemove {...props} />
);
const IndicatorSeparator = () => null;
const DropdownIndicator = (props) => {
const {
/* eslint-disable react/prop-types */
children = <Icon name="caret-down" />,
getStyles,
innerProps: { ref, ...restInnerProps },
/* eslint-enable react/prop-types */
} = props;
return (
<div style={getStyles('dropdownIndicator', props)}
ref={ref}
{...restInnerProps}>
{children}
</div>
);
};
const Control = (props) => (
<Components.Control {...props} className={CONTROL_CLASS} />
);
type CustomOptionProps = {
data: any,
};
/* eslint-disable react/prop-types */
const CustomOption = (optionRenderer: (Option) => React.ReactElement) => (
(props: CustomOptionProps): React.ReactElement => {
const { data, ...rest } = props;
return (
<Components.Option {...rest}>
{optionRenderer(data)}
</Components.Option>
);
}
);
const CustomSingleValue = (valueRenderer: (option: Option) => React.ReactElement) => (
({ data, ...rest }) => <Components.SingleValue {...rest}>{valueRenderer(data)}</Components.SingleValue>
);
/* eslint-enable react/prop-types */
const CustomInput = (inputProps: { [key: string]: any }) => (
(props) => <Components.Input {...props} {...inputProps} />
);
const dropdownIndicator = (base, state) => ({
...base,
padding: '0px',
fontSize: '150%',
marginRight: '1rem',
transform: state.selectProps.menuIsOpen && 'rotate(180deg)',
});
const clearIndicator = base => ({
...base,
padding: '5px',
});
const multiValue = base => ({
...base,
backgroundColor: '#ebf5ff',
color: '#007eff',
border: `1px solid rgba(0,126,255,.24)`,
});
const multiValueLabel = base => ({
...base,
color: 'unset',
padding: '2px 5px',
fontSize: '14px',
});
const multiValueRemove = base => ({
...base,
borderLeft: `1px solid rgba(0,126,255,.24)`,
paddingLeft: '5px',
paddingRight: '5px',
borderRadius: '0',
':hover': {
backgroundColor: 'rgba(0,113,230,.08)',
},
});
const controlSmall = {
minHeight: '30px',
height: '30px',
};
const controlNormal = {
minHeight: '34px',
};
const menu = base => ({
...base,
zIndex: 5,
color: '#007eff',
border: '1px solid rgba(102, 175, 233, 0.5)',
boxShadow: '0 0 4px rgba(102, 175, 233, 0.3)',
});
const menuPortal = base => ({
...base,
zIndex: 'auto',
});
const singleValueAndPlaceholder = base => ({
...base,
lineHeight: '28px',
fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif',
fontSize: '14px',
fontWeight: 400,
color: '#666',
});
const placeholder = base => ({
...base,
lineHeight: '28px',
fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif',
fontSize: '14px',
fontWeight: 400,
color: '#999',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
overflow: 'hidden',
maxWidth: '100%',
paddingRight: '20px',
});
const controlFocus = ({ size }) => (base, { isFocused }) => {
const borderColor = isFocused ? '#66afe9' : base.borderColor;
const borderWidth = isFocused ? 1 : base.borderWidth;
const outline = isFocused ? 0 : base.outline;
const boxShadow = isFocused ? 'inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, 0.6)' : 'inset 0 1px 1px rgba(0, 0, 0, 0.075)';
const controlSize = size === 'small' ? controlSmall : controlNormal;
return {
...base,
...controlSize,
borderColor,
borderWidth,
boxShadow,
outline,
alignItems: 'center',
};
};
const valueContainer = base => ({
...base,
padding: '2px 12px',
});
type OverriddenComponents = {
DropdownIndicator: React.ComponentType<any>;
MultiValueRemove: React.ComponentType<any>;
IndicatorSeparator: React.ComponentType<any>;
Control: React.ComponentType<any>;
};
const _components: OverriddenComponents = {
DropdownIndicator,
MultiValueRemove,
IndicatorSeparator,
Control,
};
const _styles = props => ({
dropdownIndicator,
clearIndicator,
multiValue,
multiValueLabel,
multiValueRemove,
menu,
menuPortal,
singleValue: singleValueAndPlaceholder,
placeholder,
control: controlFocus(props),
valueContainer,
});
type ComponentsProp = {
MultiValueLabel?: React.ComponentType<any>,
SelectContainer?: React.ComponentType<any>,
};
type Props = {
addLabelText?: string,
allowCreate?: boolean,
autoFocus?: boolean,
clearable?: boolean,
components?: ComponentsProp | null | undefined,
delimiter?: string,
disabled?: boolean,
displayKey: string,
id?: string,
ignoreAccents?: boolean,
inputId?: string,
inputProps?: { [key: string]: any },
matchProp?: 'any' | 'label' | 'value',
multi?: boolean,
menuPortalTarget?: HTMLElement,
name?: string,
onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void,
onChange: (string) => void,
onReactSelectChange?: (option: Option | Option[]) => void,
optionRenderer?: (option: Option) => React.ReactElement,
options: Array<Option>,
placeholder: string,
ref?: React.Ref<React.ComponentType>,
size?: 'normal' | 'small',
value?: Object | Array<Object> | null | undefined,
valueKey: string,
valueRenderer?: (option: Option) => React.ReactElement,
};
type CustomComponents = {
Input?: React.ComponentType<any>,
Option?: React.ComponentType<any>,
SingleValue?: React.ComponentType<any>,
};
type State = {
customComponents: CustomComponents,
value: any,
};
class Select extends React.Component<Props, State> {
static propTypes = {
/** Specifies if the user can create new entries in `multi` Selects. */
allowCreate: PropTypes.bool,
/** Indicates if the Select value is clearable or not. */
clearable: PropTypes.bool,
/**
* A collection of custom `react-select` components from https://react-select.com/components
*/
components: PropTypes.objectOf(PropTypes.elementType),
/** Delimiter to use as value separator in `multi` Selects. */
delimiter: PropTypes.string,
/** Indicates whether the Select component is disabled or not. */
disabled: PropTypes.bool,
/** Indicates which option object key contains the text to display in the select input. Same as react-select's `labelKey` prop. */
displayKey: PropTypes.string,
/** ID of Select container component */
id: PropTypes.string,
/** ID of underlying input */
inputId: PropTypes.string,
/** Indicates whether the auto-completion should return results including accents/diacritics when searching for their non-accent counterpart */
ignoreAccents: PropTypes.bool,
/**
* @deprecated Use `inputId` or custom components with the `components` prop instead.
* Custom attributes for the input (inside the Select).
*/
inputProps: PropTypes.object,
/** Indicates which option property to filter on. */
matchProp: PropTypes.oneOf(['any', 'label', 'value']),
/** Specifies if multiple values can be selected or not. */
multi: PropTypes.bool,
/** name attribute for Select element */
name: PropTypes.string,
/** Callback when select has lost focus */
onBlur: PropTypes.func,
/**
* Callback when selected option changes. It receives the value of the
* selected option as an argument. If `multi` is enabled, the passed
* argument will be a string separated by `delimiter` with all selected
* options.
*/
onChange: PropTypes.func.isRequired,
/**
* Available options shown in the select field. It should be an array of objects,
* each one with a display key (specified in `displayKey`), and a value key
* (specified in `valueKey`).
* Options including an optional `disabled: true` key-value pair, will be disabled in the Select component.
*/
options: PropTypes.array.isRequired,
/** Custom function to render the options in the menu. */
optionRenderer: PropTypes.func,
/** Size of the select input. */
size: PropTypes.oneOf(['normal', 'small']),
/**
* Value which can be the selected option or the value of the selected option.
* If `multi` is enabled, it must be a string containing all values separated by the `delimiter`.
*/
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
PropTypes.arrayOf(PropTypes.object),
]),
/** Indicates which option object key contains the value of the option. */
valueKey: PropTypes.string,
/** Custom function to render the selected option in the Select. */
valueRenderer: PropTypes.func,
/** Label text for add button */
addLabelText: PropTypes.string,
/** Automatically Focus on Select */
autoFocus: PropTypes.bool,
/** special onChange handler */
onReactSelectChange: PropTypes.func,
/** Select placeholder text */
placeholder: PropTypes.string,
/** Placement of the menu: "top", "bottom", "auto" */
menuPlacement: PropTypes.oneOf(['top', 'bottom', 'auto']),
/** Max height of the menu */
maxMenuHeight: PropTypes.number,
}
static defaultProps = {
addLabelText: undefined,
allowCreate: false,
autoFocus: false,
clearable: true,
components: null,
delimiter: ',',
disabled: false,
displayKey: 'label',
id: undefined,
ignoreAccents: true,
inputId: undefined,
onBlur: undefined,
inputProps: undefined,
matchProp: 'any',
multi: false,
name: undefined,
onReactSelectChange: undefined,
optionRenderer: undefined,
placeholder: undefined,
size: 'normal',
value: undefined,
valueKey: 'value',
valueRenderer: undefined,
menuPlacement: 'bottom',
maxMenuHeight: 300,
};
constructor(props: Props) {
super(props);
const { inputProps, optionRenderer, value, valueRenderer } = props;
this.state = {
customComponents: this.getCustomComponents(inputProps, optionRenderer, valueRenderer),
value,
};
}
UNSAFE_componentWillReceiveProps = (nextProps: Props) => {
const { inputProps, optionRenderer, value, valueRenderer } = this.props;
if (value !== nextProps.value) {
this.setState({ value: nextProps.value });
}
if (!isEqual(inputProps, nextProps.inputProps)
|| optionRenderer !== nextProps.optionRenderer
|| valueRenderer !== nextProps.valueRenderer) {
this.setState({ customComponents: this.getCustomComponents(inputProps, optionRenderer, valueRenderer) });
}
};
getCustomComponents = (inputProps?: { [key: string]: any }, optionRenderer?: (option: Option) => React.ReactElement,
valueRenderer?: (option: Option) => React.ReactElement): any => {
const customComponents: { [key: string]: any } = {};
if (inputProps) {
customComponents.Input = CustomInput(inputProps);
}
if (optionRenderer) {
customComponents.Option = CustomOption(optionRenderer);
}
if (valueRenderer) {
customComponents.SingleValue = CustomSingleValue(valueRenderer);
}
return customComponents;
};
getValue = () => {
const { value } = this.state;
return value;
};
clearValue = () => {
this.setState({ value: undefined });
};
_extractOptionValue = (option: Option) => {
const { multi, valueKey, delimiter } = this.props;
if (option) {
return multi ? option.map((i) => i[valueKey]).join(delimiter) : option[valueKey || ''];
}
return '';
};
_onChange = (selectedOption: Option) => {
const value = this._extractOptionValue(selectedOption);
this.setState({ value: value });
// eslint-disable-next-line @typescript-eslint/no-empty-function
const { onChange = () => {} } = this.props;
onChange(value);
};
// Using ReactSelect.Creatable now needs to get values as objects or they are not display
// This method takes care of formatting a string value into options react-select supports.
_formatInputValue = (value: string): Array<Option> => {
const { options, displayKey, valueKey, delimiter } = this.props;
return value.split(delimiter).map((v: string) => {
const predicate: Option = {
[valueKey]: v,
[displayKey]: v,
};
const option = find(options, predicate);
return option || predicate;
});
};
createCustomFilter = (stringify: (any) => string) => {
const { matchProp, ignoreAccents } = this.props;
const options = { ignoreAccents };
return matchProp === 'any' ? createFilter(options) : createFilter({ ...options, stringify });
};
render() {
const {
allowCreate = false,
delimiter,
displayKey,
components,
options,
valueKey,
onReactSelectChange,
} = this.props;
const { customComponents, value } = this.state;
const SelectComponent = allowCreate ? CreatableSelect : ReactSelect;
let formattedValue = value;
if (formattedValue && allowCreate) {
formattedValue = this._formatInputValue(value);
} else {
formattedValue = (typeof value === 'string'
? (value ?? '').split(delimiter)
: [value])
.map((v) => options.find((option) => option[valueKey || ''] === v));
}
const {
multi: isMulti,
disabled: isDisabled,
clearable: isClearable,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
inputProps, // Do not pass down prop
matchProp,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
optionRenderer, // Do not pass down prop
// eslint-disable-next-line @typescript-eslint/no-unused-vars
valueRenderer, // Do not pass down prop
menuPortalTarget,
...rest
} = this.props;
const stringify = (option) => option[matchProp];
const customFilter = this.createCustomFilter(stringify);
const mergedComponents = {
..._components,
...components,
...customComponents,
};
return (
<SelectComponent {...rest}
onChange={onReactSelectChange || this._onChange}
isMulti={isMulti}
isDisabled={isDisabled}
isClearable={isClearable}
getOptionLabel={(option) => option[displayKey] || option.label}
getOptionValue={(option) => option[valueKey]}
filterOption={customFilter}
components={mergedComponents}
menuPortalTarget={menuPortalTarget}
isOptionDisabled={(option) => !!option.disabled}
/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */
// @ts-ignore TODO: Fix props assignment for _styles
styles={_styles(this.props)}
value={formattedValue} />
);
}
}
export default Select; | the_stack |
import { Component, ElementRef, NgZone, Input, OnDestroy, ChangeDetectionStrategy, Inject, ViewChild } from '@angular/core';
import { normalizePassiveListenerOptions } from '@angular/cdk/platform';
import { Style, WithStyles, StyleRenderer, lyl } from '@alyle/ui';
import { STYLES, LyImageCropper } from './image-cropper';
import { DOCUMENT } from '@angular/common';
const activeEventOptions = normalizePassiveListenerOptions({passive: false});
const pos = (100 * Math.sqrt(2) - 100) / 2 / Math.sqrt(2);
/**
* @dynamic
*/
@Component({
selector: 'ly-cropper-area',
templateUrl: './image-cropper-area.html',
providers: [
StyleRenderer
],
changeDetection: ChangeDetectionStrategy.OnPush,
exportAs: 'lyCropperArea'
})
export class LyCropperArea implements WithStyles, OnDestroy {
readonly classes = this.sRenderer.renderSheet(STYLES, 'area');
private _isSliding: boolean;
/** Keeps track of the last pointer event that was captured by the crop area. */
private _lastPointerEvent: MouseEvent | TouchEvent | null;
private _startPointerEvent: {
x: number
y: number
} | null;
private _currentWidth: number;
private _currentHeight: number;
private _startAreaRect: DOMRect;
private _startImgRect: DOMRect;
/** Used to subscribe to global move and end events */
protected _document: Document;
@ViewChild('resizer') readonly _resizer?: ElementRef;
@Input()
set resizableArea(val: boolean) {
if (val !== this._resizableArea) {
this._resizableArea = val;
Promise.resolve(null).then(() => {
if (val) {
this._removeResizableArea();
this._addResizableArea();
} else {
this._removeResizableArea();
}
});
}
}
get resizableArea() {
return this._resizableArea;
}
private _resizableArea: boolean;
@Input() keepAspectRatio: boolean;
@Input()
@Style<boolean, LyCropperArea>(
(_value, _, { classes: __ }) => ({ after }) => lyl `{
border-radius: 50%
.${__.resizer} {
${after}: ${pos}%
bottom: ${pos}%
transform: translate(4px, 4px)
}
}`
) round: boolean;
constructor(
readonly sRenderer: StyleRenderer,
readonly _elementRef: ElementRef,
private _ngZone: NgZone,
readonly _cropper: LyImageCropper,
@Inject(DOCUMENT) _document: any,
) {
this._document = _document;
}
ngOnDestroy() {
this._removeResizableArea();
}
private _addResizableArea() {
this._ngZone.runOutsideAngular(() => {
const element = this._resizer!.nativeElement;
element.addEventListener('mousedown', this._pointerDown, activeEventOptions);
element.addEventListener('touchstart', this._pointerDown, activeEventOptions);
});
}
private _removeResizableArea() {
const element = this._resizer?.nativeElement;
if (element) {
this._lastPointerEvent = null;
this._removeGlobalEvents();
element.removeEventListener('mousedown', this._pointerDown, activeEventOptions);
element.removeEventListener('touchstart', this._pointerDown, activeEventOptions);
}
}
private _pointerDown = (event: MouseEvent | TouchEvent) => {
// Don't do anything if the
// user is using anything other than the main mouse button.
if (this._isSliding || (!isTouchEvent(event) && event.button !== 0)) {
return;
}
event.preventDefault();
this._ngZone.run(() => {
this._isSliding = true;
this._lastPointerEvent = event;
this._startPointerEvent = getGesturePointFromEvent(event);
this._startAreaRect = this._cropper._areaCropperRect();
this._startImgRect = this._cropper._canvasRect();
event.preventDefault();
this._bindGlobalEvents(event);
});
}
private _pointerMove = (event: MouseEvent | TouchEvent) => {
if (this._isSliding) {
event.preventDefault();
this._lastPointerEvent = event;
const element: HTMLDivElement = this._elementRef.nativeElement;
const { width, height, minWidth, minHeight } = this._cropper.config;
const point = getGesturePointFromEvent(event);
const deltaX = point.x - this._startPointerEvent!.x;
const deltaY = point.y - this._startPointerEvent!.y;
const startAreaRect = this._startAreaRect;
const startImgRect = this._startImgRect;
const round = this.round;
const keepAspectRatio = this._cropper.config.keepAspectRatio || event.shiftKey;
let newWidth = 0;
let newHeight = 0;
const rootRect = this._cropper._rootRect();
if (round) {
// The distance from the center of the cropper area to the pointer
const originX = ((width / 2 / Math.sqrt(2)) + deltaX);
const originY = ((height / 2 / Math.sqrt(2)) + deltaY);
// Leg
const side = Math.sqrt(originX ** 2 + originY ** 2);
newWidth = newHeight = side * 2;
} else if (keepAspectRatio) {
newWidth = width + deltaX * 2;
newHeight = height + deltaY * 2;
if (width !== height) {
if (width > height) {
newHeight = height / (width / newWidth);
} else if (height > width) {
newWidth = width / (height / newHeight);
}
} else {
newWidth = newHeight = Math.max(newWidth, newHeight);
}
} else {
newWidth = width + deltaX * 2;
newHeight = height + deltaY * 2;
}
// To min width
if (newWidth < minWidth!) {
newWidth = minWidth!;
}
// To min height
if (newHeight < minHeight!) {
newHeight = minHeight!;
}
// Do not overflow the cropper area
const centerX = startAreaRect.x + startAreaRect.width / 2;
const centerY = startAreaRect.y + startAreaRect.height / 2;
const topOverflow = startImgRect.y > centerY - (newHeight / 2);
const bottomOverflow = centerY + (newHeight / 2) > startImgRect.bottom;
const minHeightOnOverflow = Math.min((centerY - startImgRect.y) * 2, (startImgRect.bottom - centerY) * 2);
const leftOverflow = startImgRect.x > centerX - (newWidth / 2);
const rightOverflow = centerX + (newWidth / 2) > startImgRect.right;
const minWidthOnOverflow = Math.min((centerX - startImgRect.x) * 2, (startImgRect.right - centerX) * 2);
const minOnOverflow = Math.min(minWidthOnOverflow, minHeightOnOverflow);
if (round) {
if (topOverflow || bottomOverflow || leftOverflow || rightOverflow) {
newHeight = newWidth = minOnOverflow;
}
} else if (keepAspectRatio) {
const newNewWidth: number[] = [];
const newNewHeight: number[] = [];
if ((topOverflow || bottomOverflow)) {
newHeight = minHeightOnOverflow;
newNewHeight.push(newHeight);
newWidth = width / (height / minHeightOnOverflow);
newNewWidth.push(newWidth);
}
if ((leftOverflow || rightOverflow)) {
newWidth = minWidthOnOverflow;
newNewWidth.push(newWidth);
newHeight = height / (width / minWidthOnOverflow);
newNewHeight.push(newHeight);
}
if (newNewWidth.length === 2) {
newWidth = Math.min(...newNewWidth);
}
if (newNewHeight.length === 2) {
newHeight = Math.min(...newNewHeight);
}
} else {
if (topOverflow || bottomOverflow) {
newHeight = minHeightOnOverflow;
}
if (leftOverflow || rightOverflow) {
newWidth = minWidthOnOverflow;
}
}
// Do not overflow the container
if (round) {
const min = Math.min(rootRect.width, rootRect.height);
if (newWidth > min) {
newWidth = newHeight = min;
} else if (newHeight > min) {
newWidth = newHeight = min;
}
} else if (keepAspectRatio) {
if (newWidth > rootRect.width) {
newWidth = rootRect.width;
newHeight = height / (width / rootRect.width);
}
if (newHeight > rootRect.height) {
newWidth = width / (height / rootRect.height);
newHeight = rootRect.height;
}
} else {
if (newWidth > rootRect.width) {
newWidth = rootRect.width;
}
if (newHeight > rootRect.height) {
newHeight = rootRect.height;
}
}
// round values
newWidth = Math.round(newWidth);
newHeight = Math.round(newHeight);
element.style.width = `${newWidth}px`;
element.style.height = `${newHeight}px`;
this._currentWidth = newWidth;
this._currentHeight = newHeight;
}
}
/** Called when the user has lifted their pointer. */
private _pointerUp = (event: TouchEvent | MouseEvent) => {
if (this._isSliding) {
event.preventDefault();
this._removeGlobalEvents();
this._cropper._primaryAreaWidth = this._cropper.config.width = this._currentWidth;
this._cropper._primaryAreaHeight = this._cropper.config.height = this._currentHeight;
this._cropper.config = this._cropper.config;
this._cropper._updateMinScale();
this._isSliding = false;
this._startPointerEvent = null;
}
}
/** Called when the window has lost focus. */
private _windowBlur = () => {
// If the window is blurred while dragging we need to stop dragging because the
// browser won't dispatch the `mouseup` and `touchend` events anymore.
if (this._lastPointerEvent) {
this._pointerUp(this._lastPointerEvent);
}
}
private _bindGlobalEvents(triggerEvent: TouchEvent | MouseEvent) {
const element = this._document;
const isTouch = isTouchEvent(triggerEvent);
const moveEventName = isTouch ? 'touchmove' : 'mousemove';
const endEventName = isTouch ? 'touchend' : 'mouseup';
element.addEventListener(moveEventName, this._pointerMove, activeEventOptions);
element.addEventListener(endEventName, this._pointerUp, activeEventOptions);
if (isTouch) {
element.addEventListener('touchcancel', this._pointerUp, activeEventOptions);
}
const window = this._getWindow();
if (typeof window !== 'undefined' && window) {
window.addEventListener('blur', this._windowBlur);
}
}
/** Removes any global event listeners that we may have added. */
private _removeGlobalEvents() {
const element = this._document;
element.removeEventListener('mousemove', this._pointerMove, activeEventOptions);
element.removeEventListener('mouseup', this._pointerUp, activeEventOptions);
element.removeEventListener('touchmove', this._pointerMove, activeEventOptions);
element.removeEventListener('touchend', this._pointerUp, activeEventOptions);
element.removeEventListener('touchcancel', this._pointerUp, activeEventOptions);
const window = this._getWindow();
if (typeof window !== 'undefined' && window) {
window.removeEventListener('blur', this._windowBlur);
}
}
/** Use defaultView of injected document if available or fallback to global window reference */
private _getWindow(): Window {
return this._document.defaultView || window;
}
}
function getGesturePointFromEvent(event: TouchEvent | MouseEvent) {
// `touches` will be empty for start/end events so we have to fall back to `changedTouches`.
const point = isTouchEvent(event)
? (event.touches[0] || event.changedTouches[0])
: event;
return {
x: point.clientX,
y: point.clientY
};
}
/** Returns whether an event is a touch event. */
function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent {
return event.type[0] === 't';
} | the_stack |
type ErrorWithCode = Error & { code: number };
type MaybeErrorWithCode = ErrorWithCode | null | undefined;
const createErrorFromCodeLookup: Map<number, () => ErrorWithCode> = new Map();
const createErrorFromNameLookup: Map<string, () => ErrorWithCode> = new Map();
/**
* InstructionUnpackError: 'Failed to unpack instruction data'
*
* @category Errors
* @category generated
*/
export class InstructionUnpackErrorError extends Error {
readonly code: number = 0x0;
readonly name: string = 'InstructionUnpackError';
constructor() {
super('Failed to unpack instruction data');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InstructionUnpackErrorError);
}
}
}
createErrorFromCodeLookup.set(0x0, () => new InstructionUnpackErrorError());
createErrorFromNameLookup.set('InstructionUnpackError', () => new InstructionUnpackErrorError());
/**
* InstructionPackError: 'Failed to pack instruction data'
*
* @category Errors
* @category generated
*/
export class InstructionPackErrorError extends Error {
readonly code: number = 0x1;
readonly name: string = 'InstructionPackError';
constructor() {
super('Failed to pack instruction data');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InstructionPackErrorError);
}
}
}
createErrorFromCodeLookup.set(0x1, () => new InstructionPackErrorError());
createErrorFromNameLookup.set('InstructionPackError', () => new InstructionPackErrorError());
/**
* NotRentExempt: 'Lamport balance below rent-exempt threshold'
*
* @category Errors
* @category generated
*/
export class NotRentExemptError extends Error {
readonly code: number = 0x2;
readonly name: string = 'NotRentExempt';
constructor() {
super('Lamport balance below rent-exempt threshold');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotRentExemptError);
}
}
}
createErrorFromCodeLookup.set(0x2, () => new NotRentExemptError());
createErrorFromNameLookup.set('NotRentExempt', () => new NotRentExemptError());
/**
* AlreadyInitialized: 'Already initialized'
*
* @category Errors
* @category generated
*/
export class AlreadyInitializedError extends Error {
readonly code: number = 0x3;
readonly name: string = 'AlreadyInitialized';
constructor() {
super('Already initialized');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, AlreadyInitializedError);
}
}
}
createErrorFromCodeLookup.set(0x3, () => new AlreadyInitializedError());
createErrorFromNameLookup.set('AlreadyInitialized', () => new AlreadyInitializedError());
/**
* Uninitialized: 'Uninitialized'
*
* @category Errors
* @category generated
*/
export class UninitializedError extends Error {
readonly code: number = 0x4;
readonly name: string = 'Uninitialized';
constructor() {
super('Uninitialized');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UninitializedError);
}
}
}
createErrorFromCodeLookup.set(0x4, () => new UninitializedError());
createErrorFromNameLookup.set('Uninitialized', () => new UninitializedError());
/**
* InvalidMetadataKey: ' Metadata's key must match seed of ['metadata', program id, mint] provided'
*
* @category Errors
* @category generated
*/
export class InvalidMetadataKeyError extends Error {
readonly code: number = 0x5;
readonly name: string = 'InvalidMetadataKey';
constructor() {
super(" Metadata's key must match seed of ['metadata', program id, mint] provided");
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidMetadataKeyError);
}
}
}
createErrorFromCodeLookup.set(0x5, () => new InvalidMetadataKeyError());
createErrorFromNameLookup.set('InvalidMetadataKey', () => new InvalidMetadataKeyError());
/**
* InvalidEditionKey: 'Edition's key must match seed of ['metadata', program id, name, 'edition'] provided'
*
* @category Errors
* @category generated
*/
export class InvalidEditionKeyError extends Error {
readonly code: number = 0x6;
readonly name: string = 'InvalidEditionKey';
constructor() {
super("Edition's key must match seed of ['metadata', program id, name, 'edition'] provided");
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidEditionKeyError);
}
}
}
createErrorFromCodeLookup.set(0x6, () => new InvalidEditionKeyError());
createErrorFromNameLookup.set('InvalidEditionKey', () => new InvalidEditionKeyError());
/**
* UpdateAuthorityIncorrect: 'Update Authority given does not match'
*
* @category Errors
* @category generated
*/
export class UpdateAuthorityIncorrectError extends Error {
readonly code: number = 0x7;
readonly name: string = 'UpdateAuthorityIncorrect';
constructor() {
super('Update Authority given does not match');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UpdateAuthorityIncorrectError);
}
}
}
createErrorFromCodeLookup.set(0x7, () => new UpdateAuthorityIncorrectError());
createErrorFromNameLookup.set(
'UpdateAuthorityIncorrect',
() => new UpdateAuthorityIncorrectError(),
);
/**
* UpdateAuthorityIsNotSigner: 'Update Authority needs to be signer to update metadata'
*
* @category Errors
* @category generated
*/
export class UpdateAuthorityIsNotSignerError extends Error {
readonly code: number = 0x8;
readonly name: string = 'UpdateAuthorityIsNotSigner';
constructor() {
super('Update Authority needs to be signer to update metadata');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UpdateAuthorityIsNotSignerError);
}
}
}
createErrorFromCodeLookup.set(0x8, () => new UpdateAuthorityIsNotSignerError());
createErrorFromNameLookup.set(
'UpdateAuthorityIsNotSigner',
() => new UpdateAuthorityIsNotSignerError(),
);
/**
* NotMintAuthority: 'You must be the mint authority and signer on this transaction'
*
* @category Errors
* @category generated
*/
export class NotMintAuthorityError extends Error {
readonly code: number = 0x9;
readonly name: string = 'NotMintAuthority';
constructor() {
super('You must be the mint authority and signer on this transaction');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotMintAuthorityError);
}
}
}
createErrorFromCodeLookup.set(0x9, () => new NotMintAuthorityError());
createErrorFromNameLookup.set('NotMintAuthority', () => new NotMintAuthorityError());
/**
* InvalidMintAuthority: 'Mint authority provided does not match the authority on the mint'
*
* @category Errors
* @category generated
*/
export class InvalidMintAuthorityError extends Error {
readonly code: number = 0xa;
readonly name: string = 'InvalidMintAuthority';
constructor() {
super('Mint authority provided does not match the authority on the mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidMintAuthorityError);
}
}
}
createErrorFromCodeLookup.set(0xa, () => new InvalidMintAuthorityError());
createErrorFromNameLookup.set('InvalidMintAuthority', () => new InvalidMintAuthorityError());
/**
* NameTooLong: 'Name too long'
*
* @category Errors
* @category generated
*/
export class NameTooLongError extends Error {
readonly code: number = 0xb;
readonly name: string = 'NameTooLong';
constructor() {
super('Name too long');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NameTooLongError);
}
}
}
createErrorFromCodeLookup.set(0xb, () => new NameTooLongError());
createErrorFromNameLookup.set('NameTooLong', () => new NameTooLongError());
/**
* SymbolTooLong: 'Symbol too long'
*
* @category Errors
* @category generated
*/
export class SymbolTooLongError extends Error {
readonly code: number = 0xc;
readonly name: string = 'SymbolTooLong';
constructor() {
super('Symbol too long');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SymbolTooLongError);
}
}
}
createErrorFromCodeLookup.set(0xc, () => new SymbolTooLongError());
createErrorFromNameLookup.set('SymbolTooLong', () => new SymbolTooLongError());
/**
* UriTooLong: 'URI too long'
*
* @category Errors
* @category generated
*/
export class UriTooLongError extends Error {
readonly code: number = 0xd;
readonly name: string = 'UriTooLong';
constructor() {
super('URI too long');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UriTooLongError);
}
}
}
createErrorFromCodeLookup.set(0xd, () => new UriTooLongError());
createErrorFromNameLookup.set('UriTooLong', () => new UriTooLongError());
/**
* UpdateAuthorityMustBeEqualToMetadataAuthorityAndSigner: 'Update authority must be equivalent to the metadata's authority and also signer of this transaction'
*
* @category Errors
* @category generated
*/
export class UpdateAuthorityMustBeEqualToMetadataAuthorityAndSignerError extends Error {
readonly code: number = 0xe;
readonly name: string = 'UpdateAuthorityMustBeEqualToMetadataAuthorityAndSigner';
constructor() {
super(
"Update authority must be equivalent to the metadata's authority and also signer of this transaction",
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UpdateAuthorityMustBeEqualToMetadataAuthorityAndSignerError);
}
}
}
createErrorFromCodeLookup.set(
0xe,
() => new UpdateAuthorityMustBeEqualToMetadataAuthorityAndSignerError(),
);
createErrorFromNameLookup.set(
'UpdateAuthorityMustBeEqualToMetadataAuthorityAndSigner',
() => new UpdateAuthorityMustBeEqualToMetadataAuthorityAndSignerError(),
);
/**
* MintMismatch: 'Mint given does not match mint on Metadata'
*
* @category Errors
* @category generated
*/
export class MintMismatchError extends Error {
readonly code: number = 0xf;
readonly name: string = 'MintMismatch';
constructor() {
super('Mint given does not match mint on Metadata');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MintMismatchError);
}
}
}
createErrorFromCodeLookup.set(0xf, () => new MintMismatchError());
createErrorFromNameLookup.set('MintMismatch', () => new MintMismatchError());
/**
* EditionsMustHaveExactlyOneToken: 'Editions must have exactly one token'
*
* @category Errors
* @category generated
*/
export class EditionsMustHaveExactlyOneTokenError extends Error {
readonly code: number = 0x10;
readonly name: string = 'EditionsMustHaveExactlyOneToken';
constructor() {
super('Editions must have exactly one token');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, EditionsMustHaveExactlyOneTokenError);
}
}
}
createErrorFromCodeLookup.set(0x10, () => new EditionsMustHaveExactlyOneTokenError());
createErrorFromNameLookup.set(
'EditionsMustHaveExactlyOneToken',
() => new EditionsMustHaveExactlyOneTokenError(),
);
/**
* MaxEditionsMintedAlready: 'Maximum editions printed already'
*
* @category Errors
* @category generated
*/
export class MaxEditionsMintedAlreadyError extends Error {
readonly code: number = 0x11;
readonly name: string = 'MaxEditionsMintedAlready';
constructor() {
super('Maximum editions printed already');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MaxEditionsMintedAlreadyError);
}
}
}
createErrorFromCodeLookup.set(0x11, () => new MaxEditionsMintedAlreadyError());
createErrorFromNameLookup.set(
'MaxEditionsMintedAlready',
() => new MaxEditionsMintedAlreadyError(),
);
/**
* TokenMintToFailed: 'Token mint to failed'
*
* @category Errors
* @category generated
*/
export class TokenMintToFailedError extends Error {
readonly code: number = 0x12;
readonly name: string = 'TokenMintToFailed';
constructor() {
super('Token mint to failed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenMintToFailedError);
}
}
}
createErrorFromCodeLookup.set(0x12, () => new TokenMintToFailedError());
createErrorFromNameLookup.set('TokenMintToFailed', () => new TokenMintToFailedError());
/**
* MasterRecordMismatch: 'The master edition record passed must match the master record on the edition given'
*
* @category Errors
* @category generated
*/
export class MasterRecordMismatchError extends Error {
readonly code: number = 0x13;
readonly name: string = 'MasterRecordMismatch';
constructor() {
super('The master edition record passed must match the master record on the edition given');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MasterRecordMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x13, () => new MasterRecordMismatchError());
createErrorFromNameLookup.set('MasterRecordMismatch', () => new MasterRecordMismatchError());
/**
* DestinationMintMismatch: 'The destination account does not have the right mint'
*
* @category Errors
* @category generated
*/
export class DestinationMintMismatchError extends Error {
readonly code: number = 0x14;
readonly name: string = 'DestinationMintMismatch';
constructor() {
super('The destination account does not have the right mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DestinationMintMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x14, () => new DestinationMintMismatchError());
createErrorFromNameLookup.set('DestinationMintMismatch', () => new DestinationMintMismatchError());
/**
* EditionAlreadyMinted: 'An edition can only mint one of its kind!'
*
* @category Errors
* @category generated
*/
export class EditionAlreadyMintedError extends Error {
readonly code: number = 0x15;
readonly name: string = 'EditionAlreadyMinted';
constructor() {
super('An edition can only mint one of its kind!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, EditionAlreadyMintedError);
}
}
}
createErrorFromCodeLookup.set(0x15, () => new EditionAlreadyMintedError());
createErrorFromNameLookup.set('EditionAlreadyMinted', () => new EditionAlreadyMintedError());
/**
* PrintingMintDecimalsShouldBeZero: 'Printing mint decimals should be zero'
*
* @category Errors
* @category generated
*/
export class PrintingMintDecimalsShouldBeZeroError extends Error {
readonly code: number = 0x16;
readonly name: string = 'PrintingMintDecimalsShouldBeZero';
constructor() {
super('Printing mint decimals should be zero');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrintingMintDecimalsShouldBeZeroError);
}
}
}
createErrorFromCodeLookup.set(0x16, () => new PrintingMintDecimalsShouldBeZeroError());
createErrorFromNameLookup.set(
'PrintingMintDecimalsShouldBeZero',
() => new PrintingMintDecimalsShouldBeZeroError(),
);
/**
* OneTimePrintingAuthorizationMintDecimalsShouldBeZero: 'OneTimePrintingAuthorization mint decimals should be zero'
*
* @category Errors
* @category generated
*/
export class OneTimePrintingAuthorizationMintDecimalsShouldBeZeroError extends Error {
readonly code: number = 0x17;
readonly name: string = 'OneTimePrintingAuthorizationMintDecimalsShouldBeZero';
constructor() {
super('OneTimePrintingAuthorization mint decimals should be zero');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, OneTimePrintingAuthorizationMintDecimalsShouldBeZeroError);
}
}
}
createErrorFromCodeLookup.set(
0x17,
() => new OneTimePrintingAuthorizationMintDecimalsShouldBeZeroError(),
);
createErrorFromNameLookup.set(
'OneTimePrintingAuthorizationMintDecimalsShouldBeZero',
() => new OneTimePrintingAuthorizationMintDecimalsShouldBeZeroError(),
);
/**
* EditionMintDecimalsShouldBeZero: 'EditionMintDecimalsShouldBeZero'
*
* @category Errors
* @category generated
*/
export class EditionMintDecimalsShouldBeZeroError extends Error {
readonly code: number = 0x18;
readonly name: string = 'EditionMintDecimalsShouldBeZero';
constructor() {
super('EditionMintDecimalsShouldBeZero');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, EditionMintDecimalsShouldBeZeroError);
}
}
}
createErrorFromCodeLookup.set(0x18, () => new EditionMintDecimalsShouldBeZeroError());
createErrorFromNameLookup.set(
'EditionMintDecimalsShouldBeZero',
() => new EditionMintDecimalsShouldBeZeroError(),
);
/**
* TokenBurnFailed: 'Token burn failed'
*
* @category Errors
* @category generated
*/
export class TokenBurnFailedError extends Error {
readonly code: number = 0x19;
readonly name: string = 'TokenBurnFailed';
constructor() {
super('Token burn failed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenBurnFailedError);
}
}
}
createErrorFromCodeLookup.set(0x19, () => new TokenBurnFailedError());
createErrorFromNameLookup.set('TokenBurnFailed', () => new TokenBurnFailedError());
/**
* TokenAccountOneTimeAuthMintMismatch: 'The One Time authorization mint does not match that on the token account!'
*
* @category Errors
* @category generated
*/
export class TokenAccountOneTimeAuthMintMismatchError extends Error {
readonly code: number = 0x1a;
readonly name: string = 'TokenAccountOneTimeAuthMintMismatch';
constructor() {
super('The One Time authorization mint does not match that on the token account!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenAccountOneTimeAuthMintMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x1a, () => new TokenAccountOneTimeAuthMintMismatchError());
createErrorFromNameLookup.set(
'TokenAccountOneTimeAuthMintMismatch',
() => new TokenAccountOneTimeAuthMintMismatchError(),
);
/**
* DerivedKeyInvalid: 'Derived key invalid'
*
* @category Errors
* @category generated
*/
export class DerivedKeyInvalidError extends Error {
readonly code: number = 0x1b;
readonly name: string = 'DerivedKeyInvalid';
constructor() {
super('Derived key invalid');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DerivedKeyInvalidError);
}
}
}
createErrorFromCodeLookup.set(0x1b, () => new DerivedKeyInvalidError());
createErrorFromNameLookup.set('DerivedKeyInvalid', () => new DerivedKeyInvalidError());
/**
* PrintingMintMismatch: 'The Printing mint does not match that on the master edition!'
*
* @category Errors
* @category generated
*/
export class PrintingMintMismatchError extends Error {
readonly code: number = 0x1c;
readonly name: string = 'PrintingMintMismatch';
constructor() {
super('The Printing mint does not match that on the master edition!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrintingMintMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x1c, () => new PrintingMintMismatchError());
createErrorFromNameLookup.set('PrintingMintMismatch', () => new PrintingMintMismatchError());
/**
* OneTimePrintingAuthMintMismatch: 'The One Time Printing Auth mint does not match that on the master edition!'
*
* @category Errors
* @category generated
*/
export class OneTimePrintingAuthMintMismatchError extends Error {
readonly code: number = 0x1d;
readonly name: string = 'OneTimePrintingAuthMintMismatch';
constructor() {
super('The One Time Printing Auth mint does not match that on the master edition!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, OneTimePrintingAuthMintMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x1d, () => new OneTimePrintingAuthMintMismatchError());
createErrorFromNameLookup.set(
'OneTimePrintingAuthMintMismatch',
() => new OneTimePrintingAuthMintMismatchError(),
);
/**
* TokenAccountMintMismatch: 'The mint of the token account does not match the Printing mint!'
*
* @category Errors
* @category generated
*/
export class TokenAccountMintMismatchError extends Error {
readonly code: number = 0x1e;
readonly name: string = 'TokenAccountMintMismatch';
constructor() {
super('The mint of the token account does not match the Printing mint!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenAccountMintMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x1e, () => new TokenAccountMintMismatchError());
createErrorFromNameLookup.set(
'TokenAccountMintMismatch',
() => new TokenAccountMintMismatchError(),
);
/**
* TokenAccountMintMismatchV2: 'The mint of the token account does not match the master metadata mint!'
*
* @category Errors
* @category generated
*/
export class TokenAccountMintMismatchV2Error extends Error {
readonly code: number = 0x1f;
readonly name: string = 'TokenAccountMintMismatchV2';
constructor() {
super('The mint of the token account does not match the master metadata mint!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenAccountMintMismatchV2Error);
}
}
}
createErrorFromCodeLookup.set(0x1f, () => new TokenAccountMintMismatchV2Error());
createErrorFromNameLookup.set(
'TokenAccountMintMismatchV2',
() => new TokenAccountMintMismatchV2Error(),
);
/**
* NotEnoughTokens: 'Not enough tokens to mint a limited edition'
*
* @category Errors
* @category generated
*/
export class NotEnoughTokensError extends Error {
readonly code: number = 0x20;
readonly name: string = 'NotEnoughTokens';
constructor() {
super('Not enough tokens to mint a limited edition');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotEnoughTokensError);
}
}
}
createErrorFromCodeLookup.set(0x20, () => new NotEnoughTokensError());
createErrorFromNameLookup.set('NotEnoughTokens', () => new NotEnoughTokensError());
/**
* PrintingMintAuthorizationAccountMismatch: 'The mint on your authorization token holding account does not match your Printing mint!'
*
* @category Errors
* @category generated
*/
export class PrintingMintAuthorizationAccountMismatchError extends Error {
readonly code: number = 0x21;
readonly name: string = 'PrintingMintAuthorizationAccountMismatch';
constructor() {
super(
'The mint on your authorization token holding account does not match your Printing mint!',
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrintingMintAuthorizationAccountMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x21, () => new PrintingMintAuthorizationAccountMismatchError());
createErrorFromNameLookup.set(
'PrintingMintAuthorizationAccountMismatch',
() => new PrintingMintAuthorizationAccountMismatchError(),
);
/**
* AuthorizationTokenAccountOwnerMismatch: 'The authorization token account has a different owner than the update authority for the master edition!'
*
* @category Errors
* @category generated
*/
export class AuthorizationTokenAccountOwnerMismatchError extends Error {
readonly code: number = 0x22;
readonly name: string = 'AuthorizationTokenAccountOwnerMismatch';
constructor() {
super(
'The authorization token account has a different owner than the update authority for the master edition!',
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, AuthorizationTokenAccountOwnerMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x22, () => new AuthorizationTokenAccountOwnerMismatchError());
createErrorFromNameLookup.set(
'AuthorizationTokenAccountOwnerMismatch',
() => new AuthorizationTokenAccountOwnerMismatchError(),
);
/**
* Disabled: 'This feature is currently disabled.'
*
* @category Errors
* @category generated
*/
export class DisabledError extends Error {
readonly code: number = 0x23;
readonly name: string = 'Disabled';
constructor() {
super('This feature is currently disabled.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DisabledError);
}
}
}
createErrorFromCodeLookup.set(0x23, () => new DisabledError());
createErrorFromNameLookup.set('Disabled', () => new DisabledError());
/**
* CreatorsTooLong: 'Creators list too long'
*
* @category Errors
* @category generated
*/
export class CreatorsTooLongError extends Error {
readonly code: number = 0x24;
readonly name: string = 'CreatorsTooLong';
constructor() {
super('Creators list too long');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CreatorsTooLongError);
}
}
}
createErrorFromCodeLookup.set(0x24, () => new CreatorsTooLongError());
createErrorFromNameLookup.set('CreatorsTooLong', () => new CreatorsTooLongError());
/**
* CreatorsMustBeAtleastOne: 'Creators must be at least one if set'
*
* @category Errors
* @category generated
*/
export class CreatorsMustBeAtleastOneError extends Error {
readonly code: number = 0x25;
readonly name: string = 'CreatorsMustBeAtleastOne';
constructor() {
super('Creators must be at least one if set');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CreatorsMustBeAtleastOneError);
}
}
}
createErrorFromCodeLookup.set(0x25, () => new CreatorsMustBeAtleastOneError());
createErrorFromNameLookup.set(
'CreatorsMustBeAtleastOne',
() => new CreatorsMustBeAtleastOneError(),
);
/**
* MustBeOneOfCreators: 'If using a creators array, you must be one of the creators listed'
*
* @category Errors
* @category generated
*/
export class MustBeOneOfCreatorsError extends Error {
readonly code: number = 0x26;
readonly name: string = 'MustBeOneOfCreators';
constructor() {
super('If using a creators array, you must be one of the creators listed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MustBeOneOfCreatorsError);
}
}
}
createErrorFromCodeLookup.set(0x26, () => new MustBeOneOfCreatorsError());
createErrorFromNameLookup.set('MustBeOneOfCreators', () => new MustBeOneOfCreatorsError());
/**
* NoCreatorsPresentOnMetadata: 'This metadata does not have creators'
*
* @category Errors
* @category generated
*/
export class NoCreatorsPresentOnMetadataError extends Error {
readonly code: number = 0x27;
readonly name: string = 'NoCreatorsPresentOnMetadata';
constructor() {
super('This metadata does not have creators');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NoCreatorsPresentOnMetadataError);
}
}
}
createErrorFromCodeLookup.set(0x27, () => new NoCreatorsPresentOnMetadataError());
createErrorFromNameLookup.set(
'NoCreatorsPresentOnMetadata',
() => new NoCreatorsPresentOnMetadataError(),
);
/**
* CreatorNotFound: 'This creator address was not found'
*
* @category Errors
* @category generated
*/
export class CreatorNotFoundError extends Error {
readonly code: number = 0x28;
readonly name: string = 'CreatorNotFound';
constructor() {
super('This creator address was not found');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CreatorNotFoundError);
}
}
}
createErrorFromCodeLookup.set(0x28, () => new CreatorNotFoundError());
createErrorFromNameLookup.set('CreatorNotFound', () => new CreatorNotFoundError());
/**
* InvalidBasisPoints: 'Basis points cannot be more than 10000'
*
* @category Errors
* @category generated
*/
export class InvalidBasisPointsError extends Error {
readonly code: number = 0x29;
readonly name: string = 'InvalidBasisPoints';
constructor() {
super('Basis points cannot be more than 10000');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidBasisPointsError);
}
}
}
createErrorFromCodeLookup.set(0x29, () => new InvalidBasisPointsError());
createErrorFromNameLookup.set('InvalidBasisPoints', () => new InvalidBasisPointsError());
/**
* PrimarySaleCanOnlyBeFlippedToTrue: 'Primary sale can only be flipped to true and is immutable'
*
* @category Errors
* @category generated
*/
export class PrimarySaleCanOnlyBeFlippedToTrueError extends Error {
readonly code: number = 0x2a;
readonly name: string = 'PrimarySaleCanOnlyBeFlippedToTrue';
constructor() {
super('Primary sale can only be flipped to true and is immutable');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrimarySaleCanOnlyBeFlippedToTrueError);
}
}
}
createErrorFromCodeLookup.set(0x2a, () => new PrimarySaleCanOnlyBeFlippedToTrueError());
createErrorFromNameLookup.set(
'PrimarySaleCanOnlyBeFlippedToTrue',
() => new PrimarySaleCanOnlyBeFlippedToTrueError(),
);
/**
* OwnerMismatch: 'Owner does not match that on the account given'
*
* @category Errors
* @category generated
*/
export class OwnerMismatchError extends Error {
readonly code: number = 0x2b;
readonly name: string = 'OwnerMismatch';
constructor() {
super('Owner does not match that on the account given');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, OwnerMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x2b, () => new OwnerMismatchError());
createErrorFromNameLookup.set('OwnerMismatch', () => new OwnerMismatchError());
/**
* NoBalanceInAccountForAuthorization: 'This account has no tokens to be used for authorization'
*
* @category Errors
* @category generated
*/
export class NoBalanceInAccountForAuthorizationError extends Error {
readonly code: number = 0x2c;
readonly name: string = 'NoBalanceInAccountForAuthorization';
constructor() {
super('This account has no tokens to be used for authorization');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NoBalanceInAccountForAuthorizationError);
}
}
}
createErrorFromCodeLookup.set(0x2c, () => new NoBalanceInAccountForAuthorizationError());
createErrorFromNameLookup.set(
'NoBalanceInAccountForAuthorization',
() => new NoBalanceInAccountForAuthorizationError(),
);
/**
* ShareTotalMustBe100: 'Share total must equal 100 for creator array'
*
* @category Errors
* @category generated
*/
export class ShareTotalMustBe100Error extends Error {
readonly code: number = 0x2d;
readonly name: string = 'ShareTotalMustBe100';
constructor() {
super('Share total must equal 100 for creator array');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ShareTotalMustBe100Error);
}
}
}
createErrorFromCodeLookup.set(0x2d, () => new ShareTotalMustBe100Error());
createErrorFromNameLookup.set('ShareTotalMustBe100', () => new ShareTotalMustBe100Error());
/**
* ReservationExists: 'This reservation list already exists!'
*
* @category Errors
* @category generated
*/
export class ReservationExistsError extends Error {
readonly code: number = 0x2e;
readonly name: string = 'ReservationExists';
constructor() {
super('This reservation list already exists!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationExistsError);
}
}
}
createErrorFromCodeLookup.set(0x2e, () => new ReservationExistsError());
createErrorFromNameLookup.set('ReservationExists', () => new ReservationExistsError());
/**
* ReservationDoesNotExist: 'This reservation list does not exist!'
*
* @category Errors
* @category generated
*/
export class ReservationDoesNotExistError extends Error {
readonly code: number = 0x2f;
readonly name: string = 'ReservationDoesNotExist';
constructor() {
super('This reservation list does not exist!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationDoesNotExistError);
}
}
}
createErrorFromCodeLookup.set(0x2f, () => new ReservationDoesNotExistError());
createErrorFromNameLookup.set('ReservationDoesNotExist', () => new ReservationDoesNotExistError());
/**
* ReservationNotSet: 'This reservation list exists but was never set with reservations'
*
* @category Errors
* @category generated
*/
export class ReservationNotSetError extends Error {
readonly code: number = 0x30;
readonly name: string = 'ReservationNotSet';
constructor() {
super('This reservation list exists but was never set with reservations');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationNotSetError);
}
}
}
createErrorFromCodeLookup.set(0x30, () => new ReservationNotSetError());
createErrorFromNameLookup.set('ReservationNotSet', () => new ReservationNotSetError());
/**
* ReservationAlreadyMade: 'This reservation list has already been set!'
*
* @category Errors
* @category generated
*/
export class ReservationAlreadyMadeError extends Error {
readonly code: number = 0x31;
readonly name: string = 'ReservationAlreadyMade';
constructor() {
super('This reservation list has already been set!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationAlreadyMadeError);
}
}
}
createErrorFromCodeLookup.set(0x31, () => new ReservationAlreadyMadeError());
createErrorFromNameLookup.set('ReservationAlreadyMade', () => new ReservationAlreadyMadeError());
/**
* BeyondMaxAddressSize: 'Provided more addresses than max allowed in single reservation'
*
* @category Errors
* @category generated
*/
export class BeyondMaxAddressSizeError extends Error {
readonly code: number = 0x32;
readonly name: string = 'BeyondMaxAddressSize';
constructor() {
super('Provided more addresses than max allowed in single reservation');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, BeyondMaxAddressSizeError);
}
}
}
createErrorFromCodeLookup.set(0x32, () => new BeyondMaxAddressSizeError());
createErrorFromNameLookup.set('BeyondMaxAddressSize', () => new BeyondMaxAddressSizeError());
/**
* NumericalOverflowError: 'NumericalOverflowError'
*
* @category Errors
* @category generated
*/
export class NumericalOverflowErrorError extends Error {
readonly code: number = 0x33;
readonly name: string = 'NumericalOverflowError';
constructor() {
super('NumericalOverflowError');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NumericalOverflowErrorError);
}
}
}
createErrorFromCodeLookup.set(0x33, () => new NumericalOverflowErrorError());
createErrorFromNameLookup.set('NumericalOverflowError', () => new NumericalOverflowErrorError());
/**
* ReservationBreachesMaximumSupply: 'This reservation would go beyond the maximum supply of the master edition!'
*
* @category Errors
* @category generated
*/
export class ReservationBreachesMaximumSupplyError extends Error {
readonly code: number = 0x34;
readonly name: string = 'ReservationBreachesMaximumSupply';
constructor() {
super('This reservation would go beyond the maximum supply of the master edition!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationBreachesMaximumSupplyError);
}
}
}
createErrorFromCodeLookup.set(0x34, () => new ReservationBreachesMaximumSupplyError());
createErrorFromNameLookup.set(
'ReservationBreachesMaximumSupply',
() => new ReservationBreachesMaximumSupplyError(),
);
/**
* AddressNotInReservation: 'Address not in reservation!'
*
* @category Errors
* @category generated
*/
export class AddressNotInReservationError extends Error {
readonly code: number = 0x35;
readonly name: string = 'AddressNotInReservation';
constructor() {
super('Address not in reservation!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, AddressNotInReservationError);
}
}
}
createErrorFromCodeLookup.set(0x35, () => new AddressNotInReservationError());
createErrorFromNameLookup.set('AddressNotInReservation', () => new AddressNotInReservationError());
/**
* CannotVerifyAnotherCreator: 'You cannot unilaterally verify another creator, they must sign'
*
* @category Errors
* @category generated
*/
export class CannotVerifyAnotherCreatorError extends Error {
readonly code: number = 0x36;
readonly name: string = 'CannotVerifyAnotherCreator';
constructor() {
super('You cannot unilaterally verify another creator, they must sign');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotVerifyAnotherCreatorError);
}
}
}
createErrorFromCodeLookup.set(0x36, () => new CannotVerifyAnotherCreatorError());
createErrorFromNameLookup.set(
'CannotVerifyAnotherCreator',
() => new CannotVerifyAnotherCreatorError(),
);
/**
* CannotUnverifyAnotherCreator: 'You cannot unilaterally unverify another creator'
*
* @category Errors
* @category generated
*/
export class CannotUnverifyAnotherCreatorError extends Error {
readonly code: number = 0x37;
readonly name: string = 'CannotUnverifyAnotherCreator';
constructor() {
super('You cannot unilaterally unverify another creator');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotUnverifyAnotherCreatorError);
}
}
}
createErrorFromCodeLookup.set(0x37, () => new CannotUnverifyAnotherCreatorError());
createErrorFromNameLookup.set(
'CannotUnverifyAnotherCreator',
() => new CannotUnverifyAnotherCreatorError(),
);
/**
* SpotMismatch: 'In initial reservation setting, spots remaining should equal total spots'
*
* @category Errors
* @category generated
*/
export class SpotMismatchError extends Error {
readonly code: number = 0x38;
readonly name: string = 'SpotMismatch';
constructor() {
super('In initial reservation setting, spots remaining should equal total spots');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SpotMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x38, () => new SpotMismatchError());
createErrorFromNameLookup.set('SpotMismatch', () => new SpotMismatchError());
/**
* IncorrectOwner: 'Incorrect account owner'
*
* @category Errors
* @category generated
*/
export class IncorrectOwnerError extends Error {
readonly code: number = 0x39;
readonly name: string = 'IncorrectOwner';
constructor() {
super('Incorrect account owner');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, IncorrectOwnerError);
}
}
}
createErrorFromCodeLookup.set(0x39, () => new IncorrectOwnerError());
createErrorFromNameLookup.set('IncorrectOwner', () => new IncorrectOwnerError());
/**
* PrintingWouldBreachMaximumSupply: 'printing these tokens would breach the maximum supply limit of the master edition'
*
* @category Errors
* @category generated
*/
export class PrintingWouldBreachMaximumSupplyError extends Error {
readonly code: number = 0x3a;
readonly name: string = 'PrintingWouldBreachMaximumSupply';
constructor() {
super('printing these tokens would breach the maximum supply limit of the master edition');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrintingWouldBreachMaximumSupplyError);
}
}
}
createErrorFromCodeLookup.set(0x3a, () => new PrintingWouldBreachMaximumSupplyError());
createErrorFromNameLookup.set(
'PrintingWouldBreachMaximumSupply',
() => new PrintingWouldBreachMaximumSupplyError(),
);
/**
* DataIsImmutable: 'Data is immutable'
*
* @category Errors
* @category generated
*/
export class DataIsImmutableError extends Error {
readonly code: number = 0x3b;
readonly name: string = 'DataIsImmutable';
constructor() {
super('Data is immutable');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DataIsImmutableError);
}
}
}
createErrorFromCodeLookup.set(0x3b, () => new DataIsImmutableError());
createErrorFromNameLookup.set('DataIsImmutable', () => new DataIsImmutableError());
/**
* DuplicateCreatorAddress: 'No duplicate creator addresses'
*
* @category Errors
* @category generated
*/
export class DuplicateCreatorAddressError extends Error {
readonly code: number = 0x3c;
readonly name: string = 'DuplicateCreatorAddress';
constructor() {
super('No duplicate creator addresses');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DuplicateCreatorAddressError);
}
}
}
createErrorFromCodeLookup.set(0x3c, () => new DuplicateCreatorAddressError());
createErrorFromNameLookup.set('DuplicateCreatorAddress', () => new DuplicateCreatorAddressError());
/**
* ReservationSpotsRemainingShouldMatchTotalSpotsAtStart: 'Reservation spots remaining should match total spots when first being created'
*
* @category Errors
* @category generated
*/
export class ReservationSpotsRemainingShouldMatchTotalSpotsAtStartError extends Error {
readonly code: number = 0x3d;
readonly name: string = 'ReservationSpotsRemainingShouldMatchTotalSpotsAtStart';
constructor() {
super('Reservation spots remaining should match total spots when first being created');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationSpotsRemainingShouldMatchTotalSpotsAtStartError);
}
}
}
createErrorFromCodeLookup.set(
0x3d,
() => new ReservationSpotsRemainingShouldMatchTotalSpotsAtStartError(),
);
createErrorFromNameLookup.set(
'ReservationSpotsRemainingShouldMatchTotalSpotsAtStart',
() => new ReservationSpotsRemainingShouldMatchTotalSpotsAtStartError(),
);
/**
* InvalidTokenProgram: 'Invalid token program'
*
* @category Errors
* @category generated
*/
export class InvalidTokenProgramError extends Error {
readonly code: number = 0x3e;
readonly name: string = 'InvalidTokenProgram';
constructor() {
super('Invalid token program');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidTokenProgramError);
}
}
}
createErrorFromCodeLookup.set(0x3e, () => new InvalidTokenProgramError());
createErrorFromNameLookup.set('InvalidTokenProgram', () => new InvalidTokenProgramError());
/**
* DataTypeMismatch: 'Data type mismatch'
*
* @category Errors
* @category generated
*/
export class DataTypeMismatchError extends Error {
readonly code: number = 0x3f;
readonly name: string = 'DataTypeMismatch';
constructor() {
super('Data type mismatch');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DataTypeMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x3f, () => new DataTypeMismatchError());
createErrorFromNameLookup.set('DataTypeMismatch', () => new DataTypeMismatchError());
/**
* BeyondAlottedAddressSize: 'Beyond alotted address size in reservation!'
*
* @category Errors
* @category generated
*/
export class BeyondAlottedAddressSizeError extends Error {
readonly code: number = 0x40;
readonly name: string = 'BeyondAlottedAddressSize';
constructor() {
super('Beyond alotted address size in reservation!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, BeyondAlottedAddressSizeError);
}
}
}
createErrorFromCodeLookup.set(0x40, () => new BeyondAlottedAddressSizeError());
createErrorFromNameLookup.set(
'BeyondAlottedAddressSize',
() => new BeyondAlottedAddressSizeError(),
);
/**
* ReservationNotComplete: 'The reservation has only been partially alotted'
*
* @category Errors
* @category generated
*/
export class ReservationNotCompleteError extends Error {
readonly code: number = 0x41;
readonly name: string = 'ReservationNotComplete';
constructor() {
super('The reservation has only been partially alotted');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationNotCompleteError);
}
}
}
createErrorFromCodeLookup.set(0x41, () => new ReservationNotCompleteError());
createErrorFromNameLookup.set('ReservationNotComplete', () => new ReservationNotCompleteError());
/**
* TriedToReplaceAnExistingReservation: 'You cannot splice over an existing reservation!'
*
* @category Errors
* @category generated
*/
export class TriedToReplaceAnExistingReservationError extends Error {
readonly code: number = 0x42;
readonly name: string = 'TriedToReplaceAnExistingReservation';
constructor() {
super('You cannot splice over an existing reservation!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TriedToReplaceAnExistingReservationError);
}
}
}
createErrorFromCodeLookup.set(0x42, () => new TriedToReplaceAnExistingReservationError());
createErrorFromNameLookup.set(
'TriedToReplaceAnExistingReservation',
() => new TriedToReplaceAnExistingReservationError(),
);
/**
* InvalidOperation: 'Invalid operation'
*
* @category Errors
* @category generated
*/
export class InvalidOperationError extends Error {
readonly code: number = 0x43;
readonly name: string = 'InvalidOperation';
constructor() {
super('Invalid operation');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidOperationError);
}
}
}
createErrorFromCodeLookup.set(0x43, () => new InvalidOperationError());
createErrorFromNameLookup.set('InvalidOperation', () => new InvalidOperationError());
/**
* InvalidOwner: 'Invalid Owner'
*
* @category Errors
* @category generated
*/
export class InvalidOwnerError extends Error {
readonly code: number = 0x44;
readonly name: string = 'InvalidOwner';
constructor() {
super('Invalid Owner');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidOwnerError);
}
}
}
createErrorFromCodeLookup.set(0x44, () => new InvalidOwnerError());
createErrorFromNameLookup.set('InvalidOwner', () => new InvalidOwnerError());
/**
* PrintingMintSupplyMustBeZeroForConversion: 'Printing mint supply must be zero for conversion'
*
* @category Errors
* @category generated
*/
export class PrintingMintSupplyMustBeZeroForConversionError extends Error {
readonly code: number = 0x45;
readonly name: string = 'PrintingMintSupplyMustBeZeroForConversion';
constructor() {
super('Printing mint supply must be zero for conversion');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrintingMintSupplyMustBeZeroForConversionError);
}
}
}
createErrorFromCodeLookup.set(0x45, () => new PrintingMintSupplyMustBeZeroForConversionError());
createErrorFromNameLookup.set(
'PrintingMintSupplyMustBeZeroForConversion',
() => new PrintingMintSupplyMustBeZeroForConversionError(),
);
/**
* OneTimeAuthMintSupplyMustBeZeroForConversion: 'One Time Auth mint supply must be zero for conversion'
*
* @category Errors
* @category generated
*/
export class OneTimeAuthMintSupplyMustBeZeroForConversionError extends Error {
readonly code: number = 0x46;
readonly name: string = 'OneTimeAuthMintSupplyMustBeZeroForConversion';
constructor() {
super('One Time Auth mint supply must be zero for conversion');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, OneTimeAuthMintSupplyMustBeZeroForConversionError);
}
}
}
createErrorFromCodeLookup.set(0x46, () => new OneTimeAuthMintSupplyMustBeZeroForConversionError());
createErrorFromNameLookup.set(
'OneTimeAuthMintSupplyMustBeZeroForConversion',
() => new OneTimeAuthMintSupplyMustBeZeroForConversionError(),
);
/**
* InvalidEditionIndex: 'You tried to insert one edition too many into an edition mark pda'
*
* @category Errors
* @category generated
*/
export class InvalidEditionIndexError extends Error {
readonly code: number = 0x47;
readonly name: string = 'InvalidEditionIndex';
constructor() {
super('You tried to insert one edition too many into an edition mark pda');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidEditionIndexError);
}
}
}
createErrorFromCodeLookup.set(0x47, () => new InvalidEditionIndexError());
createErrorFromNameLookup.set('InvalidEditionIndex', () => new InvalidEditionIndexError());
/**
* ReservationArrayShouldBeSizeOne: 'In the legacy system the reservation needs to be of size one for cpu limit reasons'
*
* @category Errors
* @category generated
*/
export class ReservationArrayShouldBeSizeOneError extends Error {
readonly code: number = 0x48;
readonly name: string = 'ReservationArrayShouldBeSizeOne';
constructor() {
super('In the legacy system the reservation needs to be of size one for cpu limit reasons');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReservationArrayShouldBeSizeOneError);
}
}
}
createErrorFromCodeLookup.set(0x48, () => new ReservationArrayShouldBeSizeOneError());
createErrorFromNameLookup.set(
'ReservationArrayShouldBeSizeOne',
() => new ReservationArrayShouldBeSizeOneError(),
);
/**
* IsMutableCanOnlyBeFlippedToFalse: 'Is Mutable can only be flipped to false'
*
* @category Errors
* @category generated
*/
export class IsMutableCanOnlyBeFlippedToFalseError extends Error {
readonly code: number = 0x49;
readonly name: string = 'IsMutableCanOnlyBeFlippedToFalse';
constructor() {
super('Is Mutable can only be flipped to false');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, IsMutableCanOnlyBeFlippedToFalseError);
}
}
}
createErrorFromCodeLookup.set(0x49, () => new IsMutableCanOnlyBeFlippedToFalseError());
createErrorFromNameLookup.set(
'IsMutableCanOnlyBeFlippedToFalse',
() => new IsMutableCanOnlyBeFlippedToFalseError(),
);
/**
* CollectionCannotBeVerifiedInThisInstruction: 'Cannont Verify Collection in this Instruction'
*
* @category Errors
* @category generated
*/
export class CollectionCannotBeVerifiedInThisInstructionError extends Error {
readonly code: number = 0x4a;
readonly name: string = 'CollectionCannotBeVerifiedInThisInstruction';
constructor() {
super('Cannont Verify Collection in this Instruction');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CollectionCannotBeVerifiedInThisInstructionError);
}
}
}
createErrorFromCodeLookup.set(0x4a, () => new CollectionCannotBeVerifiedInThisInstructionError());
createErrorFromNameLookup.set(
'CollectionCannotBeVerifiedInThisInstruction',
() => new CollectionCannotBeVerifiedInThisInstructionError(),
);
/**
* Removed: 'This instruction was deprecated in a previous release and is now removed'
*
* @category Errors
* @category generated
*/
export class RemovedError extends Error {
readonly code: number = 0x4b;
readonly name: string = 'Removed';
constructor() {
super('This instruction was deprecated in a previous release and is now removed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, RemovedError);
}
}
}
createErrorFromCodeLookup.set(0x4b, () => new RemovedError());
createErrorFromNameLookup.set('Removed', () => new RemovedError());
/**
* MustBeBurned: 'This token use method is burn and there are no remaining uses, it must be burned'
*
* @category Errors
* @category generated
*/
export class MustBeBurnedError extends Error {
readonly code: number = 0x4c;
readonly name: string = 'MustBeBurned';
constructor() {
super('This token use method is burn and there are no remaining uses, it must be burned');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MustBeBurnedError);
}
}
}
createErrorFromCodeLookup.set(0x4c, () => new MustBeBurnedError());
createErrorFromNameLookup.set('MustBeBurned', () => new MustBeBurnedError());
/**
* InvalidUseMethod: 'This use method is invalid'
*
* @category Errors
* @category generated
*/
export class InvalidUseMethodError extends Error {
readonly code: number = 0x4d;
readonly name: string = 'InvalidUseMethod';
constructor() {
super('This use method is invalid');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidUseMethodError);
}
}
}
createErrorFromCodeLookup.set(0x4d, () => new InvalidUseMethodError());
createErrorFromNameLookup.set('InvalidUseMethod', () => new InvalidUseMethodError());
/**
* CannotChangeUseMethodAfterFirstUse: 'Cannot Change Use Method after the first use'
*
* @category Errors
* @category generated
*/
export class CannotChangeUseMethodAfterFirstUseError extends Error {
readonly code: number = 0x4e;
readonly name: string = 'CannotChangeUseMethodAfterFirstUse';
constructor() {
super('Cannot Change Use Method after the first use');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotChangeUseMethodAfterFirstUseError);
}
}
}
createErrorFromCodeLookup.set(0x4e, () => new CannotChangeUseMethodAfterFirstUseError());
createErrorFromNameLookup.set(
'CannotChangeUseMethodAfterFirstUse',
() => new CannotChangeUseMethodAfterFirstUseError(),
);
/**
* CannotChangeUsesAfterFirstUse: 'Cannot Change Remaining or Available uses after the first use'
*
* @category Errors
* @category generated
*/
export class CannotChangeUsesAfterFirstUseError extends Error {
readonly code: number = 0x4f;
readonly name: string = 'CannotChangeUsesAfterFirstUse';
constructor() {
super('Cannot Change Remaining or Available uses after the first use');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotChangeUsesAfterFirstUseError);
}
}
}
createErrorFromCodeLookup.set(0x4f, () => new CannotChangeUsesAfterFirstUseError());
createErrorFromNameLookup.set(
'CannotChangeUsesAfterFirstUse',
() => new CannotChangeUsesAfterFirstUseError(),
);
/**
* CollectionNotFound: 'Collection Not Found on Metadata'
*
* @category Errors
* @category generated
*/
export class CollectionNotFoundError extends Error {
readonly code: number = 0x50;
readonly name: string = 'CollectionNotFound';
constructor() {
super('Collection Not Found on Metadata');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CollectionNotFoundError);
}
}
}
createErrorFromCodeLookup.set(0x50, () => new CollectionNotFoundError());
createErrorFromNameLookup.set('CollectionNotFound', () => new CollectionNotFoundError());
/**
* InvalidCollectionUpdateAuthority: 'Collection Update Authority is invalid'
*
* @category Errors
* @category generated
*/
export class InvalidCollectionUpdateAuthorityError extends Error {
readonly code: number = 0x51;
readonly name: string = 'InvalidCollectionUpdateAuthority';
constructor() {
super('Collection Update Authority is invalid');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidCollectionUpdateAuthorityError);
}
}
}
createErrorFromCodeLookup.set(0x51, () => new InvalidCollectionUpdateAuthorityError());
createErrorFromNameLookup.set(
'InvalidCollectionUpdateAuthority',
() => new InvalidCollectionUpdateAuthorityError(),
);
/**
* CollectionMustBeAUniqueMasterEdition: 'Collection Must Be a Unique Master Edition v2'
*
* @category Errors
* @category generated
*/
export class CollectionMustBeAUniqueMasterEditionError extends Error {
readonly code: number = 0x52;
readonly name: string = 'CollectionMustBeAUniqueMasterEdition';
constructor() {
super('Collection Must Be a Unique Master Edition v2');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CollectionMustBeAUniqueMasterEditionError);
}
}
}
createErrorFromCodeLookup.set(0x52, () => new CollectionMustBeAUniqueMasterEditionError());
createErrorFromNameLookup.set(
'CollectionMustBeAUniqueMasterEdition',
() => new CollectionMustBeAUniqueMasterEditionError(),
);
/**
* UseAuthorityRecordAlreadyExists: 'The Use Authority Record Already Exists, to modify it Revoke, then Approve'
*
* @category Errors
* @category generated
*/
export class UseAuthorityRecordAlreadyExistsError extends Error {
readonly code: number = 0x53;
readonly name: string = 'UseAuthorityRecordAlreadyExists';
constructor() {
super('The Use Authority Record Already Exists, to modify it Revoke, then Approve');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UseAuthorityRecordAlreadyExistsError);
}
}
}
createErrorFromCodeLookup.set(0x53, () => new UseAuthorityRecordAlreadyExistsError());
createErrorFromNameLookup.set(
'UseAuthorityRecordAlreadyExists',
() => new UseAuthorityRecordAlreadyExistsError(),
);
/**
* UseAuthorityRecordAlreadyRevoked: 'The Use Authority Record is empty or already revoked'
*
* @category Errors
* @category generated
*/
export class UseAuthorityRecordAlreadyRevokedError extends Error {
readonly code: number = 0x54;
readonly name: string = 'UseAuthorityRecordAlreadyRevoked';
constructor() {
super('The Use Authority Record is empty or already revoked');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UseAuthorityRecordAlreadyRevokedError);
}
}
}
createErrorFromCodeLookup.set(0x54, () => new UseAuthorityRecordAlreadyRevokedError());
createErrorFromNameLookup.set(
'UseAuthorityRecordAlreadyRevoked',
() => new UseAuthorityRecordAlreadyRevokedError(),
);
/**
* Unusable: 'This token has no uses'
*
* @category Errors
* @category generated
*/
export class UnusableError extends Error {
readonly code: number = 0x55;
readonly name: string = 'Unusable';
constructor() {
super('This token has no uses');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UnusableError);
}
}
}
createErrorFromCodeLookup.set(0x55, () => new UnusableError());
createErrorFromNameLookup.set('Unusable', () => new UnusableError());
/**
* NotEnoughUses: 'There are not enough Uses left on this token.'
*
* @category Errors
* @category generated
*/
export class NotEnoughUsesError extends Error {
readonly code: number = 0x56;
readonly name: string = 'NotEnoughUses';
constructor() {
super('There are not enough Uses left on this token.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotEnoughUsesError);
}
}
}
createErrorFromCodeLookup.set(0x56, () => new NotEnoughUsesError());
createErrorFromNameLookup.set('NotEnoughUses', () => new NotEnoughUsesError());
/**
* CollectionAuthorityRecordAlreadyExists: 'This Collection Authority Record Already Exists.'
*
* @category Errors
* @category generated
*/
export class CollectionAuthorityRecordAlreadyExistsError extends Error {
readonly code: number = 0x57;
readonly name: string = 'CollectionAuthorityRecordAlreadyExists';
constructor() {
super('This Collection Authority Record Already Exists.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CollectionAuthorityRecordAlreadyExistsError);
}
}
}
createErrorFromCodeLookup.set(0x57, () => new CollectionAuthorityRecordAlreadyExistsError());
createErrorFromNameLookup.set(
'CollectionAuthorityRecordAlreadyExists',
() => new CollectionAuthorityRecordAlreadyExistsError(),
);
/**
* CollectionAuthorityDoesNotExist: 'This Collection Authority Record Does Not Exist.'
*
* @category Errors
* @category generated
*/
export class CollectionAuthorityDoesNotExistError extends Error {
readonly code: number = 0x58;
readonly name: string = 'CollectionAuthorityDoesNotExist';
constructor() {
super('This Collection Authority Record Does Not Exist.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CollectionAuthorityDoesNotExistError);
}
}
}
createErrorFromCodeLookup.set(0x58, () => new CollectionAuthorityDoesNotExistError());
createErrorFromNameLookup.set(
'CollectionAuthorityDoesNotExist',
() => new CollectionAuthorityDoesNotExistError(),
);
/**
* InvalidUseAuthorityRecord: 'This Use Authority Record is invalid.'
*
* @category Errors
* @category generated
*/
export class InvalidUseAuthorityRecordError extends Error {
readonly code: number = 0x59;
readonly name: string = 'InvalidUseAuthorityRecord';
constructor() {
super('This Use Authority Record is invalid.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidUseAuthorityRecordError);
}
}
}
createErrorFromCodeLookup.set(0x59, () => new InvalidUseAuthorityRecordError());
createErrorFromNameLookup.set(
'InvalidUseAuthorityRecord',
() => new InvalidUseAuthorityRecordError(),
);
/**
* InvalidCollectionAuthorityRecord: 'This Collection Authority Record is invalid.'
*
* @category Errors
* @category generated
*/
export class InvalidCollectionAuthorityRecordError extends Error {
readonly code: number = 0x5a;
readonly name: string = 'InvalidCollectionAuthorityRecord';
constructor() {
super('This Collection Authority Record is invalid.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidCollectionAuthorityRecordError);
}
}
}
createErrorFromCodeLookup.set(0x5a, () => new InvalidCollectionAuthorityRecordError());
createErrorFromNameLookup.set(
'InvalidCollectionAuthorityRecord',
() => new InvalidCollectionAuthorityRecordError(),
);
/**
* InvalidFreezeAuthority: 'Metadata does not match the freeze authority on the mint'
*
* @category Errors
* @category generated
*/
export class InvalidFreezeAuthorityError extends Error {
readonly code: number = 0x5b;
readonly name: string = 'InvalidFreezeAuthority';
constructor() {
super('Metadata does not match the freeze authority on the mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidFreezeAuthorityError);
}
}
}
createErrorFromCodeLookup.set(0x5b, () => new InvalidFreezeAuthorityError());
createErrorFromNameLookup.set('InvalidFreezeAuthority', () => new InvalidFreezeAuthorityError());
/**
* InvalidDelegate: 'All tokens in this account have not been delegated to this user.'
*
* @category Errors
* @category generated
*/
export class InvalidDelegateError extends Error {
readonly code: number = 0x5c;
readonly name: string = 'InvalidDelegate';
constructor() {
super('All tokens in this account have not been delegated to this user.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidDelegateError);
}
}
}
createErrorFromCodeLookup.set(0x5c, () => new InvalidDelegateError());
createErrorFromNameLookup.set('InvalidDelegate', () => new InvalidDelegateError());
/**
* CannotAdjustVerifiedCreator: 'Creator can not be adjusted once they are verified.'
*
* @category Errors
* @category generated
*/
export class CannotAdjustVerifiedCreatorError extends Error {
readonly code: number = 0x5d;
readonly name: string = 'CannotAdjustVerifiedCreator';
constructor() {
super('Creator can not be adjusted once they are verified.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotAdjustVerifiedCreatorError);
}
}
}
createErrorFromCodeLookup.set(0x5d, () => new CannotAdjustVerifiedCreatorError());
createErrorFromNameLookup.set(
'CannotAdjustVerifiedCreator',
() => new CannotAdjustVerifiedCreatorError(),
);
/**
* CannotRemoveVerifiedCreator: 'Verified creators cannot be removed.'
*
* @category Errors
* @category generated
*/
export class CannotRemoveVerifiedCreatorError extends Error {
readonly code: number = 0x5e;
readonly name: string = 'CannotRemoveVerifiedCreator';
constructor() {
super('Verified creators cannot be removed.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotRemoveVerifiedCreatorError);
}
}
}
createErrorFromCodeLookup.set(0x5e, () => new CannotRemoveVerifiedCreatorError());
createErrorFromNameLookup.set(
'CannotRemoveVerifiedCreator',
() => new CannotRemoveVerifiedCreatorError(),
);
/**
* CannotWipeVerifiedCreators: 'Can not wipe verified creators.'
*
* @category Errors
* @category generated
*/
export class CannotWipeVerifiedCreatorsError extends Error {
readonly code: number = 0x5f;
readonly name: string = 'CannotWipeVerifiedCreators';
constructor() {
super('Can not wipe verified creators.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotWipeVerifiedCreatorsError);
}
}
}
createErrorFromCodeLookup.set(0x5f, () => new CannotWipeVerifiedCreatorsError());
createErrorFromNameLookup.set(
'CannotWipeVerifiedCreators',
() => new CannotWipeVerifiedCreatorsError(),
);
/**
* NotAllowedToChangeSellerFeeBasisPoints: 'Not allowed to change seller fee basis points.'
*
* @category Errors
* @category generated
*/
export class NotAllowedToChangeSellerFeeBasisPointsError extends Error {
readonly code: number = 0x60;
readonly name: string = 'NotAllowedToChangeSellerFeeBasisPoints';
constructor() {
super('Not allowed to change seller fee basis points.');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotAllowedToChangeSellerFeeBasisPointsError);
}
}
}
createErrorFromCodeLookup.set(0x60, () => new NotAllowedToChangeSellerFeeBasisPointsError());
createErrorFromNameLookup.set(
'NotAllowedToChangeSellerFeeBasisPoints',
() => new NotAllowedToChangeSellerFeeBasisPointsError(),
);
/**
* EditionOverrideCannotBeZero: 'Edition override cannot be zero'
*
* @category Errors
* @category generated
*/
export class EditionOverrideCannotBeZeroError extends Error {
readonly code: number = 0x61;
readonly name: string = 'EditionOverrideCannotBeZero';
constructor() {
super('Edition override cannot be zero');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, EditionOverrideCannotBeZeroError);
}
}
}
createErrorFromCodeLookup.set(0x61, () => new EditionOverrideCannotBeZeroError());
createErrorFromNameLookup.set(
'EditionOverrideCannotBeZero',
() => new EditionOverrideCannotBeZeroError(),
);
/**
* InvalidUser: 'Invalid User'
*
* @category Errors
* @category generated
*/
export class InvalidUserError extends Error {
readonly code: number = 0x62;
readonly name: string = 'InvalidUser';
constructor() {
super('Invalid User');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidUserError);
}
}
}
createErrorFromCodeLookup.set(0x62, () => new InvalidUserError());
createErrorFromNameLookup.set('InvalidUser', () => new InvalidUserError());
/**
* Attempts to resolve a custom program error from the provided error code.
* @category Errors
* @category generated
*/
export function errorFromCode(code: number): MaybeErrorWithCode {
const createError = createErrorFromCodeLookup.get(code);
return createError != null ? createError() : null;
}
/**
* Attempts to resolve a custom program error from the provided error name, i.e. 'Unauthorized'.
* @category Errors
* @category generated
*/
export function errorFromName(name: string): MaybeErrorWithCode {
const createError = createErrorFromNameLookup.get(name);
return createError != null ? createError() : null;
} | the_stack |
import * as _ from 'lodash';
import React, { Component } from 'react';
import './index.css';
import { Trace } from '../../../types/trace';
import HeaderTable from './HeaderTable';
import MainTableData from './MainTableData';
import DetailTableData from './DetailTableData';
import TraceStatisticsHeader from './TraceStatisticsHeader';
import { ITableSpan } from './types';
import sortTable from './sortTable';
import { TNil } from '../../../types';
import PopupSQL from './PopupSql';
type Props = {
trace: Trace;
uiFindVertexKeys: Set<string> | TNil;
uiFind: string | null | undefined;
};
type State = {
tableValue: ITableSpan[];
sortIndex: number;
sortAsc: boolean;
showPopup: boolean;
popupContent: string;
wholeTable: ITableSpan[];
valueNameSelector1: string;
valueNameSelector2: string | null;
};
const columnsArray: any[] = [
{
title: 'Name',
attribute: 'name',
suffix: '',
isDecimal: false,
},
{
title: 'Count',
attribute: 'count',
suffix: '',
isDecimal: false,
},
{
title: 'Total',
attribute: 'total',
suffix: 'ms',
isDecimal: true,
},
{
title: 'Avg',
attribute: 'avg',
suffix: 'ms',
isDecimal: true,
},
{
title: 'Min',
attribute: 'min',
suffix: 'ms',
isDecimal: true,
},
{
title: 'Max',
attribute: 'max',
suffix: 'ms',
isDecimal: true,
},
{
title: 'ST Total',
attribute: 'selfTotal',
suffix: 'ms',
isDecimal: true,
},
{
title: 'ST Avg',
attribute: 'selfAvg',
suffix: 'ms',
isDecimal: true,
},
{
title: 'ST Min',
attribute: 'selfMin',
suffix: 'ms',
isDecimal: true,
},
{
title: 'ST Max',
attribute: 'selfMax',
suffix: 'ms',
isDecimal: true,
},
{
title: 'ST in Duration',
attribute: 'percent',
suffix: '%',
isDecimal: true,
},
];
/**
* Trace Tag Overview Component
*/
export default class TraceStatistics extends Component<Props, State> {
constructor(props: any) {
super(props);
this.state = {
tableValue: [],
sortIndex: 1,
sortAsc: false,
showPopup: false,
popupContent: '',
wholeTable: [],
valueNameSelector1: 'Service Name',
valueNameSelector2: null,
};
this.handler = this.handler.bind(this);
this.sortClick = this.sortClick.bind(this);
this.togglePopup = this.togglePopup.bind(this);
this.clickColumn = this.clickColumn.bind(this);
this.searchInTable(this.props.uiFindVertexKeys!, this.state.tableValue, this.props.uiFind);
}
/**
* If the search props change the search function is called.
* @param props all props
*/
componentDidUpdate(props: any) {
if (this.props.uiFindVertexKeys !== props.uiFindVertexKeys) {
this.changeTableValueSearch();
}
}
changeTableValueSearch() {
this.searchInTable(this.props.uiFindVertexKeys!, this.state.tableValue, this.props.uiFind);
// reload the componente
const tableValueState = this.state.tableValue;
this.setState(prevState => ({
...prevState,
tableValue: tableValueState,
}));
}
/**
* Is called from the child to change the state of the parent.
* @param tableValue the values of the column
*/
handler(
tableValue: ITableSpan[],
wholeTable: ITableSpan[],
valueNameSelector1: string,
valueNameSelector2: string | null
) {
this.setState(prevState => {
return {
...prevState,
tableValue: this.searchInTable(
this.props.uiFindVertexKeys!,
this.sortTableWithOthers(tableValue, 1, false),
this.props.uiFind
),
sortIndex: 1,
sortAsc: false,
valueNameSelector1,
valueNameSelector2,
wholeTable,
};
});
}
/**
* Searches for the others of the share and sorts afterwards.
*/
sortTableWithOthers = (tableValue: ITableSpan[], sortIndex: number, sortAsc: boolean) => {
let rememberIndexNoDetail = -1;
let rememberIndex = -1;
let othersInDetail = false;
let sortArray = [];
const sortArray2 = [];
let i;
for (i = 0; i < tableValue.length; i++) {
if (tableValue[i].type !== 'undefined') {
sortArray.push(tableValue[i]);
} else if (!tableValue[i].isDetail) {
rememberIndexNoDetail = i;
} else {
othersInDetail = true;
}
}
sortArray = sortTable(sortArray, columnsArray[sortIndex].attribute, sortAsc);
if (rememberIndexNoDetail !== -1) {
sortArray.push(tableValue[rememberIndexNoDetail]);
}
if (!othersInDetail) {
return sortArray;
}
let parentElements = [];
for (i = 0; i < tableValue.length; i++) {
if (!tableValue[i].isDetail) {
parentElements.push(tableValue[i]);
}
}
parentElements = sortTable(parentElements, columnsArray[sortIndex].attribute, sortAsc);
for (i = 0; i < parentElements.length; i++) {
sortArray2.push(parentElements[i]);
let tempArray = [];
for (let j = 0; j < tableValue.length; j++) {
if (parentElements[i].name === tableValue[j].parentElement && tableValue[j].type !== 'undefined') {
tempArray.push(tableValue[j]);
} else if (
parentElements[i].name === tableValue[j].parentElement &&
tableValue[j].type === 'undefined'
) {
rememberIndex = j;
}
}
tempArray = sortTable(tempArray, columnsArray[sortIndex].attribute, sortAsc);
if (rememberIndex !== -1) {
tempArray.push(tableValue[rememberIndex]);
rememberIndex = -1;
}
for (let j = 0; j < tempArray.length; j++) {
sortArray2.push(tempArray[j]);
}
}
return sortArray2;
};
/**
* Opern the popup button.
* @param popupContent
*/
togglePopup(popupContent: string) {
const showPopupState = this.state.showPopup;
this.setState(prevState => {
return {
...prevState,
showPopup: !showPopupState,
popupContent,
};
});
}
/**
* Change the sortButton an calls the sort function.
* @param index the index of the clicked column
*/
sortClick(index: number) {
const { tableValue, sortIndex, sortAsc } = this.state;
if (sortIndex !== index) {
this.setState(prevState => {
return {
...prevState,
sortIndex: index,
sortAsc: false,
tableValue: this.sortTableWithOthers(tableValue, index, false),
};
});
} else {
this.setState(prevState => {
return {
...prevState,
sortAsc: !sortAsc,
tableValue: this.sortTableWithOthers(tableValue, index, !sortAsc),
};
});
}
}
/**
* Hides the child at the first click.
*/
clickColumn(selectedSpan: string) {
if (this.state.valueNameSelector2 !== null) {
let add = true;
const actualTable = this.state.tableValue;
let newTable = [];
for (let i = 0; i < actualTable.length; i++) {
if (actualTable[i].parentElement === selectedSpan) {
add = false;
}
if (actualTable[i].parentElement !== selectedSpan) {
newTable.push(actualTable[i]);
}
}
if (add) {
newTable = [];
for (let i = 0; i < actualTable.length; i++) {
if (actualTable[i].name !== selectedSpan) {
newTable.push(actualTable[i]);
} else {
newTable.push(actualTable[i]);
for (let j = 0; j < this.state.wholeTable.length; j++) {
if (this.state.wholeTable[j].parentElement === selectedSpan) {
newTable.push(this.state.wholeTable[j]);
}
}
}
}
newTable = this.searchInTable(this.props.uiFindVertexKeys!, newTable, this.props.uiFind);
newTable = this.sortTableWithOthers(newTable, this.state.sortIndex, this.state.sortAsc);
}
this.setState({
tableValue: newTable,
});
}
}
/**
* Colors found entries in the table.
* @param uiFindVertexKeys Set of found spans
* @param allTableSpans entries that are shown
*/
searchInTable = (
uiFindVertexKeys: Set<string>,
allTableSpans: ITableSpan[],
uiFind: string | null | undefined
) => {
const allTableSpansChange = allTableSpans;
const yellowSearchCollor = 'rgb(255,243,215)';
const defaultGrayCollor = 'rgb(248,248,248)';
for (let i = 0; i < allTableSpansChange.length; i++) {
if (!allTableSpansChange[i].isDetail && allTableSpansChange[i].type !== 'undefined') {
allTableSpansChange[i].searchColor = 'transparent';
} else if (allTableSpansChange[i].type !== 'undefined') {
allTableSpansChange[i].searchColor = defaultGrayCollor;
} else {
allTableSpansChange[i].searchColor = defaultGrayCollor;
}
}
if (typeof uiFindVertexKeys !== 'undefined') {
uiFindVertexKeys!.forEach(function calc(value) {
const uiFindVertexKeysSplit = value.split('');
for (let i = 0; i < allTableSpansChange.length; i++) {
if (
uiFindVertexKeysSplit[uiFindVertexKeysSplit.length - 1].indexOf(allTableSpansChange[i].name) !==
-1
) {
if (allTableSpansChange[i].parentElement === 'none') {
allTableSpansChange[i].searchColor = yellowSearchCollor;
} else if (
uiFindVertexKeysSplit[uiFindVertexKeysSplit.length - 1].indexOf(
allTableSpansChange[i].parentElement
) !== -1
) {
allTableSpansChange[i].searchColor = yellowSearchCollor;
}
}
}
});
}
if (uiFind) {
for (let i = 0; i < allTableSpansChange.length; i++) {
if (allTableSpansChange[i].name.indexOf(uiFind!) !== -1) {
allTableSpansChange[i].searchColor = yellowSearchCollor;
for (let j = 0; j < allTableSpansChange.length; j++) {
if (allTableSpansChange[j].parentElement === allTableSpansChange[i].name) {
allTableSpansChange[j].searchColor = yellowSearchCollor;
}
}
if (allTableSpansChange[i].isDetail) {
for (let j = 0; j < allTableSpansChange.length; j++) {
if (allTableSpansChange[i].parentElement === allTableSpansChange[j].name) {
allTableSpansChange[j].searchColor = yellowSearchCollor;
}
}
}
}
}
}
return allTableSpansChange;
};
renderTableData() {
return this.state.tableValue.map(oneSpan => {
const {
count,
total,
avg,
min,
max,
selfTotal,
selfAvg,
selfMin,
selfMax,
percent,
color,
searchColor,
colorToPercent,
} = oneSpan;
const values: any[] = [count, total, avg, min, max, selfTotal, selfAvg, selfMin, selfMax, percent];
const uid = _.uniqueId('id');
if (!oneSpan.isDetail) {
return (
<MainTableData
key={uid}
type={oneSpan.type}
name={oneSpan.name}
searchColor={searchColor}
values={values}
columnsArray={columnsArray}
togglePopup={this.togglePopup}
valueNameSelector1={this.state.valueNameSelector1}
valueNameSelector2={this.state.valueNameSelector2}
color={color}
clickColumn={this.clickColumn}
colorToPercent={colorToPercent}
/>
);
}
return (
<DetailTableData
key={uid}
type={oneSpan.type}
name={oneSpan.name}
searchColor={searchColor}
values={values}
columnsArray={columnsArray}
color={color}
togglePopup={this.togglePopup}
valueNameSelector2={this.state.valueNameSelector2}
colorToPercent={colorToPercent}
/>
);
});
}
renderTableHead() {
const { sortAsc, sortIndex } = this.state;
return (
<tr>
{columnsArray.map((element: any, index: number) => (
<HeaderTable
element={element}
key={element.title}
sortIndex={sortIndex}
index={index}
sortClick={this.sortClick}
sortAsc={sortAsc}
/>
))}
</tr>
);
}
render() {
return (
<div>
<h3 className="title--TraceStatistics"> Trace Statistics</h3>
<TraceStatisticsHeader
trace={this.props.trace}
tableValue={this.state.tableValue}
wholeTable={this.state.wholeTable}
handler={this.handler}
/>
{this.state.showPopup ? (
<PopupSQL closePopup={this.togglePopup} popupContent={this.state.popupContent} />
) : null}
<table className="test1893">
<tbody className="DetailTraceTableTbody--TraceStatistics">
{this.renderTableHead()}
{this.renderTableData()}
</tbody>
</table>
</div>
);
}
} | the_stack |
import 'lit/experimental-hydrate-support.js';
import {html, noChange, nothing, Part} from 'lit';
import {
directive,
Directive,
DirectiveParameters,
DirectiveResult,
PartInfo,
PartType,
} from 'lit/directive.js';
import {repeat} from 'lit/directives/repeat.js';
import {guard} from 'lit/directives/guard.js';
import {cache} from 'lit/directives/cache.js';
import {classMap} from 'lit/directives/class-map.js';
import {styleMap} from 'lit/directives/style-map.js';
import {until} from 'lit/directives/until.js';
// TODO(kschaaf): Enable once async directives are implemented
// import {asyncAppend} from 'lit/directives/async-append.js';
// import {asyncReplace} from 'lit/directives/async-replace.js';
// import {TestAsyncIterable} from 'lit/test/lib/test-async-iterable.js';
import {ifDefined} from 'lit/directives/if-defined.js';
import {live} from 'lit/directives/live.js';
import {unsafeHTML} from 'lit/directives/unsafe-html.js';
import {unsafeSVG} from 'lit/directives/unsafe-svg.js';
import {createRef, ref} from 'lit/directives/ref.js';
import {LitElement, PropertyValues} from 'lit';
import {property} from 'lit/decorators/property.js';
import {
renderLight,
RenderLightHost,
} from '@lit-labs/ssr-client/directives/render-light.js';
import {SSRTest} from './ssr-test.js';
import {AsyncDirective} from 'lit/async-directive.js';
interface DivWithProp extends HTMLDivElement {
prop?: unknown;
prop2?: unknown;
}
interface ClickableButton extends HTMLButtonElement {
__wasClicked: boolean;
__wasClicked2: boolean;
}
interface ClickableInput extends HTMLInputElement {
__wasClicked: boolean;
__wasClicked2: boolean;
}
const throwIfRunOnServer = () => {
if (!(globalThis instanceof window.constructor)) {
throw new Error('Upate should not be run on the server');
}
};
const filterNodes = (nodes: ArrayLike<Node>, nodeType: number) =>
Array.from(nodes).filter((n) => n.nodeType === nodeType);
export const tests: {[name: string]: SSRTest} = {
// TODO: add suites (for now, delineating with comments)
/******************************************************
* ChildPart tests
******************************************************/
'ChildPart accepts a string': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: ['foo'],
html: '<div>foo</div>',
},
{
args: ['foo2'],
html: '<div>foo2</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts a number': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [123],
html: '<div>123</div>',
},
{
args: [456.789],
html: '<div>456.789</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts undefined': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div>foo</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts null': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [null],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div>foo</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts noChange': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [noChange],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div>foo</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts nothing': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [nothing],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div>foo</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts an object': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [{}],
html: '<div>[object Object]</div>',
},
{
args: [{}],
html: '<div>[object Object]</div>',
},
],
// Objects are not dirty-checked before being toString()'ed
expectMutationsOnFirstRender: true,
stableSelectors: ['div'],
},
'ChildPart accepts an object with a toString method': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
args: [
{
toString() {
return 'toString!';
},
},
],
html: '<div>toString!</div>',
},
{
args: [
{
toString() {
return 'toString2!';
},
},
],
html: '<div>toString2!</div>',
},
],
// Objects are not dirty-checked before being toString()'ed
expectMutationsOnFirstRender: true,
stableSelectors: ['div'],
},
'ChildPart accepts a function': {
render(x: unknown) {
return html` <div>${x}</div> `;
},
expectations: [
{
// prettier-ignore
args: [ () => { throw new Error(); }, ],
html: '<div>() => { throw new Error(); }</div>',
},
{
// prettier-ignore
args: [ () => { throw new Error("2"); }, ],
html: '<div>() => { throw new Error("2"); }</div>',
},
],
// Functions are not dirty-checked before being toString()'ed
expectMutationsOnFirstRender: true,
stableSelectors: ['div'],
},
'ChildPart accepts TemplateResult': {
render(x: unknown) {
return html` <div>${html` <span>${x}</span> `}</div> `;
},
expectations: [
{
args: ['A'],
html: '<div><span>A</span></div>',
},
{
args: ['B'],
html: '<div><span>B</span></div>',
},
],
stableSelectors: ['div', 'span'],
},
'multiple ChildParts, adjacent primitive values': {
render(x: unknown, y: unknown) {
return html` <div>${x}${y}</div> `;
},
expectations: [
{
args: ['A', 'B'],
html: '<div>AB</div>',
},
{
args: ['C', 'D'],
html: '<div>CD</div>',
},
],
stableSelectors: ['div'],
},
'multiple ChildParts, adjacent primitive & TemplateResult': {
render(x: unknown, y: unknown) {
return html` <div>${x}${html` <span>${y}</span> `}</div> `;
},
expectations: [
{
args: ['A', 'B'],
html: '<div>A\n <span>B</span></div>',
},
{
args: ['C', 'D'],
html: '<div>C\n <span>D</span></div>',
},
],
stableSelectors: ['div', 'span'],
},
'multiple ChildParts, adjacent TemplateResults': {
render(x: unknown, y: unknown) {
return html`
<div>${html` <span>${x}</span> `}${html` <span>${y}</span> `}</div>
`;
},
expectations: [
{
args: ['A', 'B'],
html: '<div><span>A</span><span>B</span></div>',
},
{
args: ['C', 'D'],
html: '<div><span>C</span><span>D</span></div>',
},
],
stableSelectors: ['div', 'span'],
},
'multiple ChildParts with whitespace': {
render(x: unknown, y: unknown) {
return html` <div>${x} ${y}</div> `;
},
expectations: [
{
args: ['A', 'B'],
html: '<div>A B</div>',
check(assert: Chai.Assert, dom: HTMLElement) {
const childNodes = dom.querySelector('div')!.childNodes;
const textContent = filterNodes(childNodes, Node.TEXT_NODE).map(
(n) => n.textContent
);
assert.deepEqual(textContent, ['A', ' ', 'B']);
},
},
{
args: ['C', 'D'],
html: '<div>C D</div>',
check(assert: Chai.Assert, dom: HTMLElement) {
const childNodes = dom.querySelector('div')!.childNodes;
const textContent = filterNodes(childNodes, Node.TEXT_NODE).map(
(n) => n.textContent
);
assert.deepEqual(textContent, ['C', ' ', 'D']);
},
},
],
stableSelectors: ['div'],
},
'ChildPart with trailing whitespace': {
render(x: unknown) {
// prettier-ignore
return html`<div>${x} </div>`;
},
expectations: [
{
args: ['A'],
html: '<div>A\n </div>',
check(assert: Chai.Assert, dom: HTMLElement) {
const childNodes = dom.querySelector('div')!.childNodes;
const textContent = filterNodes(childNodes, Node.TEXT_NODE).map(
(n) => n.textContent
);
assert.deepEqual(textContent, ['A', ' ']);
},
},
{
args: ['B'],
html: '<div>B\n </div>',
check(assert: Chai.Assert, dom: HTMLElement) {
const childNodes = dom.querySelector('div')!.childNodes;
const textContent = filterNodes(childNodes, Node.TEXT_NODE).map(
(n) => n.textContent
);
assert.deepEqual(textContent, ['B', ' ']);
},
},
],
stableSelectors: ['div'],
},
'ChildPart accepts array with strings': {
render(words: string[]) {
return html` <div>${words}</div> `;
},
expectations: [
{
args: [['A', 'B', 'C']],
html: '<div>ABC</div>',
},
{
args: [['D', 'E', 'F']],
html: '<div>DEF</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts array with strings, updated with fewer items': {
render(words: string[]) {
return html` <div>${words}</div> `;
},
expectations: [
{
args: [['A', 'B', 'C']],
html: '<div>ABC</div>',
},
// Attribute hydration not working yet
{
args: [['D', 'E']],
html: '<div>DE</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts array with strings, updated with more items': {
render(words: string[]) {
return html` <div>${words}</div> `;
},
expectations: [
{
args: [['A', 'B', 'C']],
html: '<div>ABC</div>',
},
// Attribute hydration not working yet
{
args: [['D', 'E', 'F', 'G']],
html: '<div>DEFG</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts array with templates': {
render(words: string[]) {
return html`
<ol>
${words.map((w) => html` <li>${w}</li> `)}
</ol>
`;
},
expectations: [
{
args: [['A', 'B', 'C']],
html: '<ol><li>A</li>\n <li>B</li>\n <li>C</li></ol>',
},
{
args: [['D', 'E', 'F']],
html: '<ol><li>D</li>\n <li>E</li>\n <li>F</li></ol>',
},
],
stableSelectors: ['ol', 'li'],
},
'ChildPart accepts simple directive': () => {
const basic = directive(
class extends Directive {
count = 0;
lastValue: string | undefined = undefined;
override update(_part: Part, [v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(v);
}
render(v: string) {
if (v !== this.lastValue) {
this.lastValue = v;
this.count++;
}
return `[${this.count}:${v}]`;
}
}
);
return {
render(v: string) {
return html` <div>${basic(v)}</div> `;
},
expectations: [
{
args: ['one'],
html: '<div>[1:one]</div>',
},
{
args: ['two'],
html: '<div>[2:two]</div>',
},
],
stableSelectors: ['div'],
};
},
'ChildPart directive gets PartInfo': () => {
const info = directive(
class extends Directive {
partInfo: PartInfo;
constructor(partInfo: PartInfo) {
super(partInfo);
this.partInfo = partInfo;
}
render(v: string) {
if (this.partInfo.type !== PartType.CHILD) {
throw new Error('expected PartType.CHILD');
}
return `[${v}]`;
}
}
);
return {
render(v: string) {
return html` <div>${info(v)}</div> `;
},
expectations: [
{
args: ['one'],
html: '<div>[one]</div>',
},
{
args: ['two'],
html: '<div>[two]</div>',
},
],
stableSelectors: ['div'],
};
},
'ChildPart accepts nested directives': () => {
const aDirective = directive(
class extends Directive {
override update(_part: Part, [bool, v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(bool, v);
}
render(bool: boolean, v: unknown) {
return bool ? v : nothing;
}
}
);
const bDirective = directive(
class extends Directive {
count = 0;
lastValue: string | undefined = undefined;
override update(_part: Part, [v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(v);
}
render(v: string) {
if (v !== this.lastValue) {
this.lastValue = v;
this.count++;
}
return `[B:${this.count}:${v}]`;
}
}
);
return {
render(bool: boolean, v: string) {
return html` <div>${aDirective(bool, bDirective(v))}</div> `;
},
expectations: [
{
args: [true, 'X'],
html: '<div>[B:1:X]</div>',
},
{
args: [true, 'Y'],
html: '<div>[B:2:Y]</div>',
},
{
args: [false, 'X'],
html: '<div></div>',
},
{
args: [true, 'X'],
html: '<div>[B:1:X]</div>',
},
],
stableSelectors: ['div'],
};
},
'ChildPart accepts directive: repeat (with strings)': {
render(words: string[]) {
return html` ${repeat(words, (word, i) => `(${i} ${word})`)} `;
},
expectations: [
{
args: [['foo', 'bar', 'qux']],
html: '(0 foo)(1 bar)(2 qux)',
},
{
args: [['A', 'B', 'C']],
html: '(0 A)(1 B)(2 C)',
},
],
stableSelectors: [],
},
'ChildPart accepts directive: repeat (with templates)': {
render(words: string[]) {
return html`
${repeat(words, (word, i) => html` <p>${i}) ${word}</p> `)}
`;
},
expectations: [
{
args: [['foo', 'bar', 'qux']],
html: '<p>\n 0) foo\n</p>\n<p>\n 1) bar\n</p>\n<p>\n 2) qux\n</p>\n',
},
{
args: [['A', 'B', 'C']],
html: '<p>\n 0) A\n</p>\n<p>\n 1) B\n</p>\n<p>\n 2) C\n</p>\n',
},
],
stableSelectors: ['p'],
},
'ChildPart accepts directive: cache': {
render(bool: boolean) {
return html`
${cache(bool ? html` <p>true</p> ` : html` <b>false</b> `)}
`;
},
expectations: [
{
args: [true],
html: '<p>true</p>',
},
{
args: [false],
html: '<b>false</b>',
},
{
args: [true],
html: '<p>true</p>',
},
],
stableSelectors: [],
},
'ChildPart accepts directive: guard': () => {
let guardedCallCount = 0;
const guardedTemplate = (bool: boolean) => {
guardedCallCount++;
return html` value is ${bool ? true : false} `;
};
return {
render(bool: boolean) {
return html` <div>${guard([bool], () => guardedTemplate(bool))}</div> `;
},
expectations: [
{
args: [true],
html: '<div>value is true</div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 1);
},
},
{
args: [true],
html: '<div>value is true</div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 1);
},
},
{
args: [false],
html: '<div>value is false</div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 2);
},
},
],
stableSelectors: ['div'],
};
},
'ChildPart accepts directive: until (primitive)': {
render(...args) {
return html` <div>${until(...args)}</div> `;
},
expectations: [
{
args: ['foo'],
html: '<div>foo</div>',
},
{
args: ['bar'],
html: '<div>bar</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts directive: until (promise, primitive)': () => {
let resolve: (v: string) => void;
const promise = new Promise((r) => (resolve = r));
return {
render(...args) {
return html` <div>${until(...args)}</div> `;
},
expectations: [
{
args: [promise, 'foo'],
html: '<div>foo</div>',
},
{
async setup() {
resolve('promise');
await promise;
},
args: [promise, 'foo'],
html: '<div>promise</div>',
},
],
stableSelectors: ['div'],
};
},
'ChildPart accepts directive: until (promise, promise)': () => {
let resolve1: (v: string) => void;
let resolve2: (v: string) => void;
const promise1 = new Promise((r) => (resolve1 = r));
const promise2 = new Promise((r) => (resolve2 = r));
return {
render(...args) {
return html` <div>${until(...args)}</div> `;
},
expectations: [
{
args: [promise2, promise1],
html: '<div></div>',
},
{
async setup() {
resolve1('promise1');
await promise1;
},
args: [promise2, promise1],
html: '<div>promise1</div>',
},
{
async setup() {
resolve2('promise2');
await promise2;
},
args: [promise2, promise1],
html: '<div>promise2</div>',
},
],
stableSelectors: ['div'],
};
},
// TODO(kschaaf): Enable once async directives are implemented
// 'ChildPart accepts directive: asyncAppend': () => {
// const iterable = new TestAsyncIterable();
// return {
// render(iterable) {
// return html`<div>${asyncAppend(iterable)}</div>`
// },
// expectations: [
// {
// args: [iterable],
// html: '<div></div>',
// },
// {
// async setup() {
// await iterable.push('a');
// },
// args: [iterable],
// html: '<div>a</div>',
// },
// {
// async setup() {
// await iterable.push('b');
// },
// args: [iterable],
// html: '<div>\n ab\n</div>',
// },
// ],
// stableSelectors: ['div'],
// };
// },
// 'ChildPart accepts directive: asyncReplace': () => {
// const iterable = new TestAsyncIterable();
// return {
// render(iterable) {
// return html`<div>${asyncReplace(iterable)}</div>`
// },
// expectations: [
// {
// args: [iterable],
// html: '<div></div>',
// },
// {
// async setup() {
// await iterable.push('a');
// },
// args: [iterable],
// html: '<div>a</div>',
// },
// {
// async setup() {
// await iterable.push('b');
// },
// args: [iterable],
// html: '<div>b</div>',
// },
// ],
// stableSelectors: ['div'],
// };
// },
'ChildPart accepts directive: ifDefined (undefined)': {
render(v) {
return html` <div>${ifDefined(v)}</div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div>foo</div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts directive: ifDefined (defined)': {
render(v) {
return html` <div>${ifDefined(v)}</div> `;
},
expectations: [
{
args: ['foo'],
html: '<div>foo</div>',
},
{
args: [undefined],
html: '<div></div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts directive: unsafeHTML': {
render(v) {
return html` <div>${unsafeHTML(v)}</div> `;
},
expectations: [
{
args: ['<span foo="bar"></span>'],
html: '<div><span foo="bar"></span></div>',
},
{
args: ['<p bar="foo"></p>'],
html: '<div><p bar="foo"></p></div>',
},
],
stableSelectors: ['div'],
},
'ChildPart accepts directive: unsafeSVG': {
render(v) {
return html` <svg>${unsafeSVG(v)}</svg> `;
},
expectations: [
{
args: ['<circle cx="50" cy="50" r="40" />'],
html: '<svg><circle cx="50" cy="50" r="40"></circle></svg>',
},
{
args: ['<ellipse cx="100" cy="50" rx="100" ry="50" />'],
html: '<svg><ellipse cx="100" cy="50" rx="100" ry="50"></ellipse></svg>',
},
],
stableSelectors: ['div'],
},
/******************************************************
* AttributePart tests
******************************************************/
'AttributePart after a text node': {
render(x: unknown) {
return html`
ABC
<div class=${x}></div>
`;
},
expectations: [
{
args: ['TEST'],
html: 'ABC<div class="TEST"></div>',
},
{
args: ['TEST2'],
html: 'ABC<div class="TEST2"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts a string': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: ['TEST'],
html: '<div class="TEST"></div>',
},
{
args: ['TEST2'],
html: '<div class="TEST2"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts a number': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [123],
html: '<div class="123"></div>',
},
{
args: [456.789],
html: '<div class="456.789"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts undefined': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [undefined],
html: '<div class=""></div>',
},
{
args: ['TEST'],
html: '<div class="TEST"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts null': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [null],
html: '<div class=""></div>',
},
{
args: ['TEST'],
html: '<div class="TEST"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts noChange': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [noChange],
html: '<div></div>',
},
{
args: ['TEST'],
html: '<div class="TEST"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts nothing': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [nothing],
html: '<div></div>',
},
{
args: ['TEST'],
html: '<div class="TEST"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts an array': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [['a', 'b', 'c']],
html: '<div class="a,b,c"></div>',
},
{
args: [['d', 'e', 'f']],
html: '<div class="d,e,f"></div>',
},
],
stableSelectors: ['div'],
// Setting an object/array always results in setAttribute being called
expectMutationsOnFirstRender: true,
},
'AttributePart accepts an object': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [{foo: 'bar'}],
html: '<div class="[object Object]"></div>',
},
{
args: [{ziz: 'zaz'}],
html: '<div class="[object Object]"></div>',
},
],
stableSelectors: ['div'],
// Setting an object/array always results in setAttribute being called
expectMutationsOnFirstRender: true,
},
'AttributePart accepts an object with a toString method': {
render(x: unknown) {
return html` <div class=${x}></div> `;
},
expectations: [
{
args: [
{
toString() {
return 'toString!';
},
},
],
html: '<div class="toString!"></div>',
},
{
args: [
{
toString() {
return 'toString2!';
},
},
],
html: '<div class="toString2!"></div>',
},
],
stableSelectors: ['div'],
// Setting an object/array always results in setAttribute being called
expectMutationsOnFirstRender: true,
},
'AttributePart accepts simple directive': () => {
const basic = directive(
class extends Directive {
count = 0;
lastValue: string | undefined = undefined;
override update(_part: Part, [v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(v);
}
render(v: string) {
if (v !== this.lastValue) {
this.lastValue = v;
this.count++;
}
return `[${this.count}:${v}]`;
}
}
);
return {
render(v: string) {
return html` <div a="${basic(v)}"></div> `;
},
expectations: [
{
args: ['one'],
html: '<div a="[1:one]"></div>',
},
{
args: ['two'],
html: '<div a="[2:two]"></div>',
},
],
stableSelectors: ['div'],
};
},
'AttributePart directive gets PartInfo': () => {
const info = directive(
class extends Directive {
partInfo: PartInfo;
constructor(partInfo: PartInfo) {
super(partInfo);
this.partInfo = partInfo;
}
render(v: string) {
if (this.partInfo.type !== PartType.ATTRIBUTE) {
throw new Error('expected PartType.ATTRIBUTE');
}
const {tagName, name, strings} = this.partInfo;
return `[${v}:${tagName}:${name}:${strings!.join(':')}]`;
}
}
);
return {
render(v: string) {
return html` <div title="a${info(v)}b"></div> `;
},
expectations: [
{
args: ['one'],
html: '<div title="a[one:DIV:title:a:b]b"></div>',
},
{
args: ['two'],
html: '<div title="a[two:DIV:title:a:b]b"></div>',
},
],
stableSelectors: ['div'],
};
},
'AttributePart accepts nested directives': () => {
const aDirective = directive(
class extends Directive {
override update(_part: Part, [bool, v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(bool, v);
}
render(bool: boolean, v: unknown) {
return bool ? v : nothing;
}
}
);
const bDirective = directive(
class extends Directive {
count = 0;
lastValue: string | undefined = undefined;
override update(_part: Part, [v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(v);
}
render(v: string) {
if (v !== this.lastValue) {
this.lastValue = v;
this.count++;
}
return `[B:${this.count}:${v}]`;
}
}
);
return {
render(bool: boolean, v: string) {
return html` <div a="${aDirective(bool, bDirective(v))}"></div> `;
},
expectations: [
{
args: [true, 'X'],
html: '<div a="[B:1:X]"></div>',
},
{
args: [true, 'Y'],
html: '<div a="[B:2:Y]"></div>',
},
{
args: [false, 'X'],
html: '<div></div>',
},
{
args: [true, 'X'],
html: '<div a="[B:1:X]"></div>',
},
],
stableSelectors: ['div'],
};
},
'AttributePart accepts directive: classMap': {
render(map: {}) {
return html` <div class=${classMap(map)}></div> `;
},
expectations: [
{
args: [{foo: true, bar: false, baz: true}],
html: '<div class="foo baz"></div>',
},
{
args: [{foo: false, bar: true, baz: true, zug: true}],
html: '<div class="bar baz zug"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts directive: classMap (with statics)': {
render(map: {}) {
return html` <div class="static1 ${classMap(map)} static2"></div> `;
},
expectations: [
{
args: [{foo: true, bar: false, baz: true}],
html: '<div class="static1 foo baz static2"></div>',
},
{
args: [{foo: false, bar: true, baz: true, zug: true}],
html: '<div class="static1 bar baz zug static2"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts directive: styleMap': {
render(map: {}) {
return html` <div style=${styleMap(map)}></div> `;
},
expectations: [
{
// Note that (at least on chrome, vendor-prefixed properties get
// collapsed down to the standard property name when re-parsed on the
// browser)
args: [
{
height: '5px',
paddingTop: '10px',
},
],
html: '<div style="height: 5px; padding-top: 10px;"></div>',
},
{
args: [
{
paddingTop: '20px',
backgroundColor: 'white',
},
],
html: '<div style="padding-top: 20px; background-color: white;"></div>',
},
],
// styleMap does not dirty check individual properties before setting,
// which causes an attribute mutation even if the text has not changed
expectMutationsOnFirstRender: true,
stableSelectors: ['div'],
},
'AttributePart accepts directive: styleMap (custom properties & browser-prefixed)':
{
// The parsed results of style text with custom properties and browser
// prefixes differs across browsers (due to whitespace and re-writing
// prefixed names) enough to make a single cross-platform assertion
// difficult. For now, just test these on Chrome.
skip: Boolean(
globalThis.navigator && !navigator.userAgent.match(/Chrome/)
),
render(map: {}) {
return html` <div style=${styleMap(map)}></div> `;
},
expectations: [
{
// Note that (at least on chrome, vendor-prefixed properties get
// collapsed down to the standard property name when re-parsed on the
// browser)
args: [
{
'--my-prop': 'green',
webkitAppearance: 'none',
},
],
html: '<div style="--my-prop:green; appearance: none;"></div>',
},
{
args: [
{
'--my-prop': 'gray',
webkitAppearance: 'inherit',
},
],
html: '<div style="--my-prop:gray; appearance: inherit;"></div>',
},
],
// styleMap does not dirty check individual properties before setting,
// which causes an attribute mutation even if the text has not changed
expectMutationsOnFirstRender: true,
stableSelectors: ['div'],
},
'AttributePart accepts directive: styleMap (with statics)': {
render(map: {}) {
return html`
<div style="color: red; ${styleMap(map)} height: 3px;"></div>
`;
},
expectations: [
{
args: [{width: '5px'}],
html: '<div style="color: red; width: 5px; height: 3px;"></div>',
},
{
args: [{paddingTop: '20px'}],
html: '<div style="color: red; height: 3px; padding-top: 20px;"></div>',
},
],
// styleMap does not dirty check individual properties before setting,
// which causes an attribute mutation even if the text has not changed
expectMutationsOnFirstRender: true,
stableSelectors: ['div'],
},
'AttributePart accepts directive: guard': () => {
let guardedCallCount = 0;
const guardedValue = (bool: boolean) => {
guardedCallCount++;
return bool ? 'true' : 'false';
};
return {
render(bool: boolean) {
return html`
<div attr="${guard([bool], () => guardedValue(bool))}"></div>
`;
},
expectations: [
{
args: [true],
html: '<div attr="true"></div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 1);
},
},
{
args: [true],
html: '<div attr="true"></div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 1);
},
},
{
args: [false],
html: '<div attr="false"></div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 2);
},
},
],
stableSelectors: ['div'],
};
},
'AttributePart accepts directive: until (primitive)': {
render(...args) {
return html` <div attr="${until(...args)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div attr="foo"></div>',
},
{
args: ['bar'],
html: '<div attr="bar"></div>',
},
],
stableSelectors: ['div'],
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
},
'AttributePart accepts directive: until (promise, primitive)': () => {
let resolve: (v: string) => void;
const promise = new Promise((r) => (resolve = r));
return {
render(...args) {
return html` <div attr="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise, 'foo'],
html: '<div attr="foo"></div>',
},
{
async setup() {
resolve('promise');
await promise;
},
args: [promise, 'foo'],
html: '<div attr="promise"></div>',
},
],
stableSelectors: ['div'],
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
};
},
'AttributePart accepts directive: until (promise, promise)': () => {
let resolve1: (v: string) => void;
let resolve2: (v: string) => void;
const promise1 = new Promise((r) => (resolve1 = r));
const promise2 = new Promise((r) => (resolve2 = r));
return {
render(...args) {
return html` <div attr="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise2, promise1],
html: '<div></div>',
},
{
async setup() {
resolve1('promise1');
await promise1;
},
args: [promise2, promise1],
html: '<div attr="promise1"></div>',
},
{
async setup() {
resolve2('promise2');
await promise2;
},
args: [promise2, promise1],
html: '<div attr="promise2"></div>',
},
],
stableSelectors: ['div'],
};
},
'AttributePart accepts directive: ifDefined (undefined)': {
render(v) {
return html` <div attr="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div attr="foo"></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts directive: ifDefined (defined)': {
render(v) {
return html` <div attr="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div attr="foo"></div>',
},
{
args: [undefined],
html: '<div></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart accepts directive: live': {
render(v: string) {
return html` <div attr="${live(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div attr="foo"></div>',
},
{
args: ['bar'],
html: '<div attr="bar"></div>',
},
],
stableSelectors: ['div'],
},
'multiple AttributeParts on same node': {
render(x: unknown, y: unknown) {
return html` <div class=${x} foo=${y}></div> `;
},
expectations: [
{
args: ['A', 'B'],
html: '<div class="A" foo="B"></div>',
},
{
args: ['C', 'D'],
html: '<div class="C" foo="D"></div>',
},
],
stableSelectors: ['div'],
},
'multiple AttributeParts in same attribute': {
render(x: unknown, y: unknown) {
return html` <div class="${x} ${y}"></div> `;
},
expectations: [
{
args: ['A', 'B'],
html: '<div class="A B"></div>',
},
{
args: ['C', 'D'],
html: '<div class="C D"></div>',
},
],
stableSelectors: ['div'],
},
'multiple AttributeParts across multiple attributes': {
render(
a: unknown,
b: unknown,
c: unknown,
d: unknown,
e: unknown,
f: unknown
) {
return html`
<div ab="${a} ${b}" x c="${c}" y de="${d} ${e}" f="${f}" z></div>
`;
},
expectations: [
{
args: ['a', 'b', 'c', 'd', 'e', 'f'],
html: '<div ab="a b" x c="c" y de="d e" f="f" z></div>',
},
{
args: ['A', 'B', 'C', 'D', 'E', 'F'],
html: '<div ab="A B" x c="C" y de="D E" f="F" z></div>',
},
],
stableSelectors: ['div'],
},
'AttributePart on void element': {
render(x: string) {
return html`<input class=${x} />`;
},
expectations: [
{
args: ['TEST'],
html: '<input class="TEST">',
},
{
args: ['TEST2'],
html: '<input class="TEST2">',
},
],
stableSelectors: ['input'],
},
/******************************************************
* PropertyPart tests
******************************************************/
'PropertyPart accepts a string': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo'
);
},
},
{
args: ['foo2'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo2'
);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts a string (reflected + camelCase)': {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
args: ['foo2'],
html: '<div class="foo2"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(dom.querySelector('div')!.className, 'foo2');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
'PropertyPart accepts a number': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 1);
},
},
{
args: [2],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 2);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts a number (reflected)': {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
{
args: [2],
html: '<div class="2"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '2');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
'PropertyPart accepts a boolean': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [false],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
false
);
},
},
{
args: [true],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
true
);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts a boolean (reflected)': {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [false],
html: '<div class="false"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'false');
},
},
{
args: [true],
html: '<div class="true"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'true');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
'PropertyPart accepts undefined': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
undefined
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 1);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts undefined (reflected)': {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [undefined],
html: '<div class="undefined"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'undefined');
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
'PropertyPart accepts null': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [null],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
null
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 1);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts null (reflected)': {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [null],
html: '<div class="null"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'null');
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
'PropertyPart accepts noChange': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [noChange],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Ideally this would be `notProperty`, but this is actually how
// the client-side works right now, because the committer starts off
// as dirty
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
undefined
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 1);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts noChange (reflected)': {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [noChange],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// className will always read as '' when unset
assert.strictEqual(dom.querySelector('div')!.className, '');
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts nothing': {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [nothing],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
undefined
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 1);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts nothing (reflected)': {
// TODO: the current client-side does nothing special with `nothing`, just
// passes it on to the property; is that what we want?
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [nothing],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// className will always read as '' when unset
assert.strictEqual(dom.querySelector('div')!.className, '');
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
// Objects don't dirty check, so we get another mutation during first render
expectMutationsOnFirstRender: true,
},
'PropertyPart accepts a symbol': () => {
const testSymbol = Symbol();
return {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [testSymbol],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
testSymbol
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
1
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts an object': () => {
const testObject = {};
return {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [testObject],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
testObject
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
1
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts an object (reflected)': () => {
const testObject = {};
return {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [testObject],
html: '<div class="[object Object]"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(
dom.querySelector('div')!.className,
'[object Object]'
);
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
// Objects don't dirty check, so we get another mutation during first render
expectMutationsOnFirstRender: true,
};
},
'PropertyPart accepts an array': () => {
const testArray = [1, 2, 3];
return {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [testArray],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
testArray
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
1
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts an array (reflected)': () => {
const testArray = [1, 2, 3];
return {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [testArray],
html: '<div class="1,2,3"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1,2,3');
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
// Arrays don't dirty check, so we get another mutation during first render
expectMutationsOnFirstRender: true,
};
},
'PropertyPart accepts a function': () => {
const testFunction = () => 'test function';
return {
render(x: unknown) {
return html` <div .prop=${x}></div> `;
},
expectations: [
{
args: [testFunction],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
testFunction
);
},
},
{
args: [1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
1
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts a function (reflected)': () => {
const testFunction = () => 'test function';
return {
render(x: unknown) {
return html` <div .className=${x}></div> `;
},
expectations: [
{
args: [testFunction],
html: `<div class="() => 'test function'"></div>`,
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(
dom.querySelector('div')!.className,
`() => 'test function'`
);
},
},
{
args: [1],
html: '<div class="1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '1');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
// Arrays don't dirty check, so we get another mutation during first render
expectMutationsOnFirstRender: true,
};
},
'PropertyPart directive gets PartInfo': () => {
const info = directive(
class extends Directive {
partInfo: PartInfo;
constructor(partInfo: PartInfo) {
super(partInfo);
this.partInfo = partInfo;
}
render(v: string) {
if (this.partInfo.type !== PartType.PROPERTY) {
throw new Error('expected PartType.PROPERTY');
}
const {tagName, name, strings} = this.partInfo;
return `[${v}:${tagName}:${name}:${strings!.join(':')}]`;
}
}
);
return {
render(v: string) {
return html` <div .title="a${info(v)}b"></div> `;
},
expectations: [
{
args: ['one'],
html: '<div title="a[one:DIV:title:a:b]b"></div>',
},
{
args: ['two'],
html: '<div title="a[two:DIV:title:a:b]b"></div>',
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
};
},
'PropertyPart accepts directive: guard': () => {
let guardedCallCount = 0;
const guardedValue = (bool: boolean) => {
guardedCallCount++;
return bool;
};
return {
render(bool: boolean) {
return html`
<div .prop="${guard([bool], () => guardedValue(bool))}"></div>
`;
},
expectations: [
{
args: [true],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 1);
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
true
);
},
},
{
args: [true],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 1);
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
true
);
},
},
{
args: [false],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 2);
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
false
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts directive: guard (reflected)': () => {
let guardedCallCount = 0;
const guardedValue = (v: string) => {
guardedCallCount++;
return v;
};
return {
render(v: string) {
return html`
<div .className="${guard([v], () => guardedValue(v))}"></div>
`;
},
expectations: [
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 1);
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 1);
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
args: ['bar'],
html: '<div class="bar"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 2);
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'bar');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
};
},
'PropertyPart accepts directive: until (primitive)': {
render(...args) {
return html` <div .prop="${until(...args)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo'
);
},
},
{
args: ['bar'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'bar'
);
},
},
],
stableSelectors: ['div'],
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
},
'PropertyPart accepts directive: until (primitive) (reflected)': {
render(...args) {
return html` <div .className="${until(...args)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
args: ['bar'],
html: '<div class="bar"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'bar');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
},
'PropertyPart accepts directive: until (promise, primitive)': () => {
let resolve: (v: string) => void;
const promise = new Promise((r) => (resolve = r));
return {
render(...args) {
return html` <div .prop="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise, 'foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo'
);
},
},
{
async setup() {
resolve('promise');
await promise;
},
args: [promise, 'foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'promise'
);
},
},
],
stableSelectors: ['div'],
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
};
},
'PropertyPart accepts directive: until (promise, primitive) (reflected)':
() => {
let resolve: (v: string) => void;
const promise = new Promise((r) => (resolve = r));
return {
render(...args) {
return html` <div .className="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise, 'foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
async setup() {
resolve('promise');
await promise;
},
args: [promise, 'foo'],
html: '<div class="promise"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(
dom.querySelector('div')!.className,
'promise'
);
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
};
},
'PropertyPart accepts directive: until (promise, promise)': () => {
let resolve1: (v: string) => void;
let resolve2: (v: string) => void;
const promise1 = new Promise((r) => (resolve1 = r));
const promise2 = new Promise((r) => (resolve2 = r));
return {
render(...args) {
return html` <div .prop="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise2, promise1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.notProperty(dom.querySelector('div') as DivWithProp, 'prop');
},
},
{
async setup() {
resolve1('promise1');
await promise1;
},
args: [promise2, promise1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'promise1'
);
},
},
{
async setup() {
resolve2('promise2');
await promise2;
},
args: [promise2, promise1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'promise2'
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts directive: until (promise, promise) (reflected)':
() => {
let resolve1: (v: string) => void;
let resolve2: (v: string) => void;
const promise1 = new Promise((r) => (resolve1 = r));
const promise2 = new Promise((r) => (resolve2 = r));
return {
render(...args) {
return html` <div .className="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise2, promise1],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '');
},
},
{
async setup() {
resolve1('promise1');
await promise1;
},
args: [promise2, promise1],
html: '<div class="promise1"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(
dom.querySelector('div')!.className,
'promise1'
);
},
},
{
async setup() {
resolve2('promise2');
await promise2;
},
args: [promise2, promise1],
html: '<div class="promise2"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(
dom.querySelector('div')!.className,
'promise2'
);
},
},
],
stableSelectors: ['div'],
};
},
'PropertyPart accepts directive: ifDefined (undefined)': {
render(v) {
return html` <div .prop="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.notProperty(dom.querySelector('div') as DivWithProp, 'prop');
},
},
{
args: ['foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo'
);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts directive: ifDefined (undefined) (reflected)': {
render(v) {
return html` <div .className="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, '');
},
},
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts directive: ifDefined (defined)': {
render(v) {
return html` <div .prop="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo'
);
},
},
{
args: [undefined],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
undefined
);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts directive: ifDefined (defined) (reflected)': {
render(v) {
return html` <div .className="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
args: [undefined],
// `ifDefined` is supposed to be a no-op for non-attribute parts, which
// means it sets `undefined` through, which sets it to the className
// property which is coerced to 'undefined' and reflected
html: '<div class="undefined"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'undefined');
},
},
],
stableSelectors: ['div'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
'PropertyPart accepts directive: live': {
render(v: string) {
return html` <div .prop="${live(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'foo'
);
},
},
{
args: ['bar'],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'bar'
);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart accepts directive: live (reflected)': {
render(v: string) {
return html` <div .className="${live(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div class="foo"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'foo');
},
},
{
args: ['bar'],
html: '<div class="bar"></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
// Note className coerces to string
assert.strictEqual(dom.querySelector('div')!.className, 'bar');
},
},
],
stableSelectors: ['div'],
},
'multiple PropertyParts on same node': {
render(x: unknown, y: unknown) {
return html` <div .prop=${x} .prop2=${y}></div> `;
},
expectations: [
{
args: [1, true],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 1);
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop2,
true
);
},
},
{
args: [2, false],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual((dom.querySelector('div') as DivWithProp).prop, 2);
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop2,
false
);
},
},
],
stableSelectors: ['div'],
},
'multiple PropertyParts in one property': {
render(x: unknown, y: unknown) {
return html` <div .prop="${x},${y}"></div> `;
},
expectations: [
{
args: [1, true],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'1,true'
);
},
},
{
args: [2, false],
html: '<div></div>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.strictEqual(
(dom.querySelector('div') as DivWithProp).prop,
'2,false'
);
},
},
],
stableSelectors: ['div'],
},
'PropertyPart on void element': {
render(x: string) {
return html`<input .title=${x} />`;
},
expectations: [
{
args: ['TEST'],
html: '<input title="TEST">',
},
{
args: ['TEST2'],
html: '<input title="TEST2">',
},
],
stableSelectors: ['input'],
// We set properties during hydration, and natively-reflecting properties
// will trigger a "mutation" even when set to the same value that was
// rendered to its attribute
expectMutationsDuringHydration: true,
},
/******************************************************
* EventPart tests
******************************************************/
EventPart: {
render(listener: (e: Event) => void) {
return html` <button @click=${listener}>X</button> `;
},
expectations: [
{
args: [
(e: Event) => ((e.target as ClickableButton).__wasClicked = true),
],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during first render'
);
},
},
{
args: [
(e: Event) => ((e.target as ClickableButton).__wasClicked2 = true),
],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked2,
true,
'not clicked during second render'
);
},
},
],
stableSelectors: ['button'],
},
'EventPart accepts directive: guard': () => {
const listener1 = (e: Event) =>
((e.target as ClickableButton).__wasClicked = true);
const listener2 = (e: Event) =>
((e.target as ClickableButton).__wasClicked2 = true);
let guardedCallCount = 0;
const guardedValue = (fn: (e: Event) => unknown) => {
guardedCallCount++;
return fn;
};
return {
render(fn: (e: Event) => unknown) {
return html`
<button @click="${guard([fn], () => guardedValue(fn))}">X</button>
`;
},
expectations: [
{
args: [listener1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 1);
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during first render'
);
},
},
{
args: [listener1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 1);
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during second render'
);
},
},
{
args: [listener2],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.equal(guardedCallCount, 2);
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during third render'
);
},
},
],
stableSelectors: ['button'],
};
},
'EventPart accepts directive: until (listener)': () => {
const listener1 = (e: Event) =>
((e.target as ClickableButton).__wasClicked = true);
const listener2 = (e: Event) =>
((e.target as ClickableButton).__wasClicked2 = true);
return {
render(...args) {
return html` <button @click="${until(...args)}">X</button> `;
},
expectations: [
{
args: [listener1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during first render'
);
},
},
{
args: [listener2],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked2,
true,
'not clicked during second render'
);
},
},
],
stableSelectors: ['button'],
};
},
'EventPart accepts directive: until (promise, listener)': () => {
const listener1 = (e: Event) =>
((e.target as ClickableButton).__wasClicked = true);
const listener2 = (e: Event) =>
((e.target as ClickableButton).__wasClicked2 = true);
let resolve: (v: (e: Event) => any) => void;
const promise = new Promise((r) => (resolve = r));
return {
render(...args) {
return html` <button @click="${until(...args)}">X</button> `;
},
expectations: [
{
args: [promise, listener1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during first render'
);
},
},
{
async setup() {
resolve(listener2);
await promise;
},
args: [promise, listener1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked2,
true,
'not clicked during second render'
);
},
},
],
stableSelectors: ['button'],
};
},
'EventPart accepts directive: until (promise, promise)': () => {
const listener1 = (e: Event) =>
((e.target as ClickableButton).__wasClicked = true);
const listener2 = (e: Event) =>
((e.target as ClickableButton).__wasClicked2 = true);
let resolve1: (v: (e: Event) => any) => void;
let resolve2: (v: (e: Event) => any) => void;
const promise1 = new Promise((r) => (resolve1 = r));
const promise2 = new Promise((r) => (resolve2 = r));
return {
render(...args) {
return html` <button @click="${until(...args)}">X</button> `;
},
expectations: [
{
args: [promise2, promise1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.notProperty(
dom.querySelector('button') as ClickableButton,
'__wasClicked'
);
const button = dom.querySelector('button')!;
button.click();
assert.notProperty(
button,
'__wasClicked',
'was clicked during first render'
);
},
},
{
async setup() {
resolve1(listener1);
await promise1;
},
args: [promise2, promise1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during second render'
);
},
},
{
async setup() {
resolve2(listener2);
await promise2;
},
args: [promise2, promise1],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked2,
true,
'not clicked during third render'
);
},
},
],
stableSelectors: ['button'],
};
},
'EventPart accepts directive: ifDefined (undefined)': {
render(v) {
return html` <button @click="${ifDefined(v)}">X</button> `;
},
expectations: [
{
args: [undefined],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.notProperty(
dom.querySelector('button') as ClickableButton,
'__wasClicked'
);
const button = dom.querySelector('button')!;
button.click();
assert.notProperty(
button,
'__wasClicked',
'was clicked during first render'
);
},
},
{
args: [
(e: Event) => ((e.target as ClickableButton).__wasClicked = true),
],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during second render'
);
},
},
],
stableSelectors: ['button'],
},
'EventPart accepts directive: ifDefined (defined)': {
render(v) {
return html` <button @click="${ifDefined(v)}">X</button> `;
},
expectations: [
{
args: [
(e: Event) => ((e.target as ClickableButton).__wasClicked = true),
],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
const button = dom.querySelector('button')!;
button.click();
assert.strictEqual(
(button as ClickableButton).__wasClicked,
true,
'not clicked during second render'
);
},
},
{
args: [undefined],
html: '<button>X</button>',
check(assert: Chai.Assert, dom: HTMLElement) {
assert.notProperty(
dom.querySelector('button') as ClickableButton,
'__wasClicked1'
);
const button = dom.querySelector('button')!;
button.click();
assert.notProperty(
button,
'__wasClicked1',
'was clicked during first render'
);
},
},
],
stableSelectors: ['button'],
},
'EventPart on a void element': {
render(listener: (e: Event) => void) {
return html`<input @click=${listener} />`;
},
expectations: [
{
args: [
(e: Event) => ((e.target as ClickableInput).__wasClicked = true),
],
html: '<input>',
check(assert: Chai.Assert, dom: HTMLElement) {
const input = dom.querySelector('input')!;
input.click();
assert.strictEqual(
(input as ClickableInput).__wasClicked,
true,
'not clicked during first render'
);
},
},
{
args: [
(e: Event) => ((e.target as ClickableInput).__wasClicked2 = true),
],
html: '<input>',
check(assert: Chai.Assert, dom: HTMLElement) {
const input = dom.querySelector('input')!;
input.click();
assert.strictEqual(
(input as ClickableInput).__wasClicked2,
true,
'not clicked during second render'
);
},
},
],
stableSelectors: ['input'],
},
/******************************************************
* BooleanAttributePart tests
******************************************************/
'BooleanAttributePart, initially true': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [true],
html: '<div hidden></div>',
},
{
args: [false],
html: '<div></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially truthy (number)': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [1],
html: '<div hidden></div>',
},
{
args: [false],
html: '<div></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially truthy (object)': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [{}],
html: '<div hidden></div>',
},
{
args: [false],
html: '<div></div>',
},
],
stableSelectors: ['div'],
// Objects never dirty-check, so they cause a setAttribute despite being hydrated
expectMutationsOnFirstRender: true,
},
'BooleanAttributePart, initially false': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [false],
html: '<div></div>',
},
{
args: [true],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially falsey (number)': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [0],
html: '<div></div>',
},
{
args: [true],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially falsey (null)': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [null],
html: '<div></div>',
},
{
args: [true],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially falsey (undefined)': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
},
{
args: [true],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially nothing': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [nothing],
html: '<div></div>',
},
{
args: [true],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart, initially noChange': {
render(hide: boolean) {
return html` <div ?hidden=${hide}></div> `;
},
expectations: [
{
args: [noChange],
html: '<div></div>',
},
{
args: [true],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart accepts directive: guard': () => {
let guardedCallCount = 0;
const guardedValue = (bool: boolean) => {
guardedCallCount++;
return bool;
};
return {
render(bool: boolean) {
return html`
<div ?hidden="${guard([bool], () => guardedValue(bool))}"></div>
`;
},
expectations: [
{
args: [true],
html: '<div hidden></div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 1);
},
},
{
args: [true],
html: '<div hidden></div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 1);
},
},
{
args: [false],
html: '<div></div>',
check(assert: Chai.Assert) {
assert.equal(guardedCallCount, 2);
},
},
],
stableSelectors: ['div'],
};
},
'BooleanAttributePart accepts directive: until (primitive)': {
render(...args) {
return html` <div ?hidden="${until(...args)}"></div> `;
},
expectations: [
{
args: [true],
html: '<div hidden></div>',
},
{
args: [false],
html: '<div></div>',
},
],
stableSelectors: ['div'],
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
},
'BooleanAttributePart accepts directive: until (promise, primitive)': () => {
let resolve: (v: boolean) => void;
const promise = new Promise((r) => (resolve = r));
return {
render(...args) {
return html` <div ?hidden="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise, true],
html: '<div hidden></div>',
},
{
async setup() {
resolve(false);
await promise;
},
args: [promise, true],
html: '<div></div>',
},
],
stableSelectors: ['div'],
// until always calls setValue each render, with no dirty-check of previous
// value
expectMutationsOnFirstRender: true,
};
},
'BooleanAttributePart accepts directive: until (promise, promise)': () => {
let resolve1: (v: boolean) => void;
let resolve2: (v: boolean) => void;
const promise1 = new Promise((r) => (resolve1 = r));
const promise2 = new Promise((r) => (resolve2 = r));
return {
render(...args) {
return html` <div ?hidden="${until(...args)}"></div> `;
},
expectations: [
{
args: [promise2, promise1],
html: '<div></div>',
},
{
async setup() {
resolve1(true);
await promise1;
},
args: [promise2, promise1],
html: '<div hidden></div>',
},
{
async setup() {
resolve2(false);
await promise2;
},
args: [promise2, promise1],
html: '<div></div>',
},
],
stableSelectors: ['div'],
};
},
'BooleanAttributePart accepts directive: ifDefined (undefined)': {
render(v) {
return html` <div ?hidden="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: [undefined],
html: '<div></div>',
},
{
args: ['foo'],
html: '<div hidden></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart accepts directive: ifDefined (defined)': {
render(v) {
return html` <div ?hidden="${ifDefined(v)}"></div> `;
},
expectations: [
{
args: ['foo'],
html: '<div hidden></div>',
},
{
args: [undefined],
html: '<div></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart accepts directive: live': {
render(v: boolean) {
return html` <div ?hidden="${live(v)}"></div> `;
},
expectations: [
{
args: [true],
html: '<div hidden></div>',
},
{
args: [false],
html: '<div></div>',
},
],
stableSelectors: ['div'],
},
'BooleanAttributePart on a void element': {
render(hide: boolean) {
return html` <input ?hidden=${hide} /> `;
},
expectations: [
{
args: [true],
html: '<input hidden>',
},
{
args: [false],
html: '<input>',
},
],
stableSelectors: ['input'],
},
/******************************************************
* ElementPart tests
******************************************************/
'ElementPart accepts directive: generic': () => {
const log: string[] = [];
const dir = directive(
class extends Directive {
render(_v: string) {
log.push('render should not be called');
}
override update(_part: Part, [v]: DirectiveParameters<this>) {
throwIfRunOnServer();
log.push(v);
}
}
);
return {
render(v: string) {
return html` <div attr=${v} ${dir(v)}></div> `;
},
expectations: [
{
args: ['a'],
html: '<div attr="a"></div>',
check(assert: Chai.Assert) {
// Note, update is called once during hydration and again
// during initial render
assert.deepEqual(log, ['a', 'a']);
},
},
{
args: ['b'],
html: '<div attr="b"></div>',
check(assert: Chai.Assert) {
assert.deepEqual(log, ['a', 'a', 'b']);
},
},
],
stableSelectors: ['div'],
};
},
'ElementPart accepts directive: ref': () => {
const ref1 = createRef();
const ref2 = createRef();
const ref3 = createRef();
return {
render(v: boolean) {
return html`
<div id="div1" ${ref(ref1)}>
<div id="div2" ${ref(ref2)}>
${v ? html` <div id="div3" ${ref(ref3)}></div> ` : nothing}
</div>
</div>
`;
},
expectations: [
{
args: [true],
html: '<div id="div1"><div id="div2"><div id="div3"></div></div></div>',
check(assert: Chai.Assert) {
assert.equal(ref1.value?.id, 'div1');
assert.equal(ref2.value?.id, 'div2');
assert.equal(ref3.value?.id, 'div3');
},
},
{
args: [false],
html: '<div id="div1"><div id="div2"></div></div>',
check(assert: Chai.Assert) {
assert.equal(ref1.value?.id, 'div1');
assert.equal(ref2.value?.id, 'div2');
assert.notOk(ref3.value);
},
},
],
stableSelectors: ['div'],
};
},
'ElementPart on void element': () => {
const inputRef = createRef();
return {
render() {
return html` <input ${ref(inputRef)} /> `;
},
expectations: [
{
args: [],
html: '<input>',
check(assert: Chai.Assert) {
assert.equal(inputRef.value?.localName, 'input');
},
},
],
stableSelectors: ['input'],
};
},
/******************************************************
* Mixed part tests
******************************************************/
'ChildParts & AttributeParts on adjacent nodes': {
render(x, y) {
return html`
<div attr="${x}">${x}</div>
<div attr="${y}">${y}</div>
`;
},
expectations: [
{
args: ['x', 'y'],
html: '<div attr="x">x</div><div attr="y">y</div>',
},
{
args: ['a', 'b'],
html: '<div attr="a">a</div><div attr="b">b</div>',
},
],
stableSelectors: ['div'],
},
'ChildParts & AttributeParts on nested nodes': {
render(x, y) {
return html`
<div attr="${x}">
${x}
<div attr="${y}">${y}</div>
</div>
`;
},
expectations: [
{
args: ['x', 'y'],
html: '<div attr="x">x<div attr="y">y</div></div>',
},
{
args: ['a', 'b'],
html: '<div attr="a">a<div attr="b">b</div></div>',
},
],
stableSelectors: ['div'],
},
'ChildPart, AttributePart, and ElementPart soup': {
render(x, y, z) {
return html`
text:${x}
<div>${x}</div>
<span a1="${y}" a2="${y}"
>${x}
<p a="${y}">${y}</p>
${z}</span
>
`;
},
expectations: [
{
args: [html` <a attr=${'a'} ${'ignored'}></a> `, 'b', 'c'],
html: 'text:\n<a attr="a"></a><div><a attr="a"></a></div><span a1="b" a2="b"><a attr="a"></a><p a="b">b</p>c</span>',
},
{
args: ['x', 'y', html` <i ${'ignored'} attr=${'i'}></i> `],
html: 'text:x\n<div>x</div><span a1="y" a2="y">x<p a="y">y</p><i attr="i"></i></span>',
},
],
stableSelectors: ['div', 'span', 'p'],
},
'All part types with at various depths': () => {
const handler1 = (e: Event) => ((e.target as any).triggered1 = true);
const handler2 = (e: Event) => ((e.target as any).triggered2 = true);
const checkDiv = (
assert: Chai.Assert,
dom: HTMLElement,
id: string,
x: unknown,
triggerProp: string
) => {
const div = dom.querySelector(`#${id}`) as HTMLElement;
assert.ok(div, `Div ${id} not found`);
div.click();
assert.equal(
(div as any)[triggerProp],
true,
`Event not triggered for ${id}`
);
assert.equal((div as any).p, x, `Property not set for ${id}`);
};
const dir = directive(
class extends Directive {
value: string | undefined;
override update(_part: Part, [v]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(v);
}
render(value: string) {
if (this.value !== value) {
this.value = value;
return value ? `[${value}]` : value;
}
return noChange;
}
}
);
const check = (
assert: Chai.Assert,
dom: HTMLElement,
x: unknown,
triggerProp: string
) => {
for (let i = 0; i < 2; i++) {
checkDiv(assert, dom, `div${i}`, x, triggerProp);
for (let j = 0; j < 2; j++) {
checkDiv(assert, dom, `div${i}-${j}`, x, triggerProp);
for (let k = 0; k < 3; k++) {
checkDiv(assert, dom, `div${i}-${j}-${k}`, x, triggerProp);
}
}
}
};
return {
render(x, y, z, h) {
return html`
<div
id="div0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${x}
<div
id="div0-0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${y}
<div
id="div0-0-0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<div
id="div0-0-1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<span>static</span>
<div
id="div0-0-2"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
</div>
<span>static</span>
<span>static</span>
<div
id="div0-1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${y}
<div
id="div0-1-0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<div
id="div0-1-1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<span>static</span>
<div
id="div0-1-2"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
</div>
</div>
<div
id="div1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${x}
<div
id="div1-0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${y}
<div
id="div1-0-0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<div
id="div1-0-1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<span>static</span>
<div
id="div1-0-2"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
</div>
<span>static</span>
<span>static</span>
<div
id="div1-1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${y}
<div
id="div1-1-0"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<div
id="div1-1-1"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
<span>static</span>
<div
id="div1-1-2"
a1=${x}
a2="[${x}-${y}]"
a3="(${dir(x)})"
.p=${x}
@click=${h}
?b=${x}
>
${z}
</div>
</div>
</div>
`;
},
expectations: [
{
args: ['x', 'y', html` <a>z</a> `, handler1],
html: `
<div id="div0" a1="x" a2="[x-y]" a3="([x])" b>
x
<div id="div0-0" a1="x" a2="[x-y]" a3="([x])" b>
y
<div id="div0-0-0" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<div id="div0-0-1" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<span>static</span>
<div id="div0-0-2" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
</div>
<span>static</span>
<span>static</span>
<div id="div0-1" a1="x" a2="[x-y]" a3="([x])" b>
y
<div id="div0-1-0" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<div id="div0-1-1" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<span>static</span>
<div id="div0-1-2" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
</div>
</div>
<div id="div1" a1="x" a2="[x-y]" a3="([x])" b>
x
<div id="div1-0" a1="x" a2="[x-y]" a3="([x])" b>
y
<div id="div1-0-0" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<div id="div1-0-1" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<span>static</span>
<div id="div1-0-2" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
</div>
<span>static</span>
<span>static</span>
<div id="div1-1" a1="x" a2="[x-y]" a3="([x])" b>
y
<div id="div1-1-0" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<div id="div1-1-1" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
<span>static</span>
<div id="div1-1-2" a1="x" a2="[x-y]" a3="([x])" b>
<a>z</a>
</div>
</div>
</div>`,
check(assert: Chai.Assert, dom: HTMLElement) {
check(assert, dom, 'x', 'triggered1');
},
},
{
args: [0, 1, html` <b>2</b> `, handler2],
html: `
<div id="div0" a1="0" a2="[0-1]" a3="(0)">
0
<div id="div0-0" a1="0" a2="[0-1]" a3="(0)">
1
<div id="div0-0-0" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<div id="div0-0-1" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<span>static</span>
<div id="div0-0-2" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
</div>
<span>static</span>
<span>static</span>
<div id="div0-1" a1="0" a2="[0-1]" a3="(0)">
1
<div id="div0-1-0" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<div id="div0-1-1" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<span>static</span>
<div id="div0-1-2" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
</div>
</div>
<div id="div1" a1="0" a2="[0-1]" a3="(0)">
0
<div id="div1-0" a1="0" a2="[0-1]" a3="(0)">
1
<div id="div1-0-0" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<div id="div1-0-1" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<span>static</span>
<div id="div1-0-2" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
</div>
<span>static</span>
<span>static</span>
<div id="div1-1" a1="0" a2="[0-1]" a3="(0)">
1
<div id="div1-1-0" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<div id="div1-1-1" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
<span>static</span>
<div id="div1-1-2" a1="0" a2="[0-1]" a3="(0)">
<b>2</b>
</div>
</div>
</div>`,
check(assert: Chai.Assert, dom: HTMLElement) {
check(assert, dom, 0, 'triggered2');
},
},
],
stableSelectors: ['div', 'span'],
};
},
/******************************************************
* AsyncDirective tests
******************************************************/
AsyncDirective: () => {
const log: string[] = [];
const dir = directive(
class extends AsyncDirective {
id!: string;
render(id: string) {
this.id = id;
log.push(`render-${this.id}`);
return id;
}
override disconnected() {
log.push(`disconnected-${this.id}`);
}
}
);
return {
render(bool: boolean, id: string) {
return html`
<span
>${dir('x')}${bool
? html`
<div attr=${dir(`attr-${id}`)}>${dir(`node-${id}`)}</div>
`
: nothing}</span
>
`;
},
expectations: [
{
args: [true, 'a'],
html: '<span>x<div attr="attr-a">node-a</div></span>',
check(assert: Chai.Assert) {
// Note, update is called once during hydration and again
// during initial render
assert.deepEqual(log, [
'render-x',
'render-attr-a',
'render-node-a',
'render-x',
'render-attr-a',
'render-node-a',
]);
log.length = 0;
},
},
{
args: [false, 'a'],
html: '<span>x</span>',
check(assert: Chai.Assert) {
assert.deepEqual(log, [
'render-x',
'disconnected-attr-a',
'disconnected-node-a',
]);
log.length = 0;
},
},
{
args: [true, 'b'],
html: '<span>x<div attr="attr-b">node-b</div></span>',
check(assert: Chai.Assert) {
assert.deepEqual(log, [
'render-x',
'render-attr-b',
'render-node-b',
]);
log.length = 0;
},
},
{
args: [false, 'b'],
html: '<span>x</span>',
check(assert: Chai.Assert) {
assert.deepEqual(log, [
'render-x',
'disconnected-attr-b',
'disconnected-node-b',
]);
log.length = 0;
},
},
],
stableSelectors: ['span'],
};
},
/******************************************************
* Nested directive tests
******************************************************/
'Nested directives': () => {
const log: number[] = [];
const nest = directive(
class extends Directive {
override update(_part: Part, [n]: DirectiveParameters<this>) {
throwIfRunOnServer();
return this.render(n);
}
render(n: number): string | DirectiveResult {
log.push(n);
if (n > 1) {
return nest(n - 1);
} else {
return 'nested!';
}
}
}
);
return {
render() {
return html` <span>${nest(3)}</span> `;
},
expectations: [
{
args: [],
html: '<span>nested!</span>',
check(assert: Chai.Assert) {
// Note, update is called once during hydration and again
// during initial render
assert.deepEqual(log, [3, 2, 1, 3, 2, 1]);
log.length = 0;
},
},
{
args: [],
html: '<span>nested!</span>',
check(assert: Chai.Assert) {
assert.deepEqual(log, [3, 2, 1]);
log.length = 0;
},
},
],
stableSelectors: ['span'],
};
},
/******************************************************
* LitElement tests
******************************************************/
'LitElement: Basic': () => {
return {
registerElements() {
customElements.define(
'le-basic',
class extends LitElement {
override render() {
return html` <div>[le-basic: <slot></slot>]</div> `;
}
}
);
},
render(x: string) {
return html` <le-basic>${x}</le-basic> `;
},
expectations: [
{
args: ['x'],
html: {
root: `<le-basic>x</le-basic>`,
'le-basic': `<div>[le-basic: <slot></slot>]</div>`,
},
},
],
stableSelectors: ['le-basic'],
};
},
'LitElement: Nested': () => {
return {
registerElements() {
customElements.define(
'le-nested1',
class extends LitElement {
override render() {
return html`
<div>
[le-nested1: <le-nested2><slot></slot></le-nested2>]
</div>
`;
}
}
);
customElements.define(
'le-nested2',
class extends LitElement {
override render() {
return html` <div>[le-nested2: <slot></slot>]</div> `;
}
}
);
},
render(x: string) {
return html` <le-nested1>${x}</le-nested1> `;
},
expectations: [
{
args: ['x'],
html: {
root: `<le-nested1>x</le-nested1>`,
'le-nested1': {
root: `<div>[le-nested1: <le-nested2><slot></slot></le-nested2>]</div>`,
'le-nested2': `<div>[le-nested2: <slot></slot>]</div>`,
},
},
},
],
stableSelectors: ['le-nested1'],
};
},
'LitElement: Property binding': () => {
return {
registerElements() {
class LEPropBinding extends LitElement {
@property()
prop = 'default';
override render() {
return html` <div>[${this.prop}]</div> `;
}
}
customElements.define('le-prop-binding', LEPropBinding);
},
render(prop: unknown) {
return html` <le-prop-binding .prop=${prop}></le-prop-binding> `;
},
expectations: [
{
args: ['boundProp1'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-prop-binding')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp1');
},
html: {
root: `<le-prop-binding></le-prop-binding>`,
'le-prop-binding': `<div>\n [boundProp1]\n</div>`,
},
},
{
args: ['boundProp2'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-prop-binding')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp2');
},
html: {
root: `<le-prop-binding></le-prop-binding>`,
'le-prop-binding': `<div>\n [boundProp2]\n</div>`,
},
},
],
stableSelectors: ['le-prop-binding'],
};
},
'LitElement: willUpdate': () => {
return {
registerElements() {
class LEWillUpdate extends LitElement {
@property()
first?: string;
@property()
last?: string;
fullName = '';
override willUpdate(changedProperties: PropertyValues) {
if (
changedProperties.has('first') ||
changedProperties.has('last')
) {
this.fullName = `${this.first} ${this.last}`;
}
}
override render() {
// prettier-ignore
return html`<main>${this.fullName}</main>`;
}
}
customElements.define('le-will-update', LEWillUpdate);
},
render(first?: string, last?: string) {
return html`
<le-will-update .first=${first} .last=${last}></le-will-update>
`;
},
expectations: [
{
args: ['foo', 'bar'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-will-update')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).fullName, 'foo bar');
},
html: {
root: `<le-will-update></le-will-update>`,
'le-will-update': `<main>\n foo bar\n</main>`,
},
},
{
args: ['zot', ''],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-will-update')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).fullName, 'zot ');
},
html: {
root: `<le-will-update></le-will-update>`,
'le-will-update': `<main>\n zot\n</main>`,
},
},
],
stableSelectors: ['le-will-update'],
};
},
'LitElement: Reflected property binding': () => {
return {
registerElements() {
class LEReflectedBinding extends LitElement {
@property({reflect: true})
prop = 'default';
override render() {
return html` <div>[${this.prop}]</div> `;
}
}
customElements.define('le-reflected-binding', LEReflectedBinding);
},
render(prop: unknown) {
return html`
<le-reflected-binding .prop=${prop}></le-reflected-binding>
`;
},
expectations: [
{
args: ['boundProp1'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-reflected-binding')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp1');
},
html: {
root: `<le-reflected-binding prop="boundProp1"></le-reflected-binding>`,
'le-reflected-binding': `<div>\n [boundProp1]\n</div>`,
},
},
{
args: ['boundProp2'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-reflected-binding')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp2');
},
html: {
root: `<le-reflected-binding prop="boundProp2"></le-reflected-binding>`,
'le-reflected-binding': `<div>\n [boundProp2]\n</div>`,
},
},
],
stableSelectors: ['le-reflected-binding'],
// LitElement unconditionally sets reflecting properties to attributes
// on a property change, even if the attribute was already there
expectMutationsDuringUpgrade: true,
expectMutationsDuringHydration: true,
};
},
'LitElement: Attribute binding': () => {
return {
registerElements() {
class LEAttrBinding extends LitElement {
@property()
prop = 'default';
override render() {
return html` <div>[${this.prop}]</div> `;
}
}
customElements.define('le-attr-binding', LEAttrBinding);
},
render(prop: unknown) {
return html` <le-attr-binding prop=${prop} static></le-attr-binding> `;
},
expectations: [
{
args: ['boundProp1'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-attr-binding')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp1');
},
html: {
root: `<le-attr-binding prop="boundProp1" static></le-attr-binding>`,
'le-attr-binding': `<div>\n [boundProp1]\n</div>`,
},
},
{
args: ['boundProp2'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-attr-binding')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp2');
},
html: {
root: `<le-attr-binding prop="boundProp2" static></le-attr-binding>`,
'le-attr-binding': `<div>\n [boundProp2]\n</div>`,
},
},
],
stableSelectors: ['le-attr-binding'],
};
},
'LitElement: Static attribute deserializes': () => {
return {
registerElements() {
class LEStaticAttr extends LitElement {
@property()
prop = 'default';
override render() {
return html` <div>[${this.prop}]</div> `;
}
}
customElements.define('le-static-attr', LEStaticAttr);
},
render() {
return html` <le-static-attr prop="static" static></le-static-attr> `;
},
expectations: [
{
args: [],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-static-attr')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'static');
},
html: {
root: `<le-static-attr prop="static" static></le-static-attr>`,
'le-static-attr': `<div>\n [static]\n</div>`,
},
},
],
stableSelectors: ['le-attr-binding'],
};
},
'LitElement: TemplateResult->Node binding': () => {
return {
registerElements() {
class LENodeBinding extends LitElement {
@property()
template: unknown = 'default';
override render() {
return html` <div>${this.template}</div> `;
}
}
customElements.define('le-node-binding', LENodeBinding);
},
render(template: (s: string) => any) {
return html`
<le-node-binding .template=${template('shadow')}
>${template('light')}</le-node-binding
>
`;
},
expectations: [
{
args: [(s: string) => html` [template1: ${s}] `],
async check(_assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-node-binding')! as LitElement;
await el.updateComplete;
},
html: {
root: `<le-node-binding>\n [template1: light]\n</le-node-binding>`,
'le-node-binding': `<div>\n [template1: shadow]\n</div>`,
},
},
{
args: [(s: string) => html` [template2: ${s}] `],
async check(_assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-node-binding')! as LitElement;
await el.updateComplete;
},
html: {
root: `<le-node-binding>\n [template2: light]\n</le-node-binding>`,
'le-node-binding': `<div>\n [template2: shadow]\n</div>`,
},
},
],
stableSelectors: ['le-node-binding'],
};
},
'LitElement: renderLight': () => {
return {
registerElements() {
class LERenderLight extends LitElement implements RenderLightHost {
@property()
prop = 'default';
override render() {
return html` <div>[shadow:${this.prop}<slot></slot>]</div> `;
}
renderLight() {
return html` <div>[light:${this.prop}]</div> `;
}
}
customElements.define('le-render-light', LERenderLight);
},
render(prop: unknown) {
return html`
<le-render-light .prop=${prop}>${renderLight()}</le-render-light>
`;
},
expectations: [
{
args: ['boundProp1'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-render-light')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp1');
},
html: {
root: `<le-render-light>\n <div>\n [light:boundProp1]\n </div>\n</le-render-light>`,
'le-render-light': `<div>\n [shadow:boundProp1\n <slot></slot>\n ]\n</div>`,
},
},
{
args: ['boundProp2'],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el = dom.querySelector('le-render-light')! as LitElement;
await el.updateComplete;
assert.strictEqual((el as any).prop, 'boundProp2');
},
html: {
root: `<le-render-light>\n <div>\n [light:boundProp2]\n </div>\n</le-render-light>`,
'le-render-light': `<div>\n [shadow:boundProp2\n <slot></slot>\n ]\n</div>`,
},
},
],
stableSelectors: ['le-render-light'],
};
},
'LitElement: hydration ordering': () => {
const renderOrder: string[] = [];
return {
registerElements() {
// When defined in bottom-up order (as they will typically be based on
// import graph ordering), they should hydrate top-down
class LEOrder3 extends LitElement {
@property()
prop = 'from3';
override render() {
renderOrder.push(this.localName);
return html`le-order3:${this.prop}`;
}
}
customElements.define('le-order3', LEOrder3);
class LEOrder2 extends LitElement {
@property()
prop = 'from2';
override render() {
renderOrder.push(this.localName);
return html`le-order2:${this.prop}<le-order3
.prop=${this.prop}
></le-order3>`;
}
}
customElements.define('le-order2', LEOrder2);
class LEOrder1 extends LitElement {
@property()
prop = 'from1';
override render() {
renderOrder.push(this.localName);
return html`le-order1:${this.prop}<le-order2
.prop=${this.prop}
></le-order2>`;
}
}
customElements.define('le-order1', LEOrder1);
class LELight extends LitElement {
override render() {
renderOrder.push(this.localName);
return html`le-light`;
}
}
customElements.define('le-light', LELight);
},
render() {
return html`<le-order1><le-light></le-light></le-order1>`;
},
expectations: [
{
args: [],
async check(assert: Chai.Assert, dom: HTMLElement) {
const el1 = dom.querySelector('le-order1') as LitElement;
await el1.updateComplete;
const el2 = el1?.shadowRoot?.querySelector(
'le-order2'
) as LitElement;
await el2.updateComplete;
const el3 = el2?.shadowRoot?.querySelector(
'le-order3'
) as LitElement;
await el3.updateComplete;
assert.deepEqual(renderOrder, [
'le-order1',
'le-light',
'le-order2',
'le-order3',
]);
},
html: {
root: `<le-order1><le-light></le-light></le-order1>`,
'le-order1': {
root: `le-order1:from1\n<le-order2></le-order2>`,
'le-order2': {
root: `le-order2:from1\n<le-order3></le-order3>`,
'le-order3': {
root: 'le-order3:from1',
},
},
},
},
},
],
stableSelectors: ['le-order1'],
};
},
}; | the_stack |
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of as observableOf } from 'rxjs';
import { map, merge, mergeMap, scan } from 'rxjs/operators';
import { findIndex } from 'lodash';
import {
LOAD_MORE_NODE,
LOAD_MORE_ROOT_NODE,
TreeviewFlatNode,
TreeviewNode
} from './vocabulary-treeview-node.model';
import { VocabularyEntry } from '../../core/submission/vocabularies/models/vocabulary-entry.model';
import { VocabularyService } from '../../core/submission/vocabularies/vocabulary.service';
import { PageInfo } from '../../core/shared/page-info.model';
import { isEmpty, isNotEmpty } from '../empty.util';
import { VocabularyOptions } from '../../core/submission/vocabularies/models/vocabulary-options.model';
import {
getFirstSucceededRemoteDataPayload,
getFirstSucceededRemoteListPayload
} from '../../core/shared/operators';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { VocabularyEntryDetail } from '../../core/submission/vocabularies/models/vocabulary-entry-detail.model';
/**
* A service that provides methods to deal with vocabulary tree
*/
@Injectable()
export class VocabularyTreeviewService {
/**
* A map containing the current node showed by the tree
*/
nodeMap = new Map<string, TreeviewNode>();
/**
* A map containing all the node already created for building the tree
*/
storedNodeMap = new Map<string, TreeviewNode>();
/**
* An array containing all the node already created for building the tree
*/
storedNodes: TreeviewNode[] = [];
/**
* The {@link VocabularyOptions} object
*/
private vocabularyOptions: VocabularyOptions;
/**
* The vocabulary name
*/
private vocabularyName = '';
/**
* Contains the current tree data
*/
private dataChange = new BehaviorSubject<TreeviewNode[]>([]);
/**
* Array containing node'ids hierarchy
*/
private initValueHierarchy: string[] = [];
/**
* A boolean representing if any operation is pending
*/
private loading = new BehaviorSubject<boolean>(false);
/**
* The {@link PageInfo} object
*/
private pageInfo: PageInfo;
/**
* An observable to change the loading status
*/
private hideSearchingWhenUnsubscribed$ = new Observable(() => () => this.loading.next(false));
/**
* Initialize instance variables
*
* @param {VocabularyService} vocabularyService
*/
constructor(private vocabularyService: VocabularyService) {
}
/**
* Remove nodes saved from maps and array
*/
cleanTree() {
this.nodeMap = new Map<string, TreeviewNode>();
this.storedNodeMap = new Map<string, TreeviewNode>();
this.storedNodes = [];
this.initValueHierarchy = [];
this.dataChange.next([]);
}
/**
* Initialize the tree's nodes
*
* @param options The {@link VocabularyOptions} object
* @param pageInfo The {@link PageInfo} object
* @param initValueId The entry id of the node to mark as selected, if any
*/
initialize(options: VocabularyOptions, pageInfo: PageInfo, initValueId?: string): void {
this.loading.next(true);
this.vocabularyOptions = options;
this.vocabularyName = options.name;
this.pageInfo = pageInfo;
if (isNotEmpty(initValueId)) {
this.getNodeHierarchyById(initValueId)
.subscribe((hierarchy: string[]) => {
this.initValueHierarchy = hierarchy;
this.retrieveTopNodes(pageInfo, []);
});
} else {
this.retrieveTopNodes(pageInfo, []);
}
}
/**
* Returns array of the tree's nodes
*/
getData(): Observable<TreeviewNode[]> {
return this.dataChange;
}
/**
* Expand the root node whose children are not loaded
* @param node The root node
*/
loadMoreRoot(node: TreeviewFlatNode) {
const nodes = this.dataChange.value;
nodes.pop();
this.retrieveTopNodes(node.pageInfo, nodes);
}
/**
* Expand a node whose children are not loaded
* @param item
* @param onlyFirstTime
*/
loadMore(item: VocabularyEntryDetail, onlyFirstTime = false) {
if (!this.nodeMap.has(item.otherInformation.id)) {
return;
}
const parent: TreeviewNode = this.nodeMap.get(item.otherInformation.id)!;
const children = this.nodeMap.get(item.otherInformation.id)!.children || [];
children.pop();
this.getChildrenNodesByParent(item.otherInformation.id, parent.pageInfo).subscribe((list: PaginatedList<VocabularyEntryDetail>) => {
if (onlyFirstTime && parent.children!.length > 0) {
return;
}
const newNodes: TreeviewNode[] = list.page.map((entry) => this._generateNode(entry));
children.push(...newNodes);
if ((list.pageInfo.currentPage + 1) <= list.pageInfo.totalPages) {
// Update page info
const newPageInfo: PageInfo = Object.assign(new PageInfo(), list.pageInfo, {
currentPage: list.pageInfo.currentPage + 1
});
parent.updatePageInfo(newPageInfo);
// Need a new load more node
children.push(new TreeviewNode(LOAD_MORE_NODE, false, newPageInfo, item));
}
parent.childrenChange.next(children);
this.dataChange.next(this.dataChange.value);
});
}
/**
* Check if any operation is pending
*/
isLoading(): Observable<boolean> {
return this.loading;
}
/**
* Perform a search operation by query
*/
searchByQuery(query: string) {
this.loading.next(true);
if (isEmpty(this.storedNodes)) {
this.storedNodes = this.dataChange.value;
this.storedNodeMap = this.nodeMap;
}
this.nodeMap = new Map<string, TreeviewNode>();
this.dataChange.next([]);
this.vocabularyService.getVocabularyEntriesByValue(query, false, this.vocabularyOptions, new PageInfo()).pipe(
getFirstSucceededRemoteListPayload(),
mergeMap((result: VocabularyEntry[]) => (result.length > 0) ? result : observableOf(null)),
mergeMap((entry: VocabularyEntry) =>
this.vocabularyService.findEntryDetailById(entry.otherInformation.id, this.vocabularyName).pipe(
getFirstSucceededRemoteDataPayload()
)
),
mergeMap((entry: VocabularyEntryDetail) => this.getNodeHierarchy(entry)),
scan((acc: TreeviewNode[], value: TreeviewNode) => {
if (isEmpty(value) || findIndex(acc, (node) => node.item.otherInformation.id === value.item.otherInformation.id) !== -1) {
return acc;
} else {
return [...acc, value];
}
}, []),
merge(this.hideSearchingWhenUnsubscribed$)
).subscribe((nodes: TreeviewNode[]) => {
this.dataChange.next(nodes);
this.loading.next(false);
});
}
/**
* Reset tree state with the one before the search
*/
restoreNodes() {
this.loading.next(false);
this.dataChange.next(this.storedNodes);
this.nodeMap = this.storedNodeMap;
this.storedNodeMap = new Map<string, TreeviewNode>();
this.storedNodes = [];
}
/**
* Generate a {@link TreeviewNode} object from vocabulary entry
*
* @param entry The vocabulary entry detail
* @param isSearchNode A Boolean representing if given entry is the result of a search
* @param toStore A Boolean representing if the node created is to store or not
* @return TreeviewNode
*/
private _generateNode(entry: VocabularyEntryDetail, isSearchNode = false, toStore = true): TreeviewNode {
const entryId = entry.otherInformation.id;
if (this.nodeMap.has(entryId)) {
return this.nodeMap.get(entryId)!;
}
const hasChildren = entry.hasOtherInformation() && (entry.otherInformation as any)!.hasChildren === 'true';
const pageInfo: PageInfo = this.pageInfo;
const isInInitValueHierarchy = this.initValueHierarchy.includes(entryId);
const result = new TreeviewNode(
entry,
hasChildren,
pageInfo,
null,
isSearchNode,
isInInitValueHierarchy);
if (toStore) {
this.nodeMap.set(entryId, result);
}
return result;
}
/**
* Return the node Hierarchy by a given node's id
* @param id The node id
* @return Observable<string[]>
*/
private getNodeHierarchyById(id: string): Observable<string[]> {
return this.getById(id).pipe(
mergeMap((entry: VocabularyEntryDetail) => this.getNodeHierarchy(entry, [], false)),
map((node: TreeviewNode) => this.getNodeHierarchyIds(node))
);
}
/**
* Return the vocabulary entry's children
* @param parentId The node id
* @param pageInfo The {@link PageInfo} object
* @return Observable<PaginatedList<VocabularyEntryDetail>>
*/
private getChildrenNodesByParent(parentId: string, pageInfo: PageInfo): Observable<PaginatedList<VocabularyEntryDetail>> {
return this.vocabularyService.getEntryDetailChildren(parentId, this.vocabularyName, pageInfo).pipe(
getFirstSucceededRemoteDataPayload()
);
}
/**
* Return the vocabulary entry's parent
* @param entryId The entry id
*/
private getParentNode(entryId: string): Observable<VocabularyEntryDetail> {
return this.vocabularyService.getEntryDetailParent(entryId, this.vocabularyName).pipe(
getFirstSucceededRemoteDataPayload()
);
}
/**
* Return the vocabulary entry by id
* @param entryId The entry id
* @return Observable<VocabularyEntryDetail>
*/
private getById(entryId: string): Observable<VocabularyEntryDetail> {
return this.vocabularyService.findEntryDetailById(entryId, this.vocabularyName).pipe(
getFirstSucceededRemoteDataPayload()
);
}
/**
* Retrieve the top level vocabulary entries
* @param pageInfo The {@link PageInfo} object
* @param nodes The top level nodes already loaded, if any
*/
private retrieveTopNodes(pageInfo: PageInfo, nodes: TreeviewNode[]): void {
this.vocabularyService.searchTopEntries(this.vocabularyName, pageInfo).pipe(
getFirstSucceededRemoteDataPayload()
).subscribe((list: PaginatedList<VocabularyEntryDetail>) => {
this.vocabularyService.clearSearchTopRequests();
const newNodes: TreeviewNode[] = list.page.map((entry: VocabularyEntryDetail) => this._generateNode(entry));
nodes.push(...newNodes);
if ((list.pageInfo.currentPage + 1) <= list.pageInfo.totalPages) {
// Need a new load more node
const newPageInfo: PageInfo = Object.assign(new PageInfo(), list.pageInfo, {
currentPage: list.pageInfo.currentPage + 1
});
const loadMoreNode = new TreeviewNode(LOAD_MORE_ROOT_NODE, false, newPageInfo);
loadMoreNode.updatePageInfo(newPageInfo);
nodes.push(loadMoreNode);
}
this.loading.next(false);
// Notify the change.
this.dataChange.next(nodes);
});
}
/**
* Build and return the tree node hierarchy by a given vocabulary entry
*
* @param item The vocabulary entry
* @param children The vocabulary entry
* @param toStore A Boolean representing if the node created is to store or not
* @return Observable<string[]>
*/
private getNodeHierarchy(item: VocabularyEntryDetail, children?: TreeviewNode[], toStore = true): Observable<TreeviewNode> {
if (isEmpty(item)) {
return observableOf(null);
}
const node = this._generateNode(item, toStore, toStore);
if (isNotEmpty(children)) {
const newChildren = children
.filter((entry: TreeviewNode) => {
return findIndex(node.children, (nodeEntry) => nodeEntry.item.otherInformation.id === entry.item.otherInformation.id) === -1;
});
newChildren.forEach((entry: TreeviewNode) => {
entry.loadMoreParentItem = node.item;
});
node.children.push(...newChildren);
}
if (node.item.hasOtherInformation() && isNotEmpty(node.item.otherInformation.parent)) {
return this.getParentNode(node.item.otherInformation.id).pipe(
mergeMap((parentItem: VocabularyEntryDetail) => this.getNodeHierarchy(parentItem, [node], toStore))
);
} else {
return observableOf(node);
}
}
/**
* Build and return the node Hierarchy ids by a given node
*
* @param node The given node
* @param hierarchyIds The ids already present in the Hierarchy's array
* @return string[]
*/
private getNodeHierarchyIds(node: TreeviewNode, hierarchyIds: string[] = []): string[] {
if (!hierarchyIds.includes(node.item.otherInformation.id)) {
hierarchyIds.push(node.item.otherInformation.id);
}
if (isNotEmpty(node.children)) {
return this.getNodeHierarchyIds(node.children[0], hierarchyIds);
} else {
return hierarchyIds;
}
}
} | the_stack |
import { Commitment, PedersenParams } from '../commit/pedersen.js'
import { Group, hashPoints } from '../curves/group.js'
import { MultiMult, Relation } from '../curves/multimult.js'
import { PointAddProof, aggregatePointAdd, provePointAdd } from './pointAdd.js'
import { isOdd, rndRange } from '../bignum/big.js'
import { jsonMember, jsonObject, toJson } from 'typedjson'
@jsonObject
@toJson
export class ExpProof {
@jsonMember({ constructor: Group.Point, isRequired: true }) A: Group.Point
@jsonMember({ constructor: Group.Point, isRequired: true }) Tx: Group.Point
@jsonMember({ constructor: Group.Point, isRequired: true }) Ty: Group.Point
//response1
@jsonMember({ constructor: Group.Scalar }) alpha?: Group.Scalar
@jsonMember({ constructor: Group.Scalar }) beta1?: Group.Scalar
@jsonMember({ constructor: Group.Scalar }) beta2?: Group.Scalar
@jsonMember({ constructor: Group.Scalar }) beta3?: Group.Scalar
//response0
@jsonMember({ constructor: Group.Scalar }) z?: Group.Scalar
@jsonMember({ constructor: Group.Scalar }) z2?: Group.Scalar
@jsonMember({ constructor: PointAddProof }) proof?: PointAddProof
@jsonMember({ constructor: Group.Scalar }) r1?: Group.Scalar
@jsonMember({ constructor: Group.Scalar }) r2?: Group.Scalar
constructor(
A: Group.Point,
Tx: Group.Point,
Ty: Group.Point,
alpha?: Group.Scalar,
beta1?: Group.Scalar,
beta2?: Group.Scalar,
beta3?: Group.Scalar,
z?: Group.Scalar,
z2?: Group.Scalar,
proof?: PointAddProof,
r1?: Group.Scalar,
r2?: Group.Scalar
) {
this.A = A
this.Tx = Tx
this.Ty = Ty
this.alpha = alpha
this.beta1 = beta1
this.beta2 = beta2
this.beta3 = beta3
this.z = z
this.z2 = z2
this.proof = proof
this.r1 = r1
this.r2 = r2
}
eq(o: ExpProof): boolean {
const c0 = this.A.eq(o.A) && this.Tx.eq(o.Tx) && this.Ty.eq(o.Ty),
r0 =
(this.alpha && o.alpha ? this.alpha.eq(o.alpha) : false) &&
(this.beta1 && o.beta1 ? this.beta1.eq(o.beta1) : false) &&
(this.beta2 && o.beta2 ? this.beta2.eq(o.beta2) : false) &&
(this.beta3 && o.beta3 ? this.beta3.eq(o.beta3) : false),
r1 =
(this.z && o.z ? this.z.eq(o.z) : false) &&
(this.z2 && o.z2 ? this.z2.eq(o.z2) : false) &&
(this.proof && o.proof ? this.proof.eq(o.proof) : false) &&
(this.r1 && o.r1 ? this.r1.eq(o.r1) : false) &&
(this.r2 && o.r2 ? this.r2.eq(o.r2) : false)
return c0 && (r0 || r1)
}
}
function paddedBits(val: bigint, length: number): boolean[] {
const ret = []
for (let i = 0; i < length; i++) {
ret[i] = val % BigInt(2) == BigInt(1)
val >>= BigInt(1)
}
return ret
}
function generateIndices(indnum: number, limit: number): number[] {
const ret: number[] = []
for (let i = 0; i < limit; i++) {
ret[i] = i
}
// Algorithm P, Seminumerical algorithms, Knuth.
for (let i = 0; i < limit - 2; i++) {
const j = Number(rndRange(BigInt(i), BigInt(limit - 1))),
k = ret[i]
ret[i] = ret[j]
ret[j] = k
}
ret.slice(indnum)
return ret
}
/**
* ZK(s, r, rx, ry: sR = P + Q and Cs = sR + rS and Cx = Px G + rx H and Cy = Py G + ry H) [Q is optional]
* paramsNIST.g = R [Point R must be populated in the g field of paramsNIST]
*
* @param paramsNIST NIST params
* @param paramsWario Wario params
* @param s secret
* @param Cs: commitment to the secret with params NIST
* @param rx
* @param ry
* @param Px
* @param Py
* @param Q an optional public point
* @param secparam Soundness error
*/
export async function proveExp(
paramsNIST: PedersenParams,
paramsWario: PedersenParams,
s: bigint,
Cs: Commitment,
P: Group.Point,
Px: Commitment,
Py: Commitment,
secparam: number,
Q?: Group.Point
): Promise<Array<ExpProof>> {
const alpha = new Array<Group.Scalar>(secparam),
r = new Array<Group.Scalar>(secparam),
T = new Array<Group.Point>(secparam),
A = new Array<Group.Point>(secparam),
Tx = new Array<Commitment>(secparam),
Ty = new Array<Commitment>(secparam)
for (let i = 0; i < secparam; i++) {
alpha[i] = paramsNIST.c.randomScalar()
r[i] = paramsNIST.c.randomScalar()
T[i] = paramsNIST.g.mul(alpha[i])
A[i] = T[i].add(paramsNIST.h.mul(r[i]))
const coordT = T[i].toAffine()
if (!coordT) {
throw new Error('T[i] is at infinity')
}
const { x, y } = coordT
Tx[i] = paramsWario.commit(x)
Ty[i] = paramsWario.commit(y)
}
// Compute challenge c = H (Cx, Cy, A, Tx, Ty)
const arr = [Px.p, Py.p]
for (let i = 0; i < secparam; i++) {
arr.push(A[i])
arr.push(Tx[i].p)
arr.push(Ty[i].p)
}
let challenge = await hashPoints('SHA-256', arr)
const allProofs = new Array<ExpProof>(secparam)
let proof: ExpProof
for (let i = 0; i < secparam; i++) {
if (isOdd(challenge)) {
proof = new ExpProof(
A[i],
Tx[i].p,
Ty[i].p,
alpha[i],
r[i],
Tx[i].r,
Ty[i].r,
undefined,
undefined,
undefined,
undefined,
undefined
)
} else {
// z = alpha - s
const z = alpha[i].sub(paramsNIST.c.newScalar(s))
let T1 = paramsNIST.g.mul(z)
if (Q) {
T1 = T1.add(Q)
}
const coordT1 = T1.toAffine()
if (!coordT1) {
throw new Error('T1 is at infinity')
}
const { x, y } = coordT1,
T1x = paramsWario.commit(x),
T1y = paramsWario.commit(y),
// alpha R - s R = z R => T1 + P = T
pointAddProof = await provePointAdd(paramsWario, T1, P, T[i], T1x, T1y, Px, Py, Tx[i], Ty[i])
proof = new ExpProof(
A[i],
Tx[i].p,
Ty[i].p,
undefined,
undefined,
undefined,
undefined,
z,
r[i].sub(Cs.r),
pointAddProof,
T1x.r,
T1y.r
)
}
allProofs[i] = proof
challenge >>= BigInt(1)
}
return allProofs
}
export async function verifyExp(
paramsNIST: PedersenParams,
paramsWario: PedersenParams,
Clambda: Group.Point,
Px: Group.Point,
Py: Group.Point,
pi: Array<ExpProof>,
secparam: number,
Q?: Group.Point
): Promise<boolean> {
if (secparam > pi.length) {
throw new Error('security level not achieved')
}
const multiW = new MultiMult(paramsWario.c),
multiN = new MultiMult(paramsNIST.c)
multiW.addKnown(paramsWario.g)
multiW.addKnown(paramsWario.h)
multiN.addKnown(paramsNIST.g)
multiN.addKnown(paramsNIST.h)
multiN.addKnown(Clambda)
const arr = [Px, Py]
for (let i = 0; i < pi.length; i++) {
arr.push(pi[i].A)
arr.push(pi[i].Tx)
arr.push(pi[i].Ty)
}
const challenge = await hashPoints('SHA-256', arr),
indices = generateIndices(secparam, pi.length),
challengeBits = paddedBits(challenge, pi.length)
for (let j = 0; j < secparam; j++) {
const i = indices[j]
//const { commitment, response } = pi[i]
if (challengeBits[i]) {
const resp = {
alpha: pi[i].alpha!,
beta1: pi[i].beta1!,
beta2: pi[i].beta2!,
beta3: pi[i].beta3!,
},
T = paramsNIST.g.mul(resp.alpha),
relA = new Relation(paramsNIST.c)
relA.insertM(
[T, paramsNIST.h, pi[i].A.neg()],
[paramsNIST.c.newScalar(BigInt(1)), resp.beta1, paramsNIST.c.newScalar(BigInt(1))]
)
relA.drain(multiN)
const coordT = T.toAffine()
if (!coordT) {
throw new Error('T is at infinity')
}
const sx = paramsWario.c.newScalar(coordT.x),
sy = paramsWario.c.newScalar(coordT.y),
relTx = new Relation(paramsWario.c),
relTy = new Relation(paramsWario.c)
relTx.insertM(
[paramsWario.g, paramsWario.h, pi[i].Tx.neg()],
[sx, resp.beta2, paramsWario.c.newScalar(BigInt(1))]
)
relTy.insertM(
[paramsWario.g, paramsWario.h, pi[i].Ty.neg()],
[sy, resp.beta3, paramsWario.c.newScalar(BigInt(1))]
)
relTx.drain(multiW)
relTy.drain(multiW)
} else {
const resp = {
z: pi[i].z!,
z2: pi[i].z2!,
proof: pi[i].proof!,
r1: pi[i].r1!,
r2: pi[i].r2!,
}
let T1 = paramsNIST.g.mul(resp.z)
const relA = new Relation(paramsNIST.c)
relA.insertM(
[T1, Clambda, pi[i].A.neg(), paramsNIST.h],
[
paramsNIST.c.newScalar(BigInt(1)),
paramsNIST.c.newScalar(BigInt(1)),
paramsNIST.c.newScalar(BigInt(1)),
resp.z2,
]
)
relA.drain(multiN)
if (Q) {
T1 = T1.add(Q)
}
const coordT1 = T1.toAffine()
if (!coordT1) {
throw new Error('T1 is at infinity')
}
const sx = paramsWario.c.newScalar(coordT1.x),
sy = paramsWario.c.newScalar(coordT1.y),
T1x = paramsWario.g.dblmul(sx, paramsWario.h, resp.r1),
T1y = paramsWario.g.dblmul(sy, paramsWario.h, resp.r2)
if (!(await aggregatePointAdd(paramsWario, T1x, T1y, Px, Py, pi[i].Tx, pi[i].Ty, resp.proof, multiW))) {
return false
}
}
}
return multiW.evaluate().isIdentity() && multiN.evaluate().isIdentity()
} | the_stack |
import Jasmine = require('jasmine')
const jasmine = new Jasmine({})
jasmine.randomizeTests(false)
import { Crypto } from '@peculiar/webcrypto'
(global as any).crypto = new Crypto()
import fetch from 'node-fetch'
import * as OracleSdk from '@keydonix/uniswap-oracle-sdk'
import { keccak256 } from '@zoltu/ethereum-crypto'
import { rlpDecode, rlpEncode } from '@zoltu/rlp-encoder'
import { createMnemonicRpc, SignerFetchRpc } from './rpc-factories'
import { deployAllTheThings } from './deploy-contract'
import { ethGetBlockByNumber } from './adapters'
import { unsignedIntegerToUint8Array, isUint8Array, uint8ArrayToUnsignedInteger } from './utils'
import { resetUniswapAndAccount, mineBlocks, swap0For1, swap1For0, setPrice } from './uniswap-helpers'
import { PriceEmitter } from './generated/price-emitter'
const jsonRpcEndpoint = 'http://localhost:1237'
const gasPrice = 10n*9n
let rpc: SignerFetchRpc
let rpcSignerAddress: bigint
let contracts: ReturnType<typeof deployAllTheThings> extends Promise<infer T> ? T : never
beforeAll(async () => {
rpc = await createMnemonicRpc(jsonRpcEndpoint, gasPrice)
rpcSignerAddress = await rpc.addressProvider()
contracts = await deployAllTheThings(rpc)
})
it('block verifier', async () => {
// get the RLP encoded latest block
const blockNumber = await rpc.getBlockNumber()
const block = await rpc.getBlockByNumber(false, blockNumber)
// use the SDK so we don't have to RLP encode the block ourselves
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
// validate in TypeScript
const rlpBlockHash = await keccak256.hash(proof.block)
expect(rlpBlockHash).toEqual(block!.hash!)
// validate in Solidity
const { stateRoot, blockTimestamp } = await contracts.blockVerifierWrapper.extractStateRootAndTimestamp_(proof.block)
expect(stateRoot).toEqual(block!.stateRoot)
expect(blockTimestamp).toEqual(BigInt(block!.timestamp.getTime() / 1000))
})
it('account proof', async () => {
// get a proof from the latest block
const blockNumber = await rpc.getBlockNumber()
const block = await rpc.getBlockByNumber(false, blockNumber)
const proof = await rpc.getProof(contracts.token0.address, [2n], blockNumber)
const path = await keccak256.hash(unsignedIntegerToUint8Array(contracts.token0.address, 20))
const accountProofNodesRlp = rlpEncode(proof.accountProof.map(rlpDecode))
// extract the account proof data with solidity
const accountDetailsRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(block!.stateRoot, path, accountProofNodesRlp)
const decodedAccountDetails = rlpDecode(accountDetailsRlp)
if (!Array.isArray(decodedAccountDetails)) throw new Error(`decoded account details is not an array of items as expected`)
const accountDetails = decodedAccountDetails.filter(isUint8Array).map(uint8ArrayToUnsignedInteger)
expect(accountDetails[0]).toEqual(proof.nonce)
expect(accountDetails[1]).toEqual(proof.balance)
expect(accountDetails[2]).toEqual(proof.storageHash)
expect(accountDetails[3]).toEqual(proof.codeHash)
})
it('storage proof', async () => {
// ensure there is a token supply
if (await contracts.token0.totalSupply_() === 0n) await contracts.token0.mint(100n)
// get a proof from the latest block
const blockNumber = await rpc.getBlockNumber()
const storageSlot = 2n
const path = await keccak256.hash(unsignedIntegerToUint8Array(storageSlot, 32))
const proof = await rpc.getProof(contracts.token0.address, [2n], blockNumber)
const totalSupplyProofNodesRlp = rlpEncode(proof.storageProof[0].proof.map(rlpDecode))
// extract the leaf node in Solidity
const storedDataRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(proof.storageHash, path, totalSupplyProofNodesRlp)
const storedDataBytes = rlpDecode(storedDataRlp)
if (!(storedDataBytes instanceof Uint8Array)) throw new Error(`decoded data was not an RLP item`)
const storedData = uint8ArrayToUnsignedInteger(storedDataBytes)
expect(storedData).toEqual(await contracts.token0.totalSupply_())
})
it('block to storage', async () => {
// ensure there is a token supply
if (await contracts.token0.totalSupply_() === 0n) await contracts.token0.mint(100n)
// get the state root from latest block
const blockNumber = await rpc.getBlockNumber()
// use the SDK so we don't have to RLP encode the block ourselves
const sdkProof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const { stateRoot } = await contracts.blockVerifierWrapper.extractStateRootAndTimestamp_(sdkProof.block)
// get the account storage root from proof
const proof = await rpc.getProof(contracts.token0.address, [2n], blockNumber)
const accountPath = await keccak256.hash(unsignedIntegerToUint8Array(contracts.token0.address, 20))
const accountProofNodesRlp = rlpEncode(proof.accountProof.map(rlpDecode))
const accountDetailsRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(stateRoot, accountPath, accountProofNodesRlp)
const decodedAccountDetails = rlpDecode(accountDetailsRlp)
if (!Array.isArray(decodedAccountDetails)) throw new Error(`decoded account details is not an array of items as expected`)
const accountDetails = decodedAccountDetails.filter(isUint8Array).map(uint8ArrayToUnsignedInteger)
const storageRoot = accountDetails[2]
// extract the storage value from proof
const storageSlot = 2n
const storagePath = await keccak256.hash(unsignedIntegerToUint8Array(storageSlot, 32))
const totalSupplyProofNodesRlp = rlpEncode(proof.storageProof[0].proof.map(rlpDecode))
const storedDataRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(storageRoot, storagePath, totalSupplyProofNodesRlp)
// verify the stored data
const storedDataBytes = rlpDecode(storedDataRlp)
if (!(storedDataBytes instanceof Uint8Array)) throw new Error(`decoded data was not an RLP item`)
const storedData = uint8ArrayToUnsignedInteger(storedDataBytes)
expect(storedData).toEqual(await contracts.token0.totalSupply_())
})
it('oracle proof rlp encoding', async () => {
// setup
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await contracts.uniswapExchange.sync()
const latestBlockTimestamp = (await rpc.getBlockByNumber(false, 'latest'))!.timestamp.getTime() / 1000
await fetch(`http://localhost:12340/${latestBlockTimestamp + 10}`)
await swap0For1(contracts.uniswapExchange, contracts.token0, rpcSignerAddress, 10n * 10n**18n)
await fetch(`http://localhost:12340/${latestBlockTimestamp + 20}`)
await swap1For0(contracts.uniswapExchange, contracts.token1, rpcSignerAddress, 10n * 10n**18n)
// ensure there is a token supply
if (await contracts.token0.totalSupply_() === 0n) await contracts.token0.mint(100n)
const blockNumber = await rpc.getBlockNumber()
const block = await rpc.getBlockByNumber(false, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const accountPath = await keccak256.hash(unsignedIntegerToUint8Array(contracts.uniswapExchange.address, 20))
const accountRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(block!.stateRoot, accountPath, proof.accountProofNodesRlp)
const accountTuple = (rlpDecode(accountRlp) as Uint8Array[]).map(uint8ArrayToUnsignedInteger)
expect(accountTuple[0]).toEqual(await rpc.getTransactionCount(contracts.uniswapExchange.address))
expect(accountTuple[1]).toEqual(await rpc.getBalance(contracts.uniswapExchange.address))
const reservePath = await keccak256.hash(unsignedIntegerToUint8Array(8n, 32))
const reserveRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(accountTuple[2], reservePath, proof.reserveAndTimestampProofNodesRlp)
const decodedReserveRlp = rlpDecode(reserveRlp)
if (!(decodedReserveRlp instanceof Uint8Array)) throw new Error(`decoded reserve and timestamp is not an RLP item as expected`)
const reserveAndTimestamp = uint8ArrayToUnsignedInteger(decodedReserveRlp)
const timestamp = reserveAndTimestamp >> (112n + 112n)
const reserve1 = (reserveAndTimestamp >> 112n) & (2n**112n - 1n)
const reserve0 = reserveAndTimestamp & (2n**112n - 1n)
expect(timestamp).toEqual(BigInt(block!.timestamp.getTime() / 1000))
expect(reserve0).toEqual((await contracts.uniswapExchange.getReserves_())._reserve0)
expect(reserve1).toEqual((await contracts.uniswapExchange.getReserves_())._reserve1)
const token1AccumulatorPath = await keccak256.hash(unsignedIntegerToUint8Array(10n, 32))
const token1AccumulatorRlp = await contracts.merklePatriciaVerifierWrapper.getValueFromProof_(accountTuple[2], token1AccumulatorPath, proof.priceAccumulatorProofNodesRlp)
const decodedToken1Accumulator = rlpDecode(token1AccumulatorRlp)
if (!(decodedToken1Accumulator instanceof Uint8Array)) throw new Error(`decoded token1 accumulator is not an RLP item as expected`)
const token1Accumulator = uint8ArrayToUnsignedInteger(decodedToken1Accumulator)
expect(token1Accumulator).toEqual(await contracts.uniswapExchange.price1CumulativeLast_())
})
it('timestamp', async () => {
const latestBlockTimestamp = (await rpc.getBlockByNumber(false, 'latest'))!.timestamp.getTime() / 1000
await fetch(`http://localhost:12340/${latestBlockTimestamp + 10}`)
await rpc.sendEth(rpcSignerAddress, 0n)
const firstBlock = await rpc.getBlockByNumber(false, 'latest')
expect(firstBlock!.timestamp).toEqual(new Date((latestBlockTimestamp + 10) * 1000))
await fetch(`http://localhost:12340/${latestBlockTimestamp + 100}`)
await rpc.sendEth(rpcSignerAddress, 0n)
const secondBlock = await rpc.getBlockByNumber(false, 'latest')
expect(secondBlock!.timestamp.getTime()).toEqual((latestBlockTimestamp + 100) * 1000)
})
// TODO: deal with Geth's timestamp issue: https://github.com/ethereum/go-ethereum/issues/21184
describe('oracle vs contract price check', () => {
const testVectorsRaw = [
[1n, 1n],
[1n, 2n],
[2n, 1n],
] as const
const testVectors = testVectorsRaw.map(pair => ({ denominationTokenMultiplier: pair[0], nonDenominationTokenMultiplier: pair[1] }))
for (const { denominationTokenMultiplier, nonDenominationTokenMultiplier } of testVectors) {
it(`expect price ${Number(denominationTokenMultiplier)/Number(nonDenominationTokenMultiplier)}`, async () => {
// setup
const denominationToken = contracts.token0
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, denominationTokenMultiplier, nonDenominationTokenMultiplier)
const blockNumber = await rpc.getBlockNumber()
await mineBlocks(rpc, 10)
await contracts.uniswapExchange.sync()
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, denominationToken.address, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, denominationToken.address, blockNumber)
const { price: contractPrice } = await contracts.priceEmitter.emitPrice_(contracts.uniswapExchange.address, denominationToken.address, 12n, 12n, proof)
expect(sdkPrice).toEqual(denominationTokenMultiplier * 2n**112n / nonDenominationTokenMultiplier)
expect(contractPrice).toEqual(sdkPrice)
})
}
})
it('one trade, sync before and after', async () => {
// setup
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await swap0For1(contracts.uniswapExchange, contracts.token0, rpcSignerAddress, 10n**18n)
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 2n, 1n)
await contracts.uniswapExchange.sync()
const blockNumber = await rpc.getBlockNumber()
await mineBlocks(rpc, 10)
await contracts.uniswapExchange.sync()
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const { price: contractPrice } = await contracts.priceEmitter.emitPrice_(contracts.uniswapExchange.address, contracts.token0.address, 12n, 12n, proof)
expect(contractPrice).toEqual(sdkPrice)
})
it('no trades, no sync', async () => {
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await mineBlocks(rpc, 1)
const blockNumber = await rpc.getBlockNumber()
await mineBlocks(rpc, 10)
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const { price: contractPrice } = await contracts.priceEmitter.emitPrice_(contracts.uniswapExchange.address, contracts.token0.address, 11n, 11n, proof)
expect(contractPrice).toEqual(2n**112n)
expect(sdkPrice).toEqual(2n**112n)
})
it('no trades, sync before', async () => {
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await contracts.uniswapExchange.sync()
const blockNumber = await rpc.getBlockNumber()
await mineBlocks(rpc, 10)
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const { price: contractPrice } = await contracts.priceEmitter.emitPrice_(contracts.uniswapExchange.address, contracts.token0.address, 11n, 11n, proof)
expect(contractPrice).toEqual(2n**112n)
expect(sdkPrice).toEqual(2n**112n)
})
it('no trades, sync after', async () => {
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await mineBlocks(rpc, 1)
const blockNumber = await rpc.getBlockNumber()
await mineBlocks(rpc, 9)
await contracts.uniswapExchange.sync()
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const { price: contractPrice } = await contracts.priceEmitter.emitPrice_(contracts.uniswapExchange.address, contracts.token0.address, 11n, 11n, proof)
expect(contractPrice).toEqual(2n**112n)
expect(sdkPrice).toEqual(2n**112n)
})
it('no trades, sync before/after', async () => {
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await contracts.uniswapExchange.sync()
const blockNumber = await rpc.getBlockNumber()
await mineBlocks(rpc, 9)
await contracts.uniswapExchange.sync()
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
const { price: contractPrice } = await contracts.priceEmitter.emitPrice_(contracts.uniswapExchange.address, contracts.token0.address, 11n, 11n, proof)
expect(contractPrice).toEqual(2n**112n)
expect(sdkPrice).toEqual(2n**112n)
})
it('one trade', async () => {
await resetUniswapAndAccount(contracts.uniswapExchange, contracts.token0, contracts.token1, rpcSignerAddress, 1n, 1n)
await contracts.uniswapExchange.sync() // First block with 1:1 price starting
const blockNumber = await rpc.getBlockNumber() // Grab the first block after the sync is called, new blocks will be at 1:1 ratio from here
await setPrice(contracts.uniswapExchange, contracts.token0, contracts.token1, 2n, 1n) // So far two blocks at 1:1 price (one transfer, one sync), blocks after this will record 2:1 price
await contracts.uniswapExchange.sync() // First block with 2:1 price
const proof = await OracleSdk.getProof(rpc.getStorageAt, rpc.getProof, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
// emitPrice below takes another block, so we have another block at 2:1 price. That's 2x 1:1 and 2x 2:1
const events = await contracts.priceEmitter.emitPrice(contracts.uniswapExchange.address, contracts.token0.address, 4n, 4n, proof)
const contractPrice = (events.find(x => x.name === 'Price') as PriceEmitter.Price).parameters.price
const sdkPrice = await OracleSdk.getPrice(rpc.getStorageAt, ethGetBlockByNumber.bind(undefined, rpc), contracts.uniswapExchange.address, contracts.token0.address, blockNumber)
expect(sdkPrice).toBe(2n**112n * 3n / 2n, `sdk price wrong: ~${Number(sdkPrice / 2n**80n) / 2**32}`)
expect(contractPrice).toBe(2n**112n * 3n / 2n, `contract price wrong: ~${Number(contractPrice / 2n**80n) / 2**32}`)
})
jasmine.execute() | the_stack |
import { Subject } from "rxjs";
import { Alignment } from "../../../viewer/enums/Alignment";
import { PolygonGeometry } from "../geometry/PolygonGeometry";
import { VertexGeometry } from "../geometry/VertexGeometry";
import { OutlineTagOptions } from "../interfaces/OutlineTagOptions";
import { Tag } from "./Tag";
import { TagDomain } from "./TagDomain";
import { TagEventType } from "./events/TagEventType";
import { TagStateEvent } from "./events/TagStateEvent";
/**
* @class OutlineTag
*
* @classdesc Tag holding properties for visualizing a geometry outline.
*
* @example
* ```js
* var geometry = new RectGeometry([0.3, 0.3, 0.5, 0.4]);
* var tag = new OutlineTag(
* "id-1",
* geometry
* { editable: true, lineColor: 0xff0000 });
*
* tagComponent.add([tag]);
* ```
*/
export class OutlineTag extends Tag {
protected _geometry: VertexGeometry;
private _domain: TagDomain;
private _editable: boolean;
private _icon: string;
private _iconFloat: Alignment;
private _iconIndex: number;
private _indicateVertices: boolean;
private _lineColor: number;
private _lineOpacity: number;
private _lineWidth: number;
private _fillColor: number;
private _fillOpacity: number;
private _text: string;
private _textColor: number;
private _click$: Subject<OutlineTag>;
/**
* Create an outline tag.
*
* @override
* @constructor
* @param {string} id - Unique identifier of the tag.
* @param {VertexGeometry} geometry - Geometry defining vertices of tag.
* @param {OutlineTagOptions} options - Options defining the visual appearance and
* behavior of the outline tag.
*/
constructor(id: string, geometry: VertexGeometry, options?: OutlineTagOptions) {
super(id, geometry);
options = !!options ? options : {};
const domain: TagDomain = options.domain != null && geometry instanceof PolygonGeometry ?
options.domain : TagDomain.TwoDimensional;
const twoDimensionalPolygon: boolean = this._twoDimensionalPolygon(domain, geometry);
this._domain = domain;
this._editable = options.editable == null || twoDimensionalPolygon ? false : options.editable;
this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
this._icon = options.icon === undefined ? null : options.icon;
this._iconFloat = options.iconFloat == null ? Alignment.Center : options.iconFloat;
this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
this._text = options.text === undefined ? null : options.text;
this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
this._click$ = new Subject<OutlineTag>();
this._click$
.subscribe(
(): void => {
const type: TagEventType = "click";
const event: TagStateEvent = {
target: this,
type,
};
this.fire(type, event);
});
}
/**
* Click observable.
*
* @description An observable emitting the tag when the icon of the
* tag has been clicked.
*
* @returns {Observable<Tag>}
*/
public get click$(): Subject<OutlineTag> {
return this._click$;
}
/**
* Get domain property.
*
* @description Readonly property that can only be set in constructor.
*
* @returns Value indicating the domain of the tag.
*/
public get domain(): TagDomain {
return this._domain;
}
/**
* Get editable property.
* @returns {boolean} Value indicating if tag is editable.
*/
public get editable(): boolean {
return this._editable;
}
/**
* Set editable property.
* @param {boolean}
*
* @fires changed
*/
public set editable(value: boolean) {
if (this._twoDimensionalPolygon(this._domain, this._geometry)) {
return;
}
this._editable = value;
this._notifyChanged$.next(this);
}
/**
* Get fill color property.
* @returns {number}
*/
public get fillColor(): number {
return this._fillColor;
}
/**
* Set fill color property.
* @param {number}
*
* @fires changed
*/
public set fillColor(value: number) {
this._fillColor = value;
this._notifyChanged$.next(this);
}
/**
* Get fill opacity property.
* @returns {number}
*/
public get fillOpacity(): number {
return this._fillOpacity;
}
/**
* Set fill opacity property.
* @param {number}
*
* @fires changed
*/
public set fillOpacity(value: number) {
this._fillOpacity = value;
this._notifyChanged$.next(this);
}
/** @inheritdoc */
public get geometry(): VertexGeometry {
return this._geometry;
}
/**
* Get icon property.
* @returns {string}
*/
public get icon(): string {
return this._icon;
}
/**
* Set icon property.
* @param {string}
*
* @fires changed
*/
public set icon(value: string) {
this._icon = value;
this._notifyChanged$.next(this);
}
/**
* Get icon float property.
* @returns {Alignment}
*/
public get iconFloat(): Alignment {
return this._iconFloat;
}
/**
* Set icon float property.
* @param {Alignment}
*
* @fires changed
*/
public set iconFloat(value: Alignment) {
this._iconFloat = value;
this._notifyChanged$.next(this);
}
/**
* Get icon index property.
* @returns {number}
*/
public get iconIndex(): number {
return this._iconIndex;
}
/**
* Set icon index property.
* @param {number}
*
* @fires changed
*/
public set iconIndex(value: number) {
this._iconIndex = value;
this._notifyChanged$.next(this);
}
/**
* Get indicate vertices property.
* @returns {boolean} Value indicating if vertices should be indicated
* when tag is editable.
*/
public get indicateVertices(): boolean {
return this._indicateVertices;
}
/**
* Set indicate vertices property.
* @param {boolean}
*
* @fires changed
*/
public set indicateVertices(value: boolean) {
this._indicateVertices = value;
this._notifyChanged$.next(this);
}
/**
* Get line color property.
* @returns {number}
*/
public get lineColor(): number {
return this._lineColor;
}
/**
* Set line color property.
* @param {number}
*
* @fires changed
*/
public set lineColor(value: number) {
this._lineColor = value;
this._notifyChanged$.next(this);
}
/**
* Get line opacity property.
* @returns {number}
*/
public get lineOpacity(): number {
return this._lineOpacity;
}
/**
* Set line opacity property.
* @param {number}
*
* @fires changed
*/
public set lineOpacity(value: number) {
this._lineOpacity = value;
this._notifyChanged$.next(this);
}
/**
* Get line width property.
* @returns {number}
*/
public get lineWidth(): number {
return this._lineWidth;
}
/**
* Set line width property.
* @param {number}
*
* @fires changed
*/
public set lineWidth(value: number) {
this._lineWidth = value;
this._notifyChanged$.next(this);
}
/**
* Get text property.
* @returns {string}
*/
public get text(): string {
return this._text;
}
/**
* Set text property.
* @param {string}
*
* @fires changed
*/
public set text(value: string) {
this._text = value;
this._notifyChanged$.next(this);
}
/**
* Get text color property.
* @returns {number}
*/
public get textColor(): number {
return this._textColor;
}
/**
* Set text color property.
* @param {number}
*
* @fires changed
*/
public set textColor(value: number) {
this._textColor = value;
this._notifyChanged$.next(this);
}
public fire(
type: TagStateEvent["type"],
event: TagStateEvent)
: void;
/** @ignore */
public fire(
type: TagEventType,
event: TagStateEvent)
: void;
public fire(
type: TagEventType,
event: TagStateEvent)
: void {
super.fire(type, event);
}
public off(
type: TagStateEvent["type"],
handler: (event: TagStateEvent) => void)
: void;
/** @ignore */
public off(
type: TagEventType,
handler: (event: TagStateEvent) => void)
: void;
public off(
type: TagEventType,
handler: (event: TagStateEvent) => void)
: void {
super.off(type, handler);
}
/**
* Event fired when the icon of the outline tag is clicked.
*
* @event click
* @example
* ```js
* var tag = new OutlineTag({ // tag options });
* // Set an event listener
* tag.on('click', function() {
* console.log("A click event has occurred.");
* });
* ```
*/
public on(
type: "click",
handler: (event: TagStateEvent) => void)
: void;
/**
* Event fired when the geometry of the tag has changed.
*
* @event geometry
* @example
* ```js
* var tag = new OutlineTag({ // tag options });
* // Set an event listener
* tag.on('geometry', function() {
* console.log("A geometry event has occurred.");
* });
* ```
*/
public on(
type: "geometry",
handler: (event: TagStateEvent) => void)
: void;
/**
* Event fired when a tag has been updated.
*
* @event tag
* @example
* ```js
* var tag = new OutlineTag({ // tag options });
* // Set an event listener
* tag.on('tag', function() {
* console.log("A tag event has occurred.");
* });
* ```
*/
public on(
type: "tag",
handler: (event: TagStateEvent) => void)
: void;
public on(
type: TagEventType,
handler: (event: TagStateEvent) => void)
: void {
super.on(type, handler);
}
/**
* Set options for tag.
*
* @description Sets all the option properties provided and keeps
* the rest of the values as is.
*
* @param {OutlineTagOptions} options - Outline tag options
*
* @fires changed
*/
public setOptions(options: OutlineTagOptions): void {
const twoDimensionalPolygon: boolean = this._twoDimensionalPolygon(this._domain, this._geometry);
this._editable = twoDimensionalPolygon || options.editable == null ? this._editable : options.editable;
this._icon = options.icon === undefined ? this._icon : options.icon;
this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
this._text = options.text === undefined ? this._text : options.text;
this._textColor = options.textColor == null ? this._textColor : options.textColor;
this._notifyChanged$.next(this);
}
private _twoDimensionalPolygon(domain: TagDomain, geometry: VertexGeometry): boolean {
return domain !== TagDomain.ThreeDimensional && geometry instanceof PolygonGeometry;
}
} | the_stack |
import { EncodeOptions } from '../shared/meta';
import type WorkerBridge from 'client/lazy-app/worker-bridge';
import { h, Component } from 'preact';
import {
inputFieldCheckedAsNumber,
inputFieldValueAsNumber,
preventDefault,
} from 'client/lazy-app/util';
import * as style from 'client/lazy-app/Compress/Options/style.css';
import linkState from 'linkstate';
import Range from 'client/lazy-app/Compress/Options/Range';
import Checkbox from 'client/lazy-app/Compress/Options/Checkbox';
import Expander from 'client/lazy-app/Compress/Options/Expander';
import Select from 'client/lazy-app/Compress/Options/Select';
import Revealer from 'client/lazy-app/Compress/Options/Revealer';
export const encode = (
signal: AbortSignal,
workerBridge: WorkerBridge,
imageData: ImageData,
options: EncodeOptions,
) => workerBridge.webpEncode(signal, imageData, options);
const enum WebPImageHint {
WEBP_HINT_DEFAULT, // default preset.
WEBP_HINT_PICTURE, // digital picture, like portrait, inner shot
WEBP_HINT_PHOTO, // outdoor photograph, with natural lighting
WEBP_HINT_GRAPH, // Discrete tone image (graph, map-tile etc).
}
interface Props {
options: EncodeOptions;
onChange(newOptions: EncodeOptions): void;
}
interface State {
showAdvanced: boolean;
}
// From kLosslessPresets in config_enc.c
// The format is [method, quality].
const losslessPresets: [number, number][] = [
[0, 0],
[1, 20],
[2, 25],
[3, 30],
[3, 50],
[4, 50],
[4, 75],
[4, 90],
[5, 90],
[6, 100],
];
const losslessPresetDefault = 6;
function determineLosslessQuality(quality: number, method: number): number {
const index = losslessPresets.findIndex(
([presetMethod, presetQuality]) =>
presetMethod === method && presetQuality === quality,
);
if (index !== -1) return index;
// Quality doesn't match one of the presets.
// This can happen when toggling 'lossless'.
return losslessPresetDefault;
}
export class Options extends Component<Props, State> {
state: State = {
showAdvanced: false,
};
onChange = (event: Event) => {
const form = (event.currentTarget as HTMLInputElement).closest(
'form',
) as HTMLFormElement;
const lossless = inputFieldCheckedAsNumber(form.lossless);
const { options } = this.props;
const losslessPresetValue = inputFieldValueAsNumber(
form.lossless_preset,
determineLosslessQuality(options.quality, options.method),
);
const newOptions: EncodeOptions = {
// Copy over options the form doesn't care about, eg emulate_jpeg_size
...options,
// And now stuff from the form:
lossless,
// Special-cased inputs:
// In lossless mode, the quality is derived from the preset.
quality: lossless
? losslessPresets[losslessPresetValue][1]
: inputFieldValueAsNumber(form.quality, options.quality),
// In lossless mode, the method is derived from the preset.
method: lossless
? losslessPresets[losslessPresetValue][0]
: inputFieldValueAsNumber(form.method_input, options.method),
image_hint: inputFieldCheckedAsNumber(form.image_hint, options.image_hint)
? WebPImageHint.WEBP_HINT_GRAPH
: WebPImageHint.WEBP_HINT_DEFAULT,
// .checked
exact: inputFieldCheckedAsNumber(form.exact, options.exact),
alpha_compression: inputFieldCheckedAsNumber(
form.alpha_compression,
options.alpha_compression,
),
autofilter: inputFieldCheckedAsNumber(
form.autofilter,
options.autofilter,
),
filter_type: inputFieldCheckedAsNumber(
form.filter_type,
options.filter_type,
),
use_sharp_yuv: inputFieldCheckedAsNumber(
form.use_sharp_yuv,
options.use_sharp_yuv,
),
// .value
near_lossless:
100 -
inputFieldValueAsNumber(
form.near_lossless,
100 - options.near_lossless,
),
alpha_quality: inputFieldValueAsNumber(
form.alpha_quality,
options.alpha_quality,
),
alpha_filtering: inputFieldValueAsNumber(
form.alpha_filtering,
options.alpha_filtering,
),
sns_strength: inputFieldValueAsNumber(
form.sns_strength,
options.sns_strength,
),
filter_strength: inputFieldValueAsNumber(
form.filter_strength,
options.filter_strength,
),
filter_sharpness:
7 -
inputFieldValueAsNumber(
form.filter_sharpness,
7 - options.filter_sharpness,
),
pass: inputFieldValueAsNumber(form.pass, options.pass),
preprocessing: inputFieldValueAsNumber(
form.preprocessing,
options.preprocessing,
),
segments: inputFieldValueAsNumber(form.segments, options.segments),
partitions: inputFieldValueAsNumber(form.partitions, options.partitions),
};
this.props.onChange(newOptions);
};
private _losslessSpecificOptions(options: EncodeOptions) {
return (
<div key="lossless">
<div class={style.optionOneCell}>
<Range
name="lossless_preset"
min="0"
max="9"
value={determineLosslessQuality(options.quality, options.method)}
onInput={this.onChange}
>
Effort:
</Range>
</div>
<div class={style.optionOneCell}>
<Range
name="near_lossless"
min="0"
max="100"
value={'' + (100 - options.near_lossless)}
onInput={this.onChange}
>
Slight loss:
</Range>
</div>
<label class={style.optionToggle}>
Discrete tone image
{/*
Although there are 3 different kinds of image hint, webp only
seems to do something with the 'graph' type, and I don't really
understand what it does.
*/}
<Checkbox
name="image_hint"
checked={options.image_hint === WebPImageHint.WEBP_HINT_GRAPH}
onChange={this.onChange}
/>
</label>
</div>
);
}
private _lossySpecificOptions(options: EncodeOptions) {
const { showAdvanced } = this.state;
return (
<div key="lossy">
<div class={style.optionOneCell}>
<Range
name="method_input"
min="0"
max="6"
value={options.method}
onInput={this.onChange}
>
Effort:
</Range>
</div>
<div class={style.optionOneCell}>
<Range
name="quality"
min="0"
max="100"
step="0.1"
value={options.quality}
onInput={this.onChange}
>
Quality:
</Range>
</div>
<label class={style.optionReveal}>
<Revealer
checked={showAdvanced}
onChange={linkState(this, 'showAdvanced')}
/>
Advanced settings
</label>
<Expander>
{showAdvanced ? (
<div>
<label class={style.optionToggle}>
Compress alpha
<Checkbox
name="alpha_compression"
checked={!!options.alpha_compression}
onChange={this.onChange}
/>
</label>
<div class={style.optionOneCell}>
<Range
name="alpha_quality"
min="0"
max="100"
value={options.alpha_quality}
onInput={this.onChange}
>
Alpha quality:
</Range>
</div>
<div class={style.optionOneCell}>
<Range
name="alpha_filtering"
min="0"
max="2"
value={options.alpha_filtering}
onInput={this.onChange}
>
Alpha filter quality:
</Range>
</div>
<label class={style.optionToggle}>
Auto adjust filter strength
<Checkbox
name="autofilter"
checked={!!options.autofilter}
onChange={this.onChange}
/>
</label>
<Expander>
{options.autofilter ? null : (
<div class={style.optionOneCell}>
<Range
name="filter_strength"
min="0"
max="100"
value={options.filter_strength}
onInput={this.onChange}
>
Filter strength:
</Range>
</div>
)}
</Expander>
<label class={style.optionToggle}>
Strong filter
<Checkbox
name="filter_type"
checked={!!options.filter_type}
onChange={this.onChange}
/>
</label>
<div class={style.optionOneCell}>
<Range
name="filter_sharpness"
min="0"
max="7"
value={7 - options.filter_sharpness}
onInput={this.onChange}
>
Filter sharpness:
</Range>
</div>
<label class={style.optionToggle}>
Sharp RGB→YUV conversion
<Checkbox
name="use_sharp_yuv"
checked={!!options.use_sharp_yuv}
onChange={this.onChange}
/>
</label>
<div class={style.optionOneCell}>
<Range
name="pass"
min="1"
max="10"
value={options.pass}
onInput={this.onChange}
>
Passes:
</Range>
</div>
<div class={style.optionOneCell}>
<Range
name="sns_strength"
min="0"
max="100"
value={options.sns_strength}
onInput={this.onChange}
>
Spatial noise shaping:
</Range>
</div>
<label class={style.optionTextFirst}>
Preprocess:
<Select
name="preprocessing"
value={options.preprocessing}
onChange={this.onChange}
>
<option value="0">None</option>
<option value="1">Segment smooth</option>
<option value="2">Pseudo-random dithering</option>
</Select>
</label>
<div class={style.optionOneCell}>
<Range
name="segments"
min="1"
max="4"
value={options.segments}
onInput={this.onChange}
>
Segments:
</Range>
</div>
<div class={style.optionOneCell}>
<Range
name="partitions"
min="0"
max="3"
value={options.partitions}
onInput={this.onChange}
>
Partitions:
</Range>
</div>
</div>
) : null}
</Expander>
</div>
);
}
render({ options }: Props) {
// I'm rendering both lossy and lossless forms, as it becomes much easier when
// gathering the data.
return (
<form class={style.optionsSection} onSubmit={preventDefault}>
<label class={style.optionToggle}>
Lossless
<Checkbox
name="lossless"
checked={!!options.lossless}
onChange={this.onChange}
/>
</label>
{options.lossless
? this._losslessSpecificOptions(options)
: this._lossySpecificOptions(options)}
<label class={style.optionToggle}>
Preserve transparent data
<Checkbox
name="exact"
checked={!!options.exact}
onChange={this.onChange}
/>
</label>
</form>
);
}
} | the_stack |
import { CPU } from './cpu';
import { avrInstruction } from './instruction';
import { assemble } from '../utils/assembler';
const r0 = 0;
const r1 = 1;
const r2 = 2;
const r3 = 3;
const r4 = 4;
const r5 = 5;
const r6 = 6;
const r7 = 7;
const r8 = 8;
const r16 = 16;
const r17 = 17;
const r18 = 18;
const r19 = 19;
const r20 = 20;
const r21 = 21;
const r22 = 22;
const r23 = 23;
const r24 = 24;
const r26 = 26;
const r27 = 27;
const r31 = 31;
const X = 26;
const Y = 28;
const Z = 30;
const RAMPZ = 0x5b;
const EIND = 0x5c;
const SP = 93;
const SPH = 94;
const SREG = 95;
// SREG Bits: I-HSVNZC
const SREG_C = 0b00000001;
const SREG_Z = 0b00000010;
const SREG_N = 0b00000100;
const SREG_V = 0b00001000;
const SREG_S = 0b00010000;
const SREG_H = 0b00100000;
const SREG_I = 0b10000000;
describe('avrInstruction', () => {
let cpu: CPU;
beforeEach(() => {
cpu = new CPU(new Uint16Array(0x8000));
});
function loadProgram(...instructions: string[]) {
const { bytes, errors } = assemble(instructions.join('\n'));
if (errors.length) {
throw new Error('Assembly failed: ' + errors);
}
cpu.progBytes.set(bytes, 0);
}
it('should execute `ADC r0, r1` instruction when carry is on', () => {
loadProgram('ADC r0, r1');
cpu.data[r0] = 10;
cpu.data[r1] = 20;
cpu.data[SREG] = SREG_C;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r0]).toEqual(31);
expect(cpu.data[SREG]).toEqual(0);
});
it('should execute `ADC r0, r1` instruction when carry is on and the result overflows', () => {
loadProgram('ADC r0, r1');
cpu.data[r0] = 10;
cpu.data[r1] = 245;
cpu.data[SREG] = SREG_C;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r0]).toEqual(0);
expect(cpu.data[SREG]).toEqual(SREG_H | SREG_Z | SREG_C);
});
it('should execute `BCLR 2` instruction', () => {
loadProgram('BCLR 2');
cpu.data[SREG] = 0xff;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(0xfb);
});
it('should execute `BLD r4, 7` instruction', () => {
loadProgram('BLD r4, 7');
cpu.data[r4] = 0x15;
cpu.data[SREG] = 0x40;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r4]).toEqual(0x95);
expect(cpu.data[SREG]).toEqual(0x40);
});
it('should execute `BRBC 0, +8` instruction when SREG.C is clear', () => {
loadProgram('BRBC 0, +8');
cpu.data[SREG] = SREG_V;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1 + 8 / 2);
expect(cpu.cycles).toEqual(2);
});
it('should execute `BRBC 0, +8` instruction when SREG.C is set', () => {
loadProgram('BRBC 0, +8');
cpu.data[SREG] = SREG_C;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
});
it('should execute `BRBS 3, 92` instruction when SREG.V is set', () => {
loadProgram('BRBS 3, 92');
cpu.data[SREG] = SREG_V;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1 + 92 / 2);
expect(cpu.cycles).toEqual(2);
});
it('should execute `BRBS 3, -4` instruction when SREG.V is set', () => {
loadProgram('BRBS 3, -4');
cpu.data[SREG] = SREG_V;
avrInstruction(cpu);
avrInstruction(cpu);
expect(cpu.pc).toEqual(0);
expect(cpu.cycles).toEqual(3); // 1 for NOP, 2 for BRBS
});
it('should execute `BRBS 3, -4` instruction when SREG.V is clear', () => {
loadProgram('BRBS 3, -4');
cpu.data[SREG] = 0x0;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
});
it('should execute `CBI 0x0c, 5`', () => {
loadProgram('CBI 0x0c, 5');
cpu.data[0x2c] = 0b11111111;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[0x2c]).toEqual(0b11011111);
});
it('should execute `CALL` instruction', () => {
loadProgram('CALL 0xb8');
cpu.data[SPH] = 0;
cpu.data[SP] = 150;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x5c);
expect(cpu.cycles).toEqual(4);
expect(cpu.data[150]).toEqual(2); // return addr
expect(cpu.data[SP]).toEqual(148); // SP should be decremented
});
it('should push 3-byte return address when executing `CALL` instruction on device with >128k flash', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('CALL 0xb8');
cpu.data[SPH] = 0;
cpu.data[SP] = 150;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x5c);
expect(cpu.cycles).toEqual(5);
expect(cpu.data[150]).toEqual(2); // return addr
expect(cpu.data[SP]).toEqual(147); // SP should be decremented by 3
});
it('should execute `CPC r27, r18` instruction', () => {
loadProgram('CPC r27, r18');
cpu.data[r18] = 0x1;
cpu.data[r27] = 0x1;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(0);
});
it('should execute `CPC r24, r1` instruction and set', () => {
loadProgram('CPC r24, r1');
cpu.data[r1] = 0;
cpu.data[r24] = 0;
cpu.data[SREG] = SREG_I | SREG_C;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(SREG_I | SREG_H | SREG_S | SREG_N | SREG_C);
});
it('should execute `CPI r26, 0x9` instruction', () => {
loadProgram('CPI r26, 0x9');
cpu.data[r26] = 0x8;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(SREG_H | SREG_S | SREG_N | SREG_C);
});
it('should execute `CPSE r2, r3` when r2 != r3', () => {
loadProgram('CPSE r2, r3');
cpu.data[r2] = 10;
cpu.data[r3] = 11;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
});
it('should execute `CPSE r2, r3` when r2 == r3', () => {
loadProgram('CPSE r2, r3');
cpu.data[r2] = 10;
cpu.data[r3] = 10;
avrInstruction(cpu);
expect(cpu.pc).toEqual(2);
expect(cpu.cycles).toEqual(2);
});
it('should execute `CPSE r2, r3` when r2 == r3 and followed by 2-word instruction', () => {
loadProgram('CPSE r2, r3', 'CALL 8');
cpu.data[r2] = 10;
cpu.data[r3] = 10;
avrInstruction(cpu);
expect(cpu.pc).toEqual(3);
expect(cpu.cycles).toEqual(3);
});
it('should execute `EICALL` instruction', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('EICALL');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x80;
cpu.data[EIND] = 1;
cpu.dataView.setUint16(Z, 0x1234, true);
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x11234);
expect(cpu.cycles).toEqual(4);
expect(cpu.data[SP]).toEqual(0x80 - 3); // according to datasheet: SP ← SP - 3
expect(cpu.data[0x80]).toEqual(1); // Return address
});
it('should execute `EIJMP` instruction', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('EIJMP');
cpu.data[EIND] = 1;
cpu.dataView.setUint16(Z, 0x1040, true);
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x11040);
expect(cpu.cycles).toEqual(2);
});
it('should execute `ELPM` instruction', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('ELPM');
cpu.data[Z] = 0x50;
cpu.data[RAMPZ] = 0x2;
cpu.progBytes[0x20050] = 0x62; // value to be loaded
avrInstruction(cpu);
expect(cpu.data[r0]).toEqual(0x62); // check that value was loaded to r0
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(3);
});
it('should execute `ELPM r5, Z` instruction', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('ELPM r5, Z');
cpu.data[Z] = 0x11;
cpu.data[RAMPZ] = 0x1;
cpu.progBytes[0x10011] = 0x99; // value to be loaded
avrInstruction(cpu);
expect(cpu.data[r5]).toEqual(0x99); // check that value was loaded to r5
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(3);
});
it('should execute `ELPM r6, Z+` instruction', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('ELPM r6, Z+');
cpu.dataView.setUint16(Z, 0xffff, true);
cpu.data[RAMPZ] = 0x2;
cpu.progBytes[0x2ffff] = 0x22; // value to be loaded
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(3);
expect(cpu.data[r6]).toEqual(0x22); // check that value was loaded to r6
expect(cpu.dataView.getUint16(Z, true)).toEqual(0x0); // verify that Z was incremented
expect(cpu.data[RAMPZ]).toEqual(3); // verify that RAMPZ was incremented
});
it('should clamp RAMPZ when executing `ELPM r6, Z+` instruction', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('ELPM r6, Z+');
cpu.dataView.setUint16(Z, 0xffff, true);
cpu.data[RAMPZ] = 0x3;
avrInstruction(cpu);
expect(cpu.data[RAMPZ]).toEqual(0x0); // verify that RAMPZ was reset to zero
});
it('should execute `ICALL` instruction', () => {
loadProgram('ICALL');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x80;
cpu.dataView.setUint16(Z, 0x2020, true);
avrInstruction(cpu);
expect(cpu.cycles).toEqual(3);
expect(cpu.pc).toEqual(0x2020);
expect(cpu.data[0x80]).toEqual(1); // Return address
expect(cpu.data[SP]).toEqual(0x7e); // SP Should decrement by 2
});
it('should push 3-byte return address when executing `ICALL` instruction on device with >128k flash', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('ICALL');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x80;
cpu.dataView.setUint16(Z, 0x2020, true);
avrInstruction(cpu);
expect(cpu.cycles).toEqual(4);
expect(cpu.pc).toEqual(0x2020);
expect(cpu.data[0x80]).toEqual(1); // Return address
expect(cpu.data[SP]).toEqual(0x7d); // SP Should decrement by 3
});
it('should execute `IJMP` instruction', () => {
loadProgram('IJMP');
cpu.dataView.setUint16(Z, 0x1040, true);
avrInstruction(cpu);
expect(cpu.cycles).toEqual(2);
expect(cpu.pc).toEqual(0x1040);
});
it('should execute `IN r5, 0xb` instruction', () => {
loadProgram('IN r5, 0xb');
cpu.data[0x2b] = 0xaf;
avrInstruction(cpu);
expect(cpu.cycles).toEqual(1);
expect(cpu.pc).toEqual(1);
expect(cpu.data[r5]).toEqual(0xaf);
});
it('should execute `INC r5` instruction', () => {
loadProgram('INC r5');
cpu.data[r5] = 0x7f;
avrInstruction(cpu);
expect(cpu.data[r5]).toEqual(0x80);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(SREG_N | SREG_V);
});
it('should execute `INC r5` instruction when r5 == 0xff', () => {
loadProgram('INC r5');
cpu.data[r5] = 0xff;
avrInstruction(cpu);
expect(cpu.data[r5]).toEqual(0);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(SREG_Z);
});
it('should execute `JMP 0xb8` instruction', () => {
loadProgram('JMP 0xb8');
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x5c);
expect(cpu.cycles).toEqual(3);
});
it('should execute `LAC Z, r19` instruction', () => {
loadProgram('LAC Z, r19');
cpu.data[r19] = 0x02;
cpu.dataView.setUint16(Z, 0x100, true);
cpu.data[0x100] = 0x96;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r19]).toEqual(0x96);
expect(cpu.dataView.getUint16(Z, true)).toEqual(0x100);
expect(cpu.data[0x100]).toEqual(0x94);
});
it('should execute `LAS Z, r17` instruction', () => {
loadProgram('LAS Z, r17');
cpu.data[r17] = 0x11;
cpu.data[Z] = 0x80;
cpu.data[0x80] = 0x44;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r17]).toEqual(0x44);
expect(cpu.data[Z]).toEqual(0x80);
expect(cpu.data[0x80]).toEqual(0x55);
});
it('should execute `LAT Z, r0` instruction', () => {
loadProgram('LAT Z, r0');
cpu.data[r0] = 0x33;
cpu.data[Z] = 0x80;
cpu.data[0x80] = 0x66;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r0]).toEqual(0x66);
expect(cpu.data[Z]).toEqual(0x80);
expect(cpu.data[0x80]).toEqual(0x55);
});
it('should execute `LDI r28, 0xff` instruction', () => {
loadProgram('LDI r28, 0xff');
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[Y]).toEqual(0xff);
});
it('should execute `LDS r5, 0x150` instruction', () => {
loadProgram('LDS r5, 0x150');
cpu.data[0x150] = 0x7a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x2);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r5]).toEqual(0x7a);
});
it('should execute `LD r1, X` instruction', () => {
loadProgram('LD r1, X');
cpu.data[0xc0] = 0x15;
cpu.data[X] = 0xc0;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r1]).toEqual(0x15);
expect(cpu.data[X]).toEqual(0xc0); // verify that X was unchanged
});
it('should execute `LD r17, X+` instruction', () => {
loadProgram('LD r17, X+');
cpu.data[0xc0] = 0x15;
cpu.data[X] = 0xc0;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r17]).toEqual(0x15);
expect(cpu.data[X]).toEqual(0xc1); // verify that X was incremented
});
it('should execute `LD r1, -X` instruction', () => {
loadProgram('LD r1, -X');
cpu.data[0x98] = 0x22;
cpu.data[X] = 0x99;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r1]).toEqual(0x22);
expect(cpu.data[X]).toEqual(0x98); // verify that X was decremented
});
it('should execute `LD r8, Y` instruction', () => {
loadProgram('LD r8, Y');
cpu.data[0xc0] = 0x15;
cpu.data[Y] = 0xc0;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[8]).toEqual(0x15);
expect(cpu.data[Y]).toEqual(0xc0); // verify that Y was unchanged
});
it('should execute `LD r3, Y+` instruction', () => {
loadProgram('LD r3, Y+');
cpu.data[0xc0] = 0x15;
cpu.data[Y] = 0xc0;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r3]).toEqual(0x15);
expect(cpu.data[Y]).toEqual(0xc1); // verify that Y was incremented
});
it('should execute `LD r0, -Y` instruction', () => {
loadProgram('LD r0, -Y');
cpu.data[0x98] = 0x22;
cpu.data[Y] = 0x99;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r0]).toEqual(0x22);
expect(cpu.data[Y]).toEqual(0x98); // verify that Y was decremented
});
it('should execute `LDD r4, Y+2` instruction', () => {
loadProgram('LDD r4, Y+2');
cpu.data[0x82] = 0x33;
cpu.data[Y] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r4]).toEqual(0x33);
expect(cpu.data[Y]).toEqual(0x80); // verify that Y was unchanged
});
it('should execute `LD r5, Z` instruction', () => {
loadProgram('LD r5, Z');
cpu.data[0xcc] = 0xf5;
cpu.data[Z] = 0xcc;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r5]).toEqual(0xf5);
expect(cpu.data[Z]).toEqual(0xcc); // verify that Z was unchanged
});
it('should execute `LD r7, Z+` instruction', () => {
loadProgram('LD r7, Z+');
cpu.data[0xc0] = 0x25;
cpu.data[Z] = 0xc0;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r7]).toEqual(0x25);
expect(cpu.data[Z]).toEqual(0xc1); // verify that Y was incremented
});
it('should execute `LD r0, -Z` instruction', () => {
loadProgram('LD r0, -Z');
cpu.data[0x9e] = 0x66;
cpu.data[Z] = 0x9f;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[r0]).toEqual(0x66);
expect(cpu.data[Z]).toEqual(0x9e); // verify that Y was decremented
});
it('should execute `LDD r15, Z+31` instruction', () => {
loadProgram('LDD r15, Z+31');
cpu.data[0x9f] = 0x33;
cpu.data[Z] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[15]).toEqual(0x33);
expect(cpu.data[Z]).toEqual(0x80); // verify that Z was unchanged
});
it('should execute `LPM` instruction', () => {
loadProgram('LPM');
cpu.progMem[0x40] = 0xa0;
cpu.data[Z] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(3);
expect(cpu.data[r0]).toEqual(0xa0);
expect(cpu.data[Z]).toEqual(0x80); // verify that Z was unchanged
});
it('should execute `LPM r2, Z` instruction', () => {
loadProgram('LPM r2, Z');
cpu.progMem[0x40] = 0xa0;
cpu.data[Z] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(3);
expect(cpu.data[r2]).toEqual(0xa0);
expect(cpu.data[Z]).toEqual(0x80); // verify that Z was unchanged
});
it('should execute `LPM r1, Z+` instruction', () => {
loadProgram('LPM r1, Z+');
cpu.progMem[0x40] = 0xa0;
cpu.data[Z] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(3);
expect(cpu.data[r1]).toEqual(0xa0);
expect(cpu.data[Z]).toEqual(0x81); // verify that Z was incremented
});
it('should execute `LSR r7` instruction', () => {
loadProgram('LSR r7');
cpu.data[r7] = 0x45;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r7]).toEqual(0x22);
expect(cpu.data[SREG]).toEqual(SREG_S | SREG_V | SREG_C);
});
it('should execute `MOV r7, r8` instruction', () => {
loadProgram('MOV r7, r8');
cpu.data[r8] = 0x45;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r7]).toEqual(0x45);
});
it('should execute `MOVW r26, r22` instruction', () => {
loadProgram('MOVW r26, r22');
cpu.data[r22] = 0x45;
cpu.data[r23] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[X]).toEqual(0x45);
expect(cpu.data[r27]).toEqual(0x9a);
});
it('should execute `MUL r5, r6` instruction', () => {
loadProgram('MUL r5, r6');
cpu.data[r5] = 100;
cpu.data[r6] = 5;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.dataView.getUint16(0, true)).toEqual(500);
expect(cpu.data[SREG]).toEqual(0);
});
it('should execute `MUL r5, r6` instruction and update carry flag when numbers are big', () => {
loadProgram('MUL r5, r6');
cpu.data[r5] = 200;
cpu.data[r6] = 200;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.dataView.getUint16(0, true)).toEqual(40000);
expect(cpu.data[SREG]).toEqual(SREG_C);
});
it('should execute `MUL r0, r1` and update the zero flag', () => {
loadProgram('MUL r0, r1');
cpu.data[r0] = 0;
cpu.data[r1] = 9;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.dataView.getUint16(0, true)).toEqual(0);
expect(cpu.data[SREG]).toEqual(SREG_Z);
});
it('should execute `MULS r18, r19` instruction', () => {
loadProgram('MULS r18, r19');
cpu.data[r18] = -5;
cpu.data[r19] = 100;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.dataView.getInt16(0, true)).toEqual(-500);
expect(cpu.data[SREG]).toEqual(SREG_C);
});
it('should execute `MULSU r16, r17` instruction', () => {
loadProgram('MULSU r16, r17');
cpu.data[r16] = -5;
cpu.data[r17] = 200;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.dataView.getInt16(0, true)).toEqual(-1000);
expect(cpu.data[SREG]).toEqual(SREG_C);
});
it('should execute `NEG r20` instruction', () => {
loadProgram('NEG r20');
cpu.data[r20] = 0x56;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[20]).toEqual(0xaa);
expect(cpu.data[SREG]).toEqual(SREG_S | SREG_N | SREG_C);
});
it('should execute `NOP` instruction', () => {
loadProgram('NOP');
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
});
it('should execute `OUT 0x3f, r1` instruction', () => {
loadProgram('OUT 0x3f, r1');
cpu.data[r1] = 0x5a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[0x5f]).toEqual(0x5a);
});
it('should execute `POP r26` instruction', () => {
loadProgram('POP r26');
cpu.data[SPH] = 0;
cpu.data[SP] = 0xff;
cpu.data[0x100] = 0x1a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[X]).toEqual(0x1a);
expect(cpu.dataView.getUint16(SP, true)).toEqual(0x100);
});
it('should execute `PUSH r11` instruction', () => {
loadProgram('PUSH r11');
cpu.data[11] = 0x2a;
cpu.data[SPH] = 0;
cpu.data[SP] = 0xff;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0xff]).toEqual(0x2a);
expect(cpu.dataView.getUint16(SP, true)).toEqual(0xfe);
});
it('should execute `RCALL .+6` instruction', () => {
loadProgram('RCALL 6');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(4);
expect(cpu.cycles).toEqual(3);
expect(cpu.dataView.getUint16(0x80, true)).toEqual(1); // RET address
expect(cpu.data[SP]).toEqual(0x7e); // SP should decrement by 2
});
it('should execute `RCALL .-4` instruction', () => {
loadProgram('NOP', 'RCALL -4');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x80;
avrInstruction(cpu);
avrInstruction(cpu);
expect(cpu.pc).toEqual(0);
expect(cpu.cycles).toEqual(4); // 1 for NOP, 3 for RCALL
expect(cpu.dataView.getUint16(0x80, true)).toEqual(2); // RET address
expect(cpu.data[SP]).toEqual(0x7e); // SP should decrement by 2
});
it('should push 3-byte return address when executing `RCALL` instruction on device with >128k flash', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('RCALL 6');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x80;
cpu.dataView.setUint16(Z, 0x2020, true);
avrInstruction(cpu);
expect(cpu.pc).toEqual(4);
expect(cpu.cycles).toEqual(4);
expect(cpu.dataView.getUint16(0x80, true)).toEqual(1); // RET address
expect(cpu.data[SP]).toEqual(0x7d); // SP Should decrement by 3
});
it('should execute `RET` instruction', () => {
loadProgram('RET');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x90;
cpu.data[0x92] = 16;
avrInstruction(cpu);
expect(cpu.pc).toEqual(16);
expect(cpu.cycles).toEqual(4);
expect(cpu.data[SP]).toEqual(0x92); // SP should increment by 2
});
it('should execute `RET` instruction on device with >128k flash', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('RET');
cpu.data[SPH] = 0;
cpu.data[SP] = 0x90;
cpu.data[0x91] = 0x1;
cpu.data[0x93] = 0x16;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x10016);
expect(cpu.cycles).toEqual(5);
expect(cpu.data[SP]).toEqual(0x93); // SP should increment by 3
});
it('should execute `RETI` instruction', () => {
loadProgram('RETI');
cpu.data[SPH] = 0;
cpu.data[SP] = 0xc0;
cpu.data[0xc2] = 200;
avrInstruction(cpu);
expect(cpu.pc).toEqual(200);
expect(cpu.cycles).toEqual(4);
expect(cpu.data[SP]).toEqual(0xc2); // SP should increment by 2
expect(cpu.data[SREG]).toEqual(SREG_I);
});
it('should execute `RETI` instruction on device with >128k flash', () => {
cpu = new CPU(new Uint16Array(0x20000));
loadProgram('RETI');
cpu.data[SPH] = 0;
cpu.data[SP] = 0xc0;
cpu.data[0xc1] = 0x1;
cpu.data[0xc3] = 0x30;
avrInstruction(cpu);
expect(cpu.pc).toEqual(0x10030);
expect(cpu.cycles).toEqual(5);
expect(cpu.data[SP]).toEqual(0xc3); // SP should increment by 3
expect(cpu.data[SREG]).toEqual(SREG_I);
});
it('should execute `RJMP 2` instruction', () => {
loadProgram('RJMP 2');
avrInstruction(cpu);
expect(cpu.pc).toEqual(2);
expect(cpu.cycles).toEqual(2);
});
it('should execute `ROR r0` instruction', () => {
loadProgram('ROR r0');
cpu.data[r0] = 0x11;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r0]).toEqual(0x08); // r0 should be right-shifted
expect(cpu.data[SREG]).toEqual(SREG_S | SREG_V | SREG_C);
});
it('should execute `SBCI r23, 3`', () => {
loadProgram('SBCI r23, 3');
cpu.data[r23] = 3;
cpu.data[SREG] = SREG_I | SREG_C;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[SREG]).toEqual(SREG_I | SREG_H | SREG_S | SREG_N | SREG_C);
});
it('should execute `SBI 0x0c, 5`', () => {
loadProgram('SBI 0x0c, 5');
cpu.data[0x2c] = 0b00001111;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x2c]).toEqual(0b00101111);
});
it('should execute `SBIS 0x0c, 5` when bit is clear', () => {
loadProgram('SBIS 0x0c, 5');
cpu.data[0x2c] = 0b00001111;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
});
it('should execute `SBIS 0x0c, 5` when bit is set', () => {
loadProgram('SBIS 0x0c, 5');
cpu.data[0x2c] = 0b00101111;
avrInstruction(cpu);
expect(cpu.pc).toEqual(2);
expect(cpu.cycles).toEqual(2);
});
it('should execute `SBIS 0x0c, 5` when bit is set and followed by 2-word instruction', () => {
loadProgram('SBIS 0x0c, 5', 'CALL 0xb8');
cpu.data[0x2c] = 0b00101111;
avrInstruction(cpu);
expect(cpu.pc).toEqual(3);
expect(cpu.cycles).toEqual(3);
});
it('should execute `STS 0x151, r31` instruction', () => {
loadProgram('STS 0x151, r31');
cpu.data[r31] = 0x80;
avrInstruction(cpu);
expect(cpu.pc).toEqual(2);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x151]).toEqual(0x80);
});
it('should execute `ST X, r1` instruction', () => {
loadProgram('ST X, r1');
cpu.data[r1] = 0x5a;
cpu.data[X] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x9a]).toEqual(0x5a);
expect(cpu.data[X]).toEqual(0x9a); // verify that X was unchanged
});
it('should execute `ST X+, r1` instruction', () => {
loadProgram('ST X+, r1');
cpu.data[r1] = 0x5a;
cpu.data[X] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x9a]).toEqual(0x5a);
expect(cpu.data[X]).toEqual(0x9b); // verify that X was incremented
});
it('should execute `ST -X, r17` instruction', () => {
loadProgram('ST -X, r17');
cpu.data[r17] = 0x88;
cpu.data[X] = 0x99;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x98]).toEqual(0x88);
expect(cpu.data[X]).toEqual(0x98); // verify that X was decremented
});
it('should execute `ST Y, r2` instruction', () => {
loadProgram('ST Y, r2');
cpu.data[r2] = 0x5b;
cpu.data[Y] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x9a]).toEqual(0x5b);
expect(cpu.data[Y]).toEqual(0x9a); // verify that Y was unchanged
});
it('should execute `ST Y+, r1` instruction', () => {
loadProgram('ST Y+, r1');
cpu.data[r1] = 0x5a;
cpu.data[Y] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x9a]).toEqual(0x5a);
expect(cpu.data[Y]).toEqual(0x9b); // verify that Y was incremented
});
it('should execute `ST -Y, r1` instruction', () => {
loadProgram('ST -Y, r1');
cpu.data[r1] = 0x5a;
cpu.data[Y] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x99]).toEqual(0x5a);
expect(cpu.data[Y]).toEqual(0x99); // verify that Y was decremented
});
it('should execute `STD Y+17, r0` instruction', () => {
loadProgram('STD Y+17, r0');
cpu.data[r0] = 0xba;
cpu.data[Y] = 0x9a;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x9a + 17]).toEqual(0xba);
expect(cpu.data[Y]).toEqual(0x9a); // verify that Y was unchanged
});
it('should execute `ST Z, r16` instruction', () => {
loadProgram('ST Z, r16');
cpu.data[r16] = 0xdf;
cpu.data[Z] = 0x40;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x40]).toEqual(0xdf);
expect(cpu.data[Z]).toEqual(0x40); // verify that Z was unchanged
});
it('should execute `ST Z+, r0` instruction', () => {
loadProgram('ST Z+, r0');
cpu.data[r0] = 0x55;
cpu.dataView.setUint16(Z, 0x155, true);
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x155]).toEqual(0x55);
expect(cpu.dataView.getUint16(Z, true)).toEqual(0x156); // verify that Z was incremented
});
it('should execute `ST -Z, r16` instruction', () => {
loadProgram('ST -Z, r16');
cpu.data[r16] = 0x5a;
cpu.data[Z] = 0xff;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0xfe]).toEqual(0x5a);
expect(cpu.data[Z]).toEqual(0xfe); // verify that Z was decremented
});
it('should execute `STD Z+1, r0` instruction', () => {
loadProgram('STD Z+1, r0');
cpu.data[r0] = 0xcc;
cpu.data[Z] = 0x50;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(2);
expect(cpu.data[0x51]).toEqual(0xcc);
expect(cpu.data[Z]).toEqual(0x50); // verify that Z was unchanged
});
it('should execute `SWAP r1` instruction', () => {
loadProgram('SWAP r1');
cpu.data[r1] = 0xa5;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r1]).toEqual(0x5a);
});
it('should execute `XCH Z, r21` instruction', () => {
loadProgram('XCH Z, r21');
cpu.data[r21] = 0xa1;
cpu.data[Z] = 0x50;
cpu.data[0x50] = 0xb9;
avrInstruction(cpu);
expect(cpu.pc).toEqual(1);
expect(cpu.cycles).toEqual(1);
expect(cpu.data[r21]).toEqual(0xb9);
expect(cpu.data[0x50]).toEqual(0xa1);
});
}); | the_stack |
import * as React from "react";
import {
ConfigurationPropertyValue,
ConfigurationProperty,
TokenPluralization,
buildConfigurationPropertyValue,
makeUniqueId,
PropertyPreview,
} from "@codotype/core";
import classnames from "classnames";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrashAlt } from "@fortawesome/free-regular-svg-icons";
import { ConfigurationGroupPropertiesInput } from "./ConfigurationGroupPropertiesInput";
import { PropertyPreviewRenderer } from "../PropertyPreviewRenderer";
// // // //
interface CollectionItem {
id: string;
[key: string]: ConfigurationPropertyValue;
}
// // // //
function CollectionItemForm(props: {
properties: ConfigurationProperty[];
value: CollectionItem;
dataPreview: PropertyPreview;
onSubmit: (updatedCollectionItem: CollectionItem) => void;
onCancel: () => void;
}) {
// TODO - make sure to define a default value here
const [formValues, setFormValues] = React.useState<CollectionItem>(
props.value,
);
// Updates formValues state when props.value changes
// TODO - make sure to define a default value here
React.useEffect(() => {
setFormValues({
...props.value,
});
}, [props.value.id]);
return (
<div className="card card-body">
<ConfigurationGroupPropertiesInput
properties={props.properties}
onChange={updatedValue => {
setFormValues({
...formValues,
...updatedValue,
});
}}
value={formValues}
/>
<hr />
<PropertyPreviewRenderer
data={formValues}
propertyPreview={props.dataPreview}
/>
<hr />
<div className="flex justify-end">
<button
className="btn btn-success"
onClick={() => {
props.onSubmit(formValues);
}}
>
Submit
</button>
<button
className="btn btn-secondary ml-2"
onClick={() => {
props.onCancel();
}}
>
Cancel
</button>
</div>
</div>
);
}
// // // //
interface ConfigurationCollectionInputProps {
properties: ConfigurationProperty[];
value: ConfigurationPropertyValue;
identifiers: TokenPluralization;
propertyPreview: PropertyPreview;
onChange: (updatedVal: ConfigurationPropertyValue) => void;
}
export function ConfigurationCollectionInput(
props: ConfigurationCollectionInputProps,
) {
const { identifiers } = props;
// Stores the current value of the collection
// TODO - remove any type here
const [collectionValue, setCollectionValue] = React.useState<any>(
props.value,
);
// Invokes props.onChange when collectionValue changes
React.useEffect(() => {
props.onChange(collectionValue);
}, [collectionValue]);
// Invokes props.onChange when collectionValue changes
React.useEffect(() => {
setNewCollectionItem(null);
setEditCollectionItem(null);
setCollectionValue(props.value);
}, [props.value]);
// New + Edit hooks
const [
newCollectionItem,
setNewCollectionItem,
] = React.useState<CollectionItem | null>(null);
const [
editCollectionItem,
setEditCollectionItem,
] = React.useState<CollectionItem | null>(null);
// TODO - should this be abstracted outside the component?
function buildNewCollectionItem() {
return props.properties.reduce(
(val, property) => {
return {
...val,
[property.identifier]: buildConfigurationPropertyValue(
property,
),
};
},
{ id: "" },
);
}
const showList = editCollectionItem === null && newCollectionItem === null;
return (
<div className="row">
<div className="col-lg-12">
<div className="row">
{showList && (
<div className="col-sm-12">
<button
className="btn w-full btn-primary"
onClick={() => {
setEditCollectionItem(null);
setNewCollectionItem(
buildNewCollectionItem(),
);
}}
>
New {identifiers.singular.title}
</button>
<ul className="flex flex-col pl-0 mb-0 rounded mt-3">
{collectionValue.map(
(
collectionItem: CollectionItem,
i: number,
) => {
return (
<li
key={String(i)}
className={classnames(
"list-group-item list-group-item-action",
{
active:
editCollectionItem !==
null &&
collectionItem.id ===
editCollectionItem.id,
},
)}
onClick={() => {
setNewCollectionItem(null);
setEditCollectionItem(
collectionItem,
);
}}
>
<div className="flex justify-between">
<PropertyPreviewRenderer
data={collectionItem}
propertyPreview={
props.propertyPreview
}
/>
<button
className="btn btn-sm btn-outline-danger"
onClick={e => {
e.preventDefault();
e.stopPropagation();
const updatedCollection = collectionValue.filter(
(
c: CollectionItem,
) =>
c.id !==
collectionItem.id,
);
setCollectionValue(
updatedCollection,
);
}}
>
<FontAwesomeIcon
icon={faTrashAlt}
/>
</button>
</div>
</li>
);
},
)}
{collectionValue.length === 0 && (
<li className="list-group-item">
No {identifiers.plural.title} defined
</li>
)}
</ul>
</div>
)}
<div className="col-sm-12">
{newCollectionItem !== null && (
<CollectionItemForm
value={newCollectionItem}
properties={props.properties}
dataPreview={props.propertyPreview}
onSubmit={updatedCollectionItem => {
// Updates collectionValue
setCollectionValue([
...collectionValue,
{
...updatedCollectionItem,
id: makeUniqueId(),
},
]);
// Clears newCollectionItem
setNewCollectionItem(null);
}}
onCancel={() => {
setNewCollectionItem(null);
}}
/>
)}
{editCollectionItem !== null && (
<CollectionItemForm
value={editCollectionItem}
properties={props.properties}
dataPreview={props.propertyPreview}
onSubmit={updatedCollectionItem => {
// Updates collectionValue
setCollectionValue(
// @ts-ignore
collectionValue.map(c => {
if (
c.id === editCollectionItem.id
) {
return updatedCollectionItem;
}
return c;
}),
);
// Clears newCollectionItem
setEditCollectionItem(null);
}}
onCancel={() => {
setEditCollectionItem(null);
}}
/>
)}
</div>
{/* <pre>{JSON.stringify(props.configurationGroup, null, 4)}</pre> */}
</div>
</div>
</div>
);
} | the_stack |
import CustomListener from "../../utilities/CustomListener";
import { IRequestMaintenanceProps } from './components/IRequestMaintenanceProps';
import RequestMaintenance from './components/RequestMaintenance';
import { IPropertyPaneConfiguration, PropertyPaneDropdown, PropertyPaneTextField, PropertyPaneToggle } from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { setup as pnpSetup } from "@pnp/common";
import { ConsoleListener, Logger, LogLevel } from "@pnp/logging";
import { sp } from "@pnp/sp";
import { IRoleDefinitionInfo } from '@pnp/sp/security';
import { ISiteGroupInfo } from '@pnp/sp/site-groups';
import * as React from 'react';
import * as ReactDom from 'react-dom';
import * as strings from 'RequestMaintenanceWebPartStrings';
import "@pnp/sp/security";
import "@pnp/sp/site-groups/web";
import "@pnp/sp/site-groups/web";
import "@pnp/sp/site-users";
import "@pnp/sp/webs";
//mport { ISiteUser } from '@pnp/sp/site-users';
export interface IRequestMaintenanceWebPartProps {
rfxListTitle: string; // the name of the list that holds all the RFX Info
rfxFoldersListTitle: string;// the name of the list that holds all the RFX folder Info
instrumentationKey: string; // app insights key
archiveLibraryTitle: string;
enablePrivateFolders: boolean;
roleDefinitionForLibraryMembersGroupOnLibrary: string;// each new RFX library has an group created for internal users. What role should that group have on trghe library (Contribute)
roleDefinitionForLibraryMembersGroupOnSite: string; // each new RFX library has an group created for internal users. What role should that group have on trghe site (READ)
roleDefinitionForLibraryMembersGroupOnFolder: string; // each new RFX library has an group created for internal users. What role should that group have on trghe site (READ)
roleDefinitionForLibraryVisitorsGroupOnLibrary: string;// each new RFX library has an group created for external users. What role should that group have on trghe library (Contribute)
roleDefinitionForLibraryVisitorsGroupOnSite: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForLibraryVisitorsGroupOnFolder: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderMembersOnFolder: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderMembersOnLibrary: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderMembersOnSite: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderVisitorsOnFolder: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderVisitorsOnLibrary: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderVisitorsOnSite: string; // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
allowGroupNameChanges: boolean;
}
export default class RequestMaintenanceWebPart extends BaseClientSideWebPart<IRequestMaintenanceWebPartProps> {
private vistorsGroup: ISiteGroupInfo;
private ownersGroup: ISiteGroupInfo;
private membersGroup: ISiteGroupInfo;
private roleDefinitions: IRoleDefinitionInfo[];
private roleDefinitionsDropdownDisabled: boolean;
// private currentUser:ISiteUser;
public render(): void {
const element: React.ReactElement<IRequestMaintenanceProps> = React.createElement(
RequestMaintenance,
{
siteOwnersGroup: this.ownersGroup, // Site owners groupw will be given full contyrol on new libraros
rfxListTitle: this.properties.rfxListTitle, // the name of the list that holds all the RFX Info
rfxFoldersListTitle: this.properties.rfxFoldersListTitle, // the name of the list that holds all the RFX Info
webServerRelativeUrl: this.context.pageContext.web.serverRelativeUrl,
archiveLibraryTitle: this.properties.archiveLibraryTitle,
enablePrivateFolders: this.properties.enablePrivateFolders,
roleDefinitions: this.roleDefinitions,
roleDefinitionForLibraryMembersGroupOnSite: this.properties.roleDefinitionForLibraryMembersGroupOnSite, // each new RFX library has an group created for internal users. What role should that group have on trghe site (READ)
roleDefinitionForLibraryMembersGroupOnLibrary: this.properties.roleDefinitionForLibraryMembersGroupOnLibrary,// each new RFX library has an group created for internal users. What role should that group have on trghe library (Contribute)
roleDefinitionForLibraryMembersGroupOnFolder: this.properties.roleDefinitionForLibraryMembersGroupOnFolder,// each new RFX library has an group created for internal users. What role should that group have on trghe library (Contribute)
roleDefinitionForLibraryVisitorsGroupOnSite: this.properties.roleDefinitionForLibraryVisitorsGroupOnSite, // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForLibraryVisitorsGroupOnLibrary: this.properties.roleDefinitionForLibraryVisitorsGroupOnLibrary,// each new RFX library has an group created for external users. What role should that group have on trghe library (Contribute)
roleDefinitionForLibraryVisitorsGroupOnFolder: this.properties.roleDefinitionForLibraryVisitorsGroupOnFolder,// each new RFX library has an group created for external users. What role should that group have on trghe library (Contribute)
roleDefinitionForFolderVisitorsOnFolder: this.properties.roleDefinitionForFolderVisitorsOnFolder, // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderVisitorsOnLibrary: this.properties.roleDefinitionForFolderVisitorsOnLibrary, // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderVisitorsOnSite: this.properties.roleDefinitionForFolderVisitorsOnSite, // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderMembersOnFolder: this.properties.roleDefinitionForFolderMembersOnFolder, // each new RFX library has an group created for external users. What role should that group have on trghe site (READ)
roleDefinitionForFolderMembersOnLibrary: this.properties.roleDefinitionForFolderMembersOnLibrary,
roleDefinitionForFolderMembersOnSite: this.properties.roleDefinitionForFolderMembersOnSite,
allowGroupNameChanges: this.properties.allowGroupNameChanges
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
public onInit(): Promise<any> {
//sessionStorage.setItem("spfx-debug", ""); //// REMOVE THIS
return super.onInit().then(_ => {
pnpSetup({
spfxContext: this.context
});
Logger.activeLogLevel = LogLevel.Warning;
Logger.subscribe(new ConsoleListener());
if (this.properties.instrumentationKey) {
Logger.subscribe(new CustomListener(this.properties.instrumentationKey));
}
let groupsPromise = this.getGroups();
let roledefPromise = this.getRoleDefinitions();
return Promise.all([groupsPromise, roledefPromise]);
});
}
public getRoleDefinitions(): Promise<void> {
return sp.site.rootWeb.roleDefinitions.get().then((rds) => {
this.roleDefinitions = rds;
});
}
public getGroups(): Promise<any> {
let promises: Array<Promise<any>> = [];
promises.push(sp.web.associatedVisitorGroup()
.then((g) => {
this.vistorsGroup = g;
})
.catch((e) => {
debugger;
}));
// Gets the associated members group of a web
promises.push(sp.web.associatedMemberGroup()
.then((g) => {
this.membersGroup = g;
})
.catch((e) => {
debugger;
}));
// Gets the associated owners group of a web
promises.push(sp.web.associatedOwnerGroup()
.then((g) => {
this.ownersGroup = g;
})
.catch((e) => {
debugger;
}));
return Promise.all(promises);
}
protected onPropertyPaneConfigurationStart(): void {
if (this.roleDefinitions) { return; }
this.getRoleDefinitions().then((e) => {
this.roleDefinitionsDropdownDisabled = false;
this.context.propertyPane.refresh();
});
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('rfxListTitle', {
label: strings.rfxListTitleLabel
}),
PropertyPaneTextField('rfxFoldersListTitle', {
label: strings.rfxFoldersListTitleLabel
}),
PropertyPaneTextField('archiveLibraryTitle', {
label: strings.archiveLibraryTitle
}),
PropertyPaneDropdown('roleDefinitionForLibraryMembersGroupOnSite', {
label: strings.roleDefinitionForLibraryMembersGroupOnSite,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForLibraryMembersGroupOnLibrary', {
label: strings.roleDefinitionForLibraryMembersGroupOnLibrary,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForLibraryMembersGroupOnFolder', {
label: strings.roleDefinitionForLibraryMembersGroupOnFolder,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForLibraryVisitorsGroupOnSite', {
label: strings.roleDefinitionForLibraryVisitorsGroupOnSite,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForLibraryVisitorsGroupOnLibrary', {
label: strings.roleDefinitionForLibraryVisitorsGroupOnLibrary,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForLibraryVisitorsGroupOnFolder', {
label: strings.roleDefinitionForLibraryVisitorsGroupOnFolder,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForFolderMembersOnSite', {
label: strings.roleDefinitionForFolderMembersOnSite,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForFolderMembersOnLibrary', {
label: strings.roleDefinitionForFolderMembersOnLibrary,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForFolderMembersOnFolder', {
label: strings.roleDefinitionForFolderMembersOnFolder,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForFolderVisitorsOnSite', {
label: strings.roleDefinitionForFolderVisitorsOnSite,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForFolderVisitorsOnLibrary', {
label: strings.roleDefinitionForFolderVisitorsOnLibrary,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneDropdown('roleDefinitionForFolderVisitorsOnFolder', {
label: strings.roleDefinitionForFolderVisitorsOnFolder,
options: this.roleDefinitions.map((rd) => {
return { key: rd.Name, text: rd.Name };
}),
}),
PropertyPaneToggle('allowGroupNameChanges', {
label: strings.allowGroupNameChanges,
}),
PropertyPaneToggle('enablePrivateFolders', {
label:strings.privateFolders,
offText:strings.privateFoldersDisabled,
onText: strings.privateFoldersEnabled,
}),
PropertyPaneTextField('instrumentationKey', {
label: strings.instrumentationKey
}),
]
}
]
}
]
};
}
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { NodeModel } from '../../../src/diagram/objects/node-model';
import { ShadowModel, RadialGradientModel, StopModel } from '../../../src/diagram/core/appearance-model';
import { Canvas } from '../../../src/diagram/core/containers/canvas';
import { BpmnDiagrams } from '../../../src/diagram/objects/bpmn';
import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec';
Diagram.Inject(BpmnDiagrams);
/**
* Task shapes
*/
describe('Diagram Control', () => {
describe('BPMN Tasks', () => {
let diagram: Diagram;
let shadow: ShadowModel = { angle: 135, distance: 10, opacity: 0.9 };
let stops: StopModel[] = [{ color: 'white', offset: 0 }, { color: 'red', offset: 50 }];
let gradient: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stops, type: 'Radial' };
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram96task' });
document.body.appendChild(ele);
let node: NodeModel = {
id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100,
style: { fill: 'red', strokeColor: 'blue', strokeWidth: 5 },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'None', compensation: false,
}
},
},
};
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 100,
style: { strokeWidth: 5, },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Service', compensation: false,
}
}
},
};
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 500, offsetY: 100,
style: { fill: 'red', strokeWidth: 5, },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'BusinessRule', compensation: false,
}
},
},
};
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 700, offsetY: 100,
style: { opacity: 0.6, gradient: gradient },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'InstantiatingReceive', compensation: false,
}
},
},
};
let node4: NodeModel = {
id: 'node4', width: 100, height: 100, offsetX: 900, offsetY: 100,
style: { strokeWidth: 5, strokeDashArray: '2 2' },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Manual', compensation: false,
}
},
},
};
diagram = new Diagram({
width: 1500, height: 500, nodes: [node, node1, node2, node3, node4]
});
diagram.appendTo('#diagram96task');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking before, after, BPMN shape as Activity with Task and task Type as None', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 100) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 65 && wrapper.children[1].offsetY === 65)
).toBe(true);
done();
});
it('Checking before, after, BPMN shape as Activity with Task and task Type as Service ', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[1] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 100) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 265 && wrapper.children[1].offsetY === 65) &&
//third node
(Math.round(wrapper.children[2].actualSize.width) === 20 && Math.round(wrapper.children[2].actualSize.height) === 20)
).toBe(true);
done();
});
it('Checking before, after, BPMN shape as Activity with Task and task Type as BusinessRule ', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[2] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 500 && wrapper.children[0].offsetY === 100) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 465 && wrapper.children[1].offsetY === 65)
).toBe(true);
done();
});
it('Checking before, after, BPMN shape as Activity with Task and task Type as InstantiatingReceive ', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[3] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 700 && wrapper.children[0].offsetY === 100) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 665 && wrapper.children[1].offsetY === 65)
).toBe(true);
done();
});
it('Checking visibility of the task ', (done: Function) => {
diagram.nodes[0].visible = false;
expect(diagram.nodes[0].visible).toBe(false);
diagram.nodes[0].visible = true;
expect(diagram.nodes[0].visible).toBe(true);
done();
});
});
describe('Diagram Element', () => {
let diagram: Diagram; let shadow1: ShadowModel = { angle: 135, distance: 10, opacity: 0.9 };
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stopscol, type: 'Radial' };
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram96tasks2' });
document.body.appendChild(ele);
let node5: NodeModel = {
id: 'node5', width: 100, height: 100, offsetX: 100, offsetY: 300,
shadow: shadow1,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Receive', compensation: false,
}
},
},
};
let node6: NodeModel = {
id: 'node6', width: 100, height: 100, offsetX: 300, offsetY: 300,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Script', compensation: false,
}
},
},
};
let node7: NodeModel = {
id: 'node7', width: 100, height: 100, offsetX: 500, offsetY: 300,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Send', compensation: false,
}
},
},
};
let node8: NodeModel = {
id: 'node8', width: 100, height: 100, offsetX: 700, offsetY: 300,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'User', compensation: false,
}
},
},
};
diagram = new Diagram({
width: 1500, height: 500, nodes: [node5, node6, node7, node8]
});
diagram.appendTo('#diagram96tasks2');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking before, after, BPMN shape as Activity with Task and task Type as Receive ', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 300) &&
//second node
(wrapper.children[1].actualSize.width === 18
&& wrapper.children[1].actualSize.height === 16 &&
wrapper.children[1].offsetY === 263 && wrapper.children[1].offsetX === 64)
).toBe(true);
done();
});
});
describe('Diagram Element', () => {
let diagram: Diagram; let shadow1: ShadowModel = { angle: 135, distance: 10, opacity: 0.9 };
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stopscol, type: 'Radial' };
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram961a' });
document.body.appendChild(ele);
let node: NodeModel = {
id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100,
style: { fill: 'red', strokeWidth: 5, },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
loop: 'Standard',
}
},
},
};
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 100,
style: { strokeColor: 'red', strokeWidth: 5, },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
loop: 'ParallelMultiInstance',
}
},
},
};
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 500, offsetY: 100,
style: { opacity: 0.6, fill: 'red' },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
loop: 'SequenceMultiInstance',
}
},
},
};
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 700, offsetY: 100,
style: { gradient: gradient1 },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'InstantiatingReceive', loop: 'None',
}
},
},
};
let node4: NodeModel = {
id: 'node4', width: 100, height: 100, offsetX: 900, offsetY: 100,
shadow: shadow1,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'InstantiatingReceive', loop: 'ParallelMultiInstance',
}
},
},
};
diagram = new Diagram({
width: 1500, height: 500, nodes: [node, node1, node2, node3, node4]
});
diagram.appendTo('#diagram961a');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking before, after, BPMN shape as Activity with Task and task Type as None and loop as Standard', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 100
) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 65 && wrapper.children[1].offsetY === 65) &&
//third node
(wrapper.children[2].actualSize.width === 12
&& wrapper.children[2].actualSize.height === 12 &&
(wrapper.children[2].offsetX === 103 || wrapper.children[2].offsetX === 100) && wrapper.children[2].offsetY === 139)
).toBe(true);
done();
});
});
describe('Diagram Element', () => {
let diagram: Diagram; let shadow1: ShadowModel = { angle: 135, distance: 10, opacity: 0.9 };
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stopscol, type: 'Radial' };
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram961' });
document.body.appendChild(ele);
let node5: NodeModel = {
id: 'node5', width: 100, height: 100, offsetX: 100, offsetY: 300,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Receive', loop: 'SequenceMultiInstance',
}
},
},
};
let node6: NodeModel = {
id: 'node6', width: 100, height: 100, offsetX: 300, offsetY: 300,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: {
type: 'Service', loop: 'ParallelMultiInstance', call: true,
}
},
},
};
let node7: NodeModel = {
id: 'node7', width: 100, height: 100, offsetX: 500, offsetY: 300,
style: { fill: 'red', strokeColor: 'blue', strokeWidth: 5 },
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task',
task: { call: true, compensation: false, type: 'Service', loop: 'ParallelMultiInstance' }
},
}
};
let node8: NodeModel = {
id: 'node8', width: 100, height: 100, offsetX: 700, offsetY: 300,
shape: {
type: 'Bpmn', shape: 'Activity', activity: {
activity: 'Task', task: { call: true, compensation: true, type: 'Service', loop: 'ParallelMultiInstance', }
},
}
};
diagram = new Diagram({
width: 1500, height: 500, nodes: [node5, node6, node7, node8]
});
diagram.appendTo('#diagram961');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking before, after, task Type Receive and loop as SequenceMultiInstance', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 300) &&
//second node
(wrapper.children[1].actualSize.width === 18
&& wrapper.children[1].actualSize.height === 16 &&
wrapper.children[1].offsetX === 64 && wrapper.children[1].offsetY === 263) &&
//third node
(wrapper.children[2].actualSize.width === 12
&& wrapper.children[2].actualSize.height === 12 &&
(wrapper.children[2].offsetX === 103 || wrapper.children[2].offsetX === 100) && wrapper.children[2].offsetY === 339)
).toBe(true);
done();
});
it('Checking before, after, type - Service and loop - ParallelMultiInstance and call - true', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[1] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 300 &&
wrapper.children[0].style.strokeWidth === 4) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 265 && wrapper.children[1].offsetY === 265) &&
//third node
(wrapper.children[3].actualSize.width === 12
&& wrapper.children[3].actualSize.height === 12 &&
(wrapper.children[3].offsetX === 303 || wrapper.children[3].offsetX === 300) && wrapper.children[3].offsetY === 339)
).toBe(true);
done();
});
it('Checking before, after,call-true and compensation-false and type-Service and loop-ParallelMultiInstance', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[2] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 500 && wrapper.children[0].offsetY === 300) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 465 && wrapper.children[1].offsetY === 265) &&
//third node
(wrapper.children[3].actualSize.width === 12
&& wrapper.children[3].actualSize.height === 12 &&
(wrapper.children[3].offsetX === 503 || wrapper.children[3].offsetX === 500) && wrapper.children[3].offsetY === 339) &&
//fourth node
(wrapper.children[4].actualSize.width === 12
&& wrapper.children[4].actualSize.height === 12 &&
wrapper.children[4].offsetX === 500 && wrapper.children[4].offsetY === 339 &&
wrapper.children[4].visible === false)
).toBe(true);
done();
});
it('Checking before, after,call-true and compensation-true and type-Service and loop-ParallelMultiInstance', (done: Function) => {
let wrapper: Canvas = ((diagram.nodes[3] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas;
expect((wrapper.children[0].actualSize.width === 100
&& wrapper.children[0].actualSize.height === 100 &&
wrapper.children[0].offsetX === 700 && wrapper.children[0].offsetY === 300 &&
wrapper.children[0].style.strokeWidth === 4) &&
//second node
(wrapper.children[1].actualSize.width === 20
&& wrapper.children[1].actualSize.height === 20 &&
wrapper.children[1].offsetX === 665 && wrapper.children[1].offsetY === 265) &&
//third node
(wrapper.children[3].actualSize.width === 12
&& wrapper.children[3].actualSize.height === 12 &&
(wrapper.children[3].offsetX === 690 || wrapper.children[3].offsetX === 700) && wrapper.children[3].offsetY === 339) &&
//fourth node
(wrapper.children[4].actualSize.width === 12
&& wrapper.children[4].actualSize.height === 12 &&
wrapper.children[4].offsetX === 707 && wrapper.children[4].offsetY === 339 &&
wrapper.children[4].visible === true)
).toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
}); | the_stack |
export type ScriptEnv = typeof scriptenv
declare namespace scriptenv {
//
// The Scripter environment.
//
// What's declared here is available to scripts in their global namespace.
//
// symbolic type aliases
type int = number
type float = number
type byte = number
type bool = boolean
/** Outputs a message to the console and on screen */
function print(...args :any[]) :void
/** Throws an error if condition is not thruthy */
function assert(condition :any, ...message :any[]) :void
/** Promise which can be cancelled */
interface CancellablePromise<T=void> extends Promise<T> { cancel():void }
/**
* Creates a cancellable Promise.
*
* Example:
* ```
* let p = createCancellablePromise((resolve, reject, oncancel) => {
* let timer = setTimeout(() => resolve("ok"), 600)
* oncancel(() => {
* clearTimeout(timer)
* reject("cancelled")
* })
* })
* p.then(v => console.log("resolved", v))
* .catch(v => console.warn("rejected", v))
* setTimeout(() => { p.cancel() }, 500)
* ```
*/
function createCancellablePromise<T>(
executor :(
resolve : (v? :T | PromiseLike<T>) => void,
reject : ((reason?:any)=>void),
oncancel : (f:()=>void)=>void
)=>void,
) :CancellablePromise<T>
// timer functions
function clearInterval(id?: number): void;
function clearTimeout(id?: number): void;
function setInterval(handler: string|Function, timeout?: number, ...arguments: any[]): number;
function setTimeout(handler: string|Function, timeout?: number, ...arguments: any[]): number;
/** Start a timer that expires after `duration` milliseconds */
function Timer(duration :number, handler? :(canceled?:boolean)=>any) :Timer
function timer(duration :number, handler? :(canceled?:boolean)=>any) :Timer
interface Timer<T = void> extends CancellablePromise<T> {
cancel() :void
then<R1=T,R2=never>(
onfulfilled?: ((value: T) => R1|PromiseLike<R1>)|undefined|null,
onrejected?: ((reason: any) => R2|PromiseLike<R2>)|undefined|null,
): Timer<R1>;
catch(onrejected?: ((reason: any) => any|PromiseLike<any>)|undefined|null): Timer<T>;
}
class TimerCancellation extends Error {
readonly name :"TimerCancellation"
}
/**
* Adds a timeout to a cancellable process.
* When timeout is reached, "TIMEOUT" is returned instead R.
*/
function withTimeout<
T extends CancellablePromise<R>,
R = T extends Promise<infer U> ? U : T
>(p :T, timeout :number) :CancellablePromise<R|"TIMEOUT">
var animate :SAnimate
interface SAnimate {
/**
* animate(f) calls f at a high enough frequency to animate things.
* The time argument to f is a monotonically-incrementing number of seconds, starting at the
* call to animate(). It has millisecond precision.
* Return or throw "STOP" to end animation, which resolves the promise.
*/
(f :SAnimationCallback) :SAnimation
/**
* transition is used to create animated transitions over a set amount of time (duration).
* The provided function f is called with progress (not time) in the range [0-1] with an optional
* timing function. If no timing function is provided, animate.easeInOut is used.
* Note that duration is defined in seconds (not milliseconds.)
* See https://easings.net/ for a visual overview of timing functions.
*/
transition(duration :number, timingf :SAnimationTimingFunction|null, f :SAnimationCallback) :SAnimation
/**
* transition is used to create animated transitions over a set amount of time (duration).
* The provided function f is called with progress (not time) in the range [0-1].
* The animate.easeInOut timing function is used.
* Note that duration is defined in seconds (not milliseconds.)
*/
transition(duration :number, f :SAnimationCallback) :SAnimation
// Timing functions
// See the example script "Misc/Timing Functions" for a visualization.
// See https://easings.net/ for interactive examples.
readonly easeIn :SAnimationTimingFunction // == easeInQuad
readonly easeOut :SAnimationTimingFunction // == easeOutQuad
readonly easeInOut :SAnimationTimingFunction // == easeInOutQuad
readonly easeInQuad :SAnimationTimingFunction
readonly easeOutQuad :SAnimationTimingFunction
readonly easeInOutQuad :SAnimationTimingFunction
readonly easeInCubic :SAnimationTimingFunction
readonly easeOutCubic :SAnimationTimingFunction
readonly easeInOutCubic :SAnimationTimingFunction
readonly easeInQuart :SAnimationTimingFunction
readonly easeOutQuart :SAnimationTimingFunction
readonly easeInOutQuart :SAnimationTimingFunction
readonly easeInQuint :SAnimationTimingFunction
readonly easeOutQuint :SAnimationTimingFunction
readonly easeInOutQuint :SAnimationTimingFunction
readonly easeInSine :SAnimationTimingFunction
readonly easeOutSine :SAnimationTimingFunction
readonly easeInOutSine :SAnimationTimingFunction
readonly easeInExpo :SAnimationTimingFunction
readonly easeOutExpo :SAnimationTimingFunction
readonly easeInOutExpo :SAnimationTimingFunction
readonly easeInCirc :SAnimationTimingFunction
readonly easeOutCirc :SAnimationTimingFunction
readonly easeInOutCirc :SAnimationTimingFunction
readonly easeInBack :SAnimationTimingFunction
readonly easeOutBack :SAnimationTimingFunction
readonly easeInOutBack :SAnimationTimingFunction
readonly easeInElastic :SAnimationTimingFunction
readonly easeOutElastic :SAnimationTimingFunction
readonly easeInOutElastic :SAnimationTimingFunction
readonly easeInBounce :SAnimationTimingFunction
readonly easeInOutBounce :SAnimationTimingFunction
}
/** Cancellable and waitable animation handle */
interface SAnimation extends Promise<void> {
cancel() :void
}
type SAnimationCallback = (t :number) => void|undefined|"STOP"
/**
* Animation easing function receives time in the range [0-1] and
* outputs normalized position in the range [0-1].
*/
type SAnimationTimingFunction = (t :number) => number
/** Set to true if the script was canceled by the user */
var canceled :boolean;
/** Ignored value */
var _ :any;
/**
* Shows a modal dialog with question and yes/no buttons.
*
* Returns true if the user answered "yes".
*/
function confirm(question: string): Promise<bool>;
/** Presents a message to the user in a disruptive way. */
function alert(message: string): void;
// ------------------------------------------------------------------------------------
// worker
/** Data that can be moved from Scripter to a worker */
type ScripterTransferable = ArrayBuffer;
/** Create a worker */
function createWorker(scriptOrURL :string | ScripterWorkerFun) :ScripterWorker
/** Create a iframe-based worker, with a full DOM */
function createWorker(
opt :ScripterCreateWorkerOptions & { iframe: ScripterWorkerIframeConfig & {visible:true} },
scriptOrURL :string | ScripterWorkerDOMFun
) :ScripterWindowedWorker
/** Create an iframe-based worker, with a full DOM */
function createWorker(
opt :ScripterCreateWorkerOptions & { iframe: (ScripterWorkerIframeConfig & {visible?:false}) | true },
scriptOrURL :string | ScripterWorkerDOMFun
) :ScripterWorker
/** Create a worker, with options */
function createWorker(
opt :ScripterCreateWorkerOptions | undefined | null,
scriptOrURL :string | ScripterWorkerFun
) :ScripterWorker
/**
* Create an iframe-based worker in a visible window.
* Equivalent to createWorker({iframe:{visible:true,...opt}},scriptOrURL)
*/
function createWindow(
opt :(ScripterWorkerIframeConfig & { visible?: never }) | undefined | null,
scriptOrURL :string | ScripterWorkerDOMFun
) :ScripterWindowedWorker
/**
* Create an iframe-based worker in a visible window.
* Equivalent to createWorker({iframe:{visible:true,...opt}},scriptOrURL)
*/
function createWindow(scriptOrURL :string | ScripterWorkerDOMFun) :ScripterWindowedWorker
/** Interface to a worker */
interface ScripterWorker extends Promise<void> {
/** Event callback invoked when a message arrives from the worker */
onmessage? :((ev :ScripterMessageEvent)=>void) | null
/** Event callback invoked when a message error occurs */
onmessageerror? :((ev :ScripterMessageEvent)=>void) | null
/**
* Event callback invoked when an error occurs.
* When this happens, the worker should be considered defunct.
*/
onerror? :((err :ScripterWorkerError)=>void) | null
/** Event callback invoked when the worker closes */
onclose? :()=>void
/** Send a message to the worker */
postMessage(msg :any, transfer?: ScripterTransferable[]) :void
/** Send a message to the worker (alias for postMessage) */
send<T=any>(msg :T, transfer?: ScripterTransferable[]) :void // alias for postMessage
/**
* Receive a message from the worker. Resolves on the next message received.
* This is an alternative to event-based message processing with `onmessage`.
*/
recv<T=any>() :Promise<T>
/**
* Send a message to the worker and wait for a response.
* If the worker responds to the onrequest event, that handler is used to fullfill
* the request.
* Otherwise, if the worker does not implement onrequest, the behavior is identical
* to the following code: w.send(msg).then(() => w.recv<OutT>())
*
* timeout is given in milliseconds. Absense of timeout, zero or negative timeout
* means "no timeout". When a request times out, the promise is rejected.
*/
request<InT=any,OutT=any>(
msg :InT,
transfer?: ScripterTransferable[],
timeout? :number,
) :Promise<OutT>
request<InT=any,OutT=any>(msg :InT, timeout :number) :Promise<OutT>
/** Request termination of the worker */
terminate() :this
}
interface ScripterWindowedWorker extends ScripterWorker {
/** Move and resize the window */
setFrame(x :number, y :number, width :number, height :number) :void
/** Close the window. Alias for ScripterWorker.terminate() */
close() :void
}
interface ScripterCreateWorkerOptions {
/**
* If true, the worker will actually run in an iframe with a full DOM.
* Note that iframes are a little slower and blocks the UI thread.
* This is useful for making certain libraries work which depend on DOM features,
* like for example the popular D3 library.
*/
iframe?: ScripterWorkerIframeConfig | boolean | null
}
type ScripterWorkerFun = (self :ScripterWorkerEnv) => void|Promise<void>
type ScripterWorkerDOMFun = (self :ScripterWorkerDOMEnv) => void|Promise<void>
type WebDOMInterface = typeof WebDOM
type WebWorkerEnvInterface = typeof WebWorkerEnv
// type ScripterWorkerDOMEnv = ScripterWorkerBaseEnv & WebDOMInterface
// type ScripterWorkerEnv = ScripterWorkerBaseEnv & WebWorkerEnvInterface
interface ScripterWorkerEnv extends ScripterWorkerBaseEnv, WebWorkerEnvInterface {
}
interface ScripterWorkerDOMEnv extends ScripterWorkerBaseEnv, WebDOMInterface {
/**
* Import scripts into the worker process.
* Consider using importAll(...urls) or import(url) instead as those functions
* has better support for more modules and for loading from NPM.
* This function is defined mainly to make WebWorker-based code portable.
*/
importScripts(...urls: string[]): Promise<void>
/**
* React-style DOM builder.
* Thin wrapper around document.createElement.
*/
createElement<T extends WebDOM.Element>(
name :string,
attrs? :{[k:string]:any},
...children :any[]
) :T
}
interface ScripterWorkerBaseEnv {
/** Close this worker */
close(): void
/**
* Invoked when a request initiated by a call to ScripterWorker.request() is received.
* The return value will be sent as the response to the request.
*/
onrequest? :(req :ScripterWorkerRequest) => Promise<any>|any
/** Send a message to the main Scripter script (alias for postMessage) */
send<T=any>(msg :T, transfer?: WebDOM.Transferable[]) :void // alias for postMessage
/**
* Receive a message from the main Scripter script.
* Resolves on the next message received.
* This is an alternative to event-based message processing with `onmessage`.
*/
recv<T=any>() :Promise<T>
/**
* Wrapper around importScripts() for importing a script that expects a CommonJS
* environment, i.e. module object and exports object. Returns the exported API.
*
* Caveat: If more than one call is performed at once, the results are undefined.
* This because CommonJS relies on a global variable.
*/
importCommonJS(url :string) :Promise<any>
/**
* Import an AMD- or CommonJS-compatible library. Returns its exported API.
* Most libraries targeting web browsers support AMD or CommonJS.
* See https://github.com/amdjs/amdjs-api for details in AMD modules.
*/
import(url: string): Promise<any>
/**
* Import one or more AMD- or CommonJS-compatible libraries.
* Returns its exported APIs in the same order as the input urls.
* Most libraries targeting web browsers support AMD or CommonJS.
* See https://github.com/amdjs/amdjs-api for details in AMD modules.
*
* @see import
*/
importAll(...urls: string[]): Promise<any[]>
}
interface ScripterWorkerIframeConfig {
/** If true, show the iframe rather than hiding it */
visible? :boolean
/** Width of the iframe */
width? :number
/** Height of the iframe */
height? :number
/** Position on screen of visible iframe's window (measured from top left) */
x? :number
/** Position on screen of visible iframe's window (measured from top left) */
y? :number
/** Sets the window title of visible iframes */
title? :string
}
interface ScripterWorkerRequest {
readonly id :string
readonly data :any
}
interface ScripterWorkerError {
readonly colno?: number;
readonly error?: any;
readonly filename?: string;
readonly lineno?: number;
readonly message?: string;
}
/** Minimal version of the Web DOM MessageEvent type */
interface ScripterMessageEvent {
readonly type: "message" | "messageerror";
/** Data of the message */
readonly data: any;
readonly origin: string;
}
// ------------------------------------------------------------------------------------
// DOM
/** JSX interface for creating Figma nodes */
var DOM :DOM
interface DOM {
/**
* Create a node.
* Nodes created with createElement are initially hidden and automatically
* removed when the script ends, unless added to the scene explicitly.
*
* Can be used to created trees of nodes, e.g.
* let f = DOM.createElement(Frame, null,
* DOM.createElement(Rectangle),
* DOM.createElement(Text, {characters:"Hello", y:110}) )
* figma.currentPage.appendChild(f)
*/
createElement<N extends BaseNode, P extends Partial<N>>(
cons :(props?:P|null)=>N,
props? :P | null,
...children :BaseNode[]
): N
/**
* Create a node by name.
* Name starts with a lower-case character. e.g. "booleanOperation".
*/
createElement(
kind :string,
props? :{[k:string]:any} | null,
...children :never[]
): SceneNode
// TODO: Consider defining types for all known names.
// We could define a `nodeNames:{"name":RectangleNode, ...}` type which can
// then be used to do `keyof` to build a single type that expresses all node types.
//
// Note: Currently Monaco/TypeScript does not provide result type support for
// JSX, so doing this has little to no upside.
//
// createElement(
// kind :"rectangle",
// props? :Partial<RectangleNode> | null,
// ...children :never[]
// ): RectangleNode
}
// ------------------------------------------------------------------------------------
// JSON
/**
* Format value as JSON. Similar to JSON.stringify but returns "pretty" JSON by default.
* Pass false or 0 as the second argument to produce compact JSON.
*/
function jsonfmt(value :any, pretty? :number|boolean) :string
/**
* Parse JSON, similar to JSON.parse but supports comments and extra trailing commas.
* I.e. it allows parsing "relaxed" JSON.
* If a type parameter is provided, is has the same effect as casting. i.e.
* jsonparse<Foo>(x) == (jsonparse(x) as Foo)
*/
function jsonparse<T = any>(json :string) :T
// ------------------------------------------------------------------------------------
// fetch
/**
* Starts the process of fetching a resource from the network, returning a promise
* which is fulfilled once the response is available.
*/
function fetch(input: WebDOM.RequestInfo, init?: WebDOM.RequestInit): Promise<WebDOM.Response>;
/** Shorthand for fetch().then(r => r.text()) */
function fetchText(input: WebDOM.RequestInfo, init?: WebDOM.RequestInit): Promise<string>;
/** Shorthand for fetch().then(r => r.json()) */
function fetchJson(input: WebDOM.RequestInfo, init?: WebDOM.RequestInit): Promise<any>;
/** Shorthand for fetch().then(r => r.arrayBuffer()).then(b => new Uint8Array(b)) */
function fetchData(input: WebDOM.RequestInfo, init?: WebDOM.RequestInit): Promise<Uint8Array>;
/** Shorthand for fetchData().then(data => Img(data)) */
function fetchImg(input: WebDOM.RequestInfo, init?: WebDOM.RequestInit): Promise<Img>;
// ------------------------------------------------------------------------------------
// Img
/** Drawable image. Accepts a URL or image data. Can be passed to print for display. */
interface Img<DataType=null|Uint8Array> {
type :string // mime type
width :number // 0 means "unknown"
height :number // 0 means "unknown"
pixelWidth :number // 0 means "unknown"
pixelHeight :number // 0 means "unknown"
source :string|Uint8Array // url or image data
data :DataType // image data if loaded
/** Type-specific metadata. Populated when image data is available. */
meta :{[k:string]:any}
/** Load the image. Resolves immediately if source is Uint8Array. */
load() :Promise<Img<Uint8Array>>
/** Get Figma image. Cached. Calls load() if needed to load the data. */
getImage() :Promise<Image>
/** Create a rectangle node with the image as fill, scaleMode defaults to "FIT". */
toRectangle(scaleMode? :"FILL" | "FIT" | "CROP" | "TILE") :Promise<RectangleNode>
}
interface ImgOptions {
type? :string // mime type
width? :number
height? :number
}
interface ImgConstructor {
new(data :ArrayBufferLike|Uint8Array|ArrayLike<number>, optionsOrWidth? :ImgOptions|number): Img<Uint8Array>;
new(url :string, optionsOrWidth? :ImgOptions|number): Img<null>;
(data :ArrayBufferLike|Uint8Array|ArrayLike<number>, optionsOrWidth? :ImgOptions|number): Img<Uint8Array>;
(url :string, optionsOrWidth? :ImgOptions|number): Img<null>;
}
var Img: ImgConstructor;
// ------------------------------------------------------------------------------------
// path, file, data
namespace Path {
/** Returns the filename extension without ".". Returns "" if none. */
function ext(name :string) :string
/** Returns the directory part of the path. E.g. "/foo/bar/baz" => "/foo/bar" */
function dir(path :string) :string
/** Returns the base of the path. E.g. "/a/b" => "b" */
function base(path :string) :string
/** Cleans up the pathname. E.g. "a/c//b/.." => "a/c" */
function clean(path :string) :string
/** True if the path is absolute */
function isAbs(path :string) :bool
/** Returns a path with paths joined together. E.g. ["foo/", "//bar", "baz"] => "foo/bar/baz" */
function join(...paths :string[]) :string
function join(paths :string[]) :string
/** Returns a list of path components. E.g. "/foo//bar/" => ["", "foo", "bar"] */
function split(path :string) :string[]
}
/**
* Inspects the header (first ~20 or so bytes) of data to determine the type of file.
* Similar to the POSIX "file" program. Returns null if unknown.
*/
function fileType(data :ArrayLike<byte>|ArrayBuffer) :FileTypeInfo|null
/** Returns mime type and other information for the file, based on the provided filename. */
function fileType(filename :string) :FileTypeInfo|null
/** Data returned by the fileType function, describing a type of file data */
interface FileTypeInfo {
type :string // mime type
exts :string[] // filename extensions
description? :string
}
/**
* Returns a Uint8Array of the input.
* If the input is a string, it's expected to be a description of bytes, not a literal.
* Example: "FF a7 0x9, 4" (whitespace, linebreaks and comma are ignored)
* If the input is some kind of list, it is converted if needed to a Uint8Array.
*/
function Bytes(input :string|ArrayLike<byte>|ArrayBuffer|Iterable<byte>) :Uint8Array
// ------------------------------------------------------------------------------------
// Figma
/** A node that may have children */
type ContainerNode = BaseNode & ChildrenMixin
// [All nodes which extends DefaultShapeMixin]
/** Shape is a node with visible geometry. I.e. may have fill, stroke etc. */
type Shape = BooleanOperationNode
| EllipseNode
| LineNode
| PolygonNode
| RectangleNode
| StarNode
| TextNode
| VectorNode
/** Get the current selection in Figma */
function selection() :ReadonlyArray<SceneNode>;
/** Get the nth currently-selected node in Figma */
function selection(index :number) :SceneNode|null;
/** Set the current selection. Non-selectable nodes of n, like pages, are ignored. */
function setSelection<T extends BaseNode|null|undefined|ReadonlyArray<BaseNode|null|undefined>>(n :T) :T;
/** Version of Figma plugin API that is currently in use */
var apiVersion :string
/** The "MIXED" symbol (figma.mixed), signifying "mixed properties" */
var MIXED :symbol
/** Current page. Equivalent to figma.currentPage */
var currentPage :PageNode
// ------------------------------------------------------------------------------------
// viewport
/** Viewport */
var viewport :SViewportAPI
interface SViewportAPI extends ViewportAPI {
/**
* Save the viewport state on a stack.
* You can later call restore() to restore the last save()d viewport, or call
* restore(state) to restore a from a specific call to save().
* If autorestore=false, restore() will NOT be called when the script ends.
* Returns an opaque value that identifies the viewport state, which can be used with restore().
*/
save(autorestore? :boolean /*=true*/) :SViewportState
/** Restore the most recently save()d viewport */
restore() :void
/** Restore a specific viewport */
restore(state :SViewportState|null) :void
/** Restore the most recently save()d viewport with animation */
restoreAnimated(duration? :number, timingf? :SAnimationTimingFunction) :SAnimation
/** Restore a specific viewport with animation */
restoreAnimated(state :SViewportState|null, duration? :number, timingf? :SAnimationTimingFunction) :SAnimation
/** Convenience function equivalent to setting viewport.center and viewport.zoom */
set(center :Vector|null, zoom? :number|null) :void
/**
* Change viewport with transitional animation.
* The returned SAnimation promise resolves when the animation completes.
* Call cancel() on the returned SAnimation to cancel the animation.
* When cancelled, the viewport will be left in whatever state it was during the animation.
* duration defaults to 1.0 seconds, timingf defaults to default of animate.transition.
*/
setAnimated(center :Vector|null, zoom? :number|null, duration? :number, timingf? :SAnimationTimingFunction) :SAnimation
/**
* Convenience function equivalent to calling viewport.save() and viewport.set().
* If autorestore=false, restore() will NOT be called when the script ends.
* Returns an opaque value that identifies the viewport state, which can be used with restore().
*/
setSave(center :Vector|null, zoom? :number|null, autorestore? :boolean /*=true*/) :SViewportState
/**
* Adjust viewport position and zoom around the provided node or nodes.
*/
focus(nodes: ReadonlyArray<BaseNode>|BaseNode) :void
/**
* Save the viewport and then adjust position and zoom around the provided node or nodes.
* If zoom is provided, use explicit zoom level instead of automatic.
* If autorestore=false, restore() will NOT be called when the script ends.
*/
focusSave(nodes: ReadonlyArray<BaseNode>|BaseNode, zoom? :number, autorestore? :boolean /*=true*/) :SViewportState
/**
* Adjust viewport position and zoom around the provided node or nodes, animated starting from
* the current viewport.
*/
focusAnimated(nodes: ReadonlyArray<BaseNode>|BaseNode, duration? :number, timingf? :SAnimationTimingFunction) :SAnimation
}
interface SViewportState {} // opaque
// End of viewport
// ------------------------------------------------------------------------------------
/**
* Add node to current page.
* Equivalent to `(figma.currentPage.appendChild(n),n)`
*/
function addToPage<N extends SceneNode>(n :N) :N
/**
* Store data on the user's local machine. Similar to localStorage.
* Data may disappear if user clears their web browser cache.
*/
var clientStorage: ClientStorageAPI
type NodeProps<N> = Partial<Omit<N,"type">>
// Node constructors
// Essentially figma.createNodeType + optional assignment of props
//
/** Creates a new Page node */
function Page(props? :NodeProps<PageNode>|null, ...children :SceneNode[]): PageNode;
/** Creates a new Rectangle node */
function Rectangle(props? :NodeProps<RectangleNode>) :RectangleNode;
/** Creates a new Line node */
function Line(props? :NodeProps<LineNode>|null): LineNode;
/** Creates a new Ellipse node */
function Ellipse(props? :NodeProps<EllipseNode>|null): EllipseNode;
/** Creates a new Polygon node */
function Polygon(props? :NodeProps<PolygonNode>|null): PolygonNode;
/** Creates a new Star node */
function Star(props? :NodeProps<StarNode>|null): StarNode;
/** Creates a new Text node */
function Text(props? :NodeProps<TextNode>|null): TextNode;
/** Creates a new BooleanOperation node */
function BooleanOperation(props? :NodeProps<BooleanOperationNode>|null): BooleanOperationNode;
/** Creates a new Frame node */
function Frame(props? :NodeProps<FrameNode>|null, ...children :SceneNode[]): FrameNode;
/** Creates a new Group node */
function Group(props :NodeProps<GroupNode & {index :number}>|null, ...children :SceneNode[]): GroupNode;
/** Creates a new Group node */
function Group(...children :SceneNode[]): GroupNode;
/** Creates a new Component node */
function Component(props? :NodeProps<ComponentNode>|null, ...children :SceneNode[]): ComponentNode;
/** Creates a new Slice node */
function Slice(props? :NodeProps<SliceNode>|null): SliceNode;
/** Creates a new PaintStyle node */
function PaintStyle(props? :NodeProps<PaintStyle>|null): PaintStyle;
/** Creates a new TextStyle node */
function TextStyle(props? :NodeProps<TextStyle>|null): TextStyle;
/** Creates a new EffectStyle node */
function EffectStyle(props? :NodeProps<EffectStyle>|null): EffectStyle;
/** Creates a new GridStyle node */
function GridStyle(props? :NodeProps<GridStyle>|null): GridStyle;
/** DEPRECATED use createVector or buildVector instead. */
function Vector(props? :NodeProps<VectorNode>|null): VectorNode;
/** Creates a new Page node */
function createPage(props? :NodeProps<PageNode>|null, ...children :SceneNode[]): PageNode;
/** Creates a new Rectangle node */
function createRectangle(props? :NodeProps<RectangleNode>) :RectangleNode;
/** Creates a new Line node */
function createLine(props? :NodeProps<LineNode>|null): LineNode;
/** Creates a new Ellipse node */
function createEllipse(props? :NodeProps<EllipseNode>|null): EllipseNode;
/** Creates a new Polygon node */
function createPolygon(props? :NodeProps<PolygonNode>|null): PolygonNode;
/** Creates a new Star node */
function createStar(props? :NodeProps<StarNode>|null): StarNode;
/**
* Creates a new Vector node with an empty vector network.
* For building vector networks, see buildVector()
*/
function createVector(props? :NodeProps<VectorNode>|null): VectorNode;
/** Creates a new Text node */
function createText(props? :NodeProps<TextNode>|null): TextNode;
/** Creates a new BooleanOperation node */
function createBooleanOperation(props? :NodeProps<BooleanOperationNode>|null): BooleanOperationNode;
/** Creates a new Frame node */
function createFrame(props? :NodeProps<FrameNode>|null, ...children :SceneNode[]): FrameNode;
/** Creates a new Group node */
function createGroup(props :NodeProps<GroupNode & {index :number}>|null, ...children :SceneNode[]): GroupNode;
/** Creates a new Group node */
function createGroup(...children :SceneNode[]): GroupNode;
/** Creates a new Component node */
function createComponent(props? :NodeProps<ComponentNode>|null, ...children :SceneNode[]): ComponentNode;
/** Creates a new Slice node */
function createSlice(props? :NodeProps<SliceNode>|null): SliceNode;
/** Creates a new PaintStyle node */
function createPaintStyle(props? :NodeProps<PaintStyle>|null): PaintStyle;
/** Creates a new TextStyle node */
function createTextStyle(props? :NodeProps<TextStyle>|null): TextStyle;
/** Creates a new EffectStyle node */
function createEffectStyle(props? :NodeProps<EffectStyle>|null): EffectStyle;
/** Creates a new GridStyle node */
function createGridStyle(props? :NodeProps<GridStyle>|null): GridStyle;
// Type guards, nodes
//
/** Checks if node is of type Document */
function isDocument(n :BaseNode|null|undefined) :n is DocumentNode;
/** Checks if node is of type Page */
function isPage(n :BaseNode|null|undefined) :n is PageNode;
/** Checks if node is of type Rectangle */
function isRectangle(n :BaseNode|null|undefined) :n is RectangleNode;
/** Checks if node is of type Rectangle */
function isRect(n :BaseNode|null|undefined) :n is RectangleNode;
/** Checks if node is of type Line */
function isLine(n :BaseNode|null|undefined): n is LineNode;
/** Checks if node is of type Ellipse */
function isEllipse(n :BaseNode|null|undefined): n is EllipseNode;
/** Checks if node is of type Polygon */
function isPolygon(n :BaseNode|null|undefined): n is PolygonNode;
/** Checks if node is of type Star */
function isStar(n :BaseNode|null|undefined): n is StarNode;
/** Checks if node is of type Vector */
function isVector(n :BaseNode|null|undefined): n is VectorNode;
/** Checks if node is of type Text */
function isText(n :BaseNode|null|undefined): n is TextNode;
/** Checks if node is of type BooleanOperation */
function isBooleanOperation(n :BaseNode|null|undefined): n is BooleanOperationNode;
/** Checks if node is of type Frame */
function isFrame(n :BaseNode|null|undefined): n is FrameNode;
/** Checks if node is of type Group */
function isGroup(n :BaseNode|null|undefined): n is GroupNode;
/** Checks if node is of type Component */
function isComponent(n :BaseNode|null|undefined): n is ComponentNode;
/** Checks if node is of type Component */
function isInstance(n :BaseNode|null|undefined): n is InstanceNode;
/** Checks if node is of type Slice */
function isSlice(n :BaseNode|null|undefined): n is SliceNode;
/** Checks if node is a type of SceneNode */
function isSceneNode(n :BaseNode|null|undefined): n is SceneNode;
/** Checks if node is a type with children */
function isContainerNode(n :BaseNode|null|undefined): n is ContainerNode;
/** Checks if node is a Shape */
function isShape(n :BaseNode|null|undefined): n is Shape;
/**
* Returns true if n is a shape with at least one visible image.
* If a layer has an "image" icon in Figma, this returns true.
*/
function isImage<N extends Shape>(n :N) :n is N & { fills :ReadonlyArray<Paint> }; // fills not mixed
function isImage(n :BaseNode) :n is Shape & { fills :ReadonlyArray<Paint> }; // fills not mixed
// Type guards, paints
//
/** Checks if paint is an image */
function isImage(p :Paint|null|undefined) :p is ImagePaint;
/** Checks if paint is a gradient */
function isGradient(p :Paint|null|undefined) :p is GradientPaint;
/** Checks if paint is a solid color */
function isSolidPaint(p :Paint|null|undefined) :p is SolidPaint;
// Type guards, styles
//
/** Checks if style is a paint style */
function isPaintStyle(s :BaseStyle|null|undefined) :s is PaintStyle;
/** Checks if style is a text style */
function isTextStyle(s :BaseStyle|null|undefined) :s is TextStyle;
/** Checks if style is a effect style */
function isEffectStyle(s :BaseStyle|null|undefined) :s is EffectStyle;
/** Checks if style is a grid style */
function isGridStyle(s :BaseStyle|null|undefined) :s is GridStyle;
interface Color extends RGB { // compatible with RGB interface
readonly r: number
readonly g: number
readonly b: number
withAlpha(a :number) :ColorWithAlpha
readonly paint :SolidPaint
}
interface ColorWithAlpha extends Color, RGBA { // compatible with RGBA interface
readonly a: number
withoutAlpha() :Color
}
/** Create a color with alpha channel. Values should be in range [0-1]. */
function Color(r :number, g: number, b :number, a :number) :ColorWithAlpha;
/** Create a color. Values should be in range [0-1]. */
function Color(r :number, g: number, b :number) :Color;
/**
* Create a color from hexadecimal string.
* hexstr should be in the format "RRGGBB", "RGB" or "HH" for greyscale.
* Examples: C800A1, C0A, CC
*/
function Color(hexstr :string) :Color;
/** Create a color. Values should be in range [0-1]. */
function RGB(r :number, g: number, b :number) :Color;
/** Create a color with alpha channel. Values should be in range [0-1]. */
function RGBA(r :number, g: number, b :number, a? :number) :ColorWithAlpha;
// common colors
/** #000000 Color(0 , 0 , 0) */ const BLACK :Color;
/** #FFFFFF Color(1 , 1 , 1) */ const WHITE :Color;
/** #808080 Color(0.5 , 0.5 , 0.5) */ const GREY :Color;
/** #808080 Color(0.5 , 0.5 , 0.5) */ const GRAY :Color;
/** #FF0000 Color(1 , 0 , 0) */ const RED :Color;
/** #00FF00 Color(0 , 1 , 0) */ const GREEN :Color;
/** #0000FF Color(0 , 0 , 1) */ const BLUE :Color;
/** #00FFFF Color(0 , 1 , 1) */ const CYAN :Color;
/** #FF00FF Color(1 , 0 , 1) */ const MAGENTA :Color;
/** #FFFF00 Color(1 , 1 , 0) */ const YELLOW :Color;
/** #FF8000 Color(1 , 0.5 , 0) */ const ORANGE :Color;
// ------------------------------------------------------------------------------------
// MutVectorNetwork
interface MutVectorVertex {
x :number
y :number
strokeCap? :StrokeCap
strokeJoin? :StrokeJoin
cornerRadius? :number
handleMirroring? :HandleMirroring
}
interface MutVectorSegment {
start :number
end :number
tangentStart? :Vector // Defaults to { x: 0, y: 0 }
tangentEnd? :Vector // Defaults to { x: 0, y: 0 }
}
interface MutVectorRegion {
windingRule :WindingRule
loops :number[][]
}
interface MutVectorNetwork {
vertices :MutVectorVertex[]
segments :MutVectorSegment[]
regions :MutVectorRegion[]
}
interface MutVectorNetworkContext {
/** The underlying mutable vector network. It's okay to edit this. */
readonly vectorNetwork :MutVectorNetwork
/** Add one vertex. Returns its index. */
vertex(x :number, y :number) :int
/** Add vertices. Returns their indices. */
vertices(...v :MutVectorVertex[]) :int[]
/** Add a segment. Returns the added segment's index. */
segment(
startVertexIndex :int, endVertexIndex :int,
tangentStartX? :number, tangentStartY? :number,
tangentEndX? :number, tangentEndY? :number,
) :int
/** Add a line */
line(from :Vector, to :Vector) :void
/** Add a circle */
circle(center :Vector, radius :number) :void
}
/**
* Create a new MutVectorNetworkContext which has a mutable vector network.
* If an existing vector network is provided for init, it is deep-copied and used as
* the initial state of the context's vector network state.
*/
function createVectorNetworkContext(init? :VectorNetwork|null) :MutVectorNetworkContext
/**
* Build a new vector node based on an existing vector node or network.
* The builder function will be called with a newly created context.
*/
export function buildVector(
init :NodeProps<VectorNode>|null|undefined,
builder :(c:MutVectorNetworkContext)=>void,
) :VectorNode
/**
* Build a new vector node.
* The builder function will be called with a newly created context.
*/
export function buildVector(
builder :(c:MutVectorNetworkContext)=>void,
) :VectorNode
// ------------------------------------------------------------------------------------
// find & visit
/** Returns the first node encountered in scope which the predicate returns */
function findOne<R extends SceneNode>(scope :BaseNode, p :(n :PageNode|SceneNode) => R|false) :R|null
/** Returns the first node encountered in scope for which predicate returns a truthy value for */
function findOne(scope :DocumentNode, p :(n :PageNode|SceneNode) => boolean|undefined) :PageNode|SceneNode|null
/** Returns the first node encountered in scope for which predicate returns a truthy value for */
function findOne(scope :PageNode|SceneNode, p :(n :SceneNode) => boolean|undefined) :SceneNode|null
/** Returns the first node on the current page which the predicate returns */
function findOne<R extends SceneNode>(p :(n :SceneNode) => R|false) :R|null
/** Returns the first node on the current page for which predicate returns a truthy value for */
function findOne(p :(n :SceneNode) => boolean|undefined) :SceneNode|null
/**
* find traverses the tree represented by node and
* returns a list of all nodes for which predicate returns true.
*
* The predicate is not called for `node` when its a single node,
* but when `node` is an array, predicate is called for each item in `node`.
*/
function find<R extends BaseNode>(
node :ContainerNode|ReadonlyArray<BaseNode>,
predicate :(n :BaseNode) => R|false,
options? :FindOptions,
) :Promise<R[]>
function find(
node :ContainerNode|ReadonlyArray<BaseNode>,
predicate :(n :BaseNode) => boolean|undefined,
options? :FindOptions,
) :Promise<BaseNode[]>
/**
* find traverses the current page and
* returns a list of all nodes for which predicate returns true.
*
* The predicate is not called for `node` when its a single node,
* but when `node` is an array, predicate is called for each item in `node`.
*/
function find<R extends BaseNode>(
predicate :(n :BaseNode) => R|false,
options? :FindOptions,
) :Promise<R[]>
function find(
predicate :(n :BaseNode) => boolean|undefined,
options? :FindOptions,
) :Promise<BaseNode[]>
/**
* visit traverses the tree represented by node, calling visitor for each node.
*
* If the visitor returns false for a node with children, that
* node's children will not be visited. This allows efficient searching
* where you know that you can skip certain branches.
*
* Note: visitor is not called for the initial `node` argument.
*/
function visit(
node :ContainerNode|ReadonlyArray<ContainerNode>,
visitor :(n :BaseNode) => any,
) :Promise<void>;
/** Options to find() */
interface FindOptions {
includeHidden? :boolean // include hidden layers
}
/**
* Returns a sequence of numbers in the range [start–end),
* incrementing in steps or 1 if steps is not provided.
*
* Note that the last value may be smaller than end, depending on the value of step.
*/
function range(start :number, end :number, step? :number) :LazySeq<number,number,number>
/** Returns a sequence of numbers in the range [0–end) */
function range(end :number) :LazySeq<number,number,number>
/** Sequence which values are computed lazily; as requested */
interface LazySeq<T, OffsT = T|undefined, LenT = number|undefined> extends Iterable<T> {
readonly length :LenT // Infinity if unbounded
map<R>(f :(value :T, index :number)=>R) :R[]
array() :T[]
at(index :number) :OffsT
join(glue :string) :string
}
// ------------------------------------------------------------------------------------
namespace scripter {
/** Visualize print() results inline in editor. Defaults to true */
var visualizePrint :bool
/** Close scripter, optionally showing a message (e.g. reason, status, etc) */
function close(message? :string) :void
/** Register a function to be called when the script ends */
function addEndCallback(f :Function) :void
/** Unregister a function to be called when the script ends */
function removeEndCallback(f :Function) :void
/** A function to be called when the script ends */
var onend :()=>void
}
// ------------------------------------------------------------------------------------
namespace libui {
/** Presents a short ambient message to the user, at the bottom of the screen */
function notify(message: string, options?: NotificationOptions): NotificationHandler
/**
* Shows a range slider inline with the code.
*
* Yields values as the user interacts with the slider. Iteration ends when the user
* either closes the UI control or stops the script.
*/
function rangeInput(init? :UIRangeInit) :UIInputIterator<number>
/** Initial options for rangeInput */
interface UIRangeInit {
value? :number
min? :number
max? :number
step? :number
}
}
interface UIInputIterator<T> extends AsyncIterable<T> {
[Symbol.asyncIterator](): AsyncIterator<T,T>;
}
// ------------------------------------------------------------------------------------
namespace libgeometry {
class Rect {
x :number
y :number
width :number
height :number
constructor(x :number, y :number, width :number, height :number)
position() :Vec
containsPoint(v :Vec) :boolean
translate(v :Vec) :Rect
}
class Vec implements Vector {
x :number
y :number
constructor(x :number, y :number)
constructor(v :Vector)
isInside(r :Rect) :bool
distanceTo(v :Vec) :number
sub(v :Vec|number) :Vec
add(v :Vec|number) :Vec
mul(v :Vec|number) :Vec
div(v :Vec|number) :Vec
}
}
// ------------------------------------------------------------------------------------
namespace libvars {
interface Var<T> {
value :T
showSlider(init? :libui.UIRangeInit) :Promise<number>
}
class VarBindings {
/** coalesceDuration: group changes happening within milliseconds into one update */
constructor(coalesceDuration? :number)
/** Add a variable */
addVar<T>(value :T) :Var<T>
/** Add multiple variables */
addVars<T>(count :number, value :T) :Var<T>[]
/** Remove a variable */
removeVar(v :Var<any>) :void
/** Remove all variables */
removeAllVars() :void
/** Read updates. Ends when all vars are removed. */
updates() :AsyncIterableIterator<void>
}
}
// ------------------------------------------------------------------------------------
namespace Base64 {
/** Encode data as base-64 */
function encode(data :Uint8Array|ArrayBuffer|string) :string
/** Decode base-64 encoded data */
function decode(encoded :string) :Uint8Array
}
// ------------------------------------------------------------------------------------
// Patch TS env since Monaco doesn't seem to work with "libs" in TS compiler settigs.
// lib.es2018 async iterator
interface SymbolConstructor {
readonly asyncIterator: symbol;
}
interface AsyncIterator<T, TReturn = any, TNext = undefined> {
next(...args: [] | [TNext | PromiseLike<TNext>]): Promise<IteratorResult<T, TReturn>>;
return?(value?: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw?(e?: any): Promise<IteratorResult<T, TReturn>>;
}
interface AsyncIterable<T> {
[Symbol.asyncIterator](): AsyncIterator<T>;
}
interface AsyncIterableIterator<T> extends AsyncIterator<T> {
[Symbol.asyncIterator](): AsyncIterableIterator<T>;
}
} | the_stack |
import * as React from 'react';
import { createRef } from "office-ui-fabric-react/lib/Utilities";
import styles from './GraphCalendar.module.scss';
import * as strings from "GraphCalendarWebPartStrings";
import { IGraphCalendarProps } from './IGraphCalendarProps';
import { MSGraphClient } from "@microsoft/sp-http";
import FullCalendar from '@fullcalendar/react';
import { EventInput } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import * as moment from 'moment-timezone';
import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel';
import { extendMoment } from 'moment-range';
import allLocales from '@fullcalendar/core/locales-all';
const { range } = extendMoment(moment);
interface IGraphCalendarState {
events: EventInput[];
height: number;
currentActiveStartDate: Date;
currentActiveEndDate: Date;
isEventDetailsOpen: boolean;
currentSelectedEvent: EventInput;
groupId: string;
tabType: TabType;
}
enum TabType {
TeamsTab,
PersonalTab
}
export default class GraphCalendar extends React.Component<IGraphCalendarProps, IGraphCalendarState> {
private calendar = createRef<FullCalendar>();
private calendarLang: string = null;
/**
* Builds the Component with the provided properties
* @param props Properties of the web part
*/
constructor(props: IGraphCalendarProps) {
super(props);
// If this is running in Teams, embed the specific Teams styling
if (this._isRunningInTeams()) {
import("./GraphCalendar.Teams.module.scss");
if (this.props.teamsContext.theme == "dark") {
import("./GraphCalendar.Teams.Dark.module.scss");
}
}
//Set language of the calendar (if language is unknown, use english as default)
const allLanguages: Map<string, string> = this._createLangMap();
if (this._isRunningInTeams()) {
this.calendarLang = allLanguages.get(this.props.teamsContext.locale) || "en";
} else {
this.calendarLang = allLanguages.get(this.props.context.pageContext.cultureInfo.currentCultureName) || "en";
}
this.state = {
events: [],
height: this._calculateHeight(),
currentActiveStartDate: null,
currentActiveEndDate: null,
isEventDetailsOpen: false,
currentSelectedEvent: null,
groupId: this._isRunningInTeams() ? this.props.teamsContext.groupId : this.props.context.pageContext.site.group ? this.props.context.pageContext.site.group.id : "",
tabType: this._isRunningInTeams() ? (this._isPersonalTab() ? TabType.PersonalTab : TabType.TeamsTab) : TabType.TeamsTab
};
}
/**
* When the component is initially mounted
*/
public componentDidMount(): void {
// Gets the calendar current Active dates
let calendarStartDate = this.calendar.value.getApi().view.activeStart;
let calendarEndDate = this.calendar.value.getApi().view.activeEnd;
// Loads the events
this._loadEvents(calendarStartDate, calendarEndDate);
}
/**
* Renders the web part
*/
public render(): React.ReactElement<IGraphCalendarProps> {
return (
<div className={styles.graphCalendar}>
<FullCalendar
ref={this.calendar}
defaultView="dayGridMonth"
plugins={[dayGridPlugin]}
windowResize={this._handleResize.bind(this)}
datesRender={this._datesRender.bind(this)}
eventClick={this._openEventPanel.bind(this)}
height={this.state.height}
events={this.state.events}
locales={allLocales}
locale={this.calendarLang} />
{this.state.currentSelectedEvent &&
<Panel
isOpen={this.state.isEventDetailsOpen}
type={PanelType.smallFixedFar}
headerText={this.state.currentSelectedEvent ? this.state.currentSelectedEvent.title : ""}
onDismiss={this._closeEventPanel.bind(this)}
isLightDismiss={true}
closeButtonAriaLabel={strings.Close}>
<h3>{strings.StartTime}</h3>
<span>{moment(this.state.currentSelectedEvent.start).format('MMMM Do YYYY [at] h:mm:ss a')}</span>
<h3>{strings.EndTime}</h3>
<span>{moment(this.state.currentSelectedEvent.end).format('MMMM Do YYYY [at] h:mm:ss a')}</span>
{this.state.currentSelectedEvent.extendedProps["location"] &&
<div>
<h3>{strings.Location}</h3>
<span>{this.state.currentSelectedEvent.extendedProps["location"]}</span>
</div>
}
{this.state.currentSelectedEvent.extendedProps["body"] &&
<div>
<h3>{strings.Body}</h3>
<span>{this.state.currentSelectedEvent.extendedProps["body"]}</span>
</div>
}
</Panel>
}
</div>
);
}
/**
* Calculates the dynamic height of the surface to render.
* Mainly used for Teams validation so it renders "full-screen" in Teams
*/
private _calculateHeight(): number {
if (this._isRunningInTeams()) {
return window.innerHeight - 30;
} else {
return 600;
}
}
/**
* Validates if the current web part is running in Teams
*/
private _isRunningInTeams() {
return this.props.teamsContext;
}
/**
* Validates if the current web part is running in a Personal Tab
*/
private _isPersonalTab() {
let _isPersonalTab: Boolean = false;
if (this._isRunningInTeams() && !this.props.teamsContext.teamId) {
_isPersonalTab = true;
}
return _isPersonalTab;
}
/**
* Handles the click event and opens the OUIF Panel
* @param eventClickInfo The information about the selected event
*/
private _openEventPanel(eventClickInfo: any) {
this.setState({
isEventDetailsOpen: true,
currentSelectedEvent: eventClickInfo.event
});
}
/**
* Handles the click event on the dismiss from the Panel and closes the OUIF Panel
*/
private _closeEventPanel() {
this.setState({
isEventDetailsOpen: true,
currentSelectedEvent: null
});
}
/**
* If the view changed, reload the events based on the active view
* @param info Information about the current active view
*/
private _datesRender(info: any) {
if (this.calendar.value) {
// If the active view has changed
if ((this.state.currentActiveStartDate && this.state.currentActiveEndDate) && this.state.currentActiveStartDate.toString() != info.view.activeStart.toString() && this.state.currentActiveEndDate.toString() != info.view.activeEnd.toString()) {
this._loadEvents(info.view.activeStart, info.view.activeEnd);
}
}
}
/**
* Handles the resize event when in Microsoft Teams to ensure a proper responsive behaviour
*/
private _handleResize() {
if (this._isRunningInTeams()) {
this.setState({
height: window.innerHeight - 30
});
}
}
/**
* Convert data to Array<EventInput>
* @param data Events from API
*/
private _transformEvents(data: any): Array<EventInput> {
let events: Array<EventInput> = new Array<EventInput>();
data.value.map((item: any) => {
// Build a Timezone enabled Date
let currentStartDate = moment.tz(item.start.dateTime, item.start.timeZone);
let currentEndDate = moment.tz(item.end.dateTime, item.end.timeZone);
// Adding all retrieved events to the result array
events.push({
id: item.id,
title: item.subject,
// If the event is an All Day event, add 1 day without Timezone to the start date
start: !item.isAllDay ? currentStartDate.clone().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format() : moment(currentStartDate).add(1, 'd').toISOString(),
// If the event is an All Day event, add 1 day without Timezone to the end date
end: !item.isAllDay ? currentEndDate.clone().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format() : moment(currentEndDate).add(1, 'd').toISOString(),
allDay: item.isAllDay,
location: item.location.displayName,
body: item.bodyPreview,
type: item.type
});
});
return events;
}
/**
* Check if the recurring events need to be shown on the current state of the Calendar
* If the range of the recurring event overlaps the range of the Calendar, then the event needs to be shown.
* @param data All the recurrent (base) events ever made
* @param startDate The first visible date on the calendar
* @param endDate The last visible date on the calendar
*/
private _filterRecEvents(data: any, startDate: Date, endDate: Date): Array<EventInput> {
let events: Array<EventInput> = new Array<EventInput>();
//Range of the Calendar
var r1 = range(startDate, endDate);
data.value.map((item: any) => {
// Build a Timezone enabled Date
let currentStartDate = moment.tz(item.start.dateTime, item.start.timeZone);
let currentEndDate = moment.tz(item.end.dateTime, item.end.timeZone);
var d1 = item.recurrence.range.startDate;
var d2 = item.recurrence.range.endDate;
var recStartDate = moment(d1).toDate();
var recEndDate = moment(d2).toDate();
//Range of the recurring event item
var r2 = range(recStartDate, recEndDate);
//Check if both ranges overlap
if (!!r1.overlaps(r2)) {
events.push({
id: item.id,
title: item.subject,
// If the event is an All Day event, add 1 day without Timezone to the start date
start: !item.isAllDay ? currentStartDate.clone().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format() : moment(currentStartDate).add(1, 'd').toISOString(),
// If the event is an All Day event, add 1 day without Timezone to the end date
end: !item.isAllDay ? currentEndDate.clone().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format() : moment(currentEndDate).add(1, 'd').toISOString(),
allDay: item.isAllDay,
location: item.location.displayName,
body: item.bodyPreview,
type: item.type
});
}
});
return events;
}
/**
* Loads the Events based on the current state of the Calendar
* @param startDate The first visible date on the calendar
* @param endDate The last visible date on the calendar
*/
private _loadEvents(startDate: Date, endDate: Date): void {
// If a Group was found or running in the context of a Personal tab, execute the query. If not, do nothing.
if (this.state.groupId || this.state.tabType == TabType.PersonalTab) {
var events: Array<EventInput> = new Array<EventInput>();
this.props.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient): void => {
let apiUrl: string = `/groups/${this.state.groupId}/events`;
if (this._isPersonalTab()) {
apiUrl = '/me/events';
}
client
.api(apiUrl)
.version("v1.0")
.select('subject,start,end,location,bodyPreview,isAllDay,type')
.filter(`start/dateTime ge '${startDate.toISOString()}' and end/dateTime le '${endDate.toISOString()}' and type eq 'singleInstance'`)
.top(this.props.limit)
.get((err, res) => {
if (err) {
console.error(err);
return;
}
//Transform API data to Array<EventInput>
events = this._transformEvents(res);
if (this.props.showRecurrence) {
//Get recurring events and merge with the other (standard) events
this._getRecurringMaster(startDate, endDate).then((recData: Array<EventInput>) => {
if (recData.length > 0) {
this._getRecurrentEvents(recData, startDate, endDate).then((recEvents: Array<EventInput>) => {
this.setState({
events: [...recEvents, ...events].slice(0, this.props.limit),
});
});
} else {
this.setState({
events: events,
});
}
});
} else {
//Show only (standard) events
this.setState({
events: events,
});
}
// Sets the state with current active calendar dates
this.setState({
currentActiveStartDate: startDate,
currentActiveEndDate: endDate,
currentSelectedEvent: null
});
});
});
}
}
/**
* Get all recurrent events based on the current state of the Calendar
* @param events All the recurrent base events
* @param startDate The first visible date on the calendar
* @param endDate The last visible date on the calendar
*/
private _getRecurrentEvents(events: Array<EventInput>, startDate: Date, endDate: Date): Promise<Array<EventInput>> {
return new Promise<Array<EventInput>>((resolve, reject) => {
this.props.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient): void => {
var recEvents: Array<EventInput> = new Array<EventInput>();
var count = 0;
events.map((item: any) => {
let apiUrl: string = `/groups/${this.state.groupId}/events/${item.id}/instances?startDateTime=${startDate.toISOString()}&endDateTime=${endDate.toISOString()}`;
if (this._isPersonalTab()) {
apiUrl = `/me/events/${item.id}/instances?startDateTime=${startDate.toISOString()}&endDateTime=${endDate.toISOString()}`;
}
client
.api(apiUrl)
.version("v1.0")
.select('subject,start,end,location,bodyPreview,isAllDay,type')
.get((err, res) => {
if (err) {
reject(err);
}
recEvents = recEvents.concat(this._transformEvents(res));
count += 1;
if (count == events.length) {
resolve(recEvents);
}
});
});
});
});
}
/**
* Get all recurrent (base) events ever created
* Filter the base events based on the current state of the Calendar
* @param startDate The first visible date on the calendar
* @param endDate The last visible date on the calendar
*/
private _getRecurringMaster(startDate: Date, endDate: Date): Promise<Array<EventInput>> {
return new Promise<Array<EventInput>>((resolve, reject) => {
this.props.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient): void => {
let apiUrl: string = `/groups/${this.state.groupId}/events`;
if (this._isPersonalTab()) {
apiUrl = '/me/events';
}
client
.api(apiUrl)
.version("v1.0")
.select('subject,start,end,location,bodyPreview,isAllDay,type,recurrence')
.filter(`type eq 'seriesMaster'`) //recurrening event is type 'seriesMaster'
.get((err, res) => {
if (err) {
reject(err);
}
else {
var recEvents: Array<EventInput> = new Array<EventInput>();
recEvents = this._filterRecEvents(res, startDate, endDate);
resolve(recEvents);
}
});
});
});
}
/**
* Mapping for SharePoint languages with Fullcalendar languages
*/
private _createLangMap(): Map<string, string> {
var languages = new Map();
languages.set("en-US", "en"); //English
languages.set("ar-SA", "ar"); //Arabic
languages.set("bg-BG", "bg"); //Bulgarian
languages.set("ca-ES", "ca"); //Catalan
languages.set("cs-CZ", "cs"); //Czech
languages.set("da-DK", "da"); //Danish
languages.set("de-DE", "de"); //German
languages.set("el-GR", "el"); //Greek
languages.set("es-ES", "es"); //Spanish
languages.set("et-EE", "et"); //Estonian
languages.set("fi-FI", "fi"); //Finish
languages.set("fr-FR", "fr"); //French
languages.set("he-IL", "he"); //Hebrew
languages.set("hi-IN", "hi"); //Hindi
languages.set("hr-HR", "hr"); //Croatian
languages.set("hu-HU", "hu"); //Hungarian
languages.set("it-IT", "it"); //Italian
languages.set("kk-KZ", "kk"); //Kazakh
languages.set("ko-KR", "ko"); //Korean
languages.set("lt-LT", "lt"); //Lithuanian
languages.set("lv-LV", "lv"); //Latvian
languages.set("nb-NO", "nb"); //Norwegian
languages.set("nl-NL", "nl"); //Dutch
languages.set("pl-PL", "pl"); //Polish
languages.set("pt-BR", "pt-br"); //Portugues (Brazil)
languages.set("pt-PT", "pt"); //Portuguese (Portugal)
languages.set("ro-RO", "ro"); //Romanian
languages.set("ru-RU", "ru"); //Russian
languages.set("sk-SK", "sk"); //Slovak
languages.set("sl-SI", "sl"); //Slovenian
languages.set("sr-Latn-CS", "sr-cyrl"); //Serbian
languages.set("sv-SE", "sv"); //Swedish
languages.set("th-TH", "th"); //Thai
languages.set("tr-TR", "tr"); //Turkish
languages.set("uk-UA", "uk"); //Ukrainian
languages.set("zh-CN", "zh-cn"); //Chinese (Simplified)
languages.set("zh-TW", "zh-tw"); //Chinese (Taiwan)
return languages;
}
} | the_stack |
module android.text {
import KeyEvent = android.view.KeyEvent;
export class InputType {
/**
* Mask of bits that determine the overall class
* of text being given. Currently supported classes are:
* {@link #TYPE_CLASS_TEXT}, {@link #TYPE_CLASS_NUMBER},
* {@link #TYPE_CLASS_PHONE}, {@link #TYPE_CLASS_DATETIME}.
* <p>IME authors: If the class is not one you
* understand, assume {@link #TYPE_CLASS_TEXT} with NO variation
* or flags.<p>
*/
static TYPE_MASK_CLASS:number = 0x0000000f;
/**
* Mask of bits that determine the variation of
* the base content class.
*/
static TYPE_MASK_VARIATION:number = 0x00000ff0;
/**
* Mask of bits that provide addition bit flags
* of options.
*/
static TYPE_MASK_FLAGS:number = 0x00fff000;
/**
* Special content type for when no explicit type has been specified.
* This should be interpreted to mean that the target input connection
* is not rich, it can not process and show things like candidate text nor
* retrieve the current text, so the input method will need to run in a
* limited "generate key events" mode, if it supports it. Note that some
* input methods may not support it, for example a voice-based input
* method will likely not be able to generate key events even if this
* flag is set.
*/
static TYPE_NULL:number = 0x00000000;
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/**
* Class for normal text. This class supports the following flags (only
* one of which should be set):
* {@link #TYPE_TEXT_FLAG_CAP_CHARACTERS},
* {@link #TYPE_TEXT_FLAG_CAP_WORDS}, and.
* {@link #TYPE_TEXT_FLAG_CAP_SENTENCES}. It also supports the
* following variations:
* {@link #TYPE_TEXT_VARIATION_NORMAL}, and
* {@link #TYPE_TEXT_VARIATION_URI}. If you do not recognize the
* variation, normal should be assumed.
*/
static TYPE_CLASS_TEXT:number = 0x00000001;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: capitalize all characters. Overrides
* {@link #TYPE_TEXT_FLAG_CAP_WORDS} and
* {@link #TYPE_TEXT_FLAG_CAP_SENTENCES}. This value is explicitly defined
* to be the same as {@link TextUtils#CAP_MODE_CHARACTERS}. Of course,
* this only affects languages where there are upper-case and lower-case letters.
*/
static TYPE_TEXT_FLAG_CAP_CHARACTERS:number = 0x00001000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: capitalize the first character of
* every word. Overrides {@link #TYPE_TEXT_FLAG_CAP_SENTENCES}. This
* value is explicitly defined
* to be the same as {@link TextUtils#CAP_MODE_WORDS}. Of course,
* this only affects languages where there are upper-case and lower-case letters.
*/
static TYPE_TEXT_FLAG_CAP_WORDS:number = 0x00002000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: capitalize the first character of
* each sentence. This value is explicitly defined
* to be the same as {@link TextUtils#CAP_MODE_SENTENCES}. For example
* in English it means to capitalize after a period and a space (note that other
* languages may have different characters for period, or not use spaces,
* or use different grammatical rules). Of course,
* this only affects languages where there are upper-case and lower-case letters.
*/
static TYPE_TEXT_FLAG_CAP_SENTENCES:number = 0x00004000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: the user is entering free-form
* text that should have auto-correction applied to it. Without this flag,
* the IME will not try to correct typos. You should always set this flag
* unless you really expect users to type non-words in this field, for
* example to choose a name for a character in a game.
* Contrast this with {@link #TYPE_TEXT_FLAG_AUTO_COMPLETE} and
* {@link #TYPE_TEXT_FLAG_NO_SUGGESTIONS}:
* {@code TYPE_TEXT_FLAG_AUTO_CORRECT} means that the IME will try to
* auto-correct typos as the user is typing, but does not define whether
* the IME offers an interface to show suggestions.
*/
static TYPE_TEXT_FLAG_AUTO_CORRECT:number = 0x00008000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: the text editor (which means
* the application) is performing auto-completion of the text being entered
* based on its own semantics, which it will present to the user as they type.
* This generally means that the input method should not be showing
* candidates itself, but can expect the editor to supply its own
* completions/candidates from
* {@link android.view.inputmethod.InputMethodSession#displayCompletions
* InputMethodSession.displayCompletions()} as a result of the editor calling
* {@link android.view.inputmethod.InputMethodManager#displayCompletions
* InputMethodManager.displayCompletions()}.
* Note the contrast with {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} and
* {@link #TYPE_TEXT_FLAG_NO_SUGGESTIONS}:
* {@code TYPE_TEXT_FLAG_AUTO_COMPLETE} means the editor should show an
* interface for displaying suggestions, but instead of supplying its own
* it will rely on the Editor to pass completions/corrections.
*/
static TYPE_TEXT_FLAG_AUTO_COMPLETE:number = 0x00010000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: multiple lines of text can be
* entered into the field. If this flag is not set, the text field
* will be constrained to a single line. The IME may also choose not to
* display an enter key when this flag is not set, as there should be no
* need to create new lines.
*/
static TYPE_TEXT_FLAG_MULTI_LINE:number = 0x00020000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: the regular text view associated
* with this should not be multi-line, but when a fullscreen input method
* is providing text it should use multiple lines if it can.
*/
static TYPE_TEXT_FLAG_IME_MULTI_LINE:number = 0x00040000;
/**
* Flag for {@link #TYPE_CLASS_TEXT}: the input method does not need to
* display any dictionary-based candidates. This is useful for text views that
* do not contain words from the language and do not benefit from any
* dictionary-based completions or corrections. It overrides the
* {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} value when set.
* Please avoid using this unless you are certain this is what you want.
* Many input methods need suggestions to work well, for example the ones
* based on gesture typing. Consider clearing
* {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} instead if you just do not
* want the IME to correct typos.
* Note the contrast with {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} and
* {@link #TYPE_TEXT_FLAG_AUTO_COMPLETE}:
* {@code TYPE_TEXT_FLAG_NO_SUGGESTIONS} means the IME should never
* show an interface to display suggestions. Most IMEs will also take this to
* mean they should not try to auto-correct what the user is typing.
*/
static TYPE_TEXT_FLAG_NO_SUGGESTIONS:number = 0x00080000;
// ----------------------------------------------------------------------
/**
* Default variation of {@link #TYPE_CLASS_TEXT}: plain old normal text.
*/
static TYPE_TEXT_VARIATION_NORMAL:number = 0x00000000;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering a URI.
*/
static TYPE_TEXT_VARIATION_URI:number = 0x00000010;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering an e-mail address.
*/
static TYPE_TEXT_VARIATION_EMAIL_ADDRESS:number = 0x00000020;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering the subject line of
* an e-mail.
*/
static TYPE_TEXT_VARIATION_EMAIL_SUBJECT:number = 0x00000030;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering a short, possibly informal
* message such as an instant message or a text message.
*/
static TYPE_TEXT_VARIATION_SHORT_MESSAGE:number = 0x00000040;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering the content of a long, possibly
* formal message such as the body of an e-mail.
*/
static TYPE_TEXT_VARIATION_LONG_MESSAGE:number = 0x00000050;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering the name of a person.
*/
static TYPE_TEXT_VARIATION_PERSON_NAME:number = 0x00000060;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering a postal mailing address.
*/
static TYPE_TEXT_VARIATION_POSTAL_ADDRESS:number = 0x00000070;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering a password.
*/
static TYPE_TEXT_VARIATION_PASSWORD:number = 0x00000080;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering a password, which should
* be visible to the user.
*/
static TYPE_TEXT_VARIATION_VISIBLE_PASSWORD:number = 0x00000090;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering text inside of a web form.
*/
static TYPE_TEXT_VARIATION_WEB_EDIT_TEXT:number = 0x000000a0;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering text to filter contents
* of a list etc.
*/
static TYPE_TEXT_VARIATION_FILTER:number = 0x000000b0;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering text for phonetic
* pronunciation, such as a phonetic name field in contacts. This is mostly
* useful for languages where one spelling may have several phonetic
* readings, like Japanese.
*/
static TYPE_TEXT_VARIATION_PHONETIC:number = 0x000000c0;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering e-mail address inside
* of a web form. This was added in
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An IME must target
* this API version or later to see this input type; if it doesn't, a request
* for this type will be seen as {@link #TYPE_TEXT_VARIATION_EMAIL_ADDRESS}
* when passed through {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
* EditorInfo.makeCompatible(int)}.
*/
static TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS:number = 0x000000d0;
/**
* Variation of {@link #TYPE_CLASS_TEXT}: entering password inside
* of a web form. This was added in
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An IME must target
* this API version or later to see this input type; if it doesn't, a request
* for this type will be seen as {@link #TYPE_TEXT_VARIATION_PASSWORD}
* when passed through {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
* EditorInfo.makeCompatible(int)}.
*/
static TYPE_TEXT_VARIATION_WEB_PASSWORD:number = 0x000000e0;
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/**
* Class for numeric text. This class supports the following flags:
* {@link #TYPE_NUMBER_FLAG_SIGNED} and
* {@link #TYPE_NUMBER_FLAG_DECIMAL}. It also supports the following
* variations: {@link #TYPE_NUMBER_VARIATION_NORMAL} and
* {@link #TYPE_NUMBER_VARIATION_PASSWORD}.
* <p>IME authors: If you do not recognize
* the variation, normal should be assumed.</p>
*/
static TYPE_CLASS_NUMBER:number = 0x00000002;
/**
* Flag of {@link #TYPE_CLASS_NUMBER}: the number is signed, allowing
* a positive or negative sign at the start.
*/
static TYPE_NUMBER_FLAG_SIGNED:number = 0x00001000;
/**
* Flag of {@link #TYPE_CLASS_NUMBER}: the number is decimal, allowing
* a decimal point to provide fractional values.
*/
static TYPE_NUMBER_FLAG_DECIMAL:number = 0x00002000;// ----------------------------------------------------------------------
/**
* Default variation of {@link #TYPE_CLASS_NUMBER}: plain normal
* numeric text. This was added in
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An IME must target
* this API version or later to see this input type; if it doesn't, a request
* for this type will be dropped when passed through
* {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
* EditorInfo.makeCompatible(int)}.
*/
static TYPE_NUMBER_VARIATION_NORMAL:number = 0x00000000;
/**
* Variation of {@link #TYPE_CLASS_NUMBER}: entering a numeric password.
* This was added in {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An
* IME must target this API version or later to see this input type; if it
* doesn't, a request for this type will be dropped when passed
* through {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
* EditorInfo.makeCompatible(int)}.
*/
static TYPE_NUMBER_VARIATION_PASSWORD:number = 0x00000010;
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/**
* Class for a phone number. This class currently supports no variations
* or flags.
*/
static TYPE_CLASS_PHONE:number = 0x00000003;
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/**
* Class for dates and times. It supports the
* following variations:
* {@link #TYPE_DATETIME_VARIATION_NORMAL}
* {@link #TYPE_DATETIME_VARIATION_DATE}, and
* {@link #TYPE_DATETIME_VARIATION_TIME}.
*/
static TYPE_CLASS_DATETIME:number = 0x00000004;
/**
* Default variation of {@link #TYPE_CLASS_DATETIME}: allows entering
* both a date and time.
*/
static TYPE_DATETIME_VARIATION_NORMAL:number = 0x00000000;
/**
* Default variation of {@link #TYPE_CLASS_DATETIME}: allows entering
* only a date.
*/
static TYPE_DATETIME_VARIATION_DATE:number = 0x00000010;
/**
* Default variation of {@link #TYPE_CLASS_DATETIME}: allows entering
* only a time.
*/
static TYPE_DATETIME_VARIATION_TIME:number = 0x00000020;
}
export module InputType {
export class LimitCode {
static TYPE_CLASS_NUMBER = [
KeyEvent.KEYCODE_Digit0,
KeyEvent.KEYCODE_Digit1,
KeyEvent.KEYCODE_Digit2,
KeyEvent.KEYCODE_Digit3,
KeyEvent.KEYCODE_Digit4,
KeyEvent.KEYCODE_Digit5,
KeyEvent.KEYCODE_Digit6,
KeyEvent.KEYCODE_Digit7,
KeyEvent.KEYCODE_Digit8,
KeyEvent.KEYCODE_Digit9,
];
static TYPE_CLASS_PHONE = [
KeyEvent.KEYCODE_Comma,
KeyEvent.KEYCODE_Sharp,
KeyEvent.KEYCODE_Semicolon,
KeyEvent.KEYCODE_Asterisk,
KeyEvent.KEYCODE_Left_Parenthesis,
KeyEvent.KEYCODE_Right_Parenthesis,
KeyEvent.KEYCODE_Slash,
KeyEvent.KEYCODE_KeyN,
KeyEvent.KEYCODE_Period,
KeyEvent.KEYCODE_SPACE,
KeyEvent.KEYCODE_Add,
KeyEvent.KEYCODE_Minus,
KeyEvent.KEYCODE_Period,
KeyEvent.KEYCODE_Digit0,
KeyEvent.KEYCODE_Digit1,
KeyEvent.KEYCODE_Digit2,
KeyEvent.KEYCODE_Digit3,
KeyEvent.KEYCODE_Digit4,
KeyEvent.KEYCODE_Digit5,
KeyEvent.KEYCODE_Digit6,
KeyEvent.KEYCODE_Digit7,
KeyEvent.KEYCODE_Digit8,
KeyEvent.KEYCODE_Digit9,
];
}
}
} | the_stack |
import { BaseResource, CloudError } from "ms-rest-azure";
import * as moment from "moment";
export {
BaseResource,
CloudError
};
/**
* Resource properties.
*/
export interface ProxyResource extends BaseResource {
/**
* Resource ID
*/
readonly id?: string;
/**
* Resource name.
*/
readonly name?: string;
/**
* Resource type.
*/
readonly type?: string;
}
/**
* Resource properties including location and tags for track resources.
*/
export interface TrackedResource extends ProxyResource {
/**
* The location the resource resides in.
*/
location: string;
/**
* Application-specific metadata in the form of key-value pairs.
*/
tags?: { [propertyName: string]: string };
}
/**
* Storage Profile properties of a server
*/
export interface StorageProfile {
/**
* Backup retention days for the server.
*/
backupRetentionDays?: number;
/**
* Enable Geo-redundant or not for server backup. Possible values include: 'Enabled', 'Disabled'
*/
geoRedundantBackup?: string;
/**
* Max storage allowed for a server.
*/
storageMB?: number;
}
/**
* The properties used to create a new server.
*/
export interface ServerPropertiesForCreate {
/**
* Server version. Possible values include: '9.5', '9.6', '10', '10.0', '10.2'
*/
version?: string;
/**
* Enable ssl enforcement or not when connect to server. Possible values include: 'Enabled',
* 'Disabled'
*/
sslEnforcement?: string;
/**
* Storage profile of a server.
*/
storageProfile?: StorageProfile;
/**
* Polymorphic Discriminator
*/
createMode: string;
}
/**
* The properties used to create a new server.
*/
export interface ServerPropertiesForDefaultCreate extends ServerPropertiesForCreate {
/**
* The administrator's login name of a server. Can only be specified when the server is being
* created (and is required for creation).
*/
administratorLogin: string;
/**
* The password of the administrator login.
*/
administratorLoginPassword: string;
}
/**
* The properties used to create a new server by restoring from a backup.
*/
export interface ServerPropertiesForRestore extends ServerPropertiesForCreate {
/**
* The source server id to restore from.
*/
sourceServerId: string;
/**
* Restore point creation time (ISO8601 format), specifying the time to restore from.
*/
restorePointInTime: Date;
}
/**
* The properties used to create a new server by restoring to a different region from a geo
* replicated backup.
*/
export interface ServerPropertiesForGeoRestore extends ServerPropertiesForCreate {
/**
* The source server id to restore from.
*/
sourceServerId: string;
}
/**
* The properties to create a new replica.
*/
export interface ServerPropertiesForReplica extends ServerPropertiesForCreate {
/**
* The master server id to create replica from.
*/
sourceServerId: string;
}
/**
* Billing information related properties of a server.
*/
export interface Sku {
/**
* The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.
*/
name?: string;
/**
* The tier of the particular SKU, e.g. Basic. Possible values include: 'Basic',
* 'GeneralPurpose', 'MemoryOptimized'
*/
tier?: string;
/**
* The scale up/out capacity, representing server's compute units.
*/
capacity?: number;
/**
* The size code, to be interpreted by resource as appropriate.
*/
size?: string;
/**
* The family of hardware.
*/
family?: string;
}
/**
* Represents a server.
*/
export interface Server extends TrackedResource {
/**
* The SKU (pricing tier) of the server.
*/
sku?: Sku;
/**
* The administrator's login name of a server. Can only be specified when the server is being
* created (and is required for creation).
*/
administratorLogin?: string;
/**
* Server version. Possible values include: '9.5', '9.6', '10', '10.0', '10.2'
*/
version?: string;
/**
* Enable ssl enforcement or not when connect to server. Possible values include: 'Enabled',
* 'Disabled'
*/
sslEnforcement?: string;
/**
* A state of a server that is visible to user. Possible values include: 'Ready', 'Dropping',
* 'Disabled'
*/
userVisibleState?: string;
/**
* The fully qualified domain name of a server.
*/
fullyQualifiedDomainName?: string;
/**
* Earliest restore point creation time (ISO8601 format)
*/
earliestRestoreDate?: Date;
/**
* Storage profile of a server.
*/
storageProfile?: StorageProfile;
/**
* The replication role of the server.
*/
replicationRole?: string;
/**
* The master server id of a replica server.
*/
masterServerId?: string;
/**
* The maximum number of replicas that a master server can have.
*/
replicaCapacity?: number;
}
/**
* Represents a server to be created.
*/
export interface ServerForCreate {
/**
* The SKU (pricing tier) of the server.
*/
sku?: Sku;
/**
* Properties of the server.
*/
properties: ServerPropertiesForCreate;
/**
* The location the resource resides in.
*/
location: string;
/**
* Application-specific metadata in the form of key-value pairs.
*/
tags?: { [propertyName: string]: string };
}
/**
* Parameters allowed to update for a server.
*/
export interface ServerUpdateParameters {
/**
* The SKU (pricing tier) of the server.
*/
sku?: Sku;
/**
* Storage profile of a server.
*/
storageProfile?: StorageProfile;
/**
* The password of the administrator login.
*/
administratorLoginPassword?: string;
/**
* The version of a server. Possible values include: '9.5', '9.6', '10', '10.0', '10.2'
*/
version?: string;
/**
* Enable ssl enforcement or not when connect to server. Possible values include: 'Enabled',
* 'Disabled'
*/
sslEnforcement?: string;
/**
* The replication role of the server.
*/
replicationRole?: string;
/**
* Application-specific metadata in the form of key-value pairs.
*/
tags?: { [propertyName: string]: string };
}
/**
* Represents a server firewall rule.
*/
export interface FirewallRule extends ProxyResource {
/**
* The start IP address of the server firewall rule. Must be IPv4 format.
*/
startIpAddress: string;
/**
* The end IP address of the server firewall rule. Must be IPv4 format.
*/
endIpAddress: string;
}
/**
* A virtual network rule.
*/
export interface VirtualNetworkRule extends ProxyResource {
/**
* The ARM resource id of the virtual network subnet.
*/
virtualNetworkSubnetId: string;
/**
* Create firewall rule before the virtual network has vnet service endpoint enabled.
*/
ignoreMissingVnetServiceEndpoint?: boolean;
/**
* Virtual Network Rule State. Possible values include: 'Initializing', 'InProgress', 'Ready',
* 'Deleting', 'Unknown'
*/
readonly state?: string;
}
/**
* Represents a Database.
*/
export interface Database extends ProxyResource {
/**
* The charset of the database.
*/
charset?: string;
/**
* The collation of the database.
*/
collation?: string;
}
/**
* Represents a Configuration.
*/
export interface Configuration extends ProxyResource {
/**
* Value of the configuration.
*/
value?: string;
/**
* Description of the configuration.
*/
readonly description?: string;
/**
* Default value of the configuration.
*/
readonly defaultValue?: string;
/**
* Data type of the configuration.
*/
readonly dataType?: string;
/**
* Allowed values of the configuration.
*/
readonly allowedValues?: string;
/**
* Source of the configuration.
*/
source?: string;
}
/**
* Display metadata associated with the operation.
*/
export interface OperationDisplay {
/**
* Operation resource provider name.
*/
readonly provider?: string;
/**
* Resource on which the operation is performed.
*/
readonly resource?: string;
/**
* Localized friendly name for the operation.
*/
readonly operation?: string;
/**
* Operation description.
*/
readonly description?: string;
}
/**
* REST API operation definition.
*/
export interface Operation {
/**
* The name of the operation being performed on this particular object.
*/
readonly name?: string;
/**
* The localized display information for this particular operation or action.
*/
readonly display?: OperationDisplay;
/**
* The intended executor of the operation. Possible values include: 'NotSpecified', 'user',
* 'system'
*/
readonly origin?: string;
/**
* Additional descriptions for the operation.
*/
readonly properties?: { [propertyName: string]: any };
}
/**
* A list of resource provider operations.
*/
export interface OperationListResult {
/**
* The list of resource provider operations.
*/
value?: Operation[];
}
/**
* Represents a log file.
*/
export interface LogFile extends ProxyResource {
/**
* Size of the log file.
*/
sizeInKB?: number;
/**
* Creation timestamp of the log file.
*/
readonly createdTime?: Date;
/**
* Last modified timestamp of the log file.
*/
readonly lastModifiedTime?: Date;
/**
* Type of the log file.
*/
logFileType?: string;
/**
* The url to download the log file from.
*/
url?: string;
}
/**
* Service level objectives for performance tier.
*/
export interface PerformanceTierServiceLevelObjectives {
/**
* ID for the service level objective.
*/
id?: string;
/**
* Edition of the performance tier.
*/
edition?: string;
/**
* vCore associated with the service level objective
*/
vCore?: number;
/**
* Hardware generation associated with the service level objective
*/
hardwareGeneration?: string;
/**
* Maximum Backup retention in days for the performance tier edition
*/
maxBackupRetentionDays?: number;
/**
* Minimum Backup retention in days for the performance tier edition
*/
minBackupRetentionDays?: number;
/**
* Max storage allowed for a server.
*/
maxStorageMB?: number;
/**
* Max storage allowed for a server.
*/
minStorageMB?: number;
}
/**
* Performance tier properties
*/
export interface PerformanceTierProperties {
/**
* ID of the performance tier.
*/
id?: string;
/**
* Service level objectives associated with the performance tier
*/
serviceLevelObjectives?: PerformanceTierServiceLevelObjectives[];
}
/**
* Request from client to check resource name availability.
*/
export interface NameAvailabilityRequest {
/**
* Resource name to verify.
*/
name: string;
/**
* Resource type used for verification.
*/
type?: string;
}
/**
* Represents a resource name availability.
*/
export interface NameAvailability {
/**
* Error Message.
*/
message?: string;
/**
* Indicates whether the resource name is available.
*/
nameAvailable?: boolean;
/**
* Reason for name being unavailable.
*/
reason?: string;
}
/**
* A server security alert policy.
*/
export interface ServerSecurityAlertPolicy extends ProxyResource {
/**
* Specifies the state of the policy, whether it is enabled or disabled. Possible values include:
* 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection,
* Sql_Injection_Vulnerability, Access_Anomaly
*/
disabledAlerts?: string[];
/**
* Specifies an array of e-mail addresses to which the alert is sent.
*/
emailAddresses?: string[];
/**
* Specifies that the alert is sent to the account administrators.
*/
emailAccountAdmins?: boolean;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob
* storage will hold all Threat Detection audit logs.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the Threat Detection audit storage account.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the Threat Detection audit logs.
*/
retentionDays?: number;
}
/**
* A list of servers.
*/
export interface ServerListResult extends Array<Server> {
}
/**
* A list of firewall rules.
*/
export interface FirewallRuleListResult extends Array<FirewallRule> {
}
/**
* A list of virtual network rules.
*/
export interface VirtualNetworkRuleListResult extends Array<VirtualNetworkRule> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A List of databases.
*/
export interface DatabaseListResult extends Array<Database> {
}
/**
* A list of server configurations.
*/
export interface ConfigurationListResult extends Array<Configuration> {
}
/**
* A list of log files.
*/
export interface LogFileListResult extends Array<LogFile> {
}
/**
* A list of performance tiers.
*/
export interface PerformanceTierListResult extends Array<PerformanceTierProperties> {
} | the_stack |
import { Post } from 'app/entities/metis/post.model';
import { PostService } from 'app/shared/metis/post.service';
import { BehaviorSubject, map, Observable, ReplaySubject, tap } from 'rxjs';
import { HttpResponse } from '@angular/common/http';
import { User } from 'app/core/user/user.model';
import { AccountService } from 'app/core/auth/account.service';
import { Course } from 'app/entities/course.model';
import { Posting } from 'app/entities/metis/posting.model';
import { Injectable } from '@angular/core';
import { AnswerPostService } from 'app/shared/metis/answer-post.service';
import { AnswerPost } from 'app/entities/metis/answer-post.model';
import { Reaction } from 'app/entities/metis/reaction.model';
import { ReactionService } from 'app/shared/metis/reaction.service';
import { ContextInformation, CourseWideContext, DisplayPriority, PageType, PostContextFilter } from 'app/shared/metis/metis.util';
import { Exercise } from 'app/entities/exercise.model';
import { Lecture } from 'app/entities/lecture.model';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { Params } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
@Injectable()
export class MetisService {
private posts$: ReplaySubject<Post[]> = new ReplaySubject<Post[]>(1);
private tags$: BehaviorSubject<string[]> = new BehaviorSubject<string[]>([]);
private currentPostContextFilter: PostContextFilter = {};
private user: User;
private pageType: PageType;
private course: Course;
private courseId: number;
private cachedPosts: Post[];
constructor(
protected postService: PostService,
protected answerPostService: AnswerPostService,
protected reactionService: ReactionService,
protected accountService: AccountService,
protected exerciseService: ExerciseService,
private translateService: TranslateService,
) {
this.accountService.identity().then((user: User) => {
this.user = user!;
});
}
get posts(): Observable<Post[]> {
return this.posts$.asObservable();
}
get tags(): Observable<string[]> {
return this.tags$.asObservable();
}
getPageType(): PageType {
return this.pageType;
}
setPageType(pageType: PageType) {
this.pageType = pageType;
}
getUser(): User {
return this.user;
}
getCourse(): Course {
return this.course;
}
/**
* set course property before using metis service
* @param {Course} course in which the metis service is used
*/
setCourse(course: Course): void {
if (this.courseId === undefined || this.courseId !== course.id) {
this.courseId = course.id!;
this.course = course;
this.updateCoursePostTags();
}
}
/**
* to be used to set posts from outside
* @param {Post[]} posts that are managed by metis service
*/
setPosts(posts: Post[]): void {
this.posts$.next(posts);
}
/**
* fetches all post tags used in the current course, informs all subscribing components
*/
updateCoursePostTags(): void {
this.postService
.getAllPostTagsByCourseId(this.courseId)
.pipe(map((res: HttpResponse<string[]>) => res.body!.filter((tag) => !!tag)))
.subscribe((tags: string[]) => {
this.tags$.next(tags);
});
}
/**
* fetches all posts for a course, optionally fetching posts only for a certain context, i.e. a lecture, exercise or specified course-wide-context,
* informs all components that subscribed on posts by sending the newly fetched posts
* @param {PostContextFilter} postContextFilter criteria to filter course posts with (lecture, exercise, course-wide context)
* @param {boolean} forceUpdate if true, forces a re-fetch even if filter property did not change
*/
getFilteredPosts(postContextFilter: PostContextFilter, forceUpdate = true): void {
// check if the post context did change
if (
forceUpdate ||
postContextFilter?.courseId !== this.currentPostContextFilter?.courseId ||
postContextFilter?.courseWideContext !== this.currentPostContextFilter?.courseWideContext ||
postContextFilter?.lectureId !== this.currentPostContextFilter?.lectureId ||
postContextFilter?.exerciseId !== this.currentPostContextFilter?.exerciseId
) {
// if the context changed, we need to fetch posts before doing the content filtering and sorting
this.currentPostContextFilter = postContextFilter;
this.postService.getPosts(this.courseId, this.currentPostContextFilter).subscribe((res) => {
// cache the fetched posts, that can be emitted on next call of this `getFilteredPosts`
// that does not require to send a request to actually fetch posts from the DB
this.cachedPosts = res.body!;
this.posts$.next(res.body!);
});
} else {
// if we do not require force update, e.g. because only the sorting criterion changed,
// we can emit the previously cached posts
this.posts$.next(this.cachedPosts);
}
}
/**
* creates a new post by invoking the post service
* fetches the posts for the currently set filter on response and updates course tags
* @param {Post} post to be created
* @return {Observable<Post>} created post
*/
createPost(post: Post): Observable<Post> {
return this.postService.create(this.courseId, post).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
this.updateCoursePostTags();
}),
map((res: HttpResponse<Post>) => res.body!),
);
}
/**
* creates a new answer post by invoking the answer post service
* fetches the posts for the currently set filter on response
* @param {AnswerPost} answerPost to be created
* @return {Observable<AnswerPost>} created answer post
*/
createAnswerPost(answerPost: AnswerPost): Observable<AnswerPost> {
return this.answerPostService.create(this.courseId, answerPost).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
}),
map((res: HttpResponse<Post>) => res.body!),
);
}
/**
* updates a given posts by invoking the post service,
* fetches the posts for the currently set filter on response and updates course tags
* @param {Post} post to be updated
* @return {Observable<Post>} updated post
*/
updatePost(post: Post): Observable<Post> {
return this.postService.update(this.courseId, post).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
this.updateCoursePostTags();
}),
map((res: HttpResponse<Post>) => res.body!),
);
}
/**
* updates a given answer posts by invoking the answer post service,
* fetches the posts for the currently set filter on response
* @param {AnswerPost} answerPost to be updated
* @return {Observable<AnswerPost>} updated answer post
*/
updateAnswerPost(answerPost: AnswerPost): Observable<AnswerPost> {
return this.answerPostService.update(this.courseId, answerPost).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
}),
map((res: HttpResponse<Post>) => res.body!),
);
}
/**
* updates the display priority of a post to NONE, PINNED, ARCHIVED
* @param {number} postId id of the post for which the displayPriority is changed
* @param {DisplayPriority} displayPriority new displayPriority
* @return {Observable<Post>} updated post
*/
updatePostDisplayPriority(postId: number, displayPriority: DisplayPriority): Observable<Post> {
return this.postService.updatePostDisplayPriority(this.courseId, postId, displayPriority).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
}),
map((res: HttpResponse<Post>) => res.body!),
);
}
/**
* deletes a post by invoking the post service
* fetches the posts for the currently set filter on response and updates course tags
* @param {Post} post to be deleted
*/
deletePost(post: Post): void {
this.postService.delete(this.courseId, post).subscribe(() => {
this.getFilteredPosts(this.currentPostContextFilter);
this.updateCoursePostTags();
});
}
/**
* deletes an answer post by invoking the post service
* fetches the posts for the currently set filter on response
* @param {AnswerPost} answerPost to be deleted
*/
deleteAnswerPost(answerPost: AnswerPost): void {
this.answerPostService.delete(this.courseId, answerPost).subscribe(() => {
this.getFilteredPosts(this.currentPostContextFilter);
});
}
/**
* creates a new reaction
* fetches the posts for the currently set filter on response
* @param {Reaction} reaction to be created
* @return {Observable<Reaction>} created reaction
*/
createReaction(reaction: Reaction): Observable<Reaction> {
return this.reactionService.create(this.courseId, reaction).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
}),
map((res: HttpResponse<Post>) => res.body!),
);
}
/**
* deletes an existing reaction
* fetches the posts for the currently set filter on response
* @param {Reaction} reaction to be deleted
*/
deleteReaction(reaction: Reaction): Observable<void> {
return this.reactionService.delete(this.courseId, reaction).pipe(
tap(() => {
this.getFilteredPosts(this.currentPostContextFilter);
}),
map((res: HttpResponse<void>) => res.body!),
);
}
/**
* determines if the current user is at least tutor in the current course
* @return {boolean} tutor flag
*/
metisUserIsAtLeastTutorInCourse(): boolean {
return this.accountService.isAtLeastTutorInCourse(this.course);
}
/**
* determines if the current user is at least instructor in the current course
* @return boolean instructor flag
*/
metisUserIsAtLeastInstructorInCourse(): boolean {
return this.accountService.isAtLeastInstructorInCourse(this.course);
}
/**
* determines if the current user is the author of a given posting
* @param {Posting} posting for which the author is determined
* @return {boolean} author flag
*/
metisUserIsAuthorOfPosting(posting: Posting): boolean {
return this.user ? posting?.author!.id === this.getUser().id : false;
}
/**
* creates empty default post that is needed on initialization of a newly opened modal to edit or create a post
* @param {CourseWideContext | undefined} courseWideContext optional course-wide context as default context
* @param {Exercise | undefined} exercise optional exercise as default context
* @param {number | undefined} lectureId id of optional lecture as default context
* @return {Post} created default object
*/
createEmptyPostForContext(courseWideContext?: CourseWideContext, exercise?: Exercise, lectureId?: number): Post {
const emptyPost: Post = new Post();
if (courseWideContext) {
emptyPost.courseWideContext = courseWideContext;
emptyPost.course = this.course;
} else if (exercise) {
const exercisePost = this.exerciseService.convertExerciseForServer(exercise);
emptyPost.exercise = { id: exercisePost.id, title: exercisePost.title, type: exercisePost.type } as Exercise;
} else if (lectureId) {
emptyPost.lecture = { id: lectureId } as Lecture;
} else {
// set default
emptyPost.courseWideContext = CourseWideContext.TECH_SUPPORT as CourseWideContext;
}
return emptyPost;
}
/**
* counts the answer posts of a post, 0 if none exist
* @param {Post} post of which the answer posts are counted
* @return {number} amount of answer posts
*/
getNumberOfAnswerPosts(post: Post): number {
return post.answers?.length! ? post.answers?.length! : 0;
}
/**
* determines if the post is resolved by searching for resolving answer posts
* @param {Post} post of which the state is determined
* @return {boolean} flag that indicates if the post is resolved
*/
isPostResolved(post: Post): boolean {
if (this.getNumberOfAnswerPosts(post) > 0) {
return post.answers!.filter((answer: AnswerPost) => answer.resolvesPost === true).length > 0;
} else {
return false;
}
}
/**
* determines the router link components required for navigating to the detail view of the given post
* @param {Post} post to be navigated to
* @return {(string | number)[]} array of router link components
*/
getLinkForPost(post?: Post): (string | number)[] {
if (post?.lecture) {
return ['/courses', this.courseId, 'lectures', post.lecture.id!];
}
if (post?.exercise) {
return ['/courses', this.courseId, 'exercises', post.exercise.id!];
}
return ['/courses', this.courseId, 'discussion'];
}
/**
* determines the routing params required for navigating to the detail view of the given post
* @param {Post} post to be navigated to
* @return {Params} required parameter key-value pair
*/
getQueryParamsForPost(post: Post): Params {
const params: Params = {};
if (post.courseWideContext) {
params.searchText = `#${post.id}`;
} else {
params.postId = post.id;
}
return params;
}
/**
* Creates an object to be used when a post context should be displayed and linked (for exercise and lecture)
* @param {Post} post for which the context is displayed and linked
* @return {ContextInformation} object containing the required router link components as well as the context display name
*/
getContextInformation(post: Post): ContextInformation {
let routerLinkComponents = undefined;
let displayName;
if (post.exercise) {
displayName = post.exercise.title!;
routerLinkComponents = ['/courses', this.courseId, 'exercises', post.exercise.id!];
} else if (post.lecture) {
displayName = post.lecture.title!;
routerLinkComponents = ['/courses', this.courseId, 'lectures', post.lecture.id!];
} else {
// course-wide topics are not linked, only displayName is set
displayName = this.translateService.instant('artemisApp.metis.overview.' + post.courseWideContext);
}
return { routerLinkComponents, displayName };
}
/**
* Invokes the post service to get a top-k-list of course posts with high similarity scores when compared with a certain strategy
* @param {Post} tempPost that is currently created and compared against existing course posts on updates in the form group
* @return {Observable<Post[]>} array of similar posts that were found in the course
*/
getSimilarPosts(tempPost: Post): Observable<Post[]> {
return this.postService.computeSimilarityScoresWithCoursePosts(tempPost, this.courseId).pipe(map((res: HttpResponse<Post[]>) => res.body!));
}
} | the_stack |
import {IConstant} from "./i-constant";
import tempDirectory from "temp-dir";
import {join} from "crosspath";
import {ALL_CONTEXTS, WINDOW_CONTEXT, WINDOW_NODE_CONTEXT, WINDOW_WORKER_CONTEXT} from "../polyfill/polyfill-context";
import pkg from "../../package.json";
import {booleanize} from "../api/util";
const tempRoot = join(
tempDirectory,
pkg.name,
(process.env.PRODUCTION != null && (process.env.PRODUCTION === "" || booleanize(process.env.PRODUCTION))) || process.env.NODE_ENV === "production" ? "production" : "development"
);
export const constant: IConstant = {
cacheVersion: 5,
endpoint: {
index: "/api",
polyfill: "/api/polyfill"
},
header: {
polyfills: "x-applied-polyfills",
cache: {
immutable: "public,max-age=31536000,immutable"
},
maxChars: 600
},
meta: {
name: pkg.name,
version: pkg.version,
github: pkg.repository.url
},
path: {
cacheRoot: join(tempRoot),
cachePackageVersionMap: join(tempRoot, "cache_package_version_map.json"),
configChecksum: join(tempRoot, "config_checksum")
},
polyfill: {
systemjs: {
library: "systemjs",
relativePaths: {
window: ["dist/system.js"],
worker: ["dist/system.js"],
node: ["dist/system-node.cjs"]
},
meta: {
system: {
window: ["dist/system.js"],
worker: ["dist/system.js"],
node: ["dist/system-node.cjs"]
},
s: "dist/s.js"
},
features: [],
dependencies: ["es.object.create", "es.object.freeze", "es.object.define-property", "es.promise", "fetch"],
contexts: ALL_CONTEXTS
},
zone: {
library: "zone.js",
meta: {
error: "fesm2015/zone-error.js",
shadydom: "fesm2015/webapis-shadydom.js",
mediaquery: "fesm2015/webapis-media-query.js",
fetch: "fesm2015/zone-patch-fetch.js",
resizeobserver: "fesm2015/zone-patch-resize-observer.js"
},
relativePaths: {
window: ["fesm2015/zone.js"],
worker: ["fesm2015/zone.js"],
node: ["fesm2015/zone-node.js"]
},
features: [],
dependencies: [],
mustComeAfter: "*",
contexts: WINDOW_NODE_CONTEXT
},
"performance.now": {
library: {
window: "perfnow",
worker: "perfnow",
node: "performance-now"
},
relativePaths: {
window: ["perfnow.js"],
worker: ["perfnow.js"],
node: ["lib/performance-now.js"]
},
features: ["high-resolution-time"],
dependencies: ["es.date.now"],
contexts: ALL_CONTEXTS
},
url: {
library: "url-polyfill",
relativePaths: ["url-polyfill.js"],
features: ["url", "urlsearchparams"],
dependencies: ["es.object.define-properties", "es.array.for-each"],
contexts: ALL_CONTEXTS
},
formdata: {
polyfills: ["form-data"]
},
"form-data": {
library: "@polyfiller/form-data",
relativePaths: ["polyfill/index.js"],
features: ["api.FormData", "api.FormData.get", "api.FormData.getAll", "api.FormData.has", "api.FormData.set", "api.FormData.entries"],
dependencies: [],
contexts: WINDOW_WORKER_CONTEXT
},
"object-fit": {
library: "@polyfiller/object-fit",
relativePaths: ["polyfill/index.js"],
features: ["object-fit"],
dependencies: [
"window",
"document",
"element",
"event",
"mutation-observer",
"get-computed-style",
"dom.collections.iterable",
"request-animation-frame",
"es.array.concat",
"es.array.filter",
"es.array.for-each",
"es.array.from",
"es.array.is-array",
"es.map",
"es.set",
"es.weak-map",
"es.symbol.iterator",
"es.symbol.to-string-tag",
"es.symbol.constructor",
"es.number.to-fixed",
"es.object.define-property",
"es.object.get-own-property-descriptor",
"es.object.keys"
],
contexts: WINDOW_CONTEXT
},
console: {
library: "console-polyfill",
relativePaths: ["index.js"],
features: ["console-basic", "console-time"],
dependencies: [],
contexts: ALL_CONTEXTS
},
base64: {
library: "Base64",
relativePaths: ["base64.js"],
features: ["atob-btoa"],
dependencies: [],
contexts: ALL_CONTEXTS
},
blob: {
library: "blob-polyfill",
relativePaths: ["Blob.js"],
features: ["blobbuilder", "bloburls"],
dependencies: ["base64", "url"],
contexts: ALL_CONTEXTS
},
requestidlecallback: {
polyfills: ["request-idle-callback"]
},
requestanimationframe: {
polyfills: ["request-animation-frame"]
},
"request-idle-callback": {
library: "requestidlecallback",
relativePaths: ["index.js"],
features: ["requestidlecallback"],
dependencies: ["requestanimationframe"],
contexts: WINDOW_CONTEXT
},
"request-animation-frame": {
library: "requestanimationframe",
relativePaths: ["app/requestAnimationFrame.js"],
features: ["requestanimationframe"],
dependencies: ["es.date.now", "performance.now"],
contexts: WINDOW_CONTEXT
},
proxy: {
library: "proxy-polyfill",
relativePaths: ["proxy.min.js"],
features: ["proxy"],
dependencies: ["es"],
contexts: ALL_CONTEXTS
},
es: {
polyfills: [
"es.promise",
"es.object",
"es.function",
"es.array",
"es.array-buffer",
"es.string",
"es.data-view",
"es.regexp",
"es.number",
"es.math",
"es.date",
"es.symbol",
"es.collections",
"es.typed-array",
"es.reflect"
]
},
// es2015 is an alias for 'es'
es2015: {
polyfills: ["es"]
},
"es.promise": {
polyfills: ["es.promise.constructor", "es.promise.any", "es.promise.all-settled", "es.promise.finally"]
},
"es.promise.constructor": {
library: "core-js",
relativePaths: ["modules/es.promise.js"],
features: ["promises"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.promise.finally": {
library: "core-js",
relativePaths: ["modules/es.promise.finally.js"],
features: ["javascript.builtins.Promise.finally"],
dependencies: ["es.promise.constructor"],
contexts: ALL_CONTEXTS
},
"es.promise.all-settled": {
library: "core-js",
relativePaths: ["modules/es.promise.all-settled.js"],
features: ["javascript.builtins.Promise.allSettled"],
dependencies: ["es.promise.constructor"],
contexts: ALL_CONTEXTS
},
"es.promise.try": {
library: "core-js",
relativePaths: ["modules/esnext.promise.try.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.promise.constructor"],
contexts: ALL_CONTEXTS
},
"es.promise.any": {
library: "core-js",
relativePaths: ["modules/es.promise.any.js"],
features: ["javascript.builtins.Promise.any"],
dependencies: ["es.promise.constructor"],
contexts: ALL_CONTEXTS
},
"es.object": {
polyfills: [
"es.object.assign",
"es.object.create",
"es.object.define-getter",
"es.object.define-setter",
"es.object.entries",
"es.object.from-entries",
"es.object.get-own-property-descriptors",
"es.object.lookup-getter",
"es.object.lookup-setter",
"es.object.values",
"es.object.define-properties",
"es.object.define-property",
"es.object.freeze",
"es.object.get-own-property-descriptor",
"es.object.get-own-property-names",
"es.object.get-prototype-of",
"es.object.is-extensible",
"es.object.is-frozen",
"es.object.is-sealed",
"es.object.is",
"es.object.keys",
"es.object.prevent-extensions",
"es.object.seal",
"es.object.set-prototype-of",
"es.object.to-string"
]
},
"es.object.lookup-getter": {
library: "core-js",
relativePaths: ["modules/es.object.lookup-getter.js"],
features: ["javascript.builtins.Object.lookupGetter"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.from-entries": {
library: "core-js",
relativePaths: ["modules/es.object.from-entries.js"],
features: ["javascript.builtins.Object.fromEntries"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.lookup-setter": {
library: "core-js",
relativePaths: ["modules/es.object.lookup-setter.js"],
features: ["javascript.builtins.Object.lookupSetter"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.define-getter": {
library: "core-js",
relativePaths: ["modules/es.object.define-getter.js"],
features: ["javascript.builtins.Object.defineGetter"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.define-setter": {
library: "core-js",
relativePaths: ["modules/es.object.define-setter.js"],
features: ["javascript.builtins.Object.defineSetter"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.entries": {
library: "core-js",
relativePaths: ["modules/es.object.entries.js"],
features: ["javascript.builtins.Object.entries"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.values": {
library: "core-js",
relativePaths: ["modules/es.object.values.js"],
features: ["object-values"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.get-own-property-descriptors": {
library: "core-js",
relativePaths: ["modules/es.object.get-own-property-descriptors.js"],
features: ["javascript.builtins.Object.getOwnPropertyDescriptors"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.assign": {
library: "core-js",
relativePaths: ["modules/es.object.assign.js"],
features: ["javascript.builtins.Object.assign"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.create": {
library: "core-js",
relativePaths: ["modules/es.object.create.js"],
features: ["javascript.builtins.Object.create"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.define-properties": {
library: "core-js",
relativePaths: ["modules/es.object.define-properties.js"],
features: ["javascript.builtins.Object.defineProperties"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.define-property": {
library: "core-js",
relativePaths: ["modules/es.object.define-property.js"],
features: ["javascript.builtins.Object.defineProperty"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.freeze": {
library: "core-js",
relativePaths: ["modules/es.object.freeze.js"],
features: ["javascript.builtins.Object.freeze"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.get-own-property-descriptor": {
library: "core-js",
relativePaths: ["modules/es.object.get-own-property-descriptor.js"],
features: ["javascript.builtins.Object.getOwnPropertyDescriptor"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.get-own-property-names": {
library: "core-js",
relativePaths: ["modules/es.object.get-own-property-names.js"],
features: ["javascript.builtins.Object.getOwnPropertyNames"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.get-prototype-of": {
library: "core-js",
relativePaths: ["modules/es.object.get-prototype-of.js"],
features: ["javascript.builtins.Object.getPrototypeOf"],
dependencies: ["proto"],
contexts: ALL_CONTEXTS
},
"es.object.is-extensible": {
library: "core-js",
relativePaths: ["modules/es.object.is-extensible.js"],
features: ["javascript.builtins.Object.isExtensible"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.is-frozen": {
library: "core-js",
relativePaths: ["modules/es.object.is-frozen.js"],
features: ["javascript.builtins.Object.isFrozen"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.is-sealed": {
library: "core-js",
relativePaths: ["modules/es.object.is-sealed.js"],
features: ["javascript.builtins.Object.isSealed"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.is": {
library: "core-js",
relativePaths: ["modules/es.object.is.js"],
features: ["javascript.builtins.Object.is"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.keys": {
library: "core-js",
relativePaths: ["modules/es.object.keys.js"],
features: ["javascript.builtins.Object.keys"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.prevent-extensions": {
library: "core-js",
relativePaths: ["modules/es.object.prevent-extensions.js"],
features: ["javascript.builtins.Object.preventExtensions"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.seal": {
library: "core-js",
relativePaths: ["modules/es.object.seal.js"],
features: ["javascript.builtins.Object.seal"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.object.set-prototype-of": {
library: "core-js",
relativePaths: ["modules/es.object.set-prototype-of.js"],
features: ["javascript.builtins.Object.setPrototypeOf"],
dependencies: ["proto"],
contexts: ALL_CONTEXTS
},
"es.object.to-string": {
library: "core-js",
relativePaths: ["modules/es.object.to-string.js"],
features: ["javascript.builtins.Object.toString"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.function": {
polyfills: ["es.function.bind", "es.function.name"]
},
"es.function.bind": {
library: "core-js",
relativePaths: ["modules/es.function.bind.js"],
features: ["javascript.builtins.Function.bind"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.function.name": {
library: "core-js",
relativePaths: ["modules/es.function.name.js"],
features: ["javascript.builtins.Function.name"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array": {
polyfills: [
"es.array.concat",
"es.array.copy-within",
"es.array.every",
"es.array.flat",
"es.array.flat-map",
"es.array.fill",
"es.array.filter",
"es.array.find",
"es.array.find-index",
"es.array.for-each",
"es.array.from",
"es.array.includes",
"es.array.index-of",
"es.array.is-array",
"es.array.iterator",
"es.array.join",
"es.array.last-index-of",
"es.array.map",
"es.array.of",
"es.array.reduce",
"es.array.reduce-right",
"es.array.slice",
"es.array.some",
"es.array.sort",
"es.array.species",
"es.array.splice"
]
},
"es.array.concat": {
library: "core-js",
relativePaths: ["modules/es.array.concat.js"],
features: ["javascript.builtins.Array.concat"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.flat": {
library: "core-js",
relativePaths: ["modules/es.array.flat.js"],
features: ["javascript.builtins.Array.flat"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.flat-map": {
library: "core-js",
relativePaths: ["modules/es.array.flat-map.js"],
features: ["javascript.builtins.Array.flatMap"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.last-index": {
library: "core-js",
relativePaths: ["modules/esnext.array.last-index.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.last-item": {
library: "core-js",
relativePaths: ["modules/esnext.array.last-item.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.copy-within": {
library: "core-js",
relativePaths: ["modules/es.array.copy-within.js"],
features: ["javascript.builtins.Array.copyWithin"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.every": {
library: "core-js",
relativePaths: ["modules/es.array.every.js"],
features: ["javascript.builtins.Array.every"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.fill": {
library: "core-js",
relativePaths: ["modules/es.array.fill.js"],
features: ["javascript.builtins.Array.fill"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.filter": {
library: "core-js",
relativePaths: ["modules/es.array.filter.js"],
features: ["javascript.builtins.Array.filter"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.find-index": {
library: "core-js",
relativePaths: ["modules/es.array.find-index.js"],
features: ["javascript.builtins.Array.findIndex"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.find": {
library: "core-js",
relativePaths: ["modules/es.array.find.js"],
features: ["javascript.builtins.Array.find"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.for-each": {
library: "core-js",
relativePaths: ["modules/es.array.for-each.js"],
features: ["javascript.builtins.Array.forEach"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.from": {
library: "core-js",
relativePaths: ["modules/es.array.from.js"],
features: ["javascript.builtins.Array.from"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.includes": {
library: "core-js",
relativePaths: ["modules/es.array.includes.js"],
features: ["javascript.builtins.Array.includes"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.index-of": {
library: "core-js",
relativePaths: ["modules/es.array.index-of.js"],
features: ["javascript.builtins.Array.indexOf"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.is-array": {
library: "core-js",
relativePaths: ["modules/es.array.is-array.js"],
features: ["javascript.builtins.Array.isArray"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.iterator": {
library: "core-js",
relativePaths: ["modules/es.array.iterator.js"],
features: ["javascript.builtins.Array.@@iterator"],
dependencies: ["es.symbol.iterator"],
contexts: ALL_CONTEXTS
},
"es.array.join": {
library: "core-js",
relativePaths: ["modules/es.array.join.js"],
features: ["javascript.builtins.Array.join"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.last-index-of": {
library: "core-js",
relativePaths: ["modules/es.array.last-index-of.js"],
features: ["javascript.builtins.Array.lastIndexOf"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.map": {
library: "core-js",
relativePaths: ["modules/es.array.map.js"],
features: ["javascript.builtins.Array.map"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.of": {
library: "core-js",
relativePaths: ["modules/es.array.of.js"],
features: ["javascript.builtins.Array.of"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.reduce-right": {
library: "core-js",
relativePaths: ["modules/es.array.reduce-right.js"],
features: ["javascript.builtins.Array.reduceRight"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.reduce": {
library: "core-js",
relativePaths: ["modules/es.array.reduce.js"],
features: ["javascript.builtins.Array.reduce"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.slice": {
library: "core-js",
relativePaths: ["modules/es.array.slice.js"],
features: ["javascript.builtins.Array.slice"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.some": {
library: "core-js",
relativePaths: ["modules/es.array.some.js"],
features: ["javascript.builtins.Array.some"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.sort": {
library: "core-js",
relativePaths: ["modules/es.array.sort.js"],
features: ["javascript.builtins.Array.sort"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array.species": {
library: "core-js",
relativePaths: ["modules/es.array.species.js"],
features: ["javascript.builtins.Array.@@species"],
dependencies: ["es.symbol.species"],
contexts: ALL_CONTEXTS
},
"es.array.splice": {
library: "core-js",
relativePaths: ["modules/es.array.splice.js"],
features: ["javascript.builtins.Array.splice"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array-buffer": {
polyfills: ["es.array-buffer.constructor", "es.array-buffer.is-view", "es.array-buffer.slice"]
},
"es.array-buffer.constructor": {
library: "core-js",
relativePaths: ["modules/es.array-buffer.constructor.js"],
features: ["javascript.builtins.ArrayBuffer"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.array-buffer.is-view": {
library: "core-js",
relativePaths: ["modules/es.array-buffer.is-view.js"],
features: ["javascript.builtins.ArrayBuffer.isView"],
dependencies: ["es.array-buffer.constructor"],
contexts: ALL_CONTEXTS
},
"es.array-buffer.slice": {
library: "core-js",
relativePaths: ["modules/es.array-buffer.slice.js"],
features: ["javascript.builtins.ArrayBuffer.slice"],
dependencies: ["es.array-buffer.constructor"],
contexts: ALL_CONTEXTS
},
"es.string": {
polyfills: [
"es.string.anchor",
"es.string.big",
"es.string.blink",
"es.string.bold",
"es.string.code-point-at",
"es.string.ends-with",
"es.string.fixed",
"es.string.fontcolor",
"es.string.fontsize",
"es.string.from-code-point",
"es.string.includes",
"es.string.italics",
"es.string.iterator",
"es.string.link",
"es.string.match",
"es.string.pad-end",
"es.string.pad-start",
"es.string.raw",
"es.string.repeat",
"es.string.search",
"es.string.small",
"es.string.split",
"es.string.starts-with",
"es.string.strike",
"es.string.sub",
"es.string.sup",
"es.string.trim",
"es.string.trim-start",
"es.string.trim-end",
"es.string.replace-all"
]
},
"es.string.at": {
library: "core-js",
relativePaths: ["modules/esnext.string.at.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.code-points": {
library: "core-js",
relativePaths: ["modules/esnext.string.code-points.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.match-all": {
library: "core-js",
relativePaths: ["modules/es.string.match-all.js"],
features: ["javascript.builtins.String.matchAll"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.replace-all": {
library: "core-js",
relativePaths: ["modules/es.string.replace-all.js"],
features: ["javascript.builtins.String.replaceAll"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.trim-start": {
library: "core-js",
relativePaths: ["modules/es.string.trim-start.js"],
features: ["javascript.builtins.String.trimStart"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.trim-end": {
library: "core-js",
relativePaths: ["modules/es.string.trim-end.js"],
features: ["javascript.builtins.String.trimEnd"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.anchor": {
library: "core-js",
relativePaths: ["modules/es.string.anchor.js"],
features: ["javascript.builtins.String.anchor"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.big": {
library: "core-js",
relativePaths: ["modules/es.string.big.js"],
features: ["javascript.builtins.String.big"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.blink": {
library: "core-js",
relativePaths: ["modules/es.string.blink.js"],
features: ["javascript.builtins.String.blink"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.bold": {
library: "core-js",
relativePaths: ["modules/es.string.bold.js"],
features: ["javascript.builtins.String.bold"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.code-point-at": {
library: "core-js",
relativePaths: ["modules/es.string.code-point-at.js"],
features: ["javascript.builtins.String.codePointAt"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.ends-with": {
library: "core-js",
relativePaths: ["modules/es.string.ends-with.js"],
features: ["javascript.builtins.String.endsWith"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.fixed": {
library: "core-js",
relativePaths: ["modules/es.string.fixed.js"],
features: ["javascript.builtins.String.fixed"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.fontcolor": {
library: "core-js",
relativePaths: ["modules/es.string.fontcolor.js"],
features: ["javascript.builtins.String.fontcolor"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.fontsize": {
library: "core-js",
relativePaths: ["modules/es.string.fontsize.js"],
features: ["javascript.builtins.String.fontsize"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.from-code-point": {
library: "core-js",
relativePaths: ["modules/es.string.from-code-point.js"],
features: ["javascript.builtins.String.fromCodePoint"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.includes": {
library: "core-js",
relativePaths: ["modules/es.string.includes.js"],
features: ["javascript.builtins.String.includes"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.italics": {
library: "core-js",
relativePaths: ["modules/es.string.italics.js"],
features: ["javascript.builtins.String.italics"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.iterator": {
library: "core-js",
relativePaths: ["modules/es.string.iterator.js"],
features: ["javascript.builtins.String.@@iterator"],
dependencies: ["es.symbol.iterator"],
contexts: ALL_CONTEXTS
},
"es.string.link": {
library: "core-js",
relativePaths: ["modules/es.string.link.js"],
features: ["javascript.builtins.String.link"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.match": {
library: "core-js",
relativePaths: ["modules/es.string.match.js"],
features: ["javascript.builtins.String.match"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.pad-end": {
library: "core-js",
relativePaths: ["modules/es.string.pad-end.js"],
features: ["javascript.builtins.String.padEnd"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.pad-start": {
library: "core-js",
relativePaths: ["modules/es.string.pad-start.js"],
features: ["javascript.builtins.String.padStart"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.raw": {
library: "core-js",
relativePaths: ["modules/es.string.raw.js"],
features: ["javascript.builtins.String.raw"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.repeat": {
library: "core-js",
relativePaths: ["modules/es.string.repeat.js"],
features: ["javascript.builtins.String.repeat"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.replace": {
library: "core-js",
relativePaths: ["modules/es.string.replace.js"],
features: ["javascript.builtins.String.replace"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.search": {
library: "core-js",
relativePaths: ["modules/es.string.search.js"],
features: ["javascript.builtins.String.search"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.small": {
library: "core-js",
relativePaths: ["modules/es.string.small.js"],
features: ["javascript.builtins.String.small"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.split": {
library: "core-js",
relativePaths: ["modules/es.string.split.js"],
features: ["javascript.builtins.String.split"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.starts-with": {
library: "core-js",
relativePaths: ["modules/es.string.starts-with.js"],
features: ["javascript.builtins.String.startsWith"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.strike": {
library: "core-js",
relativePaths: ["modules/es.string.strike.js"],
features: ["javascript.builtins.String.strike"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.sub": {
library: "core-js",
relativePaths: ["modules/es.string.sub.js"],
features: ["javascript.builtins.String.sub"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.sup": {
library: "core-js",
relativePaths: ["modules/es.string.sup.js"],
features: ["javascript.builtins.String.sup"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.string.trim": {
library: "core-js",
relativePaths: ["modules/es.string.trim.js"],
features: ["javascript.builtins.String.trim"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.regexp": {
polyfills: ["es.regexp.constructor", "es.regexp.flags", "es.regexp.to-string"]
},
"es.regexp.constructor": {
library: "core-js",
relativePaths: ["modules/es.regexp.constructor.js"],
features: ["javascript.builtins.RegExp"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.regexp.flags": {
library: "core-js",
relativePaths: ["modules/es.regexp.flags.js"],
features: ["javascript.builtins.RegExp.flags"],
dependencies: ["es.regexp.constructor"],
contexts: ALL_CONTEXTS
},
"es.regexp.to-string": {
library: "core-js",
relativePaths: ["modules/es.regexp.to-string.js"],
features: ["javascript.builtins.RegExp.toString"],
dependencies: ["es.regexp.constructor"],
contexts: ALL_CONTEXTS
},
"es.number": {
polyfills: [
"es.number.constructor",
"es.number.epsilon",
"es.number.is-finite",
"es.number.is-integer",
"es.number.is-nan",
"es.number.is-safe-integer",
"es.number.max-safe-integer",
"es.number.min-safe-integer",
"es.number.parse-float",
"es.number.parse-int",
"es.number.to-fixed",
"es.number.to-precision"
]
},
"es.number.from-string": {
library: "core-js",
relativePaths: ["modules/esnext.number.from-string.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.constructor": {
library: "core-js",
relativePaths: ["modules/es.number.constructor.js"],
features: ["javascript.builtins.Number"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.epsilon": {
library: "core-js",
relativePaths: ["modules/es.number.epsilon.js"],
features: ["javascript.builtins.Number.EPSILON"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.is-finite": {
library: "core-js",
relativePaths: ["modules/es.number.is-finite.js"],
features: ["javascript.builtins.Number.isFinite"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.is-integer": {
library: "core-js",
relativePaths: ["modules/es.number.is-integer.js"],
features: ["javascript.builtins.Number.isInteger"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.is-nan": {
library: "core-js",
relativePaths: ["modules/es.number.is-nan.js"],
features: ["javascript.builtins.Number.isNaN"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.is-safe-integer": {
library: "core-js",
relativePaths: ["modules/es.number.is-safe-integer.js"],
features: ["javascript.builtins.Number.isSafeInteger"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.max-safe-integer": {
library: "core-js",
relativePaths: ["modules/es.number.max-safe-integer.js"],
features: ["javascript.builtins.Number.MAX_SAFE_INTEGER"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.min-safe-integer": {
library: "core-js",
relativePaths: ["modules/es.number.min-safe-integer.js"],
features: ["javascript.builtins.Number.MIN_SAFE_INTEGER"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.parse-float": {
library: "core-js",
relativePaths: ["modules/es.number.parse-float.js"],
features: ["javascript.builtins.Number.parseFloat"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.parse-int": {
library: "core-js",
relativePaths: ["modules/es.number.parse-int.js"],
features: ["javascript.builtins.Number.parseInt"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.to-fixed": {
library: "core-js",
relativePaths: ["modules/es.number.to-fixed.js"],
features: ["javascript.builtins.Number.toFixed"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.number.to-precision": {
library: "core-js",
relativePaths: ["modules/es.number.to-precision.js"],
features: ["javascript.builtins.Number.toPrecision"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math": {
polyfills: [
"es.math.acosh",
"es.math.asinh",
"es.math.atanh",
"es.math.cbrt",
"es.math.clz32",
"es.math.cosh",
"es.math.expm1",
"es.math.fround",
"es.math.hypot",
"es.math.imul",
"es.math.log1p",
"es.math.log2",
"es.math.log10",
"es.math.sign",
"es.math.sinh",
"es.math.tanh",
"es.math.trunc"
]
},
"es.math.clamp": {
library: "core-js",
relativePaths: ["modules/esnext.math.clamp.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.deg-per-rad": {
library: "core-js",
relativePaths: ["modules/esnext.math.deg-per-rad.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.degrees": {
library: "core-js",
relativePaths: ["modules/esnext.math.degrees.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.fscale": {
library: "core-js",
relativePaths: ["modules/esnext.math.fscale.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.iaddh": {
library: "core-js",
relativePaths: ["modules/esnext.math.iaddh.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.imulh": {
library: "core-js",
relativePaths: ["modules/esnext.math.imulh.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.isubh": {
library: "core-js",
relativePaths: ["modules/esnext.math.isubh.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.rad-per-deg": {
library: "core-js",
relativePaths: ["modules/esnext.math.rad-per-deg.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.radians": {
library: "core-js",
relativePaths: ["modules/esnext.math.radians.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.scale": {
library: "core-js",
relativePaths: ["modules/esnext.math.scale.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.signbit": {
library: "core-js",
relativePaths: ["modules/esnext.math.signbit.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.umulh": {
library: "core-js",
relativePaths: ["modules/esnext.math.umulh.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.acosh": {
library: "core-js",
relativePaths: ["modules/es.math.acosh.js"],
features: ["javascript.builtins.Math.acosh"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.asinh": {
library: "core-js",
relativePaths: ["modules/es.math.asinh.js"],
features: ["javascript.builtins.Math.asinh"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.atanh": {
library: "core-js",
relativePaths: ["modules/es.math.atanh.js"],
features: ["javascript.builtins.Math.atanh"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.cbrt": {
library: "core-js",
relativePaths: ["modules/es.math.cbrt.js"],
features: ["javascript.builtins.Math.cbrt"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.clz32": {
library: "core-js",
relativePaths: ["modules/es.math.clz32.js"],
features: ["javascript.builtins.Math.clz32"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.cosh": {
library: "core-js",
relativePaths: ["modules/es.math.cosh.js"],
features: ["javascript.builtins.Math.cosh"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.expm1": {
library: "core-js",
relativePaths: ["modules/es.math.expm1.js"],
features: ["javascript.builtins.Math.expm1"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.fround": {
library: "core-js",
relativePaths: ["modules/es.math.fround.js"],
features: ["javascript.builtins.Math.fround"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.hypot": {
library: "core-js",
relativePaths: ["modules/es.math.hypot.js"],
features: ["javascript.builtins.Math.hypot"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.imul": {
library: "core-js",
relativePaths: ["modules/es.math.imul.js"],
features: ["javascript.builtins.Math.imul"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.log1p": {
library: "core-js",
relativePaths: ["modules/es.math.log1p.js"],
features: ["javascript.builtins.Math.log1p"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.log2": {
library: "core-js",
relativePaths: ["modules/es.math.log2.js"],
features: ["javascript.builtins.Math.log2"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.log10": {
library: "core-js",
relativePaths: ["modules/es.math.log10.js"],
features: ["javascript.builtins.Math.log10"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.sign": {
library: "core-js",
relativePaths: ["modules/es.math.sign.js"],
features: ["javascript.builtins.Math.sign"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.sinh": {
library: "core-js",
relativePaths: ["modules/es.math.sinh.js"],
features: ["javascript.builtins.Math.sinh"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.tanh": {
library: "core-js",
relativePaths: ["modules/es.math.tanh.js"],
features: ["javascript.builtins.Math.tanh"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.math.trunc": {
library: "core-js",
relativePaths: ["modules/es.math.trunc.js"],
features: ["javascript.builtins.Math.trunc"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.data-view": {
library: "core-js",
relativePaths: ["modules/es.data-view.js"],
features: ["javascript.builtins.DataView"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.date": {
polyfills: ["es.date.now", "es.date.to-iso-string", "es.date.to-json", "es.date.to-primitive", "es.date.to-string"]
},
"es.date.now": {
library: "core-js",
relativePaths: ["modules/es.date.now.js"],
features: ["javascript.builtins.Date.now"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.date.to-iso-string": {
library: "core-js",
relativePaths: ["modules/es.date.to-iso-string.js"],
features: ["javascript.builtins.Date.toISOString"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.date.to-json": {
library: "core-js",
relativePaths: ["modules/es.date.to-json.js"],
features: ["javascript.builtins.Date.toJSON"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.date.to-primitive": {
library: "core-js",
relativePaths: ["modules/es.date.to-primitive.js"],
features: ["javascript.builtins.Date.@@toPrimitive"],
dependencies: ["es.symbol.to-primitive"],
contexts: ALL_CONTEXTS
},
"es.date.to-string": {
library: "core-js",
relativePaths: ["modules/es.date.to-string.js"],
features: ["javascript.builtins.Date.toString"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.symbol": {
polyfills: [
"es.symbol.async-iterator",
"es.symbol.has-instance",
"es.symbol.is-concat-spreadable",
"es.symbol.iterator",
"es.symbol.constructor",
"es.symbol.match",
"es.symbol.match-all",
"es.symbol.replace",
"es.symbol.search",
"es.symbol.species",
"es.symbol.split",
"es.symbol.to-primitive",
"es.symbol.to-string-tag",
"es.symbol.unscopables",
"es.symbol.description"
]
},
"es.symbol.description": {
library: "core-js",
relativePaths: ["modules/es.symbol.description.js"],
features: ["javascript.builtins.Symbol.description"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.pattern-match": {
library: "core-js",
relativePaths: ["modules/esnext.symbol.pattern-match.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.constructor": {
library: "core-js",
relativePaths: ["modules/es.symbol.js"],
features: ["javascript.builtins.Symbol"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.symbol.async-iterator": {
library: "core-js",
relativePaths: ["modules/es.symbol.async-iterator.js"],
features: ["javascript.builtins.Symbol.asyncIterator"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.has-instance": {
library: "core-js",
relativePaths: ["modules/es.symbol.has-instance.js", "modules/es.function.has-instance.js"],
features: ["javascript.builtins.Symbol.hasInstance"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.is-concat-spreadable": {
library: "core-js",
relativePaths: ["modules/es.symbol.is-concat-spreadable.js"],
features: ["javascript.builtins.Symbol.isConcatSpreadable"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.iterator": {
library: "core-js",
relativePaths: ["modules/es.symbol.iterator.js"],
features: ["javascript.builtins.Symbol.iterator"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.match": {
library: "core-js",
relativePaths: ["modules/es.symbol.match.js"],
features: ["javascript.builtins.Symbol.match"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.match-all": {
library: "core-js",
relativePaths: ["modules/es.symbol.match-all.js"],
features: ["javascript.builtins.Symbol.matchAll"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.replace": {
library: "core-js",
relativePaths: ["modules/es.symbol.replace.js"],
features: ["javascript.builtins.Symbol.replace"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.search": {
library: "core-js",
relativePaths: ["modules/es.symbol.search.js"],
features: ["javascript.builtins.Symbol.search"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.species": {
library: "core-js",
relativePaths: ["modules/es.symbol.species.js"],
features: ["javascript.builtins.Symbol.species"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.split": {
library: "core-js",
relativePaths: ["modules/es.symbol.split.js"],
features: ["javascript.builtins.Symbol.split"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.to-primitive": {
library: "core-js",
relativePaths: ["modules/es.symbol.to-primitive.js"],
features: ["javascript.builtins.Symbol.toPrimitive"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.to-string-tag": {
library: "core-js",
relativePaths: ["modules/es.symbol.to-string-tag.js", "modules/es.json.to-string-tag.js", "modules/es.math.to-string-tag.js"],
features: ["javascript.builtins.Symbol.toStringTag"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.symbol.unscopables": {
library: "core-js",
relativePaths: ["modules/es.symbol.unscopables.js"],
features: ["javascript.builtins.Symbol.unscopables"],
dependencies: ["es.symbol.constructor"],
contexts: ALL_CONTEXTS
},
"es.collections": {
polyfills: ["es.map", "es.weak-map", "es.set", "es.weak-set"]
},
"es.map": {
library: "core-js",
relativePaths: ["modules/es.map.js"],
features: ["javascript.builtins.Map", "javascript.builtins.Map.@@iterator"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.map.every": {
library: "core-js",
relativePaths: ["modules/esnext.map.every.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.filter": {
library: "core-js",
relativePaths: ["modules/esnext.map.filter.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.find": {
library: "core-js",
relativePaths: ["modules/esnext.map.find.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.find-key": {
library: "core-js",
relativePaths: ["modules/esnext.map.find-key.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.from": {
library: "core-js",
relativePaths: ["modules/esnext.map.from.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.group-by": {
library: "core-js",
relativePaths: ["modules/esnext.map.group-by.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.includes": {
library: "core-js",
relativePaths: ["modules/esnext.map.includes.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.key-by": {
library: "core-js",
relativePaths: ["modules/esnext.map.key-by.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.key-of": {
library: "core-js",
relativePaths: ["modules/esnext.map.key-of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.map-keys": {
library: "core-js",
relativePaths: ["modules/esnext.map.map-keys.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.map-values": {
library: "core-js",
relativePaths: ["modules/esnext.map.map-values.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.merge": {
library: "core-js",
relativePaths: ["modules/esnext.map.merge.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.of": {
library: "core-js",
relativePaths: ["modules/esnext.map.of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.reduce": {
library: "core-js",
relativePaths: ["modules/esnext.map.reduce.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.some": {
library: "core-js",
relativePaths: ["modules/esnext.map.some.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.update": {
library: "core-js",
relativePaths: ["modules/esnext.map.update.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.map.emplace": {
library: "core-js",
relativePaths: ["modules/esnext.map.emplace.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.map"],
contexts: ALL_CONTEXTS
},
"es.weak-map": {
library: "core-js",
relativePaths: ["modules/es.weak-map.js"],
features: ["javascript.builtins.WeakMap"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.weak-map.from": {
library: "core-js",
relativePaths: ["modules/esnext.weak-map.from.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.weak-map"],
contexts: ALL_CONTEXTS
},
"es.weak-map.of": {
library: "core-js",
relativePaths: ["modules/esnext.weak-map.of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.weak-map"],
contexts: ALL_CONTEXTS
},
"es.set": {
library: "core-js",
relativePaths: ["modules/es.set.js"],
features: ["javascript.builtins.Set", "javascript.builtins.Set.@@iterator"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.set.add-all": {
library: "core-js",
relativePaths: ["modules/esnext.set.add-all.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.delete-all": {
library: "core-js",
relativePaths: ["modules/esnext.set.delete-all.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.difference": {
library: "core-js",
relativePaths: ["modules/esnext.set.difference.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.every": {
library: "core-js",
relativePaths: ["modules/esnext.set.every.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.filter": {
library: "core-js",
relativePaths: ["modules/esnext.set.filter.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.find": {
library: "core-js",
relativePaths: ["modules/esnext.set.find.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.from": {
library: "core-js",
relativePaths: ["modules/esnext.set.from.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.intersection": {
library: "core-js",
relativePaths: ["modules/esnext.set.intersection.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.join": {
library: "core-js",
relativePaths: ["modules/esnext.set.join.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.map": {
library: "core-js",
relativePaths: ["modules/esnext.set.map.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.of": {
library: "core-js",
relativePaths: ["modules/esnext.set.of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.reduce": {
library: "core-js",
relativePaths: ["modules/esnext.set.reduce.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.some": {
library: "core-js",
relativePaths: ["modules/esnext.set.some.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.symmetric-difference": {
library: "core-js",
relativePaths: ["modules/esnext.set.symmetric-difference.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.union": {
library: "core-js",
relativePaths: ["modules/esnext.set.union.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.is-disjoint-from": {
library: "core-js",
relativePaths: ["modules/esnext.set.is-disjoint-from.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.is-subset-of": {
library: "core-js",
relativePaths: ["modules/esnext.set.is-subset-of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.set.is-superset-of": {
library: "core-js",
relativePaths: ["modules/esnext.set.is-superset-of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.set"],
contexts: ALL_CONTEXTS
},
"es.weak-set": {
library: "core-js",
relativePaths: ["modules/es.weak-set.js"],
features: ["javascript.builtins.WeakSet"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.weak-set.from": {
library: "core-js",
relativePaths: ["modules/esnext.weak-set.from.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.weak-set"],
contexts: ALL_CONTEXTS
},
"es.weak-set.of": {
library: "core-js",
relativePaths: ["modules/esnext.weak-set.of.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: ["es.weak-set"],
contexts: ALL_CONTEXTS
},
"es.typed-array": {
polyfills: [
"es.typed-array.copy-within",
"es.typed-array.every",
"es.typed-array.fill",
"es.typed-array.filter",
"es.typed-array.find",
"es.typed-array.find-index",
"es.typed-array.float32-array",
"es.typed-array.float64-array",
"es.typed-array.for-each",
"es.typed-array.from",
"es.typed-array.includes",
"es.typed-array.index-of",
"es.typed-array.int8-array",
"es.typed-array.int16-array",
"es.typed-array.int32-array",
"es.typed-array.iterator",
"es.typed-array.join",
"es.typed-array.last-index-of",
"es.typed-array.map",
"es.typed-array.of",
"es.typed-array.reduce",
"es.typed-array.reduce-right",
"es.typed-array.reverse",
"es.typed-array.set",
"es.typed-array.slice",
"es.typed-array.some",
"es.typed-array.sort",
"es.typed-array.subarray",
"es.typed-array.to-locale-string",
"es.typed-array.to-string",
"es.typed-array.uint8-array",
"es.typed-array.uint8-clamped-array",
"es.typed-array.uint16-array",
"es.typed-array.uint32-array"
]
},
"es.typed-array.copy-within": {
library: "core-js",
relativePaths: ["modules/es.typed-array.copy-within.js"],
features: ["javascript.builtins.TypedArray.copyWithin"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.every": {
library: "core-js",
relativePaths: ["modules/es.typed-array.every.js"],
features: ["javascript.builtins.TypedArray.every"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.fill": {
library: "core-js",
relativePaths: ["modules/es.typed-array.fill.js"],
features: ["javascript.builtins.TypedArray.fill"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.filter": {
library: "core-js",
relativePaths: ["modules/es.typed-array.filter.js"],
features: ["javascript.builtins.TypedArray.filter"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.find": {
library: "core-js",
relativePaths: ["modules/es.typed-array.find.js"],
features: ["javascript.builtins.TypedArray.find"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.find-index": {
library: "core-js",
relativePaths: ["modules/es.typed-array.find-index.js"],
features: ["javascript.builtins.TypedArray.findIndex"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.float32-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.float32-array.js"],
features: ["javascript.builtins.Float32Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.float64-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.float64-array.js"],
features: ["javascript.builtins.Float64Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.for-each": {
library: "core-js",
relativePaths: ["modules/es.typed-array.for-each.js"],
features: ["javascript.builtins.TypedArray.forEach"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.from": {
library: "core-js",
relativePaths: ["modules/es.typed-array.from.js"],
features: ["javascript.builtins.TypedArray.from"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.includes": {
library: "core-js",
relativePaths: ["modules/es.typed-array.includes.js"],
features: ["javascript.builtins.TypedArray.includes"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.index-of": {
library: "core-js",
relativePaths: ["modules/es.typed-array.index-of.js"],
features: ["javascript.builtins.TypedArray.indexOf"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.int8-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.int8-array.js"],
features: ["javascript.builtins.Int8Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.int16-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.int16-array.js"],
features: ["javascript.builtins.Int16Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.int32-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.int32-array.js"],
features: ["javascript.builtins.Int32Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.iterator": {
library: "core-js",
relativePaths: ["modules/es.typed-array.iterator.js"],
features: ["javascript.builtins.TypedArray.@@iterator"],
dependencies: ["es.symbol.iterator"],
contexts: ALL_CONTEXTS
},
"es.typed-array.join": {
library: "core-js",
relativePaths: ["modules/es.typed-array.join.js"],
features: ["javascript.builtins.TypedArray.join"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.last-index-of": {
library: "core-js",
relativePaths: ["modules/es.typed-array.last-index-of.js"],
features: ["javascript.builtins.TypedArray.lastIndexOf"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.map": {
library: "core-js",
relativePaths: ["modules/es.typed-array.map.js"],
features: ["javascript.builtins.TypedArray.map"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.of": {
library: "core-js",
relativePaths: ["modules/es.typed-array.of.js"],
features: ["javascript.builtins.TypedArray.of"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.reduce": {
library: "core-js",
relativePaths: ["modules/es.typed-array.reduce.js"],
features: ["javascript.builtins.TypedArray.reduce"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.reduce-right": {
library: "core-js",
relativePaths: ["modules/es.typed-array.reduce-right.js"],
features: ["javascript.builtins.TypedArray.reduceRight"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.reverse": {
library: "core-js",
relativePaths: ["modules/es.typed-array.reverse.js"],
features: ["javascript.builtins.TypedArray.reverse"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.set": {
library: "core-js",
relativePaths: ["modules/es.typed-array.set.js"],
features: ["javascript.builtins.TypedArray.set"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.slice": {
library: "core-js",
relativePaths: ["modules/es.typed-array.slice.js"],
features: ["javascript.builtins.TypedArray.slice"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.some": {
library: "core-js",
relativePaths: ["modules/es.typed-array.some.js"],
features: ["javascript.builtins.TypedArray.some"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.sort": {
library: "core-js",
relativePaths: ["modules/es.typed-array.sort.js"],
features: ["javascript.builtins.TypedArray.sort"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.subarray": {
library: "core-js",
relativePaths: ["modules/es.typed-array.subarray.js"],
features: ["javascript.builtins.TypedArray.subarray"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.to-locale-string": {
library: "core-js",
relativePaths: ["modules/es.typed-array.to-locale-string.js"],
features: ["javascript.builtins.TypedArray.toLocaleString"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.to-string": {
library: "core-js",
relativePaths: ["modules/es.typed-array.to-string.js"],
features: ["javascript.builtins.TypedArray.toString"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.uint8-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.uint8-array.js"],
features: ["javascript.builtins.Uint8Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.uint8-clamped-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.uint8-clamped-array.js"],
features: ["javascript.builtins.Uint8ClampedArray"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.uint16-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.uint16-array.js"],
features: ["javascript.builtins.Uint16Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.typed-array.uint32-array": {
library: "core-js",
relativePaths: ["modules/es.typed-array.uint32-array.js"],
features: ["javascript.builtins.Uint32Array"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect": {
polyfills: [
"es.reflect.apply",
"es.reflect.construct",
"es.reflect.define-property",
"es.reflect.delete-property",
"es.reflect.get",
"es.reflect.get-own-property-descriptor",
"es.reflect.get-prototype-of",
"es.reflect.has",
"es.reflect.is-extensible",
"es.reflect.own-keys",
"es.reflect.prevent-extensions",
"es.reflect.set",
"es.reflect.set-prototype-of"
]
},
"es.reflect.define-metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.define-metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.delete-metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.delete-metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get-metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.get-metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get-metadata-keys": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.get-metadata-keys.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get-own-metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.get-own-metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get-own-metadata-keys": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.get-own-metadata-keys.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.has-metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.has-metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.has-own-metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.has-own-metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.metadata": {
library: "core-js",
relativePaths: ["modules/esnext.reflect.metadata.js"],
// TODO: Update when MDN or Caniuse Compatibility is added
features: [],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.apply": {
library: "core-js",
relativePaths: ["modules/es.reflect.apply.js"],
features: ["javascript.builtins.Reflect.apply"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.construct": {
library: "core-js",
relativePaths: ["modules/es.reflect.construct.js"],
features: ["javascript.builtins.Reflect.construct"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.define-property": {
library: "core-js",
relativePaths: ["modules/es.reflect.define-property.js"],
features: ["javascript.builtins.Reflect.defineProperty"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.delete-property": {
library: "core-js",
relativePaths: ["modules/es.reflect.delete-property.js"],
features: ["javascript.builtins.Reflect.deleteProperty"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get": {
library: "core-js",
relativePaths: ["modules/es.reflect.get.js"],
features: ["javascript.builtins.Reflect.get"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get-own-property-descriptor": {
library: "core-js",
relativePaths: ["modules/es.reflect.get-own-property-descriptor.js"],
features: ["javascript.builtins.Reflect.getOwnPropertyDescriptor"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.get-prototype-of": {
library: "core-js",
relativePaths: ["modules/es.reflect.get-prototype-of.js"],
features: ["javascript.builtins.Reflect.getPrototypeOf"],
dependencies: ["proto"],
contexts: ALL_CONTEXTS
},
"es.reflect.has": {
library: "core-js",
relativePaths: ["modules/es.reflect.has.js"],
features: ["javascript.builtins.Reflect.has"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.is-extensible": {
library: "core-js",
relativePaths: ["modules/es.reflect.is-extensible.js"],
features: ["javascript.builtins.Reflect.isExtensible"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.own-keys": {
library: "core-js",
relativePaths: ["modules/es.reflect.own-keys.js"],
features: ["javascript.builtins.Reflect.ownKeys"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.prevent-extensions": {
library: "core-js",
relativePaths: ["modules/es.reflect.prevent-extensions.js"],
features: ["javascript.builtins.Reflect.preventExtensions"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.set": {
library: "core-js",
relativePaths: ["modules/es.reflect.set.js"],
features: ["javascript.builtins.Reflect.set"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"es.reflect.set-prototype-of": {
library: "core-js",
relativePaths: ["modules/es.reflect.set-prototype-of.js"],
features: ["javascript.builtins.Reflect.setPrototypeOf"],
dependencies: ["proto"],
contexts: ALL_CONTEXTS
},
esnext: {
polyfills: ["esnext.array", "esnext.collections", "esnext.math", "esnext.number", "esnext.object", "esnext.promise", "esnext.reflect", "esnext.string", "esnext.symbol"]
},
// An alias for the alias 'esnext'
"es2016+": {
polyfills: ["esnext"]
},
"esnext.array": {
polyfills: ["es.array.last-index", "es.array.last-item"]
},
"esnext.object": {
polyfills: []
},
"esnext.collections": {
polyfills: ["esnext.map", "esnext.weak-map", "esnext.set", "esnext.weak-set"]
},
"esnext.map": {
polyfills: [
"es.map.every",
"es.map.filter",
"es.map.find",
"es.map.find-key",
"es.map.from",
"es.map.group-by",
"es.map.includes",
"es.map.key-by",
"es.map.key-of",
"es.map.map-keys",
"es.map.map-values",
"es.map.merge",
"es.map.of",
"es.map.reduce",
"es.map.some",
"es.map.update",
"es.map.emplace"
]
},
"esnext.weak-map": {
polyfills: ["es.weak-map.from", "es.weak-map.of"]
},
"esnext.set": {
polyfills: [
"es.set.add-all",
"es.set.delete-all",
"es.set.difference",
"es.set.every",
"es.set.filter",
"es.set.find",
"es.set.from",
"es.set.intersection",
"es.set.join",
"es.set.map",
"es.set.of",
"es.set.reduce",
"es.set.some",
"es.set.symmetric-difference",
"es.set.union",
"es.set.is-disjoint-from",
"es.set.is-subset-of",
"es.set.is-superset-of"
]
},
"esnext.weak-set": {
polyfills: ["es.weak-set.from", "es.weak-set.of"]
},
"esnext.math": {
polyfills: [
"es.math.clamp",
"es.math.deg-per-rad",
"es.math.degrees",
"es.math.fscale",
"es.math.iaddh",
"es.math.imulh",
"es.math.isubh",
"es.math.rad-per-deg",
"es.math.radians",
"es.math.scale",
"es.math.signbit",
"es.math.umulh"
]
},
"esnext.number": {
polyfills: ["es.number.from-string"]
},
"esnext.promise": {
polyfills: ["es.promise.try"]
},
"esnext.reflect": {
polyfills: [
"es.reflect.define-metadata",
"es.reflect.delete-metadata",
"es.reflect.get-metadata",
"es.reflect.get-metadata-keys",
"es.reflect.get-own-metadata",
"es.reflect.get-own-metadata-keys",
"es.reflect.has-metadata",
"es.reflect.has-own-metadata",
"es.reflect.metadata"
]
},
"esnext.string": {
polyfills: ["es.string.at", "es.string.code-points", "es.string.match-all"]
},
"esnext.symbol": {
polyfills: ["es.symbol.pattern-match"]
},
"dom.collections.iterable": {
polyfills: ["dom.collections.iterator", "dom.collections.for-each"]
},
"dom.collections.iterator": {
library: "core-js",
relativePaths: ["modules/web.dom-collections.iterator.js"],
features: ["api.NodeList.forEach"],
dependencies: ["es.symbol.iterator"],
contexts: WINDOW_CONTEXT
},
"dom.collections.for-each": {
library: "core-js",
relativePaths: ["modules/web.dom-collections.for-each.js"],
features: ["api.NodeList.forEach"],
dependencies: ["es.symbol.iterator"],
contexts: WINDOW_CONTEXT
},
"pointer-event": {
library: "@wessberg/pointer-events",
relativePaths: ["dist/index.js"],
features: ["pointer"],
dependencies: [
// TODO: Also relies on "elementFromPoint" which there isn't a polyfill for yet. Add it to the dependencies when the polyfill is ready
// TODO: Also relies on EventTarget and will throw in browsers where EventTarget is not defined
"es.array.from",
"es.array.some",
"es.array.every",
"es.string.includes",
"es.set",
"es.map",
"es.object.define-properties",
"es.object.define-property",
"event",
"custom-event",
"get-computed-style"
],
contexts: WINDOW_CONTEXT
},
xhr: {
library: "xhr-polyfill",
relativePaths: ["dist/xhr-polyfill.js"],
features: ["xhr2"],
dependencies: [],
contexts: WINDOW_CONTEXT
},
fetch: {
localPaths: ["polyfill-lib/fetch/fetch.js"],
features: ["fetch"],
version: "1.0.0",
dependencies: ["es.array.for-each", "es.object.get-own-property-names", "es.promise", "xhr"],
contexts: WINDOW_CONTEXT
},
intl: {
polyfills: [
"intl.date-time-format",
"intl.display-names",
"intl.get-canonical-locales",
"intl.list-format",
"intl.locale",
"intl.number-format",
"intl.plural-rules",
"intl.relative-time-format"
]
},
"intl.date-time-format": {
library: "@formatjs/intl-datetimeformat",
relativePaths: ["lib/polyfill.js"],
meta: {
localeDir: "locale-data"
},
features: ["javascript.builtins.Intl.DateTimeFormat"],
dependencies: [
"intl.locale",
"intl.number-format",
"es.set",
"es.weak-map",
"es.object.is",
"es.object.keys",
"es.object.set-prototype-of",
"es.object.define-property",
"es.object.assign",
"es.object.create",
"es.array.is-array",
"es.array.map",
"es.array.reduce",
"es.array.join",
"es.array.filter",
"es.array.index-of",
"es.date.now",
"es.string.replace"
],
contexts: ALL_CONTEXTS
},
"intl.display-names": {
library: "@formatjs/intl-displaynames",
relativePaths: ["lib/polyfill.js"],
meta: {
localeDir: "locale-data"
},
features: ["javascript.builtins.Intl.DisplayNames"],
dependencies: [
"intl.locale",
"es.weak-map",
"es.object.keys",
"es.object.set-prototype-of",
"es.object.define-property",
"es.object.assign",
"es.object.create",
"es.array.is-array",
"es.array.map",
"es.array.reduce",
"es.array.join",
"es.array.filter"
],
contexts: ALL_CONTEXTS
},
"intl.get-canonical-locales": {
library: "@formatjs/intl-getcanonicallocales",
relativePaths: ["lib/polyfill.js"],
meta: {},
features: ["javascript.builtins.Intl.getCanonicalLocales"],
dependencies: ["es.array.filter", "es.array.index-of", "es.array.join", "es.array.sort", "es.object.define-property", "es.object.keys", "es.string.split"],
contexts: ALL_CONTEXTS
},
"intl.list-format": {
library: "@formatjs/intl-listformat",
relativePaths: ["lib/polyfill.js"],
meta: {
localeDir: "locale-data"
},
features: ["javascript.builtins.Intl.ListFormat"],
dependencies: [
"intl.locale",
"es.array.filter",
"es.array.is-array",
"es.array.join",
"es.array.map",
"es.array.reduce",
"es.object.assign",
"es.object.create",
"es.object.define-property",
"es.object.keys",
"es.object.set-prototype-of",
"es.weak-map"
],
contexts: ALL_CONTEXTS
},
"intl.locale": {
library: "@formatjs/intl-locale",
relativePaths: ["lib/polyfill.js"],
meta: {},
features: ["javascript.builtins.Intl.Locale"],
dependencies: [
"intl.get-canonical-locales",
"es.array.concat",
"es.array.filter",
"es.array.for-each",
"es.array.index-of",
"es.array.is-array",
"es.array.join",
"es.array.sort",
"es.object.assign",
"es.object.create",
"es.object.define-property",
"es.object.freeze",
"es.object.get-own-property-descriptor",
"es.object.is",
"es.object.keys",
"es.object.set-prototype-of",
"es.string.split",
"es.weak-map"
],
contexts: ALL_CONTEXTS
},
"intl.number-format": {
library: "@formatjs/intl-numberformat",
relativePaths: ["lib/polyfill.js"],
meta: {
localeDir: "locale-data"
},
features: ["javascript.builtins.Intl.NumberFormat", "javascript.builtins.Intl.NumberFormat.NumberFormat.options_unit_parameter"],
dependencies: [
"intl.plural-rules",
"intl.locale",
"es.array.filter",
"es.array.index-of",
"es.array.is-array",
"es.array.join",
"es.array.map",
"es.array.reduce",
"es.object.assign",
"es.object.create",
"es.object.define-property",
"es.object.freeze",
"es.object.freeze",
"es.object.is",
"es.object.keys",
"es.object.set-prototype-of",
"es.string.replace",
"es.string.split",
"es.weak-map"
],
contexts: ALL_CONTEXTS
},
"intl.plural-rules": {
library: "@formatjs/intl-pluralrules",
relativePaths: ["lib/polyfill.js"],
meta: {
localeDir: "locale-data"
},
features: ["javascript.builtins.Intl.PluralRules"],
dependencies: [
"intl.locale",
"es.array.filter",
"es.array.for-each",
"es.array.is-array",
"es.array.join",
"es.array.map",
"es.array.reduce",
"es.object.assign",
"es.object.create",
"es.object.define-property",
"es.object.is",
"es.object.keys",
"es.object.set-prototype-of",
"es.string.replace",
"es.string.split",
"es.weak-map"
],
contexts: ALL_CONTEXTS
},
"intl.relative-time-format": {
library: "@formatjs/intl-relativetimeformat",
relativePaths: ["lib/polyfill.js"],
meta: {
localeDir: "locale-data"
},
features: ["javascript.builtins.Intl.RelativeTimeFormat"],
dependencies: [
"intl.plural-rules",
"intl.number-format",
"intl.locale",
"es.array.filter",
"es.array.is-array",
"es.array.join",
"es.array.map",
"es.array.reduce",
"es.object.assign",
"es.object.create",
"es.object.define-property",
"es.object.is",
"es.object.keys",
"es.object.set-prototype-of",
"es.weak-map"
],
contexts: ALL_CONTEXTS
},
animation: {
polyfills: ["web-animations"]
},
"web-animations": {
library: "web-animations-js",
relativePaths: ["web-animations.min.js"],
features: ["web-animation"],
dependencies: ["element", "requestanimationframe"],
contexts: WINDOW_CONTEXT
},
"regenerator-runtime": {
library: "regenerator-runtime",
relativePaths: ["runtime.js"],
features: [],
dependencies: ["es.promise"],
contexts: ALL_CONTEXTS
},
template: {
library: "@webcomponents/template",
relativePaths: ["template.js"],
features: ["template"],
dependencies: ["es"],
contexts: WINDOW_CONTEXT
},
"web-components": {
polyfills: ["custom-elements", "shadow-dom", "template"]
},
"custom-elements": {
library: "@webcomponents/custom-elements",
relativePaths: ["src/custom-elements.js"],
features: ["custom-elementsv1"],
dependencies: ["es", "mutation-observer"],
contexts: WINDOW_CONTEXT
},
"shadow-dom": {
localPaths: [
"node_modules/@webcomponents/shadydom/src/shadydom.js",
"node_modules/@webcomponents/shadycss/entrypoints/scoping-shim.js",
"node_modules/@webcomponents/shadycss/entrypoints/custom-style-interface.js"
],
meta: {
// The experimental variant is based on https://github.com/webcomponents/shadycss/pull/242
experimental: [
"node_modules/@webcomponents/shadydom/src/shadydom.js",
"polyfill-lib/@webcomponents/shadycss-experimental/entrypoints/scoping-shim.js",
"polyfill-lib/@webcomponents/shadycss-experimental/entrypoints/custom-style-interface.js"
]
},
features: ["shadowdomv1"],
version: pkg.dependencies["@webcomponents/shadydom"],
dependencies: ["es", "template", "mutation-observer", "event", "node.contains", "queryselector"],
contexts: WINDOW_CONTEXT,
mustComeAfter: ["pointer-event"]
},
queryselector: {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/document.querySelector/raw.js"],
features: ["queryselector"],
dependencies: ["element", "document", "document-fragment"],
contexts: WINDOW_CONTEXT
},
"document-fragment": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/DocumentFragment/raw.js"],
features: ["queryselector"],
dependencies: [],
contexts: WINDOW_CONTEXT
},
"node.parentelement": {
library: "node.parentelement",
relativePaths: ["polyfill.js"],
// If 'addEventListener' isn't found, the Window interface shouldn't exist on the window
features: ["addeventlistener"],
dependencies: ["document"],
contexts: WINDOW_CONTEXT
},
"scroll-behavior": {
library: "scroll-behavior-polyfill",
relativePaths: ["dist/index.js"],
features: ["css-scroll-behavior", "scrollintoview"],
dependencies: ["es.object.define-property", "es.object.get-own-property-descriptor", "requestanimationframe"],
contexts: WINDOW_CONTEXT
},
"focus-visible": {
library: "focus-visible",
relativePaths: ["dist/focus-visible.js"],
features: ["css-focus-visible"],
dependencies: ["class-list"],
contexts: WINDOW_CONTEXT
},
"node.contains": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/Node.prototype.contains/raw.js"],
// If 'addEventListener' isn't found, the Window interface shouldn't exist on the window
features: ["addeventlistener"],
dependencies: ["element"],
contexts: WINDOW_CONTEXT
},
window: {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/Window/raw.js"],
features: ["addeventlistener"],
dependencies: [],
contexts: WINDOW_CONTEXT
},
document: {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/document/raw.js"],
// If 'addEventListener' isn't found, the Document interface shouldn't exist on the window
features: ["addeventlistener"],
dependencies: [],
contexts: WINDOW_CONTEXT
},
"class-list": {
localPaths: ["polyfill-lib/class-list/class-list.js"],
features: ["api.Element.classList"],
version: "1.0.0",
dependencies: ["dom-token-list"],
contexts: WINDOW_CONTEXT
},
"dom-token-list": {
localPaths: ["polyfill-lib/dom-token-list/dom-token-list.js"],
features: ["api.DOMTokenList"],
version: "1.0.0",
dependencies: ["es.object.define-property"],
contexts: WINDOW_CONTEXT
},
element: {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/Element/raw.js"],
// If 'addEventListener' isn't found, the Element interface shouldn't exist on the window
features: ["addeventlistener"],
dependencies: ["document"],
contexts: WINDOW_CONTEXT
},
event: {
polyfills: ["event.constructor", "event.focusin", "event.hashchange"]
},
"event.constructor": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/Event/raw.js"],
features: ["api.Event.Event"],
dependencies: ["window", "document", "element", "es.object.define-property"],
contexts: WINDOW_CONTEXT
},
"event.focusin": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/Event.focusin/raw.js"],
features: ["focusin-focusout-events"],
dependencies: ["event.constructor"],
contexts: WINDOW_CONTEXT
},
"event.hashchange": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/Event.hashchange/raw.js"],
features: ["hashchange"],
dependencies: ["event.constructor"],
contexts: WINDOW_CONTEXT
},
"custom-event": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/CustomEvent/raw.js"],
features: ["customevent"],
dependencies: ["event"],
contexts: WINDOW_CONTEXT
},
"event-source": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/EventSource/raw.js"],
features: ["eventsource"],
dependencies: [],
contexts: WINDOW_CONTEXT
},
"get-computed-style": {
library: "polyfill-library",
relativePaths: ["polyfills/__dist/getComputedStyle/raw.js"],
features: ["getcomputedstyle"],
dependencies: ["window"],
contexts: WINDOW_CONTEXT
},
"intersection-observer": {
library: "intersection-observer",
relativePaths: ["intersection-observer.js"],
features: ["intersectionobserver"],
dependencies: [
"get-computed-style",
"es.array.is-array",
"es.array.filter",
"es.array.for-each",
"es.array.index-of",
"es.array.map",
"es.array.some",
"event",
"es.function",
"performance.now"
],
contexts: WINDOW_CONTEXT
},
"mutation-observer": {
library: "mutationobserver-shim",
relativePaths: ["dist/mutationobserver.min.js"],
features: ["mutationobserver"],
dependencies: [],
contexts: WINDOW_CONTEXT
},
"resize-observer": {
localPaths: ["polyfill-lib/resize-observer/resize-observer.js"],
features: ["resizeobserver"],
version: "1.0.0",
dependencies: ["es.weak-map", "es.object.create", "mutation-observer", "get-computed-style", "requestanimationframe"],
contexts: WINDOW_CONTEXT
},
"broadcast-channel": {
localPaths: ["polyfill-lib/broadcast-channel/broadcast-channel.js"],
features: ["broadcastchannel"],
version: "1.0.0",
dependencies: [],
contexts: WINDOW_CONTEXT
},
setimmediate: {
polyfills: ["set-immediate"]
},
"set-immediate": {
library: "setimmediate",
relativePaths: ["setImmediate.js"],
features: ["setimmediate"],
dependencies: [],
contexts: ALL_CONTEXTS
},
globalthis: {
polyfills: ["global-this"]
},
"global-this": {
library: "core-js",
relativePaths: ["modules/es.global-this.js"],
features: ["javascript.builtins.globalThis"],
dependencies: [],
contexts: ALL_CONTEXTS
},
"adopted-style-sheets": {
polyfills: ["constructable-style-sheets"]
},
"constructable-style-sheets": {
library: "construct-style-sheets-polyfill",
relativePaths: ["dist/adoptedStyleSheets.js"],
features: ["api.Document.adoptedStyleSheets", "api.ShadowRoot.adoptedStyleSheets"],
dependencies: ["es.symbol.has-instance"],
mustComeAfter: ["shadow-dom"],
contexts: ALL_CONTEXTS
},
proto: {
localPaths: ["polyfill-lib/proto/proto.js"],
features: ["javascript.builtins.Object.proto"],
version: "1.0.0",
dependencies: [],
contexts: ALL_CONTEXTS
}
}
}; | the_stack |
import React, { useState, useEffect, useCallback } from 'react';
import Button from '@material-ui/core/Button';
import sumBy from 'lodash/sumBy'
import { registerComponent, Components, getFragment } from '../../lib/vulcan-lib';
import { useUpdate } from '../../lib/crud/withUpdate';
import { updateEachQueryResultOfType, handleUpdateMutation } from '../../lib/crud/cacheUpdates';
import { useMulti } from '../../lib/crud/withMulti';
import { useMutation, gql } from '@apollo/client';
import Paper from '@material-ui/core/Paper';
import { useCurrentUser } from '../common/withUser';
import classNames from 'classnames';
import * as _ from "underscore"
import CachedIcon from '@material-ui/icons/Cached';
import KeyboardTabIcon from '@material-ui/icons/KeyboardTab';
import { Link } from '../../lib/reactRouterWrapper';
import { AnalyticsContext, useTracking } from '../../lib/analyticsEvents'
import seedrandom from '../../lib/seedrandom';
const YEAR = 2019
const NOMINATIONS_VIEW = "nominations2019"
const VOTING_VIEW = "voting2019" // unfortunately this can't just inhereit from YEAR. It needs to exactly match a view-type so that the type-check of the view can pass.
const REVIEW_COMMENTS_VIEW = "reviews2019"
const userVotesAreQuadraticField: keyof DbUser = "reviewVotesQuadratic2019";
export const currentUserCanVote = (currentUser: UsersCurrent|null) =>
currentUser && new Date(currentUser.createdAt) < new Date(`${YEAR}-01-01`)
//const YEAR = 2018
//const NOMINATIONS_VIEW = "nominations2018"
//const REVIEWS_VIEW = "reviews2018"
const defaultReactions = [
"I personally benefited from this post",
"Deserves followup work",
"Should be edited/improved",
"Important but shouldn't be in book",
"I spent 30+ minutes reviewing this in-depth"
]
const styles = (theme: ThemeType): JssStyles => ({
grid: {
display: 'grid',
gridTemplateColumns: `
minmax(10px, 0.5fr) minmax(300px, 740px) minmax(30px, 0.5fr) minmax(100px, 600px) minmax(30px, 0.5fr)
`,
gridTemplateAreas: `
"... leftColumn ... rightColumn ..."
`,
paddingBottom: 175
},
instructions: {
maxWidth: 545,
paddingBottom: 35
},
leftColumn: {
gridArea: "leftColumn",
[theme.breakpoints.down('sm')]: {
display: "none"
}
},
rightColumn: {
gridArea: "rightColumn",
[theme.breakpoints.down('sm')]: {
display: "none"
},
},
result: {
...theme.typography.smallText,
...theme.typography.commentStyle,
lineHeight: "1.3rem",
marginBottom: 10,
position: "relative"
},
votingBox: {
maxWidth: 700
},
expandedInfo: {
maxWidth: 600,
marginBottom: 175,
},
menu: {
position: "sticky",
top:0,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
backgroundColor: "white",
zIndex: theme.zIndexes.reviewVotingMenu,
padding: theme.spacing.unit,
background: "#ddd",
borderBottom: "solid 1px rgba(0,0,0,.15)"
},
menuIcon: {
marginLeft: theme.spacing.unit
},
returnToBasicIcon: {
transform: "rotate(180deg)",
marginRight: theme.spacing.unit
},
expandedInfoWrapper: {
position: "fixed",
top: 100,
overflowY: "auto",
height: "100vh",
paddingRight: 8
},
header: {
...theme.typography.display3,
...theme.typography.commentStyle,
marginTop: 6,
},
postHeader: {
...theme.typography.display1,
...theme.typography.postStyle,
marginTop: 0,
},
comments: {
},
voteTotal: {
...theme.typography.body2,
...theme.typography.commentStyle,
},
excessVotes: {
color: theme.palette.error.main,
border: `solid 1px ${theme.palette.error.light}`,
paddingLeft: 12,
paddingRight: 12,
paddingTop: 6,
paddingBottom: 6,
borderRadius: 3,
'&:hover': {
opacity: .5
}
},
message: {
width: "100%",
textAlign: "center",
paddingTop: 50,
...theme.typography.body2,
...theme.typography.commentStyle,
},
hideOnMobile: {
[theme.breakpoints.up('md')]: {
display: "none"
}
},
writeAReview: {
paddingTop: 12,
paddingLeft: 12,
paddingRight: 12,
paddingBottom: 8,
border: "solid 1px rgba(0,0,0,.3)",
marginBottom: 8,
},
reviewPrompt: {
fontWeight: 600,
fontSize: "1.2rem",
color: theme.palette.text.normal,
width: "100%",
display: "block"
},
fakeTextfield: {
marginTop: 5,
width: "100%",
borderBottom: "dashed 1px rgba(0,0,0,.25)",
color: theme.palette.grey[400]
},
warning: {
color: theme.palette.error.main
},
// averageVoteInstructions: {
// padding: 12,
// ...commentBodyStyles(theme),
// },
// averageVoteRow: {
// padding: 12,
// display: "flex",
// },
// averageVoteLabel: {
// marginTop: 8,
// flexGrow: 1,
// fontSize: "1.3rem",
// fontFamily: theme.typography.postStyle.fontFamily,
// },
// averageVote: {
// ...theme.typography.body1,
// ...theme.typography.commentStyle
// },
// averageVoteButton: {
// ...theme.typography.body2,
// ...theme.typography.commentStyle,
// fontWeight: 600,
// paddingLeft: 10,
// paddingRight: 10,
// cursor: "pointer"
// },
voteAverage: {
cursor: 'pointer',
},
leaveReactions: {
marginTop: 16,
}
});
export type ReviewVote = {_id: string, postId: string, score: number, type?: string, reactions: string[]}
export type quadraticVote = ReviewVote & {type: "quadratic"}
export type qualitativeVote = ReviewVote & {type: "qualitative", score: 0|1|2|3|4}
const generatePermutation = (count: number, user: UsersCurrent|null): Array<number> => {
const seed = user?._id || "";
const rng = seedrandom(seed);
let remaining = _.range(count);
let result: Array<number> = [];
while(remaining.length > 0) {
let idx = Math.floor(rng() * remaining.length);
result.push(remaining[idx]);
remaining.splice(idx, 1);
}
return result;
}
const ReviewVotingPage2019 = ({classes}: {
classes: ClassesType,
}) => {
// return <div>This page no longer exists, sorry. :(</div>
const currentUser = useCurrentUser()
const { captureEvent } = useTracking({eventType: "reviewVotingEvent"})
const { results: posts, loading: postsLoading } = useMulti({
terms: {view: VOTING_VIEW, limit: 300},
collectionName: "Posts",
fragmentName: 'PostsListWithVotes',
fetchPolicy: 'cache-and-network',
});
const { results: dbVotes, loading: dbVotesLoading } = useMulti({
terms: {view: "reviewVotesFromUser", limit: 300, userId: currentUser?._id, year: YEAR+""},
collectionName: "ReviewVotes",
fragmentName: "reviewVoteFragment",
fetchPolicy: 'cache-and-network',
})
const {mutate: updateUser} = useUpdate({
collectionName: "Users",
fragmentName: 'UsersCurrent',
});
const [submitVote] = useMutation(gql`
mutation submitReviewVote($postId: String, $qualitativeScore: Int, $quadraticChange: Int, $newQuadraticScore: Int, $comment: String, $year: String, $dummy: Boolean, $reactions: [String]) {
submitReviewVote(postId: $postId, qualitativeScore: $qualitativeScore, quadraticChange: $quadraticChange, comment: $comment, newQuadraticScore: $newQuadraticScore, year: $year, dummy: $dummy, reactions: $reactions) {
...reviewVoteFragment
}
}
${getFragment("reviewVoteFragment")}
`, {
update: (store, mutationResult) => {
updateEachQueryResultOfType({
func: handleUpdateMutation,
document: mutationResult.data.submitReviewVote,
store, typeName: "ReviewVote",
});
}
});
const [useQuadratic, setUseQuadratic] = useState(currentUser ? currentUser[userVotesAreQuadraticField] : false)
const [loading, setLoading] = useState(false)
const [expandedPost, setExpandedPost] = useState<any>(null)
const [showKarmaVotes, setShowKarmaVotes] = useState<any>(null)
const votes = dbVotes?.map(({_id, qualitativeScore, postId, reactions}) => ({_id, postId, score: qualitativeScore, type: "qualitative", reactions})) as qualitativeVote[]
const handleSetUseQuadratic = (newUseQuadratic: boolean) => {
if (!newUseQuadratic) {
if (!confirm("WARNING: This will discard your quadratic vote data. Are you sure you want to return to basic voting?")) {
return
}
}
setUseQuadratic(newUseQuadratic)
void updateUser({
selector: {_id: currentUser?._id},
data: {
[userVotesAreQuadraticField]: newUseQuadratic,
}
});
}
const dispatchQualitativeVote = useCallback(async ({_id, postId, score, reactions}: {
_id: string|null,
postId: string,
score: number,
reactions?: string[],
}) => {
const existingVote = _id ? dbVotes?.find(vote => vote._id === _id) : null;
const newReactions = reactions || existingVote?.reactions || []
return await submitVote({variables: {postId, qualitativeScore: score, year: YEAR+"", dummy: false, reactions: newReactions}})
}, [submitVote, dbVotes]);
const quadraticVotes = dbVotes?.map(({_id, quadraticScore, postId}) => ({_id, postId, score: quadraticScore, type: "quadratic"})) as quadraticVote[]
const dispatchQuadraticVote = async ({_id, postId, change, set, reactions}: {
_id?: string|null,
postId: string,
change?: number,
set?: number,
reactions?: string[],
}) => {
const existingVote = _id ? dbVotes?.find(vote => vote._id === _id) : null;
const newReactions = reactions || existingVote?.reactions || []
await submitVote({
variables: {postId, quadraticChange: change, newQuadraticScore: set, year: YEAR+"", reactions: newReactions, dummy: false},
optimisticResponse: _id && {
__typename: "Mutation",
submitReviewVote: {
__typename: "ReviewVote",
...existingVote,
quadraticScore: (typeof set !== 'undefined') ? set : ((existingVote?.quadraticScore || 0) + (change || 0)),
reactions: newReactions
}
}
})
}
const { ReviewPostComments, LWTooltip, Loading, ReviewPostButton, ReviewVoteTableRow, ReactionsButton, ContentStyles } = Components
const [postOrder, setPostOrder] = useState<Map<number, number> | undefined>(undefined)
const reSortPosts = () => {
setPostOrder(new Map(getPostOrder(posts, useQuadratic ? quadraticVotes : votes, currentUser)))
captureEvent(undefined, {eventSubType: "postsResorted"})
}
// Re-sort in response to changes. (But we don't need to re-sort in response
// to everything exhaustively)
useEffect(() => {
if (!!posts && useQuadratic ? !!quadraticVotes : !!votes) setPostOrder(new Map(getPostOrder(posts, useQuadratic ? quadraticVotes : votes, currentUser)))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [!!posts, useQuadratic, !!quadraticVotes, !!votes])
if (!currentUserCanVote(currentUser)) {
return (
<div className={classes.message}>
Only users registered before {YEAR} can vote in the {YEAR} LessWrong Review
</div>
)
}
const voteTotal = useQuadratic ? computeTotalCost(quadraticVotes) : 0
// const averageQuadraticVote = posts?.length>0 ? sumBy(quadraticVotes, v=>v.score)/posts.length : 0;
// const averageQuadraticVoteStr = averageQuadraticVote.toFixed(2);
// const adjustAllQuadratic = (delta: number) => {
// for (let post of posts) {
// const existingVote = votes.find(vote => vote.postId === post._id);
// void dispatchQuadraticVote({
// _id: existingVote?._id || null,
// postId: post._id,
// change: delta,
// });
// }
// }
const currentReactions = expandedPost ? [...(votes.find(vote => vote.postId === expandedPost._id)?.reactions || [])] : []
// TODO: Redundancy here due to merge
const voteSum = useQuadratic ? computeTotalVote(quadraticVotes) : 0
const voteAverage = (posts && posts.length > 0) ? voteSum/posts?.length : 0
const renormalizeVotes = (quadraticVotes:quadraticVote[], voteAverage: number) => {
const voteAdjustment = -Math.trunc(voteAverage)
quadraticVotes.forEach(vote => dispatchQuadraticVote({...vote, change: voteAdjustment, set: undefined }))
}
return (
<AnalyticsContext pageContext="ReviewVotingPage">
<div>
<div className={classNames(classes.hideOnMobile, classes.message)}>
Voting is not available on small screens
</div>
<div className={classes.grid}>
<div className={classes.leftColumn}>
<div className={classes.menu}>
<LWTooltip title="Sorts the list of post by vote-strength">
<Button onClick={reSortPosts}>
Re-Sort <CachedIcon className={classes.menuIcon} />
</Button>
</LWTooltip>
<LWTooltip title="Show which posts you have upvoted or downvoted">
<Button onClick={() => setShowKarmaVotes(!showKarmaVotes)}>
{showKarmaVotes ? "Hide Karma Votes" : "Show Karma Votes"}
</Button>
</LWTooltip>
{(postsLoading || dbVotesLoading || loading) && <Loading/>}
{!useQuadratic && <LWTooltip title="WARNING: Once you switch to quadratic-voting, you cannot go back to default-voting without losing your quadratic data.">
<Button className={classes.convert} onClick={async () => {
setLoading(true)
await Promise.all(votesToQuadraticVotes(votes, posts).map(dispatchQuadraticVote))
handleSetUseQuadratic(true)
captureEvent(undefined, {eventSubType: "quadraticVotingSet", quadraticVoting:true})
setLoading(false)
}}>
Convert to Quadratic <KeyboardTabIcon className={classes.menuIcon} />
</Button>
</LWTooltip>}
{useQuadratic && <LWTooltip title="Discard your quadratic data and return to default voting.">
<Button className={classes.convert} onClick={async () => {
handleSetUseQuadratic(false)
captureEvent(undefined, {eventSubType: "quadraticVotingSet", quadraticVoting:false})
}}>
<KeyboardTabIcon className={classes.returnToBasicIcon} /> Return to Basic Voting
</Button>
</LWTooltip>}
{useQuadratic && <LWTooltip title={`You have ${500 - voteTotal} points remaining`}>
<div className={classNames(classes.voteTotal, {[classes.excessVotes]: voteTotal > 500})}>
{voteTotal}/500
</div>
</LWTooltip>}
{useQuadratic && Math.abs(voteAverage) > 1 && <LWTooltip title={<div>
<p><em>Click to renormalize your votes, closer to an optimal allocation</em></p>
<p>If the average of your votes is above 1 or below -1 you are always better off by shifting all of your votes by 1 to move closer to an average of 0. See voting instructions for details.</p></div>}>
<div className={classNames(classes.voteTotal, classes.excessVotes, classes.voteAverage)} onClick={() => renormalizeVotes(quadraticVotes, voteAverage)}>
Avg: {posts ? (voteSum / posts.length).toFixed(2) : 0}
</div>
</LWTooltip>}
<Button disabled={!expandedPost} onClick={()=>{
setExpandedPost(null)
captureEvent(undefined, {eventSubType: "showInstructionsClicked"})
}}>Show Instructions</Button>
</div>
<Paper>
{!!posts && !!postOrder && applyOrdering(posts, postOrder).map((post) => {
const currentQualitativeVote = votes.find(vote => vote.postId === post._id)
const currentQuadraticVote = quadraticVotes.find(vote => vote.postId === post._id)
return <div key={post._id} onClick={()=>{
setExpandedPost(post)
captureEvent(undefined, {eventSubType: "voteTableRowClicked", postId: post._id})}}
>
<ReviewVoteTableRow
post={post}
showKarmaVotes={showKarmaVotes}
dispatch={dispatchQualitativeVote as any}
currentVote={(useQuadratic ? currentQuadraticVote : currentQualitativeVote) as any}
// dispatchQuadraticVote={dispatchQuadraticVote}
// useQuadratic={useQuadratic}
expandedPostId={expandedPost?._id}
/>
</div>
})}
</Paper>
</div>
<div className={classes.rightColumn}>
{!expandedPost && <div className={classes.expandedInfoWrapper}>
<div className={classes.expandedInfo}>
<h1 className={classes.header}>Vote on nominated and reviewed posts from {YEAR}</h1>
<ContentStyles contentType="comment" className={classes.instructions}>
{/* <p className={classes.warning}>For now this is just a dummy page that you can use to understand how the vote works. All submissions will be discarded, and the list of posts replaced by posts in the {YEAR} Review on January 12th.</p> */}
<p> Your vote should reflect a post’s overall level of importance (with whatever weightings seem right to you for “usefulness”, “accuracy”, “following good norms”, and other virtues).</p>
<p>Voting is done in two passes. First, roughly sort each post into one of the following buckets:</p>
<ul>
<li><b>No</b> – Misleading, harmful or low quality.</li>
<li><b>Neutral</b> – You wouldn't personally recommend it, but seems fine if others do. <em>(If you don’t have strong opinions about a post, leaving it ‘neutral’ is fine)</em></li>
<li><b>Good</b> – Useful ideas that I still think about sometimes.</li>
<li><b>Important</b> – A key insight or excellent distillation.</li>
<li><b>Crucial</b> – One of the most significant posts of {YEAR}, for LessWrong to discuss and build upon over the coming years.</li>
</ul>
<p>After that, click “Convert to Quadratic”, and you will then have the option to use the quadratic voting system to fine-tune your votes. (Quadratic voting gives you a limited number of “points” to spend on votes, allowing you to vote multiple times, with each additional vote on an item costing more. See <Link to="/posts/qQ7oJwnH9kkmKm2dC/feedback-request-quadratic-voting-for-the-2018-review">this post</Link> for details. Also note that your vote allocation is not optimal if the average of your votes is above 1 or below -1, see <Link to="/posts/3yqf6zJSwBF34Zbys/2018-review-voting-results?commentId=HL9cPrFqMexGn4jmZ">this comment</Link> for details..)</p>
<p>If you’re having difficulties, please message the LessWrong Team using Intercom, the circle at the bottom right corner of the screen, or leave a comment on <Link to="/posts/QFBEjjAvT6KbaA3dY/the-lesswrong-2019-review">this post</Link>.</p>
<p>The vote closes on Jan 26th. If you leave this page and come back, your votes will be saved.</p>
</ContentStyles>
</div>
</div>}
{expandedPost && <div className={classes.expandedInfoWrapper}>
<div className={classes.expandedInfo}>
<div className={classes.leaveReactions}>
{[...new Set([...defaultReactions, ...currentReactions])].map(reaction => <ReactionsButton
postId={expandedPost._id}
key={reaction}
vote={useQuadratic ? dispatchQuadraticVote : dispatchQualitativeVote}
votes={votes as any}
reaction={reaction}
freeEntry={false}
/>)}
<ReactionsButton
postId={expandedPost._id}
vote={useQuadratic ? dispatchQuadraticVote : dispatchQualitativeVote}
votes={votes as any}
reaction={"Other..."}
freeEntry={true}
/>
</div>
<ReviewPostButton post={expandedPost} year={YEAR+""} reviewMessage={<div>
<div className={classes.writeAReview}>
<div className={classes.reviewPrompt}>Write a review for "{expandedPost.title}"</div>
<div className={classes.fakeTextfield}>Any thoughts about this post you want to share with other voters?</div>
</div>
</div>}/>
<div className={classes.comments}>
<ReviewPostComments
title="nomination"
singleLine
terms={{view: NOMINATIONS_VIEW, postId: expandedPost._id}}
post={expandedPost}
/>
<ReviewPostComments
title="review"
terms={{view: REVIEW_COMMENTS_VIEW, postId: expandedPost._id}}
post={expandedPost}
/>
</div>
</div>
</div>}
</div>
</div>
</div>
</AnalyticsContext>
);
}
function getPostOrder(posts: Array<PostsList> | undefined, votes: Array<qualitativeVote|quadraticVote>, currentUser: UsersCurrent|null): Array<[number,number]> {
if (!posts) return []
const randomPermutation = generatePermutation(posts.length, currentUser);
const result = posts.map(
(post: PostsList, i: number): [PostsList, qualitativeVote | quadraticVote | undefined, number, number, number] => {
const voteForPost = votes.find(vote => vote.postId === post._id)
const voteScore = voteForPost ? voteForPost.score : 1;
return [post, voteForPost, voteScore, i, randomPermutation[i]]
})
.sort(([post1, vote1, voteScore1, i1, permuted1], [post2, vote2, voteScore2, i2, permuted2]) => {
if (voteScore1 < voteScore2) return -1;
if (voteScore1 > voteScore2) return 1;
if (permuted1 < permuted2) return -1;
if (permuted1 > permuted2) return 1;
else return 0;
})
.reverse()
.map(([post,vote,voteScore,originalIndex,permuted], sortedIndex) => [sortedIndex, originalIndex])
return result as Array<[number,number]>;
}
function applyOrdering<T extends any>(array:T[], order:Map<number, number>):T[] {
const newArray = array.map((value, i) => {
const newIndex = order.get(i)
if (typeof newIndex !== 'number') throw Error(`Can't find value for key: ${i}`)
return array[newIndex]
})
return newArray
}
const qualitativeScoreScaling = {
0: -4,
1: 0,
2: 1,
3: 4,
4: 15
}
const VOTE_BUDGET = 500
const MAX_SCALING = 6
const votesToQuadraticVotes = (votes:qualitativeVote[], posts: any[] | undefined):{postId: string, change?: number, set?: number, _id?: string, previousValue?: number}[] => {
const sumScaled = sumBy(votes, vote => Math.abs(qualitativeScoreScaling[vote ? vote.score : 1]) || 0)
return createPostVoteTuples(posts, votes).map(([post, vote]) => {
if (vote) {
const newScore = computeQuadraticVoteScore(vote.score, sumScaled)
return {postId: post._id, set: newScore}
} else {
return {postId: post._id, set: 0}
}
})
}
const computeQuadraticVoteScore = (qualitativeScore: 0|1|2|3|4, totalCost: number) => {
const scaledScore = qualitativeScoreScaling[qualitativeScore]
const scaledCost = scaledScore * Math.min(VOTE_BUDGET/totalCost, MAX_SCALING)
const newScore = Math.sign(scaledCost) * Math.floor(inverseSumOf1ToN(Math.abs(scaledCost)))
return newScore
}
const inverseSumOf1ToN = (x:number) => {
return Math.sign(x)*(1/2 * (Math.sqrt((8 * Math.abs(x)) + 1) - 1))
}
const sumOf1ToN = (x:number) => {
const absX = Math.abs(x)
return absX*(absX+1)/2
}
const computeTotalCost = (votes: ReviewVote[]) => {
return sumBy(votes, ({score}) => sumOf1ToN(score))
}
const computeTotalVote = (votes: ReviewVote[]) => {
return sumBy(votes, ({score}) => score)
}
function createPostVoteTuples<K extends HasIdType,T extends ReviewVote> (posts: K[] | undefined, votes: T[]):[K, T | undefined][] {
if (!posts) return []
return posts.map(post => {
const voteForPost = votes.find(vote => vote.postId === post._id)
return [post, voteForPost]
})
}
const ReviewVotingPage2019Component = registerComponent('ReviewVotingPage2019', ReviewVotingPage2019, {styles});
declare global {
interface ComponentTypes {
ReviewVotingPage2019: typeof ReviewVotingPage2019Component
}
} | the_stack |
import {
CancellationToken,
ExtensionContext,
NotebookCellExecution,
NotebookCellOutput,
NotebookCellOutputItem
} from 'vscode';
import { getNotebookCwd, registerDisposable } from '../utils';
import { CellExecutionState } from './types';
import { spawn } from 'child_process';
import type { Terminal } from 'xterm';
import type { SerializeAddon } from 'xterm-addon-serialize';
import * as os from 'os';
import * as tmp from 'tmp';
import * as fs from 'fs';
import * as path from 'path';
import { quote } from 'shell-quote';
import { IPty } from 'node-pty';
import { noop } from '../coreUtils';
import { getNextExecutionOrder } from './executionOrder';
import { getConfiguration } from '../configuration';
const shell = os.platform() === 'win32' ? 'powershell.exe' : process.env['SHELL'] || 'bash';
const startSeparator = '51e9f0e8-77a0-4bf0-9733-335153be2ec0:Start';
const endSeparator = '51e9f0e8-77a0-4bf0-9733-335153be2ec0:End';
const env = JSON.parse(JSON.stringify(process.env));
// Totally guessing what this env variables are...
delete env.ELECTRON_RUN_AS_NODE;
env.XPC_SERVICE_NAME = '0';
env.SHLVL = '0';
export class ShellKernel {
public static register(context: ExtensionContext) {
ShellPty.shellJsPath = path.join(context.extensionUri.fsPath, 'resources', 'scripts', 'shell.js');
ShellPty.nodePtyPath = path.join(
context.extensionUri.fsPath,
'resources',
'scripts',
'node_modules',
'profoundjs-node-pty'
);
}
public static async execute(task: NotebookCellExecution, token: CancellationToken): Promise<CellExecutionState> {
task.start(Date.now());
const command = task.cell.document.getText();
await task.clearOutput();
if (isEmptyShellCommand(command)) {
task.end(undefined);
return CellExecutionState.notExecutedEmptyCell;
}
if (token.isCancellationRequested) {
task.end(undefined);
return CellExecutionState.success;
}
task.executionOrder = getNextExecutionOrder(task.cell.notebook);
const cwd = getNotebookCwd(task.cell.notebook);
if (isSimpleSingleLineShellCommand(command) || !ShellPty.available()) {
return ShellProcess.execute(task, token, cwd);
} else {
return ShellPty.execute(task, token, cwd);
}
}
}
/**
* List of simple Shell commands that can be run in a node process instead of spinning a node-pty process, which is much slower.
* The benefit is spinning node process is significantly faster & we're not expecting these to be slow with streaming output like `npm i` with progress bars.
*/
const simpleSigleLineShellCommands = new Set<string>(
'git,echo,rm,cp,cd,ls,cat,pwd,ln,mkdir,nv,sed,set,cat,touch,grep,more,wc,df,tar,chown,chgrp,chmod,sort,tail,find,man,nano,rmdir,less,ssh,hostname,top,history,yppasswd,display,page,just,head,lpq,awk,split,gzip,kill,uptime,last,users,lun,vmstat,netstat,w,ps,date,reset,script,time,homequota,iostat,printenv,mail,ftp,tftp,sftp,rcp,scp,wget,curl,telnet,ssh,rlogin,rsh,make,size,nm,strip,who,pushd,popd,dirs,which'.split(
','
)
);
function getPossibleShellCommandLines(command: string) {
return command
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.filter((line) => !line.startsWith('#'));
}
function isEmptyShellCommand(command: string) {
return getPossibleShellCommandLines(command).length === 0;
}
function isSimpleSingleLineShellCommand(command: string) {
if (getPossibleShellCommandLines(command).length !== 1) {
return false;
}
// Get the first word (command)
const cmd = getPossibleShellCommandLines(command)[0].split(' ')[0];
return simpleSigleLineShellCommands.has(cmd);
}
class ShellProcess {
public static async execute(task: NotebookCellExecution, token: CancellationToken, cwd?: string) {
const commands = getPossibleShellCommandLines(task.cell.document.getText());
const command = commands.length === 1 ? commands[0] : task.cell.document.getText();
let taskExited = false;
return new Promise<CellExecutionState>((resolve) => {
let promise = Promise.resolve();
const endTask = (success = true) => {
taskExited = true;
promise = promise.finally(() => task.end(true, Date.now()));
resolve(success ? CellExecutionState.success : CellExecutionState.error);
};
try {
const proc = spawn(command, {
cwd,
env: process.env,
shell: true
});
token.onCancellationRequested(() => {
if (taskExited) {
return;
}
proc.kill();
endTask();
});
let lastOutput: { stdout?: NotebookCellOutput; stdErr?: NotebookCellOutput } | undefined;
proc.once('close', (code) => {
console.info(`Shell exec Failed with code ${code} for ${command}`);
if (!taskExited) {
endTask(true);
}
});
proc.once('error', () => {
if (!taskExited) {
endTask(false);
}
});
proc.stdout?.on('data', (data: Buffer | string) => {
promise = promise.finally(() => {
if (token.isCancellationRequested) {
return;
}
data = data.toString();
const item = NotebookCellOutputItem.stdout(data.toString());
if (lastOutput?.stdout) {
return task.appendOutputItems(item, lastOutput.stdout).then(noop, noop);
} else {
lastOutput = { stdout: new NotebookCellOutput([item]) };
return task.appendOutput(lastOutput.stdout!).then(noop, noop);
}
});
});
proc.stderr?.on('data', (data: Buffer | string) => {
promise = promise.finally(() => {
if (token.isCancellationRequested) {
return;
}
const item = NotebookCellOutputItem.stderr(data.toString());
if (lastOutput?.stdErr) {
return task.appendOutputItems(item, lastOutput.stdErr).then(noop, noop);
} else {
lastOutput = { stdErr: new NotebookCellOutput([item]) };
return task.appendOutput(lastOutput.stdErr!).then(noop, noop);
}
});
});
} catch (ex) {
promise = promise.finally(() => {
if (token.isCancellationRequested) {
return;
}
task.appendOutput(new NotebookCellOutput([NotebookCellOutputItem.error(ex as Error)])).then(
noop,
noop
);
});
endTask(false);
}
});
}
}
class ShellPty {
public static shellJsPath: string;
public static nodePtyPath: string;
public static instance = new ShellPty();
private static pty: typeof import('node-pty');
public static available() {
if (getConfiguration().disablePseudoTerminal) {
return false;
}
if (ShellPty.pty) {
return true;
}
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
ShellPty.pty = require(ShellPty.nodePtyPath) as typeof import('node-pty');
return true;
} catch (ex) {
console.log('Unable to load nodepty', ex);
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
ShellPty.pty = require(path.join(ShellPty.nodePtyPath, 'lib', 'index.js')) as typeof import('node-pty');
return true;
} catch (ex) {
console.log('Unable to load nodepty (lib/index.js)', ex);
return false;
}
}
}
public static get(cwd?: string) {
const proc = ShellPty.pty.spawn(shell, [], {
name: 'node-kernel',
cols: 80,
rows: 30,
cwd,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
env: { ...env, PDW: cwd, OLDPWD: cwd }
});
registerDisposable({
dispose: () => {
try {
proc.kill();
} catch {
//
}
}
});
return proc;
}
public static async execute(task: NotebookCellExecution, token: CancellationToken, cwd?: string) {
const command = task.cell.document.getText();
// eslint-disable-next-line @typescript-eslint/ban-types
const tmpFile = await new Promise<{ path: string; cleanupCallback: Function }>((resolve, reject) => {
tmp.file({ postfix: '.tmp' }, (err, path, _, cleanupCallback) => {
if (err) {
return reject(err);
}
resolve({ path, cleanupCallback });
});
});
await fs.promises.writeFile(tmpFile.path, task.cell.document.getText());
const terminal = new TerminalRenderer();
return new Promise<CellExecutionState>((resolve) => {
let taskExited = false;
let promise = Promise.resolve();
let proc: IPty | undefined;
const endTask = (success = true) => {
taskExited = true;
promise = promise.finally(() => task.end(true, Date.now()));
tmpFile.cleanupCallback();
terminal.dispose();
proc?.kill();
resolve(success ? CellExecutionState.success : CellExecutionState.error);
};
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
proc = ShellPty.get(cwd);
token.onCancellationRequested(() => {
if (taskExited) {
return;
}
endTask();
});
proc.onExit((e) => {
console.info(`Shell exec Failed with code ${e.exitCode} for ${command}`);
if (!taskExited) {
endTask(e.exitCode === 0);
}
});
let startProcessing = false;
let stopProcessing = false;
// let cmdExcluded = false;
proc.onData((data) => {
if (token.isCancellationRequested) {
return;
}
// We get weird output from node-pty, not bothered identifying that,
// easy solution is to add markers, and look for after we've received a certain string (GUID)
// Similarly, stop processing the output after we've received a certain string that marks the end.
if ((!startProcessing && !data.includes(startSeparator)) || stopProcessing) {
return;
}
if (!startProcessing && data.includes(startSeparator)) {
startProcessing = true;
data = data.substring(data.indexOf(startSeparator) + startSeparator.length);
}
if (data.includes(endSeparator)) {
stopProcessing = true;
data = data.substring(0, data.indexOf(endSeparator));
}
// if (!cmdExcluded && data.includes(command)) {
// cmdExcluded = true;
// data = data.substring(data.indexOf(command) + command.length);
// }
const writePromise = terminal.write(data);
promise = promise
.finally(async () => {
if (token.isCancellationRequested) {
return;
}
const termOutput = await writePromise;
const item = NotebookCellOutputItem.stdout(termOutput);
return task
.replaceOutput(new NotebookCellOutput([item]))
.then(noop, (ex) => console.error(ex));
})
.finally(() => {
if (!terminal.completed || token.isCancellationRequested) {
return;
}
if (stopProcessing && !taskExited) {
endTask(true);
}
});
});
const shellCommand = `node ${quote([ShellPty.shellJsPath, tmpFile.path])}`;
proc.write(`${shellCommand}\r`);
} catch (ex) {
promise = promise.finally(() => {
if (token.isCancellationRequested) {
return;
}
void task
.appendOutput(new NotebookCellOutput([NotebookCellOutputItem.error(ex as Error)]))
.then(noop, (ex) => console.error(ex));
});
endTask(false);
}
});
}
}
class TerminalRenderer {
private readonly terminal: Terminal;
private readonly serializeAddon: SerializeAddon;
private pendingRequests = 0;
public get completed() {
return this.pendingRequests === 0;
}
constructor() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const glob: any = globalThis;
const oldSelfExisted = 'self' in glob;
const oldSelf = oldSelfExisted ? glob.self : undefined;
glob.self = glob;
// eslint-disable-next-line @typescript-eslint/no-var-requires
const xterm = require('xterm') as typeof import('xterm');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { SerializeAddon } = require('xterm-addon-serialize') as typeof import('xterm-addon-serialize');
if (oldSelfExisted) {
glob.self = oldSelf;
} else {
delete glob.self;
}
this.terminal = new xterm.Terminal({ cols: 80, rows: 30 });
this.serializeAddon = new SerializeAddon();
this.terminal.loadAddon(this.serializeAddon);
}
public async write(value: string): Promise<string> {
this.pendingRequests += 1;
return new Promise<string>((resolve) => {
this.terminal.write(value, () => {
this.pendingRequests -= 1;
resolve(this.serializeAddon.serialize());
});
});
}
public dispose() {
this.terminal.dispose();
this.serializeAddon.dispose();
}
} | the_stack |
export const TERRAIN_LOD_VERTS = 33;
export const TERRAIN_LOD_TILES = 32;
export const TERRAIN_LOD_LEVELS = 4;
export const TERRAIN_LOD_NORTH_INDEX = 0;
export const TERRAIN_LOD_SOUTH_INDEX = 1;
export const TERRAIN_LOD_WEST_INDEX = 2;
export const TERRAIN_LOD_EAST_INDEX = 3;
export const TERRAIN_LOD_MAX_DISTANCE = 100000000000000.0;
export class TerrainLodKey {
public level = 0;
public north = 0;
public south = 0;
public west = 0;
public east = 0;
public compare (rk: TerrainLodKey) {
return this.level === rk.level && this.north === rk.north && this.south === rk.south && this.west === rk.west && this.east === rk.east;
}
}
export class TerrainIndexPool {
public size = 0;
public indices: Uint16Array|null = null;
}
export class TerrainIndexData {
public key: TerrainLodKey = new TerrainLodKey();
public start = 0;
public size = 0;
public buffer: Uint16Array|null = null;
public primCount = 0;
}
export class TerrainLod {
public static mapIndex (i: number, j: number, k: number) {
return i * (TERRAIN_LOD_LEVELS * TERRAIN_LOD_LEVELS) + j * TERRAIN_LOD_LEVELS + k;
}
public _bodyIndexPool: TerrainIndexPool[];
public _connecterIndexPool: TerrainIndexPool[];
public _indexMap: TerrainIndexData[] = [];
public _indexBuffer: Uint16Array = new Uint16Array();
constructor () {
this._bodyIndexPool = new Array<TerrainIndexPool>(TERRAIN_LOD_LEVELS);
for (let i = 0; i < TERRAIN_LOD_LEVELS; ++i) {
this._bodyIndexPool[i] = new TerrainIndexPool();
}
this._connecterIndexPool = new Array<TerrainIndexPool>(TERRAIN_LOD_LEVELS * TERRAIN_LOD_LEVELS * 4);
for (let i = 0; i < TERRAIN_LOD_LEVELS; ++i) {
for (let j = 0; j < TERRAIN_LOD_LEVELS; ++j) {
for (let k = 0; k < 4; ++k) {
this._connecterIndexPool[TerrainLod.mapIndex(i, j, k)] = new TerrainIndexPool();
}
}
}
for (let i = 0; i < TERRAIN_LOD_LEVELS; ++i) {
this._genBodyIndex(i);
}
for (let i = 0; i < TERRAIN_LOD_LEVELS; ++i) {
for (let j = 0; j < TERRAIN_LOD_LEVELS; ++j) {
this._genConnecterIndexNorth(i, j);
this._genConnecterIndexSouth(i, j);
this._genConnecterIndexWest(i, j);
this._genConnecterIndexEast(i, j);
}
}
const levels = TERRAIN_LOD_LEVELS;
for (let l = 0; l < levels; ++l) {
for (let n = 0; n < levels; ++n) {
if (n < l) {
continue;
}
for (let s = 0; s < levels; ++s) {
if (s < l) {
continue;
}
for (let w = 0; w < levels; ++w) {
if (w < l) {
continue;
}
for (let e = 0; e < levels; ++e) {
if (e < l) {
continue;
}
const k = new TerrainLodKey();
k.level = l;
k.north = n;
k.south = s;
k.west = w;
k.east = e;
this._genIndexData(k);
}
}
}
}
}
}
public getIndexData (k: TerrainLodKey) {
for (let i = 0; i < this._indexMap.length; ++i) {
if (this._indexMap[i].key.compare(k)) {
return this._indexMap[i];
}
}
return null;
}
private _genBodyIndex (level: number) {
const step = 1 << level;
let tiles = TERRAIN_LOD_TILES >> level;
let start = 0;
if (level < TERRAIN_LOD_LEVELS - 1) {
tiles -= 2;
start = step * TERRAIN_LOD_VERTS + step;
}
if (tiles === 0 || tiles === 0) {
return;
}
const count = tiles * tiles * 6;
this._bodyIndexPool[level].indices = new Uint16Array(count);
let index = 0;
const indices = new Uint16Array(count);
// generate triangle list cw
//
let row_c = start;
let row_n = row_c + TERRAIN_LOD_VERTS * step;
for (let y = 0; y < tiles; ++y) {
for (let x = 0; x < tiles; ++x) {
/*
indices[index++] = row_n + x * step;
indices[index++] = row_c + x * step;
indices[index++] = row_n + (x + 1) * step;
indices[index++] = row_n + (x + 1) * step;
indices[index++] = row_c + x * step;
indices[index++] = row_c + (x + 1) * step;
*/
indices[index++] = row_n + x * step;
indices[index++] = row_n + (x + 1) * step;
indices[index++] = row_c + x * step;
indices[index++] = row_n + (x + 1) * step;
indices[index++] = row_c + (x + 1) * step;
indices[index++] = row_c + x * step;
}
row_c += TERRAIN_LOD_VERTS * step;
row_n += TERRAIN_LOD_VERTS * step;
}
this._bodyIndexPool[level].size = index;
this._bodyIndexPool[level].indices = indices;
}
private _genConnecterIndexNorth (level: number, connecter: number) {
const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_NORTH_INDEX);
if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
this._connecterIndexPool[connecterIndex].size = 0;
this._connecterIndexPool[connecterIndex].indices = null;
return;
}
const self_step = 1 << level;
const neighbor_step = 1 << connecter;
const self_tile = TERRAIN_LOD_TILES >> level;
const count = self_tile * 2 + 2;
let index = 0;
const indices = new Uint16Array(count);
// starter
indices[index++] = 0;
indices[index++] = 0;
// middler
for (let i = 1; i < self_tile; ++i) {
const x1 = i * self_step;
const y1 = self_step;
const x0 = x1 / neighbor_step * neighbor_step;
const y0 = y1 - self_step;
const index0 = y1 * TERRAIN_LOD_VERTS + x1;
const index1 = y0 * TERRAIN_LOD_VERTS + x0;
indices[index++] = index0;
indices[index++] = index1;
}
// ender
indices[index++] = TERRAIN_LOD_VERTS - 1;
indices[index++] = TERRAIN_LOD_VERTS - 1;
this._connecterIndexPool[connecterIndex].size = index;
this._connecterIndexPool[connecterIndex].indices = indices;
}
private _genConnecterIndexSouth (level: number, connecter: number) {
const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_SOUTH_INDEX);
if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
this._connecterIndexPool[connecterIndex].size = 0;
this._connecterIndexPool[connecterIndex].indices = null;
return;
}
const self_step = 1 << level;
const neighbor_step = 1 << connecter;
const self_tile = TERRAIN_LOD_TILES >> level;
const count = self_tile * 2 + 2;
let index = 0;
const indices = new Uint16Array(count);
// starter
indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
// middler
for (let i = 1; i < self_tile; ++i) {
const x0 = i * self_step;
const y0 = TERRAIN_LOD_VERTS - 1 - self_step;
const x1 = x0 / neighbor_step * neighbor_step;
const y1 = y0 + self_step;
const index0 = y1 * TERRAIN_LOD_VERTS + x1;
const index1 = y0 * TERRAIN_LOD_VERTS + x0;
indices[index++] = index0;
indices[index++] = index1;
}
// ender
indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
this._connecterIndexPool[connecterIndex].size = index;
this._connecterIndexPool[connecterIndex].indices = indices;
}
private _genConnecterIndexWest (level: number, connecter: number) {
const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_WEST_INDEX);
if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
this._connecterIndexPool[connecterIndex].size = 0;
this._connecterIndexPool[connecterIndex].indices = null;
return;
}
const self_step = 1 << level;
const neighbor_step = 1 << connecter;
const self_tile = TERRAIN_LOD_TILES >> level;
const count = self_tile * 2 + 2;
let index = 0;
const indices = new Uint16Array(count);
// starter
indices[index++] = 0;
indices[index++] = 0;
// middler
for (let i = 1; i < self_tile; ++i) {
const x0 = 0;
const y0 = i * self_step / neighbor_step * neighbor_step;
const x1 = self_step;
const y1 = i * self_step;
const index0 = y0 * TERRAIN_LOD_VERTS + x0;
const index1 = y1 * TERRAIN_LOD_VERTS + x1;
indices[index++] = index0;
indices[index++] = index1;
}
// ender
indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
this._connecterIndexPool[connecterIndex].size = index;
this._connecterIndexPool[connecterIndex].indices = indices;
}
private _genConnecterIndexEast (level: number, connecter: number) {
const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_EAST_INDEX);
if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
this._connecterIndexPool[connecterIndex].size = 0;
this._connecterIndexPool[connecterIndex].indices = null;
return;
}
const self_step = 1 << level;
const neighbor_step = 1 << connecter;
const self_tile = TERRAIN_LOD_TILES >> level;
const count = self_tile * 2 + 2;
let index = 0;
const indices = new Uint16Array(count);
// starter
indices[index++] = TERRAIN_LOD_VERTS - 1;
indices[index++] = TERRAIN_LOD_VERTS - 1;
// middler
for (let i = 1; i < self_tile; ++i) {
const x0 = TERRAIN_LOD_VERTS - 1 - self_step;
const y0 = i * self_step;
const x1 = TERRAIN_LOD_VERTS - 1;
const y1 = i * self_step / neighbor_step * neighbor_step;
const index0 = y0 * TERRAIN_LOD_VERTS + x0;
const index1 = y1 * TERRAIN_LOD_VERTS + x1;
indices[index++] = index0;
indices[index++] = index1;
}
// ender
indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
this._connecterIndexPool[connecterIndex].size = index;
this._connecterIndexPool[connecterIndex].indices = indices;
}
private _getConnenterIndex (i: number, j: number, k: number) {
return this._connecterIndexPool[TerrainLod.mapIndex(i, j, k)];
}
private _genIndexData (k: TerrainLodKey) {
let data = this.getIndexData(k);
if (data != null) {
return data;
}
const body = this._bodyIndexPool[k.level];
const north = this._getConnenterIndex(k.level, k.north, TERRAIN_LOD_NORTH_INDEX);
const south = this._getConnenterIndex(k.level, k.south, TERRAIN_LOD_SOUTH_INDEX);
const west = this._getConnenterIndex(k.level, k.west, TERRAIN_LOD_WEST_INDEX);
const east = this._getConnenterIndex(k.level, k.east, TERRAIN_LOD_EAST_INDEX);
data = new TerrainIndexData();
data.size = 0;
data.primCount = 0;
if (body.indices != null) {
data.size += body.size;
}
if (north.indices) {
data.size += (north.size - 2) * 3;
}
if (south.indices) {
data.size += (south.size - 2) * 3;
}
if (west.indices) {
data.size += (west.size - 2) * 3;
}
if (east.indices) {
data.size += (east.size - 2) * 3;
}
if (data.size === 0) {
return null;
}
let index = 0;
data.buffer = new Uint16Array(data.size);
data.key.level = k.level;
data.key.east = k.east;
data.key.west = k.west;
data.key.north = k.north;
data.key.south = k.south;
if (body.indices) {
for (let i = 0; i < body.size; ++i) {
data.buffer[index++] = body.indices[i];
}
}
if (north.indices) {
for (let i = 0; i < north.size - 2; i += 2) {
const a = north.indices[i + 0];
const b = north.indices[i + 1];
const c = north.indices[i + 2];
const d = north.indices[i + 3];
data.buffer[index++] = a;
data.buffer[index++] = c;
data.buffer[index++] = b;
data.buffer[index++] = c;
data.buffer[index++] = d;
data.buffer[index++] = b;
}
}
if (south.indices) {
for (let i = 0; i < south.size - 2; i += 2) {
const a = south.indices[i + 0];
const b = south.indices[i + 1];
const c = south.indices[i + 2];
const d = south.indices[i + 3];
data.buffer[index++] = a;
data.buffer[index++] = c;
data.buffer[index++] = b;
data.buffer[index++] = c;
data.buffer[index++] = d;
data.buffer[index++] = b;
}
}
if (west.indices) {
for (let i = 0; i < west.size - 2; i += 2) {
const a = west.indices[i + 0];
const b = west.indices[i + 1];
const c = west.indices[i + 2];
const d = west.indices[i + 3];
data.buffer[index++] = a;
data.buffer[index++] = c;
data.buffer[index++] = b;
data.buffer[index++] = c;
data.buffer[index++] = d;
data.buffer[index++] = b;
}
}
if (east.indices) {
for (let i = 0; i < east.size - 2; i += 2) {
const a = east.indices[i + 0];
const b = east.indices[i + 1];
const c = east.indices[i + 2];
const d = east.indices[i + 3];
data.buffer[index++] = a;
data.buffer[index++] = c;
data.buffer[index++] = b;
data.buffer[index++] = c;
data.buffer[index++] = d;
data.buffer[index++] = b;
}
}
data.primCount = index / 3;
data.start = this._indexBuffer.length;
this._indexMap.push(data);
const temp = new Uint16Array(data.start + data.size);
temp.set(this._indexBuffer, 0);
temp.set(data.buffer, data.start);
this._indexBuffer = temp;
return data;
}
} | the_stack |
import QlogConnection from '@/data/Connection';
import * as d3 from 'd3';
import * as qlog from '@/data/QlogSchema';
import StreamGraphDataHelper from './MultiplexingGraphDataHelper';
export default class MultiplexingGraphD3WaterfallRenderer {
public containerID:string;
public rendering:boolean = false;
// FIXME: do this properly with a passed-in config object or something!
public onStreamClicked: ((streamID:string) => void) | undefined = undefined // set by the CollapsedRenderer directly (yes, I know, dirty)
// TODO: merge this with the one above in a proper event emitter setup
// the above is to handle clicks from within the CollapsedRenderer (to update the ByteRangesRenderer)
// this one is to handle clicks from the upper-layer Vue renderer to show stream details
protected onStreamClickedUpper:(streamDetails:any) => void;
protected svg!:any;
protected connection!:QlogConnection;
protected barHeight = 120;
private dimensions:any = {};
constructor(containerID:string, onStreamClickedUpper:(streamDetails:any) => void) {
this.containerID = containerID;
this.onStreamClickedUpper = onStreamClickedUpper;
}
public async render(connection:QlogConnection):Promise<boolean> {
if ( this.rendering ) {
return false;
}
console.log("MultiplexingGraphD3WaterfallRenderer:render", connection);
this.rendering = true;
const canContinue:boolean = this.setup(connection);
if ( !canContinue ) {
this.rendering = false;
return false;
}
await this.renderLive();
this.rendering = false;
return true;
}
protected setup(connection:QlogConnection){
this.connection = connection;
this.connection.setupLookupTable();
const container:HTMLElement = document.getElementById(this.containerID)!;
this.dimensions.margin = {top: 40, right: 40, bottom: 0, left: 20};
// width and height are the INTERNAL widths (so without the margins)
this.dimensions.width = container.clientWidth - this.dimensions.margin.left - this.dimensions.margin.right;
this.dimensions.height = this.barHeight;
// clear old rendering
d3.select( "#" + this.containerID ).selectAll("*").remove();
this.svg = d3.select("#" + this.containerID)
.append("svg")
.attr("width", this.dimensions.width + this.dimensions.margin.left + this.dimensions.margin.right)
.attr("height", this.dimensions.height + this.dimensions.margin.top + this.dimensions.margin.bottom)
// .attr("viewBox", [0, 0, this.dimensions.width, this.dimensions.height])
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.attr("font-family", "Trebuchet-ms")
.append("g")
.attr("transform",
"translate(" + this.dimensions.margin.left + "," + this.dimensions.margin.top + ")");
return true;
}
protected async renderLive() {
console.log("Rendering multiplexing waterfall");
// const parser = this.connection.getEventParser();
// // want total millisecond range in this trace, so last - first
// const xMSRange = parser.load(this.connection.getEvents()[ this.connection.getEvents().length - 1 ]).absoluteTime -
// parser.load(this.connection.getEvents()[0]).absoluteTime;
// console.log("DEBUG MS range for this trace: ", xMSRange);
// want to render both when the request was sent/received, as well as the period of actually sending/receiving data
// so that's two different perspectives
// because we're plotting in "packet number space" instead of "time space" things do get a bit awkward...
// cannot simply only loop over the packet_sent/received events, but loop over all the events and keep track of packet indices
// this is to keep our x-axis in sync with that of the CollapsedRenderer
let requestEventType = qlog.TransportEventType.packet_sent; // client sends requests, receives data
let dataEventType = qlog.TransportEventType.packet_received;
let directionText = "received";
if ( this.connection.vantagePoint && this.connection.vantagePoint.type === qlog.VantagePointType.server ){
requestEventType = qlog.TransportEventType.packet_received;
dataEventType = qlog.TransportEventType.packet_sent;
directionText = "sent";
}
// const frames = this.connection.lookup( qlog.EventCategory.transport, eventType );
interface StreamExtents {
stream_id:number,
order:number,
requestIndex:number,
startIndex:number,
stopIndex:number,
startTime:number,
endTime:number,
requestTime:number,
frameCount:number,
totalData:number,
}
let dataFrameCount:number = 0;
const streams:Map<number, StreamExtents> = new Map<number, StreamExtents>();
for ( const eventRaw of this.connection.getEvents() ) {
const evt = this.connection.parseEvent( eventRaw );
const data = evt.data;
if ( evt.name !== requestEventType && evt.name !== dataEventType ) {
continue;
}
if ( !data.frames ){
continue;
}
const streamFrames = [];
for ( const frame of data.frames ){
if ( frame.frame_type === qlog.QUICFrameTypeName.stream ){
streamFrames.push( frame );
}
}
if ( streamFrames.length === 0 ) {
continue;
}
for ( const streamFrame of streamFrames ){
if ( !StreamGraphDataHelper.isDataStream( "" + streamFrame.stream_id )) {
// skip control streams like QPACK
continue;
}
const streamID = parseInt( streamFrame.stream_id, 10 );
if ( evt.name === dataEventType ) {
++dataFrameCount;
}
let stream = streams.get( streamID );
if ( !stream ){
if ( evt.name !== requestEventType ){
console.error("MultiplexingGraphD3WaterfallRenderer: first packet for stream was not request! Shouldn't happen!", evt);
break;
}
stream = { stream_id: streamID, order: streams.size, requestIndex: dataFrameCount, startIndex: -1, stopIndex: -1, requestTime: evt.relativeTime, startTime: -1, endTime: -1, frameCount: 0, totalData: 0 };
streams.set( streamID, stream );
}
else {
if ( evt.name !== dataEventType ){
continue;
}
if ( stream.startIndex === -1 ){
stream.startIndex = dataFrameCount;
stream.startTime = evt.relativeTime;
}
if ( dataFrameCount > stream.stopIndex ){
stream.stopIndex = dataFrameCount;
stream.endTime = evt.relativeTime;
}
stream.frameCount++;
stream.totalData += parseInt(streamFrame.length, 0);
}
}
}
let minBarHeight = 4; // 4px is minimum height. Above that, we start scrolling (at 120 normal height, 4px gives us 30 streams without scrollbar)
if ( minBarHeight * streams.size < this.barHeight ) {
minBarHeight = (this.barHeight * 0.95) / streams.size;
}
this.dimensions.height = Math.ceil(minBarHeight * streams.size) + this.dimensions.margin.top;
// update the height of the surrounding container
d3.select("#" + this.containerID + " svg").attr("height", this.dimensions.height);
// TODO: what if no H3-level stuff found?!
const xDomain = d3.scaleLinear()
.domain([1, dataFrameCount])
.range([ 0, this.dimensions.width ]);
const xAxis = this.svg.append("g");
// if( this.axisLocation === "top" ) {
// xAxis
// //.attr("transform", "translate(0," + this.dimensions.height + ")")
// .call(d3.axisTop(xDomain));
// }
// else {
// xAxis
// .attr("transform", "translate(0," + this.dimensions.height + ")")
// .call(d3.axisBottom(xDomain));
// }
// console.log("DEBUG: streamsFound", streams);
// let colorDomain = d3.scaleOrdinal()
// .domain(["0", "4", "8", "12", "16", "20", "24", "28", "32", "36", "40", "44"])
// .range([ "red", "green", "blue", "pink", "purple", "yellow", "indigo", "black", "grey", "brown", "cyan", "orange"]);
const clip = this.svg.append("defs").append("SVG:clipPath")
.attr("id", "clip")
.append("SVG:rect")
.attr("width", this.dimensions.width + this.dimensions.margin.left )
.attr("height", this.dimensions.height )
.attr("x", -this.dimensions.margin.left ) // need a bit more space for the circles at the beginning if they're at dataFrameCount 0
.attr("y", 0);
const rects = this.svg.append('g')
// .attr("clip-path", "url(#clip)");
if ( streams.size <= 1 || dataFrameCount < 5 ){
// error message is already shown in the CollapsedRenderer
rects
// text
.append("text")
.attr("x", 200 )
.attr("y", 100 ) // + 1 is eyeballed magic number
.attr("dominant-baseline", "baseline")
.style("text-anchor", "start")
.style("font-size", "14")
.style("font-family", "Trebuchet MS")
// .style("font-weight", "bold")
.attr("fill", "#000000")
.text( "This trace doesn't contain multiple independent streams (or has less than 5 STREAM frames), which is needed for the waterfall." );
return;
}
const rects2 = rects
.selectAll("rect")
.data([...streams.values()])
.enter()
.append("g");
const minWidth = 4; // 4px minimum width
rects2
// background
.append("rect")
.attr("x", (d:any) => { return xDomain(d.startIndex) - 0.15; } )
.attr("y", (d:any) => { return d.order * minBarHeight; } )
// .attr("fill", (d:any) => { return "" + colorDomain( "" + d.streamID ); } )
.attr("fill", (d:any) => { return StreamGraphDataHelper.StreamIDToColor("" + d.stream_id)[0]; } )
.style("opacity", 1)
.attr("class", "packet")
.attr("width", (d:any) => { return Math.max(minWidth, xDomain(d.stopIndex) - xDomain(d.startIndex) + 0.3); })
.attr("height", Math.max(minBarHeight, 0.01))
.on("click", (d:any) => {
if ( this.onStreamClickedUpper ) {
const details:any = {};
details.stream_id = d.stream_id;
details.data = streams.get( d.stream_id );
this.onStreamClickedUpper( details ); // updates stream detail in vue-layer
}
if ( this.onStreamClicked ) {
this.onStreamClicked("" + d.stream_id); // updates byteRangeRenderer
}
});
const circleWidth = Math.min(15 ,Math.max(minBarHeight / 1.2, 0.01));
rects2
.append("circle")
.attr("cx", (d:any) => { return xDomain(d.requestIndex) + circleWidth / 2; } )
.attr("cy", (d:any) => { return ((d.order) * minBarHeight) + (circleWidth / 1.6); } ) // 1.6 should be 2, but 1.6 somehow looks better...
.attr("fill", (d:any) => { return StreamGraphDataHelper.StreamIDToColor("" + d.stream_id)[0]; } )
.attr("stroke", "black" )
.attr("stroke-width", (d:any) => { return circleWidth / 5; } )
.attr("r", circleWidth / 2 );
// const legendY = ((-2) * (this.barHeight / streams.size)) + (circleWidth / 1.6); // 1.6 should be 2, but 1.6 somehow looks better...
const legendY = -this.dimensions.margin.top / 2;
const legendIconWidth = 13;
rects
.append("circle")
.attr("cx", xDomain(0) + legendIconWidth / 2 )
.attr("cy", legendY )
.attr("fill", (d:any) => { return "white" } )
.attr("stroke", (d:any) => { return "black"; } )
.attr("stroke-width", (d:any) => { return legendIconWidth / 5; } )
.attr("r", legendIconWidth / 2 );
rects
// text
.append("text")
.attr("x", xDomain(0) + legendIconWidth / 2 + 20 )
.attr("y", legendY + 1 ) // + 1 is eyeballed magic number
.attr("dominant-baseline", "middle")
.style("text-anchor", "start")
.style("font-size", "14")
.style("font-family", "Trebuchet MS")
// .style("font-weight", "bold")
.attr("fill", "#000000")
.text( "Request " + directionText );
rects
.append("rect")
.attr("x", xDomain(0) + legendIconWidth / 2 + 150 )
.attr("y", legendY - legendIconWidth / 2 )
.attr("fill", (d:any) => { return "white" } )
.attr("stroke", (d:any) => { return "black"; } )
.attr("stroke-width", (d:any) => { return legendIconWidth / 5; } )
.attr("width", 20 )
.attr("height", legendIconWidth );
rects
// text
.append("text")
.attr("x", xDomain(0) + legendIconWidth / 2 + 180 )
.attr("y", legendY ) // + 1 is eyeballed magic number
.attr("dominant-baseline", "middle")
.style("text-anchor", "start")
.style("font-size", "14")
.style("font-family", "Trebuchet MS")
// .style("font-weight", "bold")
.attr("fill", "#000000")
.text( "Colored while stream is \"active\" (between first and last STREAM frame " + directionText + ")");
}
} | the_stack |
import {
arrayBuffer2HexArray,
recordAllocations,
makeCarrier,
} from "../testUtils";
import {
linkedListItemInsert,
linkedListItemRemove,
initLinkedList,
linkedListLowLevelIterator,
linkedListGetValue,
linkedListGetPointersToFree,
// LINKED_LIST_ITEM_MACHINE
} from "./linkedList";
describe("LinkedList", () => {
let carrier = makeCarrier(512);
let ab = carrier.allocator.getArrayBuffer();
function setABSize(size: number) {
carrier = makeCarrier(size);
ab = carrier.allocator.getArrayBuffer();
}
beforeEach(() => {
setABSize(512);
});
test("linkedList init & add", () => {
const linkedListPointer = initLinkedList(carrier);
expect(
arrayBuffer2HexArray(ab.slice(0, carrier.allocator.stats().top), true)
).toMatchSnapshot();
const itemPointer = linkedListItemInsert(carrier, linkedListPointer, 7);
expect(itemPointer).toBe(88);
expect(
arrayBuffer2HexArray(ab.slice(0, carrier.allocator.stats().top), true)
).toMatchSnapshot();
});
test("linkedList init & add 2 & delete 2", () => {
const linkedListPointer = initLinkedList(carrier);
// const copyToCompare = ab.slice(0);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
const pointer1 = linkedListItemInsert(carrier, linkedListPointer, 7);
const pointer2 = linkedListItemInsert(carrier, linkedListPointer, 8);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`144`);
expect(pointer1).toBe(88);
expect(pointer2).toBe(112);
linkedListItemRemove(carrier, pointer2);
linkedListItemRemove(carrier, pointer1);
// fails on github action ??
// expect(
// jestDiff(
// arrayBuffer2HexArray(copyToCompare, true),
// arrayBuffer2HexArray(ab, true),
// { contextLines: 0, expand: false }
// )
// ).toMatchInlineSnapshot(`
// "[32m- Expected[39m
// [31m+ Received[39m
// [33m@@ -45,1 +45,1 @@[39m
// [32m- \\"43:0x38\\",[39m
// [31m+ \\"43:0x58\\",[39m
// [33m@@ -66,1 +66,1 @@[39m
// [32m- \\"64:0x00\\",[39m
// [31m+ \\"64:0x10\\",[39m
// [33m@@ -82,1 +82,1 @@[39m
// [32m- \\"80:0x00\\",[39m
// [31m+ \\"80:0x10\\",[39m"
// `);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
});
test("linkedList linkedListLowLevelIterator test 1", () => {
const linkedListPointer = initLinkedList(carrier);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
const itemsPointers = [
linkedListItemInsert(carrier, linkedListPointer, 7),
linkedListItemInsert(carrier, linkedListPointer, 6),
linkedListItemInsert(carrier, linkedListPointer, 5),
linkedListItemInsert(carrier, linkedListPointer, 4),
];
const values = [];
let iteratorPointer = 0;
while (
(iteratorPointer = linkedListLowLevelIterator(
carrier.heap,
linkedListPointer,
iteratorPointer
))
) {
values.push(linkedListGetValue(carrier.heap, iteratorPointer));
}
expect(values).toMatchInlineSnapshot(`
Array [
7,
6,
5,
4,
]
`);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`192`);
itemsPointers.forEach((p) => linkedListItemRemove(carrier, p));
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
});
test("linkedList linkedListLowLevelIterator - delete while iteration", () => {
const linkedListPointer = initLinkedList(carrier);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
const itemsPointers = [
linkedListItemInsert(carrier, linkedListPointer, 7),
linkedListItemInsert(carrier, linkedListPointer, 6),
linkedListItemInsert(carrier, linkedListPointer, 5),
linkedListItemInsert(carrier, linkedListPointer, 4),
];
const values = [];
let iteratorPointer = 0;
while (
(iteratorPointer = linkedListLowLevelIterator(
carrier.heap,
linkedListPointer,
iteratorPointer
))
) {
values.push(linkedListGetValue(carrier.heap, iteratorPointer));
linkedListItemRemove(carrier, iteratorPointer);
}
const regularSetResults: number[] = [];
const regularSet = new Set([7, 6, 5, 4]);
for (const v of regularSet) {
regularSetResults.push(v);
regularSet.delete(v - 1);
}
expect(regularSetResults).toEqual(values);
expect(values).toMatchInlineSnapshot(`
Array [
7,
5,
]
`);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`192`);
itemsPointers.forEach((p) => linkedListItemRemove(carrier, p));
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`168`);
});
test.skip("linkedList linkedListLowLevelIterator - delete while iteration - delete current value", () => {
const linkedListPointer = initLinkedList(carrier);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`184`);
const regularSet = new Set([7, 6, 5, 4]);
const itemsPointers = [
linkedListItemInsert(carrier, linkedListPointer, 7),
linkedListItemInsert(carrier, linkedListPointer, 6),
linkedListItemInsert(carrier, linkedListPointer, 5),
linkedListItemInsert(carrier, linkedListPointer, 4),
];
const linkedLintResults = [];
let iteratorPointer = 0;
while (
(iteratorPointer = linkedListLowLevelIterator(
carrier.heap,
linkedListPointer,
iteratorPointer
))
) {
linkedLintResults.push(linkedListGetValue(carrier.heap, iteratorPointer));
linkedListItemRemove(carrier, iteratorPointer);
}
const regularSetResults: number[] = [];
for (const v of regularSet) {
regularSetResults.push(v);
regularSet.delete(v);
}
expect(regularSetResults).toMatchInlineSnapshot(`
Array [
7,
6,
5,
4,
]
`);
expect(linkedLintResults).toMatchInlineSnapshot(`
Array [
7,
5,
]
`);
expect(regularSetResults).toEqual(linkedLintResults);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`152`);
itemsPointers.forEach((p) => linkedListItemRemove(carrier, p));
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`184`);
});
test("linkedList linkedListLowLevelIterator - add while iteration", () => {
const linkedListPointer = initLinkedList(carrier);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
const itemsPointers = [
linkedListItemInsert(carrier, linkedListPointer, 7),
linkedListItemInsert(carrier, linkedListPointer, 6),
];
const toAdd = [8, 9];
let c = 0;
const values = [];
let iteratorPointer = 0;
while (
(iteratorPointer = linkedListLowLevelIterator(
carrier.heap,
linkedListPointer,
iteratorPointer
))
) {
values.push(linkedListGetValue(carrier.heap, iteratorPointer));
if (c < toAdd.length) {
linkedListItemInsert(carrier, linkedListPointer, toAdd[c++]);
}
}
c = 0;
const regularSetResults: number[] = [];
const regularSet = new Set([7, 6]);
for (const v of regularSet) {
regularSetResults.push(v);
if (c < toAdd.length) {
regularSet.add(toAdd[c++]);
}
}
expect(regularSetResults).toEqual(values);
expect(values).toMatchInlineSnapshot(`
Array [
7,
6,
8,
9,
]
`);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`192`);
itemsPointers.forEach((p) => linkedListItemRemove(carrier, p));
const iteratorPointerToFree = 0;
while (
(iteratorPointer = linkedListLowLevelIterator(
carrier.heap,
linkedListPointer,
iteratorPointerToFree
))
) {
linkedListItemRemove(carrier, iteratorPointer);
}
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`120`);
});
test("linkedList linkedListGetPointersToFree", () => {
let linkedListPointer = 0;
const toAddItems = [8, 9, 10, 11];
const toAddItemsCopy = toAddItems.slice();
const { allocations } = recordAllocations(() => {
linkedListPointer = initLinkedList(carrier);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
let toAdd: undefined | number = 0;
while ((toAdd = toAddItemsCopy.pop()) !== undefined) {
linkedListItemInsert(carrier, linkedListPointer, toAdd);
}
}, carrier.allocator);
const r = linkedListGetPointersToFree(carrier.heap, linkedListPointer);
expect(r).toMatchInlineSnapshot(`
Object {
"pointers": Array [
64,
88,
112,
136,
160,
184,
],
"valuePointers": Array [
11,
10,
9,
8,
],
}
`);
expect(r.pointers.sort()).toEqual(allocations.sort());
expect(r.valuePointers.sort()).toEqual(toAddItems.sort());
});
test("linkedList linkedListGetPointersToFree empty list", () => {
let linkedListPointer = 0;
const toAddItems: number[] = [];
const toAddItemsCopy = toAddItems.slice();
const { allocations } = recordAllocations(() => {
linkedListPointer = initLinkedList(carrier);
expect(carrier.allocator.stats().top).toMatchInlineSnapshot(`96`);
let toAdd: undefined | number = 0;
while ((toAdd = toAddItemsCopy.pop()) !== undefined) {
linkedListItemInsert(carrier, linkedListPointer, toAdd);
}
}, carrier.allocator);
const r = linkedListGetPointersToFree(carrier.heap, linkedListPointer);
expect(r).toMatchInlineSnapshot(`
Object {
"pointers": Array [
64,
88,
],
"valuePointers": Array [],
}
`);
expect(r.pointers.sort()).toEqual(allocations.sort());
expect(r.valuePointers.sort()).toEqual(toAddItems.sort());
});
}); | the_stack |
import {
GeoCoordinates,
mercatorProjection,
Projection,
sphereProjection
} from "@here/harp-geoutils";
import { expect } from "chai";
import * as THREE from "three";
import { CameraUtils } from "../lib/CameraUtils";
import { TiltViewClipPlanesEvaluator } from "../lib/ClipPlanesEvaluator";
import { MapViewUtils } from "../lib/Utils";
function setupPerspectiveCamera(
projection: Projection,
zoomLevel?: number,
distance?: number,
tilt: number = 0,
principalPointNDC?: THREE.Vector2
): THREE.PerspectiveCamera {
const vFov = 40;
const vFovRad = THREE.MathUtils.degToRad(vFov);
const camera = new THREE.PerspectiveCamera(vFov, 1, 1, 100);
const geoTarget = new GeoCoordinates(0, 0);
const heading = 0;
const canvasHeight = 500;
if (principalPointNDC) {
CameraUtils.setPrincipalPoint(camera, principalPointNDC);
}
CameraUtils.setVerticalFov(camera, vFovRad, canvasHeight);
const focalLength = CameraUtils.getFocalLength(camera)!;
MapViewUtils.getCameraRotationAtTarget(projection, geoTarget, heading, tilt, camera.quaternion);
if (!distance) {
expect(zoomLevel).to.not.be.undefined;
distance = MapViewUtils.calculateDistanceFromZoomLevel({ focalLength }, zoomLevel ?? 1);
}
MapViewUtils.getCameraPositionFromTargetCoordinates(
geoTarget,
distance,
heading,
tilt,
projection,
camera.position
);
camera.updateMatrixWorld();
return camera;
}
interface ZoomLevelTest {
tilt?: number;
zoomLevel: number;
far: number;
near: number;
ppalPointNDC?: [number, number];
}
const mercatorZoomTruthTable: ZoomLevelTest[] = [
// Top down view tests.
{ zoomLevel: 1, far: 53762306, near: 53762306 },
{ zoomLevel: 2, far: 26881153, near: 26881153 },
{ zoomLevel: 3, far: 13440577, near: 13440577 },
{ zoomLevel: 4, far: 6720288, near: 6720288 },
{ zoomLevel: 5, far: 3360144, near: 3360144 },
{ zoomLevel: 6, far: 1680072, near: 1680072 },
{ zoomLevel: 7, far: 840036, near: 840036 },
{ zoomLevel: 8, far: 420018, near: 420018 },
{ zoomLevel: 9, far: 210009, near: 210009 },
{ zoomLevel: 10, far: 105005, near: 105005 },
{ zoomLevel: 11, far: 52502, near: 52502 },
{ zoomLevel: 12, far: 26251, near: 26251 },
{ zoomLevel: 13, far: 13126, near: 13126 },
{ zoomLevel: 14, far: 6563, near: 6563 },
{ zoomLevel: 15, far: 3281, near: 3281 },
{ zoomLevel: 16, far: 1641, near: 1641 },
{ zoomLevel: 17, far: 820, near: 820 },
{ zoomLevel: 18, far: 410, near: 410 },
{ zoomLevel: 19, far: 205, near: 205 },
{ zoomLevel: 20, far: 103, near: 103 },
// Tilted view, horizon not visible.
{ tilt: 45, zoomLevel: 1, far: 84527972, near: 39416041 },
{ tilt: 45, zoomLevel: 2, far: 42263986, near: 19708020 },
{ tilt: 45, zoomLevel: 3, far: 21131993, near: 9854010 },
{ tilt: 45, zoomLevel: 4, far: 10565997, near: 4927005 },
{ tilt: 45, zoomLevel: 5, far: 5282998, near: 2463503 },
{ tilt: 45, zoomLevel: 6, far: 2641499, near: 1231751 },
{ tilt: 45, zoomLevel: 7, far: 1320750, near: 615876 },
{ tilt: 45, zoomLevel: 8, far: 660375, near: 307938 },
{ tilt: 45, zoomLevel: 9, far: 330187, near: 153969 },
{ tilt: 45, zoomLevel: 10, far: 165094, near: 76984 },
{ tilt: 45, zoomLevel: 11, far: 82547, near: 38492 },
{ tilt: 45, zoomLevel: 12, far: 41273, near: 19246 },
{ tilt: 45, zoomLevel: 13, far: 20637, near: 9623 },
{ tilt: 45, zoomLevel: 14, far: 10318, near: 4812 },
{ tilt: 45, zoomLevel: 15, far: 5159, near: 2406 },
{ tilt: 45, zoomLevel: 16, far: 2580, near: 1203 },
{ tilt: 45, zoomLevel: 17, far: 1290, near: 601 },
{ tilt: 45, zoomLevel: 18, far: 645, near: 301 },
{ tilt: 45, zoomLevel: 19, far: 322, near: 150 },
{ tilt: 45, zoomLevel: 20, far: 161, near: 75 },
// Change horizon visibility by changing tilt or offsetting principal point.
{ tilt: 60, zoomLevel: 15, far: 8879, near: 2013 },
{ tilt: 60, zoomLevel: 15, far: 293891, near: 2746, ppalPointNDC: [0, -0.9] },
{ tilt: 70, zoomLevel: 15, far: 328139, near: 1641 },
{ tilt: 70, zoomLevel: 15, far: 3856, near: 1020, ppalPointNDC: [0, 0.8] },
{ tilt: 80, zoomLevel: 15, far: 328139, near: 1071 }
];
const sphereZoomTruthTable: ZoomLevelTest[] = [
{ zoomLevel: 1, far: 59464016, near: 53762306 },
{ zoomLevel: 2, far: 32036154, near: 26881153 },
{ zoomLevel: 3, far: 17766076, near: 13440577 },
{ zoomLevel: 4, far: 8418150, near: 6720288 },
{ zoomLevel: 5, far: 3641838, near: 3360144 },
{ zoomLevel: 6, far: 1743526, near: 1680072 },
{ zoomLevel: 7, far: 855246, near: 840036 },
{ zoomLevel: 8, far: 423749, near: 420018 },
{ zoomLevel: 9, far: 210933, near: 210009 },
{ zoomLevel: 10, far: 105235, near: 105005 },
{ zoomLevel: 11, far: 52560, near: 52502 },
{ zoomLevel: 12, far: 26265, near: 26251 },
{ zoomLevel: 13, far: 13129, near: 13126 },
{ zoomLevel: 14, far: 6564, near: 6563 },
{ zoomLevel: 15, far: 3282, near: 3281 },
{ zoomLevel: 16, far: 1641, near: 1641 },
{ zoomLevel: 17, far: 820, near: 820 },
{ zoomLevel: 18, far: 410, near: 410 },
{ zoomLevel: 19, far: 205, near: 205 },
{ zoomLevel: 20, far: 103, near: 103 },
{ tilt: 45, zoomLevel: 1, far: 58067604, near: 51894193 },
{ tilt: 45, zoomLevel: 2, far: 31009971, near: 25013040 },
{ tilt: 45, zoomLevel: 3, far: 17277892, near: 11579312 },
{ tilt: 45, zoomLevel: 4, far: 10131005, near: 5384245 },
{ tilt: 45, zoomLevel: 5, far: 6233888, near: 2584338 },
{ tilt: 45, zoomLevel: 6, far: 3976347, near: 1263063 },
{ tilt: 45, zoomLevel: 7, far: 1500918, near: 623865 },
{ tilt: 45, zoomLevel: 8, far: 696027, near: 309957 },
{ tilt: 45, zoomLevel: 9, far: 338345, near: 154477 },
{ tilt: 45, zoomLevel: 10, far: 167054, near: 77112 },
{ tilt: 45, zoomLevel: 11, far: 83028, near: 38524 },
{ tilt: 45, zoomLevel: 12, far: 41393, near: 19254 },
{ tilt: 45, zoomLevel: 13, far: 20666, near: 9625 },
{ tilt: 45, zoomLevel: 14, far: 10326, near: 4812 },
{ tilt: 45, zoomLevel: 15, far: 5161, near: 2406 },
{ tilt: 45, zoomLevel: 16, far: 2580, near: 1203 },
{ tilt: 45, zoomLevel: 17, far: 1290, near: 601 },
{ tilt: 45, zoomLevel: 18, far: 645, near: 301 },
{ tilt: 45, zoomLevel: 19, far: 322, near: 150 },
{ tilt: 45, zoomLevel: 20, far: 161, near: 75 },
// Make horizon visible by offseting principal point.
{ zoomLevel: 4, far: 9115538, near: 6018885, ppalPointNDC: [0, -0.9] },
{ zoomLevel: 4, far: 9115538, near: 6018885, ppalPointNDC: [0, 0.9] },
{ zoomLevel: 4, far: 9992660, near: 6720288, ppalPointNDC: [-0.9, 0] },
{ zoomLevel: 4, far: 9992660, near: 6720288, ppalPointNDC: [0.9, 0] }
];
describe("ClipPlanesEvaluator", function () {
it("constructor sets properties to valid values by default", function () {
const evaluator = new TiltViewClipPlanesEvaluator();
expect(evaluator.maxElevation).gte(evaluator.minElevation);
expect(evaluator.nearMin).gt(0);
expect(evaluator.nearFarMarginRatio).gt(0);
expect(evaluator.farMaxRatio).gt(0);
});
it("minElevation setter updates invalid maxElevation", function () {
const maxElevation = 100;
const minElevation = 10;
const evaluator = new TiltViewClipPlanesEvaluator(maxElevation, minElevation);
expect(evaluator.minElevation).eq(minElevation);
expect(evaluator.maxElevation).eq(maxElevation);
const newMinElevation = maxElevation + 1;
evaluator.minElevation = newMinElevation;
expect(evaluator.minElevation).eq(newMinElevation);
expect(evaluator.maxElevation).eq(newMinElevation);
});
it("maxElevation setter updats invalid minElevation", function () {
const maxElevation = 100;
const minElevation = 10;
const evaluator = new TiltViewClipPlanesEvaluator(maxElevation, minElevation);
expect(evaluator.minElevation).eq(minElevation);
expect(evaluator.maxElevation).eq(maxElevation);
const newMaxElevation = minElevation - 1;
evaluator.maxElevation = newMaxElevation;
expect(evaluator.minElevation).eq(newMaxElevation);
expect(evaluator.maxElevation).eq(newMaxElevation);
});
for (const [projection, projName, zoomTruthTable] of [
[mercatorProjection, "mercator", mercatorZoomTruthTable],
[sphereProjection, "sphere", sphereZoomTruthTable]
] as Array<[Projection, string, ZoomLevelTest[]]>) {
describe(`${projName}`, function () {
it("evaluateClipPlanes applies nearMin constraint", function () {
const nearMin = 100;
const distance = nearMin / 10;
const evaluator = new TiltViewClipPlanesEvaluator(0, 0, nearMin);
const camera = setupPerspectiveCamera(projection, undefined, distance);
const viewRange = evaluator.evaluateClipPlanes(camera, projection);
expect(viewRange.near).eq(nearMin);
expect(viewRange.minimum).eq(nearMin);
});
it("evaluateClipPlanes applies nearFarMarginRatio constraint", function () {
const nearMin = 1;
const nearFarMarginRatio = 2;
const distance = 50;
const evaluator = new TiltViewClipPlanesEvaluator(
0,
0,
nearMin,
nearFarMarginRatio
);
const camera = setupPerspectiveCamera(projection, undefined, distance);
const viewRange = evaluator.evaluateClipPlanes(camera, projection);
const eps = 1e-3;
expect(viewRange.far - viewRange.near).closeTo(distance * nearFarMarginRatio, eps);
});
it("evaluateClipPlanes applies farMaxRatio constraint", function () {
const nearMin = 1;
const farMaxRatio = 2;
const nearFarMarginRatio = 0; // Remove margins so that they don't affect the results.
const distance = 50;
const expectedFar = distance * farMaxRatio;
const evaluator = new TiltViewClipPlanesEvaluator(
0,
0,
nearMin,
nearFarMarginRatio,
farMaxRatio
);
// Tilt camera to force a large far distance.
const tiltDeg = 60;
const camera = setupPerspectiveCamera(projection, undefined, distance, tiltDeg);
const viewRange = evaluator.evaluateClipPlanes(camera, projection);
const eps = 1e-6;
expect(viewRange.far).closeTo(expectedFar, eps);
expect(viewRange.maximum).closeTo(expectedFar, eps);
});
describe("evaluateClipPlanes returns correct values for each zoom & tilt", function () {
zoomTruthTable.forEach((test: ZoomLevelTest) => {
it(`zoom level ${test.zoomLevel}, tilt ${test.tilt ?? 0}, ppal point ${
test.ppalPointNDC ?? [0, 0]
}`, function () {
// Relax constraints to see the effects of tilt and principal point.
const minElevation = 0;
const maxElevation = 0;
const minNear = 1;
const nearFarMarginRatio = 0;
const farMaxRatio = 100;
const evaluator = new TiltViewClipPlanesEvaluator(
minElevation,
maxElevation,
minNear,
nearFarMarginRatio,
farMaxRatio
);
const ppalPointNDC = test.ppalPointNDC
? new THREE.Vector2(test.ppalPointNDC[0], test.ppalPointNDC[1])
: undefined;
const camera = setupPerspectiveCamera(
projection,
test.zoomLevel,
undefined,
test.tilt,
ppalPointNDC
);
const viewRange = evaluator.evaluateClipPlanes(camera, projection);
expect(Math.round(viewRange.far)).eq(test.far);
expect(Math.round(viewRange.near)).eq(test.near);
});
});
});
});
}
}); | the_stack |
import {Collection} from '../collections';
import {Model} from './model';
import * as angular from 'angular';
import * as Uuid from 'uuid';
describe('Model: Model', function () {
let $rootScope, $httpBackend, $resource, mocks, v4Orig;
beforeEach(function () {
angular.mock.module('bi.core.internal');
v4Orig = Uuid.v4;
Uuid.v4 = function () {
return 'MOCK-UUID';
};
mocks = {
user: {
data: {
email: 'mock-user@wix.com'
}
},
TestCollection: Collection,
TestModel: Model
};
angular.mock.module({
user: mocks.user,
TestCollection: mocks.TestCollection,
TestModel: mocks.TestModel
});
});
beforeEach(inject(function (_$rootScope_, _$httpBackend_, _$resource_) {
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
$resource = _$resource_;
}));
afterEach(() => {
Uuid.v4 = v4Orig;
});
function createModel(data?, template?, options?, responseHook?) {
class TestModel extends Model {
constructor(data) {
super(data, template, options);
this._Resource = $resource('/:action/:id', {}, {
save: {
method: 'POST',
params: {
action: 'save'
}
},
get: {
method: 'GET',
params: {
action: 'get'
}
}
});
this._responseHook = responseHook;
}
}
let model = new TestModel(data);
spyOn(model, 'parse').and.callThrough();
spyOn(model, 'format').and.callThrough();
return model;
}
describe('instantiation', function () {
it('should create an empty new model', function () {
const model = createModel();
expect(model).toBeDefined();
expect(model.data).toEqual({});
});
it('should create a model with provided data', function () {
const data = {name: 'John'};
const model = createModel(data);
expect(model.data).toEqual(data);
});
it('should parse the provided data', function () {
const data = {name: 'John'};
const model = createModel(data, data);
expect(model.data).toEqual(data);
});
});
describe('id', function () {
it('should return a generatad id with a "new" prefix', function () {
const model = createModel();
expect(model.id.indexOf('new')).toBe(0);
});
it('should return the actual model id', function () {
const model = createModel({id: 1});
expect(model.id).toBe(1);
});
it('should set id', function () {
const model = createModel();
model.id = 2;
expect(model.id).toBe(2);
});
});
describe('isNew()', function () {
it('should be new', function () {
const model = createModel();
expect(model.isNew()).toBe(true);
});
it('should not be new', function () {
const model = createModel({id: 1});
expect(model.isNew()).toBe(false);
});
});
describe('save() (POST)', function () {
it('should call resource.save and update the data', function () {
const data = {name: 'John'};
const model = createModel(data, data);
model.save();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1});
$httpBackend.flush();
expect(model.id).toEqual(1);
});
it('should call resource.save, parse and update the data', function () {
const data = {};
const model = createModel(data, data);
model.save();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1, name: 'John'});
$httpBackend.flush();
expect((model.parse as any).calls.mostRecent().args[0].id).toBe(1);
expect((model.parse as any).calls.mostRecent().args[0].name).toBe('John');
expect(model.data.id).toBe(1);
expect(model.data.name).toBe('John');
});
it('should not be new', function () {
const model = createModel();
model.save();
$httpBackend.expectPOST('/save', {}).respond(200, {id: 1});
$httpBackend.flush();
expect(model.isNew()).toBe(false);
});
it('should be resolved with self', function () {
const model = createModel();
const promise = model.save();
const spy = jasmine.createSpy('then callback');
promise.then(spy);
$httpBackend.expectPOST('/save', {}).respond(200, {id: 1});
$httpBackend.flush();
expect(spy).toHaveBeenCalledWith(model);
});
});
describe('fetch() (GET)', function () {
it('should call resource.get and update the data', function () {
const model = createModel();
model.fetch(1);
$httpBackend.expectGET('/get/1').respond(200, {id: 1});
$httpBackend.flush();
expect(model.data.id).toBe(1);
});
it('should call resource.get, parse and update the data', function () {
const model = createModel({}, {});
model.fetch(1);
$httpBackend.expectGET('/get/1').respond(200, {id: 1, name: 'John'});
$httpBackend.flush();
expect((model.parse as any).calls.mostRecent().args[0].id).toBe(1);
expect((model.parse as any).calls.mostRecent().args[0].name).toBe('John');
expect(model.data.id).toBe(1);
expect(model.data.name).toBe('John');
});
it('should not be new', function () {
const model = createModel();
model.fetch(2);
$httpBackend.expectGET('/get/2').respond(200, {id: 2});
$httpBackend.flush();
expect(model.isNew()).toBe(false);
});
it('should be resolved with self', function () {
const model = createModel();
const promise = model.fetch(2);
const spy = jasmine.createSpy('then callback');
promise.then(spy);
$httpBackend.expectGET('/get/2').respond(200, {id: 2});
$httpBackend.flush();
expect(spy).toHaveBeenCalledWith(model);
});
});
describe('destroy()', function () {
it('should call resource.delete and update the data', function () {
const data = {id: 2};
const model = createModel(data, data);
model.destroy();
$httpBackend.expectDELETE('/2').respond(200, {id: 2});
$httpBackend.flush();
});
it('should not call resource.delete if the model is new', function () {
const model = createModel();
model.destroy();
$httpBackend.verifyNoOutstandingExpectation();
});
});
describe('resolved', function () {
it('should not be resolved until theres a response from server', function () {
const model = createModel();
model.fetch(2);
$httpBackend.expectGET('/get/2').respond(200, {id: 2});
expect(model.resolved).toBe(false);
});
it('should be resolved after a server response', function () {
const model = createModel();
model.fetch(2);
$httpBackend.expectGET('/get/2').respond(200, {id: 2});
$httpBackend.flush();
expect(model.resolved).toBe(true);
});
});
describe('promise', function () {
it('should be set to the latest resource.$promise', function () {
const model = createModel();
model.fetch(2);
$httpBackend.expectGET('/get/2').respond(200, {id: 2});
$httpBackend.flush();
expect(model.promise).toBeDefined();
});
it('should be resolved with self', function () {
const model = createModel();
const spy = jasmine.createSpy('then callback');
model.fetch(2);
model.promise.then(spy);
$httpBackend.expectGET('/get/2').respond(200, {id: 2});
$httpBackend.flush();
expect(spy).toHaveBeenCalledWith(model);
});
});
describe('parse()', function () {
describe('defaults', function () {
it('should assign defaults for properties with undefined values', function () {
const data = {};
const template = {name: 'John'};
const model = createModel(data, template);
expect(model.data).toEqual({
name: 'John'
});
});
it('should not assign defaults for properties with defined values', function () {
const data = {name: 'John'};
const template = {name: 'Sam'};
const model = createModel(data, template);
expect(model.data).toEqual({
name: 'John'
});
});
it('should support nesting', function () {
const data = {nested: {}};
const template = {nested: {name: 'John'}};
const model = createModel(data, template);
expect(model.data).toEqual({
nested: {
name: 'John'
}
});
});
});
describe('@optional', function () {
it('should assing null value to optional properties if they are undefined', function () {
const data = {name: 'John'};
const template = {name: 'John', lastname: '@optional'};
const model = createModel(data, template);
expect(model.data).toEqual({
name: 'John',
lastname: null
});
});
it('should not assign null value to optional properties if they are defined', function () {
const data = {name: 'John', lastname: 'Doe'};
const template = {name: 'John', lastname: '@optional'};
const model = createModel(data, template);
expect(model.data).toEqual({
name: 'John',
lastname: 'Doe'
});
});
});
describe('@flat', function () {
it('should unflatten the keys', function () {
const data = {value: {'a.b': 1, 'a.c': 2}};
const template = {value: '@flat'};
const model = createModel(data, template);
expect(model.data).toEqual({
value: {
a: {
b: 1,
c: 2
}
}
});
});
it('should unflatten the keys (more complex example)', function () {
const data = {value: {'a.b': 1, 'a.c': 2, 'c.d.e': 3}};
const template = {value: '@flat'};
const model = createModel(data, template);
expect(model.data).toEqual({
value: {
a: {
b: 1,
c: 2
},
c: {
d: {
e: 3
}
}
}
});
});
});
describe('@collection', function () {
it('should convert array to collection', function () {
const data = {name: 'John', lastnames: [1]};
const template = {name: 'John', lastnames: '@collection:TestCollection'};
const model = createModel(data, template);
expect(model.data.lastnames instanceof mocks.TestCollection).toBe(true);
});
it('should create empty collection if array is empty', function () {
const data = {name: 'John', lastnames: []};
const template = {name: 'John', lastnames: '@collection:TestCollection'};
const model = createModel(data, template);
expect(model.data.lastnames instanceof mocks.TestCollection).toBe(true);
expect(model.data.lastnames.models.length).toBe(0);
});
it('should create empty collection if array is undefined', function () {
const data = {name: 'John', lastnames: undefined};
const template = {name: 'John', lastnames: '@collection:TestCollection'};
const model = createModel(data, template);
expect(model.data.lastnames instanceof mocks.TestCollection).toBe(true);
expect(model.data.lastnames.models.length).toBe(0);
});
it('should support nesting', function () {
const data = {name: 'John', nested: {lastnames: []}};
const template = {name: 'John', nested: {lastnames: '@collection:TestCollection'}};
const model = createModel(data, template);
expect(model.data.nested.lastnames instanceof mocks.TestCollection).toBe(true);
});
describe('keep model references in existing collections after fetching fresh data', function () {
it('should copy new models into old models', function () {
const data = {values: [{id: 1}, {id: 2}]};
const template = {values: '@collection:TestCollection'};
const model = createModel(data, template);
const value1 = model.data.values.models[0];
const value2 = model.data.values.models[1];
model.save();
$httpBackend.expectPOST('/save', data).respond(200, {values: [{id: 10}, {id: 20}]});
$httpBackend.flush();
expect(model.data.values instanceof mocks.TestCollection).toBe(true);
expect(model.data.values.models.length).toBe(2);
expect(model.data.values.models[0].data).toEqual({id: 10});
expect(model.data.values.models[1].data).toEqual({id: 20});
expect(model.data.values.models[0]).toBe(value1);
expect(model.data.values.models[1]).toBe(value2);
});
it('should add new models to an empty collection', function () {
const data = {values: []};
const template = {values: '@collection:TestCollection'};
const model = createModel(data, template);
model.fetch(1);
$httpBackend.expectGET('/get/1').respond(200, {values: [{id: 10}, {id: 20}]});
$httpBackend.flush();
expect(model.data.values instanceof mocks.TestCollection).toBe(true);
expect(model.data.values.models.length).toBe(2);
expect(model.data.values.models[0].data).toEqual({id: 10});
expect(model.data.values.models[1].data).toEqual({id: 20});
});
});
});
describe('@model', function () {
it('should create a model object based on template', function () {
const data = {name: 'John', lastnames: {lastname: 'Smith'}};
const template = {name: 'John', lastnames: '@model:TestModel'};
const model = createModel(data, template);
expect(model.data.lastnames.data.lastname).toEqual('Smith');
expect(model.data.lastnames instanceof mocks.TestModel).toBe(true);
});
});
});
describe('format()', function () {
describe('defaults', function () {
it('should remove properties not defined in the template', function () {
const data = {prop1: true, prop2: true};
const model = createModel(data, {prop1: null});
const formatted = model.format();
expect(formatted).toEqual({
prop1: true
});
});
it('should strip keys starting with $', function () {
const data = {$prop: 1};
const model = createModel(data, {$prop: null});
const formatted = model.format();
expect(formatted).toEqual({});
});
it('should strip keys starting with $ (nested objects)', function () {
const data = {prop: {$prop: 1}};
const model = createModel(data, {prop: null});
const formatted = model.format();
expect(formatted).toEqual({prop: {}});
});
it('should strip keys starting with $ (arrays)', function () {
const data = {prop: [{$prop: 1}]};
const model = createModel(data, {prop: null});
const formatted = model.format();
expect(formatted).toEqual({prop: [{}]});
});
});
describe('@optional', function () {
it('should remove optional properties that are null', function () {
const data = {name: 'John', lastname: null};
const template = {name: null, lastname: '@optional'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({
name: 'John'
});
});
it('should not remove optional properties that are primitive values', function () {
const data = {name: 'John', lastname: 'Doe'};
const template = {name: null, lastname: '@optional'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({
name: 'John',
lastname: 'Doe'
});
});
it('should not remove optional properties that are objects', function () {
const data = {name: {first: 'John', last: 'Doe'}};
const template = {name: '@optional'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({name: {first: 'John', last: 'Doe'}});
});
it('should send optional properties that are arrays', function () {
const data = {prop: []};
const template = {prop: '@optional'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({prop: []});
});
});
describe('@collection', function () {
it('should format the collection', function () {
const data = {values: [1, 2]};
const template = {values: '@collection:TestCollection'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({values: [1, 2]});
});
});
describe('@flat', function () {
it('should flatten the keys', function () {
const data = {
values: {
a: {
b: 1,
c: 2
}
}
};
const template = {values: '@flat'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({values: {'a.b': 1, 'a.c': 2}});
});
it('should flatten the keys (more complex example)', function () {
const data = {
values: {
a: {
b: 1,
c: 2
},
c: {
d: {
e: 3
}
}
}
};
const template = {values: '@flat'};
const model = createModel(data, template);
const formatted = model.format();
expect(formatted).toEqual({values: {'a.b': 1, 'a.c': 2, 'c.d.e': 3}});
});
// it('should remove keys starting with $', function () {
// const data = {
// values: {
// a: {
// $b: 1
// }
// }
// };
// const template = {values: '@flat'};
// const model = createModel(data, template);
// const formatted = model.format();
// expect(formatted).toEqual({values: {'a.b': 1}});
// });
});
});
describe('clone()', function () {
it('should fetch event by current id and return a new instance', function () {
const model = createModel({id: 1});
const cloned = model.clone(true);
$httpBackend.expectGET('/get/1').respond(200, {id: 1, name: 'test'});
$httpBackend.flush();
expect(cloned).not.toBe(model);
expect(cloned.data.name).toBe('test');
});
it('should fetch event with provided params', function () {
const model = createModel({id: 1});
const cloned = model.clone(true, {id: 2});
$httpBackend.expectGET('/get/2').respond(200, {id: 2, name: 'test'});
$httpBackend.flush();
expect(cloned).not.toBe(model);
expect(cloned.data.name).toBe('test');
});
it('should fetch event by current id and return a new instance without id', function () {
const data = {id: 1, name: 'test'};
const model = createModel(data, {id: '@optional'});
const cloned = model.clone(true);
$httpBackend.expectGET('/get/1').respond(200, {id: 1});
$httpBackend.flush();
expect(cloned.data.id).toBe(null);
expect(cloned.isNew()).toBe(true);
});
it('should copy the data and return a new instance', function () {
const data = {name: 'test'};
const model = createModel(data, {name: ''});
const cloned = model.clone();
$rootScope.$digest();
expect(cloned).not.toBe(model);
expect(cloned.data.name).toBe('test');
expect(cloned.isNew()).toBe(true);
});
it('should copy the data and return a new instance without id', function () {
const data = {id: 1};
const model = createModel(data, {id: '@optional'});
const cloned = model.clone();
$rootScope.$digest();
expect(cloned.data.id).toBe(null);
expect(cloned.isNew()).toBe(true);
});
it('should set a promise that resolves to self', function () {
const data = {a: 1};
const model = createModel(data, data);
const cloned = model.clone();
const spy = jasmine.createSpy('cloned.promise');
cloned.promise.then(spy);
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith(cloned);
});
});
describe('meta()', function () {
it('should set and get a meta property', function () {
const model = createModel();
model.meta('test', 1);
expect(model.meta('test')).toBe(1);
});
it('should return undefined for unset values', function () {
const model = createModel();
expect(model.meta('test')).toBeUndefined();
});
it('should set a value that exists only until first read ', function () {
const model = createModel();
model.meta('test', 1, true);
expect(model.meta('test')).toBe(1);
expect(model.meta('test')).toBeUndefined();
});
});
describe('isValid()', function () {
it('should be valid by default', function () {
const model = createModel();
expect(model.isValid()).toBe(true);
});
it('should set the validity status', function () {
const model = createModel();
model.setValidity(false);
expect(model.isValid()).toBe(false);
});
});
describe('promise.noSync()', function () {
it('should not update model with next server response if called', function () {
const data = {name: 'John'};
const model = createModel(data, data);
model.save().noSync();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1, name: 'Jack'});
$httpBackend.flush();
expect(model.data.name).toEqual('John');
});
it('should return a promise resolved with self', function () {
const data = {name: 'John'};
const model = createModel(data, data);
const promise = model.save().noSync();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1, name: 'Jack'});
$httpBackend.flush();
const spy = jasmine.createSpy('promise');
promise.then(spy);
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith(model);
});
it('should apply only once per call', function () {
const data = {name: 'John'};
const model = createModel(data, data);
model.save().noSync();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1, name: 'Jack'});
$httpBackend.flush();
model.save();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1, name: 'Jack'});
$httpBackend.flush();
expect(model.data.name).toEqual('Jack');
});
});
describe('responseHook', function () {
it('should call hook with "get" action and processed model', function () {
const spy = jasmine.createSpy('responseHook');
const model = createModel(undefined, undefined, {}, spy);
model.fetch(1);
$httpBackend.expectGET('/get/1').respond(200, {id: 1});
$httpBackend.flush();
expect(spy).toHaveBeenCalledWith({id: 1}, 'get', {noSync: false});
});
it('should call hook with "save" action and processed model', function () {
const spy = jasmine.createSpy('responseHook');
const data = {name: 'John'};
const model = createModel(data, data, {}, spy);
model.save();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1});
$httpBackend.flush();
expect(spy).toHaveBeenCalledWith({id: 1, name: 'John'}, 'save', {noSync: false});
});
it('should call hook with "clone" action and processed model', function () {
const spy = jasmine.createSpy('responseHook');
const data = {name: 'John'};
const model = createModel(data, {name: ''}, {}, spy);
model.clone();
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith({id: null, name: 'John'}, 'clone', {noSync: false});
});
it('should call hook with "save" action and noSync=true', function () {
const spy = jasmine.createSpy('responseHook');
const data = {name: 'John'};
const model = createModel(data, data, {}, spy);
model.save().noSync();
$httpBackend.expectPOST('/save', data).respond(200, {id: 1});
$httpBackend.flush();
expect(spy).toHaveBeenCalledWith({id: 1, name: 'John'}, 'save', {noSync: true});
});
});
describe('options', function () {
describe('autoId', function () {
it('should generate id when data has no id param', function () {
const model = createModel(undefined, undefined, {autoId: true});
expect(model.id).toBe('MOCK-UUID');
});
it('should not generate id when data has id param', function () {
const model = createModel({id: 1}, undefined, {autoId: true});
expect(model.id).not.toBe('MOCK-UUID');
});
it('should be considered new', function () {
const model = createModel(undefined, undefined, {autoId: true});
expect(model.isNew()).toBe(true);
});
it('should not be considered new after fetching a model', function () {
const model = createModel(undefined, undefined, {autoId: true});
model.fetch('MOCK-UUID');
$httpBackend.expectGET('/get/MOCK-UUID').respond(200, {id: 'MOCK-UUID'});
$httpBackend.flush();
expect(model.id).toBe('MOCK-UUID');
expect(model.isNew()).toBe(false);
});
it('should not be considered new after saving a new model', function () {
const data = {};
const model = createModel(data, data, {autoId: true});
model.save();
$httpBackend.expectPOST('/save', data).respond(200, {id: 'MOCK-UUID'});
$httpBackend.flush();
expect(model.id).toBe('MOCK-UUID');
expect(model.isNew()).toBe(false);
});
it('should generate id for cloned model', function () {
const data = {id: 1};
const model = createModel(data, data, {autoId: true});
const clonedModel = model.clone();
$rootScope.$digest();
expect(clonedModel.id).toBe('MOCK-UUID');
});
it('should consider cloned model new', function () {
const data = {id: 1};
const model = createModel(data, data, {autoId: true});
const clonedModel = model.clone();
$rootScope.$digest();
expect(clonedModel.isNew()).toBe(true);
});
});
describe('autoOwner', function () {
it('should assign current user as owner', function () {
const model = createModel(undefined, undefined, {autoOwner: true});
expect(model.data.owner).toEqual(mocks.user.data);
});
it('should duplicate the user object', function () {
const model = createModel(undefined, undefined, {autoOwner: true});
expect(model.data.owner).toEqual(mocks.user.data);
expect(model.data.owner).not.toBe(mocks.user.data);
});
it('should assign current user if owner object is defined without email', function () {
const model = createModel({owner: {}}, {owner: {}}, {autoOwner: true});
expect(model.data.owner).toEqual(mocks.user.data);
});
it('should not assign current user if owner email is defined', function () {
const owner = {email: 'some-user@wix.com'};
const model = createModel({owner: owner}, {owner: {}}, {autoOwner: true});
expect(model.data.owner).toEqual(owner);
});
it('should assign id for cloned model', function () {
const data = {id: 1};
const model = createModel(data, data, {autoOwner: true});
const clonedModel = model.clone();
$rootScope.$digest();
expect(clonedModel.data.owner).toEqual(mocks.user.data);
});
});
});
describe('data', function () {
it('data property should be assignable', function () {
const model = createModel();
model.data = {test: true};
expect(model.data).toEqual({test: true});
});
});
}); | the_stack |
import type {Mutable, Class, Dictionary, MutableDictionary} from "@swim/util";
import {MemberFastenerClass, Provider, Component, ComponentRef, ComponentSet} from "@swim/component";
import {FileRef} from "@swim/sys";
import type {Workspace} from "../workspace/Workspace";
import {Scope} from "../scope/Scope";
import {TaskStatus, TaskConfig, Task} from "../task/Task";
import {PackageTask} from "./PackageTask";
import {DepsTask} from "./DepsTask";
import {LibsTask} from "./LibsTask";
import {TestTask} from "./TestTask";
import {DocTask} from "./DocTask";
import {VersionTask} from "./VersionTask";
import {PublishTask} from "./PublishTask";
import {CleanTask} from "./CleanTask";
import type {PackageScopeObserver} from "./PackageScopeObserver";
import {LibraryScope} from "../"; // forward import
/** @public */
export interface PackageConfig {
readonly name: string;
readonly version: string;
readonly dependencies?: Dictionary<string>;
readonly optionalDependencies?: Dictionary<string>;
readonly peerDependencies?: Dictionary<string>;
readonly devDependencies?: Dictionary<string>;
readonly scripts?: Dictionary<string>,
}
/** @public */
export class PackageScope extends Scope {
constructor(name: string) {
super();
this.name = name;
this.unscopedName = PackageScope.unscopedName(name);
}
override readonly observerType?: Class<PackageScopeObserver>;
override readonly name: string;
readonly unscopedName: string | undefined;
/** @internal */
setName(name: string): void {
(this as Mutable<this>).name = name;
(this as Mutable<this>).unscopedName = PackageScope.unscopedName(name);
}
@FileRef<PackageScope, PackageConfig | null>({
fileName: "package.json",
value: null,
getBaseDir(): string | undefined {
return this.owner.baseDir.value;
},
})
readonly package!: FileRef<this, PackageConfig | null>;
static readonly package: MemberFastenerClass<PackageScope, "package">;
@ComponentSet<PackageScope, LibraryScope>({
// avoid cyclic static reference to type: LibraryScope
binds: true,
observes: true,
libraryDidChange(libraryScope: LibraryScope): void {
this.owner.callObservers("packageLibraryDidChange", libraryScope, this.owner);
this.owner.callObservers("packageDidChange", this.owner);
},
detectComponent(component: Component): LibraryScope | null {
return component instanceof LibraryScope ? component : null;
},
})
readonly libraries!: ComponentSet<this, LibraryScope>;
static readonly libraries: MemberFastenerClass<PackageScope, "libraries">;
@ComponentSet<PackageScope, PackageScope>({
type: PackageScope,
observes: true,
didAttachComponent(dependencyScope: PackageScope): void {
dependencyScope.dependents.addComponent(this.owner);
},
willDetachComponent(dependencyScope: PackageScope): void {
dependencyScope.dependents.removeComponent(this.owner);
},
packageDidChange(dependencyScope: PackageScope): void {
this.owner.callObservers("packageDependencyDidChange", dependencyScope, this.owner);
},
})
readonly dependencies!: ComponentSet<this, PackageScope>;
static readonly dependencies: MemberFastenerClass<PackageScope, "dependencies">;
protected detectDependency(packageScope: PackageScope): void {
const packageDependencies = this.package.value !== null ? this.package.value.dependencies : void 0;
if (packageDependencies !== void 0 && packageScope.name in packageDependencies) {
this.dependencies.addComponent(packageScope);
}
}
@ComponentSet<PackageScope, PackageScope>({
type: PackageScope,
})
readonly dependents!: ComponentSet<this, PackageScope>;
static readonly dependents: MemberFastenerClass<PackageScope, "dependents">;
@Provider<PackageScope, Workspace>({
extends: true,
observes: true,
didAttachService(service: Workspace): void {
const packages = service.packageNameMap;
for (const packageName in packages) {
const packageScope = packages[packageName]!;
this.owner.detectDependency(packageScope);
}
},
workspaceDidAttachPackage(packageScope: PackageScope): void {
this.owner.detectDependency(packageScope);
},
})
override readonly workspace!: Provider<this, Workspace>;
static override readonly workspace: MemberFastenerClass<PackageScope, "workspace">;
@ComponentRef<PackageScope, DepsTask>({
type: DepsTask,
})
readonly deps!: ComponentRef<this, DepsTask>;
static readonly deps: MemberFastenerClass<PackageScope, "deps">;
@ComponentRef<PackageScope, LibsTask>({
type: LibsTask,
})
readonly libs!: ComponentRef<this, LibsTask>;
static readonly libs: MemberFastenerClass<PackageScope, "libs">;
@ComponentRef<PackageScope, TestTask>({
type: TestTask,
})
readonly test!: ComponentRef<this, TestTask>;
static readonly test: MemberFastenerClass<PackageScope, "test">;
@ComponentRef<PackageScope, DocTask>({
type: DocTask,
})
readonly doc!: ComponentRef<this, DocTask>;
static readonly doc: MemberFastenerClass<PackageScope, "doc">;
@ComponentRef<PackageScope, VersionTask>({
type: VersionTask,
})
readonly version!: ComponentRef<this, VersionTask>;
static readonly version: MemberFastenerClass<PackageScope, "version">;
@ComponentRef<PackageScope, PublishTask>({
type: PublishTask,
})
readonly publish!: ComponentRef<this, PublishTask>;
static readonly publish: MemberFastenerClass<PackageScope, "publish">;
@ComponentRef<PackageScope, CleanTask>({
type: CleanTask,
})
readonly clean!: ComponentRef<this, CleanTask>;
static readonly clean: MemberFastenerClass<PackageScope, "clean">;
getLibraries(libraryNames?: string[] | string): MutableDictionary<LibraryScope> | null {
if (typeof libraryNames === "string") {
libraryNames = libraryNames.split(",");
}
let libs: MutableDictionary<LibraryScope> | null = null;
const libraries = this.libraries.components;
for (const componentId in libraries) {
const libraryScope = libraries[componentId]!;
if (libraryNames === void 0 || libraryNames.includes(libraryScope.name)) {
if (libs === null) {
libs = {};
}
libs[libraryScope.name] = libraryScope;
}
}
return libs;
}
async forEachLibrary(libraryNames: string[] | string | undefined, callback: (libraryScope: LibraryScope) => Promise<void> | void): Promise<void>;
async forEachLibrary<S>(libraryNames: string[] | string | undefined, callback: (this: S, libraryScope: LibraryScope) => Promise<void> | void, thisArg?: S): Promise<void>;
async forEachLibrary<S>(libraryNames: string[] | string | undefined, callback: (this: S, libraryScope: LibraryScope) => Promise<void> | void, thisArg?: S): Promise<void> {
if (typeof libraryNames === "string") {
libraryNames = libraryNames.split(",");
}
const libraries = this.libraries.components;
for (const componentId in libraries) {
const libraryScope = libraries[componentId]!;
if (libraryNames === void 0 || libraryNames.includes(libraryScope.name)) {
const result = callback.call(thisArg as S, libraryScope);
if (result !== void 0) {
await result;
}
}
}
}
getDependencies(): MutableDictionary<PackageScope>;
/** @internal */
getDependencies(packages: MutableDictionary<PackageScope>): MutableDictionary<PackageScope>;
getDependencies(packages?: MutableDictionary<PackageScope>): MutableDictionary<PackageScope> {
let dependent: boolean;
if (packages === void 0) {
packages = {};
dependent = false;
} else {
dependent = true;
}
const dependencies = this.dependencies.components;
for (const componentId in dependencies) {
const dependency = dependencies[componentId]!;
packages = dependency.getDependencies(packages);
}
if (dependent && packages[this.name] === void 0) {
packages[this.name] = this;
}
return packages;
}
async forEachDependency(callback: (packageScope: PackageScope) => Promise<void> | void): Promise<void>;
async forEachDependency<S>(callback: (this: S, packageScope: PackageScope) => Promise<void> | void, thisArg?: S, packages?: MutableDictionary<PackageScope>): Promise<void>;
async forEachDependency<S>(callback: (this: S, packageScope: PackageScope) => Promise<void> | void, thisArg?: S, packages?: MutableDictionary<PackageScope>): Promise<void> {
if (packages === void 0) {
packages = {};
}
const dependencies = this.dependencies.components;
for (const componentId in dependencies) {
const dependency = dependencies[componentId]!;
await dependency.forEachDependency(callback, thisArg, packages);
}
if (packages[this.name] === void 0) {
packages[this.name] = this;
const result = callback.call(thisArg as S, this);
if (result !== void 0) {
await result;
}
}
}
getDependents(): MutableDictionary<PackageScope>;
/** @internal */
getDependents(packages: MutableDictionary<PackageScope>): MutableDictionary<PackageScope>;
getDependents(packages?: MutableDictionary<PackageScope>): MutableDictionary<PackageScope> {
let dependent: boolean;
if (packages === void 0) {
packages = {};
dependent = false;
} else {
dependent = true;
}
if (dependent && packages[this.name] === void 0) {
packages[this.name] = this;
}
const dependents = this.dependents.components;
for (const componentId in dependents) {
const dependent = dependents[componentId]!;
packages = dependent.getDependents(packages);
}
return packages;
}
override async runTask(taskConfig: TaskConfig): Promise<TaskStatus> {
const task = this.getTask(taskConfig.class);
if (task instanceof PackageTask) {
return task.run(taskConfig.options);
} else {
return TaskStatus.Skipped;
}
}
async runLibraryTasks(taskConfigs: TaskConfig | readonly TaskConfig[], libraryNames?: string[] | string): Promise<void> {
await this.forEachLibrary(libraryNames, function (libraryScope: LibraryScope): Promise<void> {
return libraryScope.runTasks(taskConfigs) as unknown as Promise<void>;
}, this);
await this.runTasks(taskConfigs);
}
libraryTaskStatus(libraryNames: string[] | string | undefined, taskClass: Class<Task>): TaskStatus;
/** @internal */
libraryTaskStatus(libraryNames: string[] | string | undefined, taskClass: Class<Task>, taskStatus: TaskStatus): TaskStatus;
libraryTaskStatus(libraryNames: string[] | string | undefined, taskClass: Class<Task>, taskStatus?: TaskStatus): TaskStatus {
if (typeof libraryNames === "string") {
libraryNames = libraryNames.split(",");
}
if (taskStatus === void 0) {
taskStatus = TaskStatus.Success;
}
const libraries = this.libraries.components;
for (const componentId in libraries) {
const libraryScope = libraries[componentId]!;
if (libraryNames === void 0 || libraryNames.includes(libraryScope.name)) {
const libraryTask = libraryScope.getTask(taskClass);
if (libraryTask !== null) {
const libraryTaskStatus = libraryTask.status.value;
if (libraryTaskStatus > taskStatus) {
taskStatus = libraryTaskStatus;
}
}
}
}
return taskStatus;
}
dependencyTaskStatus(taskClass: Class<Task>): TaskStatus;
/** @internal */
dependencyTaskStatus(taskClass: Class<Task>, taskStatus: TaskStatus, packages: MutableDictionary<PackageScope>): TaskStatus;
dependencyTaskStatus(taskClass: Class<Task>, taskStatus?: TaskStatus, packages?: MutableDictionary<PackageScope>): TaskStatus {
if (taskStatus === void 0) {
taskStatus = TaskStatus.Success;
}
if (packages === void 0) {
packages = {};
}
const dependencies = this.dependencies.components;
for (const componentId in dependencies) {
const dependency = dependencies[componentId]!;
taskStatus = dependency.dependencyTaskStatus(taskClass, taskStatus, packages);
}
if (packages[this.name] === void 0) {
packages[this.name] = this;
const dependencyTask = this.getTask(taskClass);
if (dependencyTask !== null) {
const dependencyTaskStatus = dependencyTask.status.value;
if (dependencyTaskStatus > taskStatus) {
taskStatus = dependencyTaskStatus;
}
}
}
return taskStatus;
}
libraryDependencyTaskStatus(libraryNames: string[] | string | undefined, taskClass: Class<Task>): TaskStatus;
/** @internal */
libraryDependencyTaskStatus(libraryNames: string[] | string | undefined, taskClass: Class<Task>, taskStatus: TaskStatus, packages: MutableDictionary<PackageScope>): TaskStatus;
libraryDependencyTaskStatus(libraryNames: string[] | string | undefined, taskClass: Class<Task>, taskStatus?: TaskStatus, packages?: MutableDictionary<PackageScope>): TaskStatus {
if (typeof libraryNames === "string") {
libraryNames = libraryNames.split(",");
}
if (taskStatus === void 0) {
taskStatus = TaskStatus.Success;
}
if (packages === void 0) {
packages = {};
}
const dependencies = this.dependencies.components;
for (const componentId in dependencies) {
const dependency = dependencies[componentId]!;
taskStatus = dependency.libraryDependencyTaskStatus(libraryNames, taskClass, taskStatus, packages);
}
if (packages[this.name] === void 0) {
packages[this.name] = this;
taskStatus = this.libraryTaskStatus(libraryNames, taskClass, taskStatus);
}
return taskStatus;
}
getVersion(newSemanticVersion?: string, tag?: string, snapshot?: string | boolean): string | undefined {
let oldVersion: string | undefined;
let oldSemanticVersion: string | undefined;
let oldSnapshotVersion: string | undefined;
let oldSnapshotTag: string | undefined;
let oldSnapshotUid: string | undefined;
let oldSnapshotDate: string | undefined;
let oldSnapshotInc: string | undefined;
let newVersion: string | undefined;
let newSnapshotVersion: string | undefined;
let newSnapshotTag: string | undefined;
let newSnapshotUid: string | undefined;
let newSnapshotDate: string | undefined;
let newSnapshotInc: string | undefined;
if (oldVersion === void 0 && this.package.value !== null) {
oldVersion = this.package.value.version;
}
if (oldVersion !== void 0) {
const snapshotIndex = oldVersion.lastIndexOf("-");
if (snapshotIndex >= 0) {
oldSemanticVersion = oldVersion.substr(0, snapshotIndex);
oldSnapshotVersion = oldVersion.substr(snapshotIndex + 1);
const uidIndex = oldSnapshotVersion.indexOf(".");
if (uidIndex >= 0) {
oldSnapshotTag = oldSnapshotVersion.substr(0, uidIndex);
oldSnapshotUid = oldSnapshotVersion.substr(uidIndex + 1);
if (isFinite(+oldSnapshotTag)) {
oldSnapshotUid = oldSnapshotTag;
oldSnapshotTag = void 0;
}
} else if (!isFinite(+oldSnapshotVersion)) {
oldSnapshotTag = oldSnapshotVersion;
} else {
oldSnapshotUid = oldSnapshotVersion;
}
if (oldSnapshotUid !== void 0) {
const incIndex = oldSnapshotUid.lastIndexOf(".");
if (incIndex >= 0) {
oldSnapshotDate = oldSnapshotUid.substr(0, incIndex);
oldSnapshotInc = oldSnapshotUid.substr(incIndex + 1);
} else {
oldSnapshotDate = oldSnapshotUid;
}
}
} else {
oldSemanticVersion = oldVersion;
}
if (newSemanticVersion === void 0) {
newSemanticVersion = oldSemanticVersion;
}
newVersion = newSemanticVersion;
if (tag !== void 0 || typeof snapshot === "string" || snapshot === true) {
if (typeof snapshot === "string") {
newSnapshotDate = snapshot;
} else {
const today = new Date();
const year = "" + today.getUTCFullYear();
let month = "" + (today.getUTCMonth() + 1);
while (month.length < 2) month = "0" + month;
let day = "" + today.getUTCDate();
while (day.length < 2) day = "0" + day;
newSnapshotDate = year + month + day;
}
newSnapshotTag = tag !== void 0 ? tag : oldSnapshotTag;
if (newSemanticVersion === oldSemanticVersion && newSnapshotTag === oldSnapshotTag && newSnapshotDate === oldSnapshotDate) {
if (isFinite(+(oldSnapshotInc as any))) {
newSnapshotInc = "" + (+(oldSnapshotInc as any) + 1);
} else {
newSnapshotInc = "1";
}
}
newSnapshotUid = newSnapshotDate;
if (newSnapshotInc !== void 0) {
newSnapshotUid += "." + newSnapshotInc;
}
if (newSnapshotTag !== void 0) {
newSnapshotVersion = newSnapshotTag;
if (typeof snapshot === "string" || snapshot === true) {
newSnapshotVersion += "." + newSnapshotUid;
}
} else {
newSnapshotVersion = newSnapshotUid;
}
newVersion += "-" + newSnapshotVersion;
}
}
return newVersion;
}
getDependencyVersions(version?: string, tag?: string, snapshot?: string | boolean): MutableDictionary<string>;
/** @internal */
getDependencyVersions(version: string | undefined, tag: string | undefined, snapshot: string | boolean | undefined, packageVersions: MutableDictionary<string>): MutableDictionary<string>;
getDependencyVersions(version?: string, tag?: string, snapshot?: string | boolean, packageVersions?: MutableDictionary<string>): MutableDictionary<string> {
if (packageVersions === void 0) {
packageVersions = {};
}
const dependencies = this.dependencies.components;
for (const componentId in dependencies) {
const dependency = dependencies[componentId]!;
packageVersions = dependency.getDependencyVersions(version, tag, snapshot, packageVersions);
}
if (!(this.name in packageVersions)) {
packageVersions[this.name] = this.getVersion(version, tag, snapshot);
}
return packageVersions;
}
/** @internal */
async initChildren(): Promise<void> {
const libraryScope = await LibraryScope.load(this.baseDir.value!);
if (libraryScope !== null) {
await this.initLibraryScope(libraryScope);
}
}
/** @internal */
async initLibraryScope(libraryScope: LibraryScope): Promise<void> {
const compileTask = libraryScope.compile.getComponent();
const tsconfig = await compileTask.tsconfig.getOrLoadIfExists(null);
if (tsconfig !== null) {
if (tsconfig.fileNames.length !== 0) {
this.appendChild(libraryScope, libraryScope.name);
}
const projectReferences = tsconfig.projectReferences;
if (projectReferences !== void 0) {
for (let i = 0; i < projectReferences.length; i += 1) {
const projectReference = projectReferences[i]!;
if (!projectReference.circular) {
const packageDir = projectReference.path;
const packageScope = await Scope.load(packageDir);
if (packageScope !== null) {
this.appendChild(packageScope, packageScope.name);
}
}
}
}
}
}
static override async load(baseDir: string): Promise<PackageScope | null> {
const packageScope = new PackageScope("");
packageScope.baseDir.setValue(baseDir);
const packageConfig = await packageScope.package.loadIfExists(void 0, null);
if (packageConfig !== null) {
packageScope.setName(packageConfig.name);
packageScope.deps.insertComponent();
packageScope.libs.insertComponent();
packageScope.test.insertComponent();
packageScope.doc.insertComponent();
packageScope.version.insertComponent();
packageScope.publish.insertComponent();
packageScope.clean.insertComponent();
await packageScope.initChildren();
return packageScope;
}
return null;
}
/** @internal */
static unscopedName(name: string): string | undefined {
let index: number;
if (name.charCodeAt(0) === 64/*'@'*/ && (index = name.lastIndexOf("/"), index >= 0)) {
return name.substr(index + 1);
}
return void 0;
}
} | the_stack |
import {
Directive, Input, ElementRef,
Renderer2, NgModule, Output, EventEmitter, Inject,
LOCALE_ID, OnChanges, SimpleChanges, HostListener, OnInit
} from '@angular/core';
import {
ControlValueAccessor,
Validator, AbstractControl, ValidationErrors, NG_VALIDATORS, NG_VALUE_ACCESSOR,
} from '@angular/forms';
import { DOCUMENT } from '@angular/common';
import { IgxMaskDirective } from '../mask/mask.directive';
import { MaskParsingService } from '../mask/mask-parsing.service';
import { isDate, PlatformUtil } from '../../core/utils';
import { IgxDateTimeEditorEventArgs, DatePartInfo, DatePart } from './date-time-editor.common';
import { noop } from 'rxjs';
import { DatePartDeltas } from './date-time-editor.common';
import { DateTimeUtil } from '../../date-common/util/date-time.util';
/**
* Date Time Editor provides a functionality to input, edit and format date and time.
*
* @igxModule IgxDateTimeEditorModule
*
* @igxParent IgxInputGroup
*
* @igxTheme igx-input-theme
*
* @igxKeywords date, time, editor
*
* @igxGroup Scheduling
*
* @remarks
*
* The Ignite UI Date Time Editor Directive makes it easy for developers to manipulate date/time user input.
* It requires input in a specified or default input format which is visible in the input element as a placeholder.
* It allows the input of only date (ex: 'dd/MM/yyyy'), only time (ex:'HH:mm tt') or both at once, if needed.
* Supports display format that may differ from the input format.
* Provides methods to increment and decrement any specific/targeted `DatePart`.
*
* @example
* ```html
* <igx-input-group>
* <input type="text" igxInput [igxDateTimeEditor]="'dd/MM/yyyy'" [displayFormat]="'shortDate'" [(ngModel)]="date"/>
* </igx-input-group>
* ```
*/
@Directive({
selector: '[igxDateTimeEditor]',
exportAs: 'igxDateTimeEditor',
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: IgxDateTimeEditorDirective, multi: true },
{ provide: NG_VALIDATORS, useExisting: IgxDateTimeEditorDirective, multi: true }
]
})
export class IgxDateTimeEditorDirective extends IgxMaskDirective implements OnChanges, OnInit, Validator, ControlValueAccessor {
/**
* Locale settings used for value formatting.
*
* @remarks
* Uses Angular's `LOCALE_ID` by default. Affects both input mask and display format if those are not set.
* If a `locale` is set, it must be registered via `registerLocaleData`.
* Please refer to https://angular.io/guide/i18n#i18n-pipes.
* If it is not registered, `Intl` will be used for formatting.
*
* @example
* ```html
* <input igxDateTimeEditor [locale]="'en'">
* ```
*/
@Input()
public locale: string;
/**
* Minimum value required for the editor to remain valid.
*
* @remarks
* If a `string` value is passed, it must be in the defined input format.
*
* @example
* ```html
* <input igxDateTimeEditor [minValue]="minDate">
* ```
*/
public get minValue(): string | Date {
return this._minValue;
}
@Input()
public set minValue(value: string | Date) {
this._minValue = value;
this.onValidatorChange();
}
/**
* Maximum value required for the editor to remain valid.
*
* @remarks
* If a `string` value is passed in, it must be in the defined input format.
*
* @example
* ```html
* <input igxDateTimeEditor [maxValue]="maxDate">
* ```
*/
public get maxValue(): string | Date {
return this._maxValue;
}
@Input()
public set maxValue(value: string | Date) {
this._maxValue = value;
this.onValidatorChange();
}
/**
* Specify if the currently spun date segment should loop over.
*
* @example
* ```html
* <input igxDateTimeEditor [spinLoop]="false">
* ```
*/
@Input()
public spinLoop = true;
/**
* Set both pre-defined format options such as `shortDate` and `longDate`,
* as well as constructed format string using characters supported by `DatePipe`, e.g. `EE/MM/yyyy`.
*
* @example
* ```html
* <input igxDateTimeEditor [displayFormat]="'shortDate'">
* ```
*/
@Input()
public displayFormat: string;
/**
* Expected user input format (and placeholder).
*
* @example
* ```html
* <input [igxDateTimeEditor]="'dd/MM/yyyy'">
* ```
*/
@Input(`igxDateTimeEditor`)
public set inputFormat(value: string) {
if (value) {
this.setMask(value);
this._inputFormat = value;
}
}
public get inputFormat(): string {
return this._inputFormat || this._defaultInputFormat;
}
/**
* Editor value.
*
* @example
* ```html
* <input igxDateTimeEditor [value]="date">
* ```
*/
@Input()
public set value(value: Date | string) {
this._value = value;
this.setDateValue(value);
this.onChangeCallback(value);
this.updateMask();
}
public get value(): Date | string {
return this._value;
}
/**
* Delta values used to increment or decrement each editor date part on spin actions.
* All values default to `1`.
*
* @example
* ```html
* <input igxDateTimeEditor [spinDelta]="{date: 5, minute: 30}">
* ```
*/
@Input()
public spinDelta: DatePartDeltas;
/**
* Emitted when the editor's value has changed.
*
* @example
* ```html
* <input igxDateTimeEditor (valueChange)="valueChange($event)"/>
* ```
*/
@Output()
public valueChange = new EventEmitter<Date | string>();
/**
* Emitted when the editor is not within a specified range or when the editor's value is in an invalid state.
*
* @example
* ```html
* <input igxDateTimeEditor [minValue]="minDate" [maxValue]="maxDate" (validationFailed)="onValidationFailed($event)"/>
* ```
*/
@Output()
public validationFailed = new EventEmitter<IgxDateTimeEditorEventArgs>();
private _inputFormat: string;
private _oldValue: Date;
private _dateValue: Date;
private _onClear: boolean;
private document: Document;
private _isFocused: boolean;
private _defaultInputFormat: string;
private _value: Date | string;
private _minValue: Date | string;
private _maxValue: Date | string;
private _inputDateParts: DatePartInfo[];
private _datePartDeltas: DatePartDeltas = {
date: 1,
month: 1,
year: 1,
hours: 1,
minutes: 1,
seconds: 1
};
private onTouchCallback: (...args: any[]) => void = noop;
private onChangeCallback: (...args: any[]) => void = noop;
private onValidatorChange: (...args: any[]) => void = noop;
private get datePartDeltas(): DatePartDeltas {
return Object.assign({}, this._datePartDeltas, this.spinDelta);
}
private get emptyMask(): string {
return this.maskParser.applyMask(null, this.maskOptions);
}
private get targetDatePart(): DatePart {
if (this.document.activeElement === this.nativeElement) {
return this._inputDateParts
.find(p => p.start <= this.selectionStart && this.selectionStart <= p.end && p.type !== DatePart.Literal)?.type;
} else {
if (this._inputDateParts.some(p => p.type === DatePart.Date)) {
return DatePart.Date;
} else if (this._inputDateParts.some(p => p.type === DatePart.Hours)) {
return DatePart.Hours;
}
}
}
private get hasDateParts(): boolean {
return this._inputDateParts.some(
p => p.type === DatePart.Date
|| p.type === DatePart.Month
|| p.type === DatePart.Year);
}
private get hasTimeParts(): boolean {
return this._inputDateParts.some(
p => p.type === DatePart.Hours
|| p.type === DatePart.Minutes
|| p.type === DatePart.Seconds);
}
private get dateValue(): Date {
return this._dateValue;
}
constructor(
protected renderer: Renderer2,
protected elementRef: ElementRef,
protected maskParser: MaskParsingService,
protected platform: PlatformUtil,
@Inject(DOCUMENT) private _document: any,
@Inject(LOCALE_ID) private _locale: any) {
super(elementRef, maskParser, renderer, platform);
this.document = this._document as Document;
this.locale = this.locale || this._locale;
}
@HostListener('wheel', ['$event'])
public onWheel(event: WheelEvent): void {
if (!this._isFocused) {
return;
}
event.preventDefault();
event.stopPropagation();
if (event.deltaY > 0) {
this.decrement();
} else {
this.increment();
}
}
public ngOnInit(): void {
this.updateDefaultFormat();
this.setMask(this.inputFormat);
this.updateMask();
}
/** @hidden @internal */
public ngOnChanges(changes: SimpleChanges): void {
if (changes['locale'] && !changes['locale'].firstChange) {
this.updateDefaultFormat();
if (!this._inputFormat) {
this.setMask(this.inputFormat);
this.updateMask();
}
}
if (changes['inputFormat'] && !changes['inputFormat'].firstChange) {
this.updateMask();
}
}
/** Clear the input element value. */
public clear(): void {
this._onClear = true;
this.updateValue(null);
this.setSelectionRange(0, this.inputValue.length);
this._onClear = false;
}
/**
* Increment specified DatePart.
*
* @param datePart The optional DatePart to increment. Defaults to Date or Hours (when Date is absent from the inputFormat - ex:'HH:mm').
* @param delta The optional delta to increment by. Overrides `spinDelta`.
*/
public increment(datePart?: DatePart, delta?: number): void {
const targetPart = datePart || this.targetDatePart;
if (!targetPart) {
return;
}
const newValue = this.trySpinValue(targetPart, delta);
this.updateValue(newValue);
}
/**
* Decrement specified DatePart.
*
* @param datePart The optional DatePart to decrement. Defaults to Date or Hours (when Date is absent from the inputFormat - ex:'HH:mm').
* @param delta The optional delta to decrement by. Overrides `spinDelta`.
*/
public decrement(datePart?: DatePart, delta?: number): void {
const targetPart = datePart || this.targetDatePart;
if (!targetPart) {
return;
}
const newValue = this.trySpinValue(targetPart, delta, true);
this.updateValue(newValue);
}
/** @hidden @internal */
public writeValue(value: any): void {
this._value = value;
this.setDateValue(value);
this.updateMask();
}
/** @hidden @internal */
public validate(control: AbstractControl): ValidationErrors | null {
if (!control.value) {
return null;
}
// InvalidDate handling
if (isDate(control.value) && !DateTimeUtil.isValidDate(control.value)) {
return { value: true };
}
let errors = {};
const value = DateTimeUtil.isValidDate(control.value) ? control.value : DateTimeUtil.parseIsoDate(control.value);
const minValueDate = DateTimeUtil.isValidDate(this.minValue) ? this.minValue : this.parseDate(this.minValue);
const maxValueDate = DateTimeUtil.isValidDate(this.maxValue) ? this.maxValue : this.parseDate(this.maxValue);
if (minValueDate || maxValueDate) {
errors = DateTimeUtil.validateMinMax(value,
minValueDate, maxValueDate,
this.hasTimeParts, this.hasDateParts);
}
return Object.keys(errors).length > 0 ? errors : null;
}
/** @hidden @internal */
public registerOnValidatorChange?(fn: () => void): void {
this.onValidatorChange = fn;
}
/** @hidden @internal */
public registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
/** @hidden @internal */
public registerOnTouched(fn: any): void {
this.onTouchCallback = fn;
}
/** @hidden @internal */
public setDisabledState?(_isDisabled: boolean): void { }
/** @hidden @internal */
public onCompositionEnd(): void {
super.onCompositionEnd();
this.updateValue(this.parseDate(this.inputValue));
this.updateMask();
}
/** @hidden @internal */
public onInputChanged(event): void {
super.onInputChanged(event);
if (this._composing) {
return;
}
if (this.inputIsComplete()) {
const parsedDate = this.parseDate(this.inputValue);
if (DateTimeUtil.isValidDate(parsedDate)) {
this.updateValue(parsedDate);
} else {
const oldValue = this.value && new Date(this.dateValue.getTime());
const args: IgxDateTimeEditorEventArgs = { oldValue, newValue: parsedDate, userInput: this.inputValue };
this.validationFailed.emit(args);
if (DateTimeUtil.isValidDate(args.newValue)) {
this.updateValue(args.newValue);
} else {
this.updateValue(null);
}
}
} else {
this.updateValue(null);
}
}
/** @hidden @internal */
public onKeyDown(event: KeyboardEvent): void {
if (this.nativeElement.readOnly) {
return;
}
super.onKeyDown(event);
const key = event.key;
if (event.altKey) {
return;
}
if (key === this.platform.KEYMAP.ARROW_DOWN || key === this.platform.KEYMAP.ARROW_UP) {
this.spin(event);
return;
}
if (event.ctrlKey && key === this.platform.KEYMAP.SEMICOLON) {
this.updateValue(new Date());
}
this.moveCursor(event);
}
/** @hidden @internal */
public onFocus(): void {
if (this.nativeElement.readOnly) {
return;
}
this._isFocused = true;
this.onTouchCallback();
this.updateMask();
super.onFocus();
}
/** @hidden @internal */
public onBlur(value: string): void {
this._isFocused = false;
if (!this.inputIsComplete() && this.inputValue !== this.emptyMask) {
this.updateValue(this.parseDate(this.inputValue));
} else {
this.updateMask();
}
// TODO: think of a better way to set displayValuePipe in mask directive
if (this.displayValuePipe) {
return;
}
super.onBlur(value);
}
// the date editor sets its own inputFormat as its placeholder if none is provided
/** @hidden */
protected setPlaceholder(_value: string): void { }
private updateDefaultFormat(): void {
this._defaultInputFormat = DateTimeUtil.getDefaultInputFormat(this.locale);
}
private updateMask(): void {
if (this._isFocused) {
// store the cursor position as it will be moved during masking
const cursor = this.selectionEnd;
this.inputValue = this.getMaskedValue();
this.setSelectionRange(cursor);
} else {
if (!this.dateValue || !DateTimeUtil.isValidDate(this.dateValue)) {
this.inputValue = '';
return;
}
if (this.displayValuePipe) {
// TODO: remove when formatter func has been deleted
this.inputValue = this.displayValuePipe.transform(this.value);
return;
}
const format = this.displayFormat || this.inputFormat;
if (format) {
this.inputValue = DateTimeUtil.formatDate(this.dateValue, format.replace('tt', 'aa'), this.locale);
} else {
this.inputValue = this.dateValue.toLocaleString();
}
}
}
private setMask(inputFormat: string): void {
const oldFormat = this._inputDateParts?.map(p => p.format).join('');
this._inputDateParts = DateTimeUtil.parseDateTimeFormat(inputFormat);
inputFormat = this._inputDateParts.map(p => p.format).join('');
const mask = (inputFormat || DateTimeUtil.DEFAULT_INPUT_FORMAT)
.replace(new RegExp(/(?=[^t])[\w]/, 'g'), '0');
this.mask = mask.indexOf('tt') !== -1 ? mask.replace(new RegExp('tt', 'g'), 'LL') : mask;
const placeholder = this.nativeElement.placeholder;
if (!placeholder || oldFormat === placeholder) {
this.renderer.setAttribute(this.nativeElement, 'placeholder', inputFormat);
}
}
private parseDate(val: string): Date | null {
if (!val) {
return null;
}
return DateTimeUtil.parseValueFromMask(val, this._inputDateParts, this.promptChar);
}
private getMaskedValue(): string {
let mask = this.emptyMask;
if (DateTimeUtil.isValidDate(this.value)) {
for (const part of this._inputDateParts) {
if (part.type === DatePart.Literal) {
continue;
}
const targetValue = this.getPartValue(part, part.format.length);
mask = this.maskParser.replaceInMask(mask, targetValue, this.maskOptions, part.start, part.end).value;
}
return mask;
}
if (!this.inputIsComplete() || !this._onClear) {
return this.inputValue;
}
return mask;
}
private valueInRange(value: Date): boolean {
if (!value) {
return false;
}
let errors = {};
const minValueDate = DateTimeUtil.isValidDate(this.minValue) ? this.minValue : this.parseDate(this.minValue);
const maxValueDate = DateTimeUtil.isValidDate(this.maxValue) ? this.maxValue : this.parseDate(this.maxValue);
if (minValueDate || maxValueDate) {
errors = DateTimeUtil.validateMinMax(value,
this.minValue, this.maxValue,
this.hasTimeParts, this.hasDateParts);
}
return Object.keys(errors).length === 0;
}
private spinValue(datePart: DatePart, delta: number): Date {
if (!this.dateValue || !DateTimeUtil.isValidDate(this.dateValue)) {
return null;
}
const newDate = new Date(this.dateValue.getTime());
switch (datePart) {
case DatePart.Date:
DateTimeUtil.spinDate(delta, newDate, this.spinLoop);
break;
case DatePart.Month:
DateTimeUtil.spinMonth(delta, newDate, this.spinLoop);
break;
case DatePart.Year:
DateTimeUtil.spinYear(delta, newDate);
break;
case DatePart.Hours:
DateTimeUtil.spinHours(delta, newDate, this.spinLoop);
break;
case DatePart.Minutes:
DateTimeUtil.spinMinutes(delta, newDate, this.spinLoop);
break;
case DatePart.Seconds:
DateTimeUtil.spinSeconds(delta, newDate, this.spinLoop);
break;
case DatePart.AmPm:
const formatPart = this._inputDateParts.find(dp => dp.type === DatePart.AmPm);
const amPmFromMask = this.inputValue.substring(formatPart.start, formatPart.end);
return DateTimeUtil.spinAmPm(newDate, this.dateValue, amPmFromMask);
}
return newDate;
}
private trySpinValue(datePart: DatePart, delta?: number, negative = false): Date {
if (!delta) {
// default to 1 if a delta is set to 0 or any other falsy value
delta = this.datePartDeltas[datePart] || 1;
}
const spinValue = negative ? -Math.abs(delta) : Math.abs(delta);
return this.spinValue(datePart, spinValue) || new Date();
}
private setDateValue(value: Date | string): void {
this._dateValue = DateTimeUtil.isValidDate(value)
? value
: DateTimeUtil.parseIsoDate(value);
}
private updateValue(newDate: Date): void {
this._oldValue = this.dateValue;
this.value = newDate;
// TODO: should we emit events here?
if (this.inputIsComplete() || this.inputValue === this.emptyMask) {
this.valueChange.emit(this.dateValue);
}
if (this.dateValue && !this.valueInRange(this.dateValue)) {
this.validationFailed.emit({ oldValue: this._oldValue, newValue: this.dateValue, userInput: this.inputValue });
}
}
private toTwelveHourFormat(value: string): number {
let hour = parseInt(value.replace(new RegExp(this.promptChar, 'g'), '0'), 10);
if (hour > 12) {
hour -= 12;
} else if (hour === 0) {
hour = 12;
}
return hour;
}
private getPartValue(datePartInfo: DatePartInfo, partLength: number): string {
let maskedValue;
const datePart = datePartInfo.type;
switch (datePart) {
case DatePart.Date:
maskedValue = this.dateValue.getDate();
break;
case DatePart.Month:
// months are zero based
maskedValue = this.dateValue.getMonth() + 1;
break;
case DatePart.Year:
if (partLength === 2) {
maskedValue = this.prependValue(
parseInt(this.dateValue.getFullYear().toString().slice(-2), 10), partLength, '0');
} else {
maskedValue = this.dateValue.getFullYear();
}
break;
case DatePart.Hours:
if (datePartInfo.format.indexOf('h') !== -1) {
maskedValue = this.prependValue(
this.toTwelveHourFormat(this.dateValue.getHours().toString()), partLength, '0');
} else {
maskedValue = this.dateValue.getHours();
}
break;
case DatePart.Minutes:
maskedValue = this.dateValue.getMinutes();
break;
case DatePart.Seconds:
maskedValue = this.dateValue.getSeconds();
break;
case DatePart.AmPm:
maskedValue = this.dateValue.getHours() >= 12 ? 'PM' : 'AM';
break;
}
if (datePartInfo.type !== DatePart.AmPm) {
return this.prependValue(maskedValue, partLength, '0');
}
return maskedValue;
}
private prependValue(value: number, partLength: number, prependChar: string): string {
return (prependChar + value.toString()).slice(-partLength);
}
private spin(event: KeyboardEvent): void {
event.preventDefault();
switch (event.key) {
case this.platform.KEYMAP.ARROW_UP:
this.increment();
break;
case this.platform.KEYMAP.ARROW_DOWN:
this.decrement();
break;
}
}
private inputIsComplete(): boolean {
return this.inputValue.indexOf(this.promptChar) === -1;
}
private moveCursor(event: KeyboardEvent): void {
const value = (event.target as HTMLInputElement).value;
switch (event.key) {
case this.platform.KEYMAP.ARROW_LEFT:
if (event.ctrlKey) {
event.preventDefault();
this.setSelectionRange(this.getNewPosition(value));
}
break;
case this.platform.KEYMAP.ARROW_RIGHT:
if (event.ctrlKey) {
event.preventDefault();
this.setSelectionRange(this.getNewPosition(value, 1));
}
break;
}
}
/**
* Move the cursor in a specific direction until it reaches a date/time separator.
* Then return its index.
*
* @param value The string it operates on.
* @param direction 0 is left, 1 is right. Default is 0.
*/
private getNewPosition(value: string, direction = 0): number {
const literals = this._inputDateParts.filter(p => p.type === DatePart.Literal);
let cursorPos = this.selectionStart;
if (!direction) {
do {
cursorPos = cursorPos > 0 ? --cursorPos : cursorPos;
} while (!literals.some(l => l.end === cursorPos) && cursorPos > 0);
return cursorPos;
} else {
do {
cursorPos++;
} while (!literals.some(l => l.start === cursorPos) && cursorPos < value.length);
return cursorPos;
}
}
}
@NgModule({
declarations: [IgxDateTimeEditorDirective],
exports: [IgxDateTimeEditorDirective]
})
export class IgxDateTimeEditorModule { } | the_stack |
import * as argparse from 'argparse';
import * as fs from 'fs';
import * as path from 'path';
import assert from 'assert';
import csvstringify from 'csv-stringify';
import JSONStream from 'JSONStream';
import * as StreamUtils from '../../../lib/utils/stream-utils';
import { argnameFromLabel } from './utils';
import { CSQADialogueTurn } from './csqa-converter';
const pfs = fs.promises;
interface CSQATypeMapperOptions {
domains ?: string[],
input_dir : string,
output : string,
wikidata : string,
wikidata_labels : string,
minimum_appearance : number,
minimum_percentage : number,
}
// map experiment name to CSQA type
const DOMAIN_MAP : Record<string, string> = {
'human': 'common_name',
'city': 'administrative_territorial_entity',
'country': 'designation_for_an_administrative_territorial_entity',
'art': 'work_of_art',
'song': 'release',
'music_band': 'musical_ensemble',
'game': 'application',
'organization': 'organization',
'disease': 'health_problem',
'tv': 'television_program',
'drug': 'drug'
};
class CSQATypeMapper {
private _inputDir : string;
private _output : string;
private _wikidata : string;
private _wikidataLabels : string;
private _minAppearance : number;
private _minPercentage : number;
private _domains ?: string[];
private _labels : Map<string, string|undefined>;
private _wikidataTypes : Map<string, string[]>;
private _wikidataSuperTypes : Map<string, string[]>;
private _typeMap : Map<string, any>;
constructor(options : CSQATypeMapperOptions) {
this._inputDir = options.input_dir;
this._output = options.output;
this._wikidata = options.wikidata;
this._wikidataLabels = options.wikidata_labels;
this._minAppearance = options.minimum_appearance;
this._minPercentage = options.minimum_percentage;
this._domains = options.domains ? options.domains.map((domain : string) => DOMAIN_MAP[domain] || domain) : undefined;
this._labels = new Map();
this._wikidataTypes = new Map();
this._wikidataSuperTypes = new Map();
this._typeMap = new Map();
}
private async _loadKB(kbfile : string) {
const pipeline = fs.createReadStream(kbfile).pipe(JSONStream.parse('$*'));
pipeline.on('data', async (item) => {
const entity = item.key;
const predicates = item.value;
if ('P31' in predicates) {
const entityTypes = predicates['P31'];
this._wikidataTypes.set(entity, entityTypes);
for (const type of entityTypes)
this._labels.set(type, undefined);
}
if ('P279' in predicates) {
const superTypes = predicates['P279'];
this._wikidataSuperTypes.set(entity, superTypes);
for (const type of superTypes)
this._labels.set(type, undefined);
}
});
pipeline.on('error', (error) => console.error(error));
await StreamUtils.waitEnd(pipeline);
}
private async _loadLabels() {
const pipeline = fs.createReadStream(this._wikidataLabels).pipe(JSONStream.parse('$*'));
pipeline.on('data', async (entity) => {
const qid = String(entity.key);
const label = String(entity.value);
if (this._labels.has(qid))
this._labels.set(qid, label);
});
pipeline.on('error', (error) => console.error(error));
await StreamUtils.waitEnd(pipeline);
}
async load() {
console.log('loading wikidata files ...');
for (const kbfile of this._wikidata)
await this._loadKB(kbfile);
console.log('loading wikidata labels ...');
await this._loadLabels();
}
private _processDialog(dialog : CSQADialogueTurn[]) {
let userTurn, systemTurn;
for (const turn of dialog) {
if (turn.speaker === 'USER') {
userTurn = turn;
continue;
}
assert(userTurn && turn.speaker === 'SYSTEM');
systemTurn = turn;
// extract examples from type 2.2.1, where an singular object-based question is asked.
// ie., given a relation and an object in the triple, asking for the subject
if (userTurn.ques_type_id === 2 && userTurn.sec_ques_type === 2 && userTurn.sec_ques_sub_type === 1) {
assert(userTurn.type_list && userTurn.type_list.length === 1);
const csqaType = userTurn.type_list[0];
if (!this._typeMap.has(csqaType))
this._typeMap.set(csqaType, { total: 0 });
const answer = systemTurn.entities_in_utterance!;
for (const entity of answer) {
if (!this._wikidataTypes.has(entity))
continue;
for (const type of this._wikidataTypes.get(entity) ?? []) {
const map = this._typeMap.get(csqaType);
map.total += 1;
if (!(type in map))
map[type] = 1;
else
map[type] +=1;
}
}
}
}
}
private async _processFile(file : string) {
const dialog = JSON.parse(await pfs.readFile(file, { encoding: 'utf8' }));
this._processDialog(dialog);
}
private async _processDir(dir : string) {
const files = await pfs.readdir(dir);
for (const file of files) {
const fpath = path.join(dir, file);
const stats = await pfs.lstat(fpath);
if (stats.isDirectory() || stats.isSymbolicLink())
await this._processDir(fpath);
else if (file.startsWith('QA') && file.endsWith('.json'))
await this._processFile(fpath);
}
}
async process() {
console.log('start processing dialogs');
await this._processDir(this._inputDir);
}
/**
* Output the type mapping in a tsv format, where each column shows
* 1. CSQA domain name (label of wikidata type)
* 2. CSQA domain wikidata type (QID)
* 3. the actual wikidata types for entities in the CSQA domain (filtered, used as the type map)
* 4. the actual wikidata types for entities in the CSQA domain (unfiltered, used as a reference only)
*
* each wikidata type in 3 and 4 is in the following format, and separated by space
* <QID>:<label>:<# of appearance in CSQA>
*
*/
async write() {
const sortByCount = function(a : string, b : string) {
if (a.split(':')[2] < b.split(':')[2])
return 1;
return -1;
};
console.log('write type mapping to file ...');
const output = csvstringify({ header: false, delimiter: '\t' });
output.pipe(fs.createWriteStream(this._output, { encoding: 'utf8' }));
for (const [csqaType, counter] of this._typeMap) {
const label = this._labels.get(csqaType);
if (!label) {
console.error(`Found no label for CSQA type ${csqaType}`);
continue;
}
if (this._domains && !this._domains.includes(argnameFromLabel(label)))
continue;
const mappedTypes = [];
const allTypes = [];
const total = counter.total;
if (total < this._minAppearance)
continue;
for (const type in counter) {
if (type === 'total')
continue;
const label = this._labels.get(type);
if (!label) {
console.error(`Found no label for Wikidata type ${csqaType}`);
continue;
}
const entry = `${type}:${argnameFromLabel(label)}:${counter[type]}`;
allTypes.push(entry);
if (counter[type] < this._minPercentage * total)
continue;
if (type !== csqaType) {
const superTypes = this._wikidataSuperTypes.get(type);
if (!superTypes || !superTypes.includes(csqaType))
continue;
}
mappedTypes.push(entry);
}
// HACK: in case no mapped type is found, i.e., none of the wikidata types
// are subtypes of the csqa type, then remove the subtype requirement
// but use a higher threshold
if (mappedTypes.length === 0) {
for (const entry of allTypes) {
const [,, count] = entry.split(':');
if (parseInt(count) > this._minPercentage * 2 * total)
mappedTypes.push(entry);
}
}
output.write([
argnameFromLabel(label),
csqaType,
mappedTypes.sort(sortByCount).join(' '),
allTypes.sort(sortByCount).join(' ')
]);
}
StreamUtils.waitFinish(output);
}
}
module.exports = {
initArgparse(subparsers : argparse.SubParser) {
const parser = subparsers.add_parser('wikidata-csqa-type-map', {
add_help: true,
description: "Collect how types in CSQA map to wikidata types"
});
parser.add_argument('-i', '--input-dir', {
required: true,
help: 'the directory containing the raw CSQA examples'
});
parser.add_argument('-o', '--output', {
required: true,
help: 'the path to the output json containing the type mapping in CSQA'
});
parser.add_argument('--minimum-appearance', {
required: false,
type: Number,
default: 50,
help: 'the minimum number of appearance of a CSQA type to be included in the output'
});
parser.add_argument('--minimum-percentage', {
required: false,
type: Number,
default: 0.05,
help: 'within a domain, the minimum percentage for a Wikidata type to be included in the type map'
});
parser.add_argument('--wikidata', {
required: true,
nargs: '+',
help: "full knowledge base of wikidata, named wikidata_short_1.json and wikidata_short_2.json"
});
parser.add_argument('--wikidata-labels', {
required: true,
help: "wikidata labels"
});
parser.add_argument('--domains', {
required: false,
nargs: '+',
help: "domains to include, if available, all other domains will be excluded"
});
},
async execute(args : any) {
const analyzer = new CSQATypeMapper(args);
await analyzer.load();
await analyzer.process();
await analyzer.write();
}
}; | the_stack |
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import {expect} from 'chai';
import * as sinon from 'sinon';
import {vscode} from '../utils';
import PersistentSettings from '../../src/lib/persistent-settings';
import {IState} from '../../typings/interfaces/persistent-settings';
const globalStoragePath = path.join(os.tmpdir(), 'vsc-material-theme');
describe('PersistentSettings: tests', function (): void {
context('ensures that', function (): void {
context('getting the settings', function (): void {
it('more than once, returns the same instance', function (): void {
const persistentSettings = new PersistentSettings(vscode, globalStoragePath);
const settings = persistentSettings.getSettings();
const settingsAgain = persistentSettings.getSettings();
expect(settings).to.be.an.instanceOf(Object);
expect(settingsAgain).to.be.an.instanceOf(Object);
expect(settingsAgain).to.be.deep.equal(settings);
});
context('returns the correct name when application is the', function (): void {
it('`Code - Insiders`', function (): void {
vscode.env.appName = 'Visual Studio Code - Insiders';
const settings = new PersistentSettings(vscode, globalStoragePath).getSettings();
expect(settings.isInsiders).to.be.true;
expect(settings.isOSS).to.be.false;
expect(settings.isDev).to.be.false;
});
it('`Code`', function (): void {
vscode.env.appName = 'Visual Studio Code';
const settings = new PersistentSettings(vscode, globalStoragePath).getSettings();
expect(settings.isInsiders).to.be.false;
expect(settings.isOSS).to.be.false;
expect(settings.isDev).to.be.false;
});
// it('`Code - OSS`', function () {
// vscode.env.appName = 'VSCode OSS';
// const settings = new PersistentSettings(vscode).getSettings();
// expect(settings.isInsiders).to.be.false;
// expect(settings.isOSS).to.be.true;
// expect(settings.isDev).to.be.false;
// });
// it('`Code - OSS Dev`', function () {
// vscode.env.appName = 'VSCode OSS Dev';
// const settings = new PersistentSettings(vscode).getSettings();
// expect(settings.isInsiders).to.be.false;
// expect(settings.isOSS).to.be.false;
// expect(settings.isDev).to.be.true;
// });
});
});
});
context('ensures that', function (): void {
let persistentSettings: PersistentSettings;
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
persistentSettings = new PersistentSettings(vscode, globalStoragePath);
sandbox = sinon.createSandbox();
});
afterEach(() => {
persistentSettings = undefined as any;
sandbox.restore();
});
// it('the Error gets logged when writting the state fails', function () {
// const writeToFile = sandbox.stub(fs, 'writeFileSync').throws();
// const logStub = sandbox.stub(ErrorHandler, 'logError');
// const stateMock: IState = {
// version: '0.0.0',
// status: ExtensionStatus.notActivated,
// welcomeShown: false,
// };
// settingsManager.setState(stateMock);
// expect(logStub.called).to.be.true;
// expect(writeToFile.called).to.be.true;
// });
it('the state gets written to a settings file', function (): void {
const writeToFile = sandbox.stub(fs, 'writeFileSync');
const stateMock: IState = {
version: '0.0.0'
};
persistentSettings.setState(stateMock);
expect(writeToFile.called).to.be.true;
});
it('the settings status gets updated', function (): void {
const stateMock: IState = {
version: '1.0.0'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
const setState = sinon.stub(persistentSettings, 'setState');
persistentSettings.updateStatus();
expect(getState.called).to.be.true;
expect(setState.called).to.be.true;
});
it('the settings status does not get updated if no status is provided', function (): void {
const stateMock: IState = {
version: persistentSettings.getSettings().extensionSettings.version
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
const setState = sinon.stub(persistentSettings, 'setState');
const state = persistentSettings.updateStatus();
expect(getState.called).to.be.true;
expect(setState.called).to.be.true;
expect(state.version).to.be.equal(stateMock.version);
});
it('the settings file gets deleted', function (): void {
const deleteFile = sandbox.stub(fs, 'unlinkSync');
persistentSettings.deleteState();
expect(deleteFile.called).to.be.true;
});
context('getting the state', function (): void {
it('returns the state from the settings file', function (): void {
const stateMock: IState = {
version: '1.0.0'
};
sandbox.stub(fs, 'existsSync').returns(true);
sandbox.stub(fs, 'readFileSync').returns(JSON.stringify(stateMock));
const state = persistentSettings.getState();
expect(state).to.be.an.instanceOf(Object);
expect(state).to.have.all.keys('version');
expect(Object.keys(state)).to.have.lengthOf(1);
});
context('returns a default state when', function (): void {
it('no settings file exists', function (): void {
sandbox.stub(fs, 'existsSync').returns(false);
const state = persistentSettings.getState();
expect(state).to.be.instanceOf(Object);
expect(state.version).to.be.equal('0.0.0');
});
it('reading the file fails', function (): void {
sandbox.stub(fs, 'existsSync').returns(true);
sandbox.stub(fs, 'readFileSync').throws(Error);
sandbox.stub(console, 'error');
const state = persistentSettings.getState();
expect(state).to.be.instanceOf(Object);
expect(state.version).to.be.equal('0.0.0');
});
it('parsing the file content fails', function (): void {
sandbox.stub(fs, 'existsSync').returns(true);
sandbox.stub(fs, 'readFileSync').returns('test');
const state = persistentSettings.getState();
expect(state).to.be.instanceOf(Object);
expect(state.version).to.be.equal('0.0.0');
});
});
});
context('the `isNewVersion` function is', function (): void {
it('truthy for a new extension version', function (): void {
const stateMock: IState = {
version: '0.0.1'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isNewVersion()).to.be.true;
expect(getState.called).to.be.true;
});
it('falsy for the same extension version', function (): void {
const stateMock: IState = {
version: persistentSettings.getSettings().extensionSettings.version
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isNewVersion()).to.be.false;
expect(getState.called).to.be.true;
});
it('falsy for an older extension version', function (): void {
const stateMock: IState = {
version: '100.0.0'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isNewVersion()).to.be.false;
expect(getState.called).to.be.true;
});
it('falsy for a first install', function (): void {
const stateMock: IState = {
version: '0.0.0'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isNewVersion()).to.be.false;
expect(getState.called).to.be.true;
});
});
context('the `isFirstInstall` function is', function (): void {
it('truthy for a new installation (from 0.0.0)', function (): void {
const stateMock: IState = {
version: '0.0.0'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isFirstInstall()).to.be.true;
expect(getState.called).to.be.true;
});
it('falsy for a new extension version', function (): void {
const stateMock: IState = {
version: '0.0.1'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isFirstInstall()).to.be.false;
expect(getState.called).to.be.true;
});
it('falsy for the same extension version', function (): void {
const stateMock: IState = {
version: persistentSettings.getSettings().extensionSettings.version
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isFirstInstall()).to.be.false;
expect(getState.called).to.be.true;
});
it('falsy for an older extension version', function (): void {
const stateMock: IState = {
version: '100.0.0'
};
const getState = sinon
.stub(persistentSettings, 'getState')
.returns(stateMock);
persistentSettings.getSettings();
expect(persistentSettings.isFirstInstall()).to.be.false;
expect(getState.called).to.be.true;
});
});
});
}); | the_stack |
namespace LiteMol.Viewer.PDBe.Data {
"use strict";
import Bootstrap = LiteMol.Bootstrap;
import Entity = Bootstrap.Entity;
import Transformer = Bootstrap.Entity.Transformer;
import Tree = Bootstrap.Tree;
import Transform = Tree.Transform;
import Visualization = Bootstrap.Visualization;
export const DensitySourceLabels = {
'electron-density': 'X-ray (from PDB Id)',
'emdb-pdbid': 'EMDB (from PDB Id)',
'emdb-id': 'EMDB (from EMDB Id)'
}
export const DensitySources: (keyof typeof DensitySourceLabels)[] = ['electron-density', 'emdb-pdbid', 'emdb-id'];
export interface DownloadDensityParams {
/**
* Default source is 'electron-density'
*/
sourceId?: keyof typeof DensitySourceLabels,
id?: string | { [sourceId: string]: string }
}
export interface DensityActionContext { id: string, refs: string[], groupRef?: string }
type DensityAction = Tree.Transformer.ActionWithContext<DensityActionContext>
function doElectron(a: Entity.Root, t: Transform<Entity.Root, Entity.Action, DownloadDensityParams>, id: string): DensityAction {
let action = Bootstrap.Tree.Transform.build();
id = id.trim().toLowerCase();
let groupRef = t.props.ref ? t.props.ref : Bootstrap.Utils.generateUUID();
let group = action.add(a, Transformer.Basic.CreateGroup, { label: id, description: 'Density' }, { ref: groupRef })
let diffRef = Bootstrap.Utils.generateUUID();
let mainRef = Bootstrap.Utils.generateUUID();
let diff = group
.then(Transformer.Data.Download, { url: `https://www.ebi.ac.uk/pdbe/coordinates/files/${id}_diff.ccp4`, type: 'Binary', id, description: 'Fo-Fc', title: 'Density' })
.then(Transformer.Density.ParseData, { format: LiteMol.Core.Formats.Density.SupportedFormats.CCP4, id: 'Fo-Fc' }, { isBinding: true, ref: diffRef });
diff
.then(Transformer.Density.CreateVisualBehaviour, {
id: 'Fo-Fc(-ve)',
isoSigmaMin: -5,
isoSigmaMax: 0,
minRadius: 0,
maxRadius: 10,
radius: 5,
showFull: false,
style: Visualization.Density.Style.create({
isoValue: -3,
isoValueType: Bootstrap.Visualization.Density.IsoValueType.Sigma,
color: LiteMol.Visualization.Color.fromHex(0xBB3333), // can also use fromRgb(0-255 ranges), fromHsl, fromHsv; found in Visualization/Base/Theme.ts
isWireframe: true,
transparency: { alpha: 1.0 }
})
});
diff
.then(Transformer.Density.CreateVisualBehaviour, {
id: 'Fo-Fc(+ve)',
isoSigmaMin: 0,
isoSigmaMax: 5,
minRadius: 0,
maxRadius: 10,
radius: 5,
showFull: false,
style: Visualization.Density.Style.create({
isoValue: 3,
isoValueType: Bootstrap.Visualization.Density.IsoValueType.Sigma,
color: LiteMol.Visualization.Color.fromHex(0x33BB33),
isWireframe: true,
transparency: { alpha: 1.0 }
})
});
group
.then(Transformer.Data.Download, { url: `https://www.ebi.ac.uk/pdbe/coordinates/files/${id}.ccp4`, type: 'Binary', id, description: '2Fo-Fc', title: 'Density' })
.then(Transformer.Density.ParseData, { format: LiteMol.Core.Formats.Density.SupportedFormats.CCP4, id: '2Fo-Fc' }, { isBinding: true, ref: mainRef })
.then(Transformer.Density.CreateVisualBehaviour, {
id: '2Fo-Fc',
isoSigmaMin: 0,
isoSigmaMax: 2,
minRadius: 0,
maxRadius: 10,
radius: 5,
showFull: false,
style: Visualization.Density.Style.create({
isoValue: 1.5,
isoValueType: Bootstrap.Visualization.Density.IsoValueType.Sigma,
color: LiteMol.Visualization.Color.fromHex(0x3362B2),
isWireframe: false,
transparency: { alpha: 0.4 }
})
});
return {
action,
context: { id, refs: [mainRef, diffRef], groupRef }
};
}
function doEmdb(a: Entity.Root, t: Transform<Entity.Root, Entity.Action, DownloadDensityParams>, id: string, contourLevel?: number): DensityAction {
let action = Bootstrap.Tree.Transform.build();
let mainRef = Bootstrap.Utils.generateUUID();
let labelId = 'EMD-' + id;
action
.add(a, Transformer.Data.Download, {
url: `https://www.ebi.ac.uk/pdbe/static/files/em/maps/emd_${id}.map.gz`,
type: 'Binary',
id: labelId,
description: 'EMDB Density',
responseCompression: Bootstrap.Utils.DataCompressionMethod.Gzip,
title: 'Density'
})
.then(Transformer.Density.ParseData, { format: LiteMol.Core.Formats.Density.SupportedFormats.CCP4, id: labelId }, { isBinding: true, ref: mainRef })
.then(Transformer.Density.CreateVisualBehaviour, {
id: 'Density',
isoSigmaMin: -5,
isoSigmaMax: 5,
minRadius: 0,
maxRadius: 50,
radius: 5,
showFull: false,
style: Visualization.Density.Style.create({
isoValue: contourLevel !== void 0 ? contourLevel : 1.5,
isoValueType: contourLevel !== void 0 ? Bootstrap.Visualization.Density.IsoValueType.Absolute : Bootstrap.Visualization.Density.IsoValueType.Sigma,
color: LiteMol.Visualization.Color.fromHex(0x638F8F),
isWireframe: false,
transparency: { alpha: 0.3 }
})
});
return {
action,
context: { id, refs: [mainRef] }
};
}
function fail(a: Entity.Root, message: string): DensityAction {
return {
action: Bootstrap.Tree.Transform.build()
.add(a, Transformer.Basic.Fail, { title: 'Density', message }),
context: <any>void 0
};
}
async function doEmdbPdbId(ctx: Bootstrap.Context, a: Entity.Root, t: Transform<Entity.Root, Entity.Action, DownloadDensityParams>, id: string) {
id = id.trim().toLowerCase();
let s = await Bootstrap.Utils.ajaxGetString(`https://www.ebi.ac.uk/pdbe/api/pdb/entry/summary/${id}`, 'PDB API').run(ctx)
try {
let json = JSON.parse(s);
let emdbId: string;
let e = json[id];
if (e && e[0] && e[0].related_structures) {
let emdb = e[0].related_structures.filter((s: any) => s.resource === 'EMDB');
if (!emdb.length) {
return fail(a, `No related EMDB entry found for '${id}'.`);
}
emdbId = emdb[0].accession.split('-')[1];
} else {
return fail(a, `No related EMDB entry found for '${id}'.`);
}
return doEmdbId(ctx, a, t, emdbId);
} catch (e) {
return fail(a, 'PDBe API call failed.');
}
}
async function doEmdbId(ctx: Bootstrap.Context, a: Entity.Root, t: Transform<Entity.Root, Entity.Action, DownloadDensityParams>, id: string) {
id = id.trim();
let s = await Bootstrap.Utils.ajaxGetString(`https://www.ebi.ac.uk/pdbe/api/emdb/entry/map/EMD-${id}`, 'EMDB API').run(ctx)
try {
let json = JSON.parse(s);
let contour: number | undefined = void 0;
let e = json['EMD-' + id];
if (e && e[0] && e[0].map && e[0].map.contour_level && e[0].map.contour_level.value !== void 0) {
contour = +e[0].map.contour_level.value;
}
return doEmdb(a, t, id, contour);
} catch (e) {
return fail(a, 'EMDB API call failed.');
}
}
// this creates the electron density based on the spec you sent me
export const DownloadDensity = Bootstrap.Tree.Transformer.actionWithContext<Entity.Root, Entity.Action, DownloadDensityParams, DensityActionContext>({
id: 'pdbe-density-download-data',
name: 'Density Data from PDBe',
description: 'Download density data from PDBe.',
from: [Entity.Root],
to: [Entity.Action],
defaultParams: () => ({
sourceId: 'electron-density',
id: {
'electron-density': '1cbs',
'emdb-id': '3121',
'emdb-pdbid': '5aco'
}
}),
validateParams: p => {
let source = p.sourceId ? p.sourceId : 'electron-density';
if (!p.id) return ['Enter Id'];
let id = typeof p.id === 'string' ? p.id : p.id[source];
return !id.trim().length ? ['Enter Id'] : void 0;
}
}, (context, a, t) => {
let id: string;
if (typeof t.params.id === 'string') id = t.params.id;
else id = t.params.id![t.params.sourceId!]
switch (t.params.sourceId || 'electron-density') {
case 'electron-density': return doElectron(a, t, id);
case 'emdb-id': return doEmdbId(context, a, t, id);
case 'emdb-pdbid': return doEmdbPdbId(context, a, t, id);
default: return fail(a, 'Unknown source.');
}
}, (ctx, actionCtx) => {
if (!actionCtx) return;
let { id, refs, groupRef } = actionCtx!;
let sel = ctx.select(Tree.Selection.byRef(...refs));
if (sel.length === refs.length) {
ctx.logger.message('Density loaded, click on a residue or an atom to view the data.');
} else if (sel.length > 0) {
ctx.logger.message('Density partially loaded, click on a residue or an atom to view the data.');
} else {
ctx.logger.error(`Density for ID '${id}' failed to load.`);
if (groupRef) {
Bootstrap.Command.Tree.RemoveNode.dispatch(ctx, groupRef);
}
}
});
} | the_stack |
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai'
import { spy } from 'sinon'
chai.use(sinonChai);
const expect = chai.expect
import * as Parser from 'storyboard-lang'
import checkPredicate from '../src/predicate'
import keyPathify from '../src/keyPathify'
// TODO: We have no tests for [unless foo] or [if not foo] (parsed as { not: {...predicate }})
// passageTests includes coverage for this, but it should be explicitly covered here
describe("predicates", () => {
let predicate: Parser.Predicate;
describe("predicate types", function() {
describe("lte", function() {
beforeEach(function() {
predicate = {"foo": {"lte": 5}}
});
it("should not fire for values greater than", function() {
const result = checkPredicate(predicate, {"foo": 10});
expect(result).to.be.false;
});
it("should fire for values less than", function() {
const result = checkPredicate(predicate, {"foo": 4});
expect(result).to.be.true;
});
it("should fire for values equal to", function() {
const result = checkPredicate(predicate, {"foo": 5});
expect(result).to.be.true;
});
});
describe("gte", function() {
beforeEach(function() {
predicate = {"foo": {"gte": 5}}
});
it("should not fire for values less than", function() {
const result = checkPredicate(predicate, {"foo": 4});
expect(result).to.be.false;
});
it("should fire for values greater than", function() {
const result = checkPredicate(predicate, {"foo": 6});
expect(result).to.be.true;
});
it("should fire for values equal to", function() {
const result = checkPredicate(predicate, {"foo": 5});
expect(result).to.be.true;
});
});
describe("eq", function() {
beforeEach(function() {
predicate = {"foo": {"eq": 5}}
});
context("numbers", function() {
it("should fire for equal values", function() {
const result = checkPredicate(predicate, {"foo": 5});
expect(result).to.be.true
})
it("should not fire for greater values", function() {
const result = checkPredicate(predicate, {"foo": 6});
expect(result).to.be.false
})
it("should not fire for lesser values", function() {
const result = checkPredicate(predicate, {"foo": 4});
expect(result).to.be.false
})
})
context("strings", function() {
it("should return true when two strings are equal", function() {
const predicate = {"foo": {"eq": "bar"}};
const result = checkPredicate(predicate, {foo: "bar"})
expect(result).to.be.true
})
it("should return false when two strings are not equal", function() {
const predicate = {"foo": {"eq": "bar"}};
const result = checkPredicate(predicate, {foo: "baz"})
expect(result).to.be.false
})
it("should return false when the input value is a substring", function() {
const predicate = {"foo": {"eq": "ba"}};
const result = checkPredicate(predicate, {foo: "bar"})
expect(result).to.be.false
})
it("should return false when the state value is a subtring", function() {
const predicate = {"foo": {"eq": "bar"}};
const result = checkPredicate(predicate, {foo: "ba"})
expect(result).to.be.false
})
context("when the equality value is a valid keypath", () => {
it("should return true if the keypath value matches", () => {
const predicate = {"a": {"eq": "b"}}
const state = {"a": "the answer", "b": "the answer"}
const result = checkPredicate(predicate, state)
expect(result).to.be.true
})
it("should return true when matching the exact string literal, not keypath-d", () => {
const predicate = {"a": {"eq": "exact match"}}
const state = {"a": "exact match", "exact match": "not it"}
const result = checkPredicate(predicate, state)
expect(result).to.be.true
})
})
})
})
describe("exists", function() {
describe("when asserting an object should exist", function() {
beforeEach(function() {
predicate = {"foo": {"exists": true}};
});
it("should return true if the object exists", function() {
const result = checkPredicate(predicate, {"foo": 5})
expect(result).to.be.true;
});
it("should return false if the object is undefined", function() {
const result = checkPredicate(predicate, {"foo": undefined})
expect(result).to.be.false;
});
it("should return false if the object key doesn't exist", function() {
const result = checkPredicate(predicate, {})
expect(result).to.be.false;
});
});
describe("when asserting an object shouldn't exist", function() {
beforeEach(function() {
predicate = {"foo": {"exists": false}};
});
it("should return false if the object exists", function() {
const result = checkPredicate(predicate, {"foo": 5})
expect(result).to.be.false;
});
it("should return true if the object is undefined", function() {
const result = checkPredicate(predicate, {"foo": undefined})
expect(result).to.be.true;
});
it("should return true if the object key doesn't exist", function() {
const result = checkPredicate(predicate, {})
expect(result).to.be.true;
});
});
});
});
describe("combining multiple conditions", function() {
describe("using an (implicit) AND", function() {
beforeEach(function() {
predicate = {"foo": {"lte": 10, "gte": 5}}
});
it("should return true when both are true", function() {
const result = checkPredicate(predicate, {"foo": 7});
expect(result).to.be.true;
});
it("should not return true when only one is true", function() {
const result1 = checkPredicate(predicate, {"foo": 4});
expect(result1).to.be.false;
const result2 = checkPredicate(predicate, {"foo": 11});
expect(result2).to.be.false;
});
})
describe("using an explicit AND", () => {
context("When used at the top level", () => {
beforeEach(function() {
predicate = {"and": [
{"foo": {"gte": 3}},
{"foo": {"lte": 5}}
]}
})
it("should not trigger when only the first condition is met", function() {
const result = checkPredicate(predicate, {foo: 6})
expect(result).to.be.false;
});
it("should not trigger when the only second condition is met", function() {
const result = checkPredicate(predicate, {foo: 2})
expect(result).to.be.false;
});
it("should fire when neither condition is met", function() {
const result = checkPredicate(predicate, {foo: 4})
expect(result).to.be.true;
});
})
})
describe("using an explicit OR", function() {
context("when used at the top level of the predicate", function() {
beforeEach(function() {
predicate = {"or": [
{"foo": {"eq": 3}},
{"foo": {"eq": 5}}
]}
})
it("should trigger when the first condition is met", function() {
const result = checkPredicate(predicate, {foo: 3})
expect(result).to.be.true;
});
it("should trigger when the second condition is met", function() {
const result = checkPredicate(predicate, {foo: 5})
expect(result).to.be.true;
});
it("should not fire when neither condition is met", function() {
const result = checkPredicate(predicate, {foo: 4})
expect(result).to.be.false;
});
})
// TODO: This behavior is deprecated?
context("within a predicate key", function() {
beforeEach(function() {
predicate = {"foo": {"or": [
{"eq": 3},
{"eq": 5}
]}}
})
it("should trigger when the first condition is met", function() {
const result = checkPredicate(predicate, {foo: 3})
expect(result).to.be.true;
});
it("should trigger when the second condition is met", function() {
const result = checkPredicate(predicate, {foo: 5})
expect(result).to.be.true;
});
it("should not fire when neither condition is met", function() {
const result = checkPredicate(predicate, {foo: 4})
expect(result).to.be.false;
});
})
})
});
describe("combining multiple variables", function() {
beforeEach(function() {
predicate = {"foo": {"lte": 10},
"bar": {"gte": 5}};
});
it("should return true when both are true", function() {
const result = checkPredicate(predicate, {"foo": 7, "bar": 7});
expect(result).to.be.true;
});
it("should not return true when only one is true", function() {
const result1 = checkPredicate(predicate, {"foo": 4, "bar": 4});
expect(result1).to.be.false;
const result2 = checkPredicate(predicate, {"foo": 11, "bar": 11});
expect(result2).to.be.false;
});
});
describe("random numbers", function() {
context("when the value is a random integer", function() {
let result1: boolean, result2: boolean, result3: boolean;
beforeEach(function() {
const predicate = {"foo": {
"eq": { "randInt": [0, 6] }
}}
result1 = checkPredicate(predicate, {foo: 4, rngSeed: "knownSeed"})
result2 = checkPredicate(predicate, {foo: 1, rngSeed: "knownSeed"})
result3 = checkPredicate(predicate, {foo: 0, rngSeed: "knownSeed"})
})
afterEach(function() {
keyPathify(undefined, {rngSeed: "erase"})
})
it.skip("should compare against a seeded random number", function() {
expect(result1).to.be.true
expect(result2).to.be.true
expect(result3).to.be.true
})
})
})
describe("keypath predicates", function() {
describe("checking the value of a keypath as input", function() {
context("when the value matches", function() {
it("should match the predicate", function() {
const predicate = {"foo.bar": {"lte": 10, "gte": 0}};
const state = {foo: {bar: 5}}
const result = checkPredicate(predicate, state);
expect(result).to.be.true;
});
});
context("when the predicate is not met", function() {
it("should not be a match", function() {
const predicate = {"foo.bar": {"exists": false}};
const state = {foo: {bar: 5}}
const result = checkPredicate(predicate, state);
expect(result).to.be.false;
});
});
})
describe("checking a value against a keypath value", function() {
context("when the value matches", function() {
it("should match the predicate", function() {
const predicate = {"foo": {"lte": "bar.baz", "gte": "bar.baz"}};
const state = {
foo: "hello",
bar: { baz: "hello" }
}
const result = checkPredicate(predicate, state);
expect(result).to.be.true;
});
});
context("when the predicate is not met", function() {
it("should not be a match", function() {
const predicate = {"foo": {"lte": "bar.baz"}};
const state = {
foo: 10,
bar: { baz: 5 }
}
const result = checkPredicate(predicate, state);
expect(result).to.be.false;
});
});
});
});
}) | the_stack |
import * as cdk from '@aws-cdk/core';
import * as iam from '@aws-cdk/aws-iam';
import * as sns from '@aws-cdk/aws-sns';
import * as cw from '@aws-cdk/aws-cloudwatch';
import * as cwa from '@aws-cdk/aws-cloudwatch-actions';
import * as cwe from '@aws-cdk/aws-events';
import * as cwl from '@aws-cdk/aws-logs';
import * as cwet from '@aws-cdk/aws-events-targets';
interface BLEASecurityAlarmStackProps extends cdk.StackProps {
notifyEmail: string;
cloudTrailLogGroupName: string;
}
export class BLEASecurityAlarmStack extends cdk.Stack {
public readonly alarmTopic: sns.Topic;
constructor(scope: cdk.Construct, id: string, props: BLEASecurityAlarmStackProps) {
super(scope, id, props);
// SNS Topic for Security Alarm
const secTopic = new sns.Topic(this, 'SecurityAlarmTopic');
new sns.Subscription(this, 'SecurityAlarmEmail', {
endpoint: props.notifyEmail,
protocol: sns.SubscriptionProtocol.EMAIL,
topic: secTopic,
});
this.alarmTopic = secTopic;
// Allow to publish message from CloudWatch
secTopic.addToResourcePolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
principals: [new iam.ServicePrincipal('cloudwatch.amazonaws.com')],
actions: ['sns:Publish'],
resources: [secTopic.topicArn],
}),
);
// --------------- ConfigRule Compliance Change Notification -----------------
// ConfigRule - Compliance Change
// See: https://docs.aws.amazon.com/config/latest/developerguide/monitor-config-with-cloudwatchevents.html
// See: https://aws.amazon.com/premiumsupport/knowledge-center/config-resource-non-compliant/?nc1=h_ls
// If you want to add rules to notify, add rule name text string to "configRuleName" array.
// Sample Rule 'bb-default-security-group-closed' is defined at lib/blea-config-rules-stack.ts
new cwe.Rule(this, 'BLEARuleConfigRules', {
description: 'CloudWatch Event Rule to send notification on Config Rule compliance changes.',
enabled: true,
eventPattern: {
source: ['aws.config'],
detailType: ['Config Rules Compliance Change'],
detail: {
configRuleName: ['bb-default-security-group-closed'],
newEvaluationResult: {
complianceType: ['NON_COMPLIANT'],
},
},
},
targets: [new cwet.SnsTopic(secTopic)],
});
// ------------------------ AWS Health Notification ---------------------------
// AWS Health - Notify any events on AWS Health
// See: https://aws.amazon.com/premiumsupport/knowledge-center/cloudwatch-notification-scheduled-events/?nc1=h_ls
new cwe.Rule(this, 'BLEARuleAwsHealth', {
description: 'Notify AWS Health event',
enabled: true,
eventPattern: {
source: ['aws.health'],
detailType: ['AWS Health Event'],
},
targets: [new cwet.SnsTopic(secTopic)],
});
// ------------ Detective guardrails from NIST standard template ----------------
// See: https://aws.amazon.com/quickstart/architecture/compliance-nist/?nc1=h_ls
// Security Groups Change Notification
// See: https://aws.amazon.com/premiumsupport/knowledge-center/monitor-security-group-changes-ec2/?nc1=h_ls
// from NIST template
new cwe.Rule(this, 'BLEARuleSecurityGroupChange', {
description: 'Notify to create, update or delete a Security Group.',
enabled: true,
eventPattern: {
source: ['aws.ec2'],
detailType: ['AWS API Call via CloudTrail'],
detail: {
eventSource: ['ec2.amazonaws.com'],
eventName: [
'AuthorizeSecurityGroupIngress',
'AuthorizeSecurityGroupEgress',
'RevokeSecurityGroupIngress',
'RevokeSecurityGroupEgress',
],
},
},
targets: [new cwet.SnsTopic(secTopic)],
});
// Network ACL Change Notification
// from NIST template
new cwe.Rule(this, 'BLEARuleNetworkAclChange', {
description: 'Notify to create, update or delete a Network ACL.',
enabled: true,
eventPattern: {
source: ['aws.ec2'],
detailType: ['AWS API Call via CloudTrail'],
detail: {
eventSource: ['ec2.amazonaws.com'],
eventName: [
'CreateNetworkAcl',
'CreateNetworkAclEntry',
'DeleteNetworkAcl',
'DeleteNetworkAclEntry',
'ReplaceNetworkAclEntry',
'ReplaceNetworkAclAssociation',
],
},
},
targets: [new cwet.SnsTopic(secTopic)],
});
// CloudTrail Change
// from NIST template
new cwe.Rule(this, 'BLEARuleCloudTrailChange', {
description: 'Notify to change on CloudTrail log configuration',
enabled: true,
eventPattern: {
detailType: ['AWS API Call via CloudTrail'],
detail: {
eventSource: ['cloudtrail.amazonaws.com'],
eventName: ['StopLogging', 'DeleteTrail', 'UpdateTrail'],
},
},
targets: [new cwet.SnsTopic(secTopic)],
});
// LogGroup Construct for CloudTrail
// Use LogGroup.fromLogGroupName() because...
// On ControlTower environment, it created by not BLEA but ControlTower. So we need to refer existent LogGroup.
// When you use BLEA Standalone version, the LogGroup is created by BLEA.
//
// Note:
// MetricFilter-based detection may delay for several minutes because of latency on CloudTrail Log delivery to CloudWatchLogs
// Use CloudWatch Events if you can, it deliver CloudTrail event faster.
// IAM event occur in us-east-1 region so if you want to detect it, you need to use MetrifFilter-based detection
// See: https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-aws-console-sign-in-events.html
//
const cloudTrailLogGroup = cwl.LogGroup.fromLogGroupName(this, 'CloudTrailLogGroup', props.cloudTrailLogGroupName);
// IAM Policy Change Notification
// from NIST template
const mfIAMPolicyChange = new cwl.MetricFilter(this, 'IAMPolicyChange', {
logGroup: cloudTrailLogGroup,
filterPattern: {
logPatternString:
'{($.eventName=DeleteGroupPolicy)||($.eventName=DeleteRolePolicy)||($.eventName=DeleteUserPolicy)||($.eventName=PutGroupPolicy)||($.eventName=PutRolePolicy)||($.eventName=PutUserPolicy)||($.eventName=CreatePolicy)||($.eventName=DeletePolicy)||($.eventName=CreatePolicyVersion)||($.eventName=DeletePolicyVersion)||($.eventName=AttachRolePolicy)||($.eventName=DetachRolePolicy)||($.eventName=AttachUserPolicy)||($.eventName=DetachUserPolicy)||($.eventName=AttachGroupPolicy)||($.eventName=DetachGroupPolicy)}',
},
metricNamespace: 'CloudTrailMetrics',
metricName: 'IAMPolicyEventCount',
metricValue: '1',
});
new cw.Alarm(this, 'IAMPolicyChangeAlarm', {
metric: mfIAMPolicyChange.metric({
period: cdk.Duration.seconds(300),
}),
evaluationPeriods: 1,
datapointsToAlarm: 1,
threshold: 1,
comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
alarmDescription: 'IAM Configuration changes detected!',
actionsEnabled: true,
statistic: cw.Statistic.SUM,
}).addAlarmAction(new cwa.SnsAction(secTopic));
// Unauthorized Attempts
// from NIST template
const mfUnauthorizedAttempts = new cwl.MetricFilter(this, 'UnauthorizedAttempts', {
logGroup: cloudTrailLogGroup,
filterPattern: {
logPatternString: '{($.errorCode=AccessDenied)||($.errorCode=UnauthorizedOperation)}',
},
metricNamespace: 'CloudTrailMetrics',
metricName: 'UnauthorizedAttemptsEventCount',
metricValue: '1',
});
new cw.Alarm(this, 'UnauthorizedAttemptsAlarm', {
metric: mfUnauthorizedAttempts.metric({
period: cdk.Duration.seconds(300),
}),
evaluationPeriods: 1,
datapointsToAlarm: 1,
threshold: 5,
comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
alarmDescription: 'Multiple unauthorized actions or logins attempted!',
actionsEnabled: true,
statistic: cw.Statistic.SUM,
}).addAlarmAction(new cwa.SnsAction(secTopic));
// NewAccessKeyCreated
// from NIST template
const mfNewAccessKeyCreated = new cwl.MetricFilter(this, 'NewAccessKeyCreated', {
logGroup: cloudTrailLogGroup,
filterPattern: {
logPatternString: '{($.eventName=CreateAccessKey)}',
},
metricNamespace: 'CloudTrailMetrics',
metricName: 'NewAccessKeyCreatedEventCount',
metricValue: '1',
});
new cw.Alarm(this, 'NewAccessKeyCreatedAlarm', {
metric: mfNewAccessKeyCreated.metric({
period: cdk.Duration.seconds(300),
}),
evaluationPeriods: 1,
datapointsToAlarm: 1,
threshold: 1,
comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
alarmDescription: 'Warning: New IAM access Eey was created. Please be sure this action was neccessary.',
actionsEnabled: true,
statistic: cw.Statistic.SUM,
}).addAlarmAction(new cwa.SnsAction(secTopic));
// Detect Root Activity from CloudTrail Log (For SecurityHub CIS 1.1)
// See: https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-cis-controls.html#securityhub-standards-cis-controls-1.1
// See: https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudwatch-alarms-for-cloudtrail-additional-examples.html
const mfRooUserPolicy = new cwl.MetricFilter(this, 'RootUserPolicyEventCount', {
logGroup: cloudTrailLogGroup,
filterPattern: {
logPatternString:
'{$.userIdentity.type="Root" && $.userIdentity.invokedBy NOT EXISTS && $.eventType !="AwsServiceEvent"}',
},
metricNamespace: 'CloudTrailMetrics',
metricName: 'RootUserPolicyEventCount',
metricValue: '1',
});
new cw.Alarm(this, 'RootUserPolicyEventCountAlarm', {
metric: mfRooUserPolicy.metric({
period: cdk.Duration.seconds(300),
}),
evaluationPeriods: 1,
datapointsToAlarm: 1,
threshold: 1,
comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
alarmDescription: 'Root user activity detected!',
actionsEnabled: true,
statistic: cw.Statistic.SUM,
}).addAlarmAction(new cwa.SnsAction(secTopic));
// ------------------- Other security services integration ----------------------
// SecurityHub - Imported
// Security Hub automatically sends all new findings and all updates to existing findings to EventBridge as Security Hub Findings - Imported events.
// See: https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-cwe-integration-types.html
//
// Security Hub Finding format
// See: https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-findings-format.html
new cwe.Rule(this, 'BLEARuleSecurityHub', {
description: 'CloudWatch Event Rule to send notification on SecurityHub all new findings and all updates.',
enabled: true,
eventPattern: {
source: ['aws.securityhub'],
detailType: ['Security Hub Findings - Imported'],
detail: {
findings: {
Severity: {
Label: ['CRITICAL', 'HIGH'],
},
Compliance: {
Status: ['FAILED'],
},
Workflow: {
Status: ['NEW', 'NOTIFIED'],
},
RecordState: ['ACTIVE'],
},
},
},
targets: [new cwet.SnsTopic(secTopic)],
});
// GuardDutyFindings
// Will alert for any Medium to High finding.
// See: https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings_cloudwatch.html
new cwe.Rule(this, 'BLEARuleGuardDuty', {
description: 'CloudWatch Event Rule to send notification on GuardDuty findings.',
enabled: true,
eventPattern: {
source: ['aws.guardduty'],
detailType: ['GuardDuty Finding'],
detail: {
severity: [
4, 4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5, 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6,
6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7, 7.0, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8,
8.0, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9,
],
},
},
targets: [new cwet.SnsTopic(secTopic)],
});
}
} | the_stack |
import child_process from "child_process";
import path from "path";
import fs from "fs-extra";
import { MacAddress } from "hap-nodejs";
import { IpcOutgoingEvent, IpcService } from "./ipcService";
import { ExternalPortService } from "./externalPortService";
import { HomebridgeAPI, PluginType } from "./api";
import { HomebridgeOptions } from "./server";
import { Logger, Logging } from "./logger";
import { Plugin } from "./plugin";
import { User } from "./user";
import {
AccessoryConfig,
BridgeConfiguration,
BridgeOptions,
HomebridgeConfig,
PlatformConfig,
} from "./bridgeService";
export const enum ChildProcessMessageEventType {
/**
* Sent from the child process when it is ready to accept config
*/
READY = "ready",
/**
* Sent to the child process with a ChildProcessLoadEventData payload
*/
LOAD = "load",
/**
* Sent from the child process once it has loaded the plugin
*/
LOADED = "loaded",
/**
* Sent to the child process telling it to start
*/
START = "start",
/**
* Sent from the child process when the bridge is online
*/
ONLINE = "online",
/**
* Sent from the child when it wants to request port allocation for an external accessory
*/
PORT_REQUEST = "portRequest",
/**
* Sent from the parent with the port allocation response
*/
PORT_ALLOCATED= "portAllocated",
}
export const enum ChildBridgeStatus {
/**
* When the child bridge is loading, or restarting
*/
PENDING = "pending",
/**
* The child bridge is online and has published it's accessory
*/
OK = "ok",
/**
* The bridge is shutting down, or the process ended unexpectedly
*/
DOWN = "down"
}
export interface ChildProcessMessageEvent<T> {
id: ChildProcessMessageEventType;
data?: T
}
export interface ChildProcessLoadEventData {
type: PluginType;
identifier: string;
pluginPath: string;
pluginConfig: Array<PlatformConfig | AccessoryConfig>;
bridgeConfig: BridgeConfiguration;
homebridgeConfig: HomebridgeConfig;
bridgeOptions: BridgeOptions;
}
export interface ChildProcessPluginLoadedEventData {
version: string;
}
export interface ChildProcessPortRequestEventData {
username: MacAddress;
}
export interface ChildProcessPortAllocatedEventData {
username: MacAddress;
port?: number;
}
export interface ChildMetadata {
status: ChildBridgeStatus;
username: MacAddress;
name: string;
plugin: string;
identifier: string;
pid?: number;
}
/**
* Manages the child processes of platforms/accessories being exposed as seperate forked bridges.
* A child bridge runs a single platform or accessory.
*/
export class ChildBridgeService {
private child?: child_process.ChildProcess;
private args: string[] = [];
private shuttingDown = false;
private lastBridgeStatus: ChildBridgeStatus = ChildBridgeStatus.PENDING;
private pluginConfig: Array<PlatformConfig | AccessoryConfig> = [];
private log: Logging = Logger.withPrefix(this.plugin.getPluginIdentifier());
private displayName?: string;
constructor(
public type: PluginType,
public identifier: string,
private plugin: Plugin,
private bridgeConfig: BridgeConfiguration,
private homebridgeConfig: HomebridgeConfig,
private homebridgeOptions: HomebridgeOptions,
private api: HomebridgeAPI,
private ipcService: IpcService,
private externalPortService: ExternalPortService,
) {
this.api.on("shutdown", () => {
this.shuttingDown = true;
this.teardown();
});
// make sure we don't hit the max listeners limit
this.api.setMaxListeners(this.api.getMaxListeners() + 1);
}
/**
* Start the child bridge service
*/
public start(): void {
this.setProcessFlags();
this.startChildProcess();
// set display name
if (this.pluginConfig.length > 1 || this.pluginConfig.length === 0) {
this.displayName = this.plugin.getPluginIdentifier();
} else {
this.displayName = this.pluginConfig[0]?.name || this.plugin.getPluginIdentifier();
}
// re-configured log with display name
this.log = Logger.withPrefix(this.displayName);
}
/**
* Add a config block to a child bridge.
* Platform child bridges can only contain one config block.
* @param config
*/
public addConfig(config: PlatformConfig | AccessoryConfig): void {
this.pluginConfig.push(config);
}
private get bridgeStatus(): ChildBridgeStatus {
return this.lastBridgeStatus;
}
private set bridgeStatus(value: ChildBridgeStatus) {
this.lastBridgeStatus = value;
this.ipcService.sendMessage(IpcOutgoingEvent.CHILD_BRIDGE_STATUS_UPDATE, this.getMetadata());
}
/**
* Start the child bridge process
*/
private startChildProcess(): void {
this.bridgeStatus = ChildBridgeStatus.PENDING;
this.child = child_process.fork(path.resolve(__dirname, "childBridgeFork.js"), this.args, {
silent: true,
});
this.child.stdout.on("data", (data) => {
process.stdout.write(data);
});
this.child.stderr.on("data", (data) => {
process.stderr.write(data);
});
this.child.on("exit", () => {
this.log.warn("Child bridge process ended");
});
this.child.on("error", (e) => {
this.bridgeStatus = ChildBridgeStatus.DOWN;
this.log.error("Child process error", e);
});
this.child.on("close", (code, signal) => {
this.bridgeStatus = ChildBridgeStatus.DOWN;
this.handleProcessClose(code, signal);
});
// handle incoming ipc messages from the child process
this.child.on("message", (message: ChildProcessMessageEvent<unknown>) => {
if (typeof message !== "object" || !message.id) {
return;
}
switch(message.id) {
case ChildProcessMessageEventType.READY: {
this.log(`Launched child bridge with PID ${this.child?.pid}`);
this.loadPlugin();
break;
}
case ChildProcessMessageEventType.LOADED: {
const version = (message.data as ChildProcessPluginLoadedEventData).version;
if (this.pluginConfig.length > 1) {
this.log(`Loaded ${this.plugin.getPluginIdentifier()} v${version} child bridge successfully with ${this.pluginConfig.length} accessories`);
} else {
this.log(`Loaded ${this.plugin.getPluginIdentifier()} v${version} child bridge successfully`);
}
this.startBridge();
break;
}
case ChildProcessMessageEventType.ONLINE: {
this.bridgeStatus = ChildBridgeStatus.OK;
break;
}
case ChildProcessMessageEventType.PORT_REQUEST: {
this.handlePortRequest(message.data as ChildProcessPortRequestEventData);
break;
}
}
});
}
/**
* Called when the child bridge process exits, if Homebridge is not shutting down, it will restart the process
* @param code
* @param signal
*/
private handleProcessClose(code: number, signal: string): void {
this.log(`Process Ended. Code: ${code}, Signal: ${signal}`);
setTimeout(() => {
if (!this.shuttingDown) {
this.log("Restarting Process...");
this.startChildProcess();
}
}, 7000);
}
/**
* Helper function to send a message to the child process
* @param type
* @param data
*/
private sendMessage<T = unknown>(type: ChildProcessMessageEventType, data?: T): void {
if (this.child && this.child.connected) {
this.child.send({
id: type,
data,
});
}
}
/**
* Some plugins may make use of the homebridge process flags
* These will be passed through to the forked process
*/
private setProcessFlags(): void {
if (this.homebridgeOptions.debugModeEnabled) {
this.args.push("-D");
}
if (this.homebridgeOptions.forceColourLogging) {
this.args.push("-C");
}
if (this.homebridgeOptions.insecureAccess) {
this.args.push("-I");
}
if (this.homebridgeOptions.noLogTimestamps) {
this.args.push("-T");
}
if (this.homebridgeOptions.keepOrphanedCachedAccessories) {
this.args.push("-K");
}
if (this.homebridgeOptions.customStoragePath) {
this.args.push("-U", this.homebridgeOptions.customStoragePath);
}
if (this.homebridgeOptions.customPluginPath) {
this.args.push("-P", this.homebridgeOptions.customPluginPath);
}
}
/**
* Tell the child process to load the given plugin
*/
private loadPlugin(): void {
const bridgeConfig: BridgeConfiguration = {
name: this.bridgeConfig.name || this.displayName || this.plugin.getPluginIdentifier(),
port: this.bridgeConfig.port,
username: this.bridgeConfig.username,
advertiser: this.homebridgeConfig.bridge.advertiser,
pin: this.bridgeConfig.pin || this.homebridgeConfig.bridge.pin,
bind: this.homebridgeConfig.bridge.bind,
setupID: this.bridgeConfig.setupID,
manufacturer: this.bridgeConfig.manufacturer || this.homebridgeConfig.bridge.manufacturer,
model: this.bridgeConfig.model || this.homebridgeConfig.bridge.model,
};
const bridgeOptions: BridgeOptions = {
cachedAccessoriesDir: User.cachedAccessoryPath(),
cachedAccessoriesItemName: "cachedAccessories." + this.bridgeConfig.username.replace(/:/g, "").toUpperCase(),
};
// shallow copy the homebridge options to the bridge options object
Object.assign(bridgeOptions, this.homebridgeOptions);
this.sendMessage<ChildProcessLoadEventData>(ChildProcessMessageEventType.LOAD, {
type: this.type,
identifier: this.identifier,
pluginPath: this.plugin.getPluginPath(),
pluginConfig: this.pluginConfig,
bridgeConfig,
bridgeOptions,
homebridgeConfig: { // need to break this out to avoid a circular structure to JSON from other plugins modifying their config at runtime.
bridge: this.homebridgeConfig.bridge,
mdns: this.homebridgeConfig.mdns,
ports: this.homebridgeConfig.ports,
disabledPlugins: [], // not used by child bridges
accessories: [], // not used by child bridges
platforms: [], // not used by child bridges
},
});
}
/**
* Tell the child bridge to start broadcasting
*/
private startBridge(): void {
this.sendMessage(ChildProcessMessageEventType.START);
}
/**
* Handle external port requests from child
*/
private async handlePortRequest(request: ChildProcessPortRequestEventData) {
const port = await this.externalPortService.requestPort(request.username);
this.sendMessage<ChildProcessPortAllocatedEventData>(ChildProcessMessageEventType.PORT_ALLOCATED, {
username: request.username,
port: port,
});
}
/**
* Send sigterm to the child bridge
*/
private teardown(): void {
if (this.child && this.child.connected) {
this.bridgeStatus = ChildBridgeStatus.DOWN;
this.child.kill("SIGTERM");
}
}
/**
* Restarts the child bridge process
*/
public restartBridge(): void {
this.log.warn("Restarting child bridge...");
this.refreshConfig();
this.teardown();
}
/**
* Read the config.json file from disk and refresh the plugin config block for just this plugin
*/
public async refreshConfig(): Promise<void> {
try {
const homebridgeConfig: HomebridgeConfig = await fs.readJson(User.configPath());
if (this.type === PluginType.PLATFORM) {
const config = homebridgeConfig.platforms?.filter(x => x.platform === this.identifier && x._bridge?.username === this.bridgeConfig.username);
if (config.length) {
this.pluginConfig = config;
this.bridgeConfig = this.pluginConfig[0]._bridge || this.bridgeConfig;
} else {
this.log.warn("Platform config could not be found, using existing config.");
}
} else if (this.type === PluginType.ACCESSORY) {
const config = homebridgeConfig.accessories?.filter(x => x.accessory === this.identifier && x._bridge?.username === this.bridgeConfig.username);
if (config.length) {
this.pluginConfig = config;
this.bridgeConfig = this.pluginConfig[0]._bridge || this.bridgeConfig;
} else {
this.log.warn("Accessory config could not be found, using existing config.");
}
}
} catch (e) {
this.log.error("Failed to refresh plugin config:", e.message);
}
}
/**
* Returns metadata about this child bridge
*/
public getMetadata(): ChildMetadata {
return {
status: this.bridgeStatus,
username: this.bridgeConfig.username,
name: this.bridgeConfig.name || this.displayName || this.plugin.getPluginIdentifier(),
plugin: this.plugin.getPluginIdentifier(),
identifier: this.identifier,
pid: this.child?.pid,
};
}
} | the_stack |
import React, { useState, useRef, useEffect, useCallback } from "react"
import ReactDOM from "react-dom"
import { Script } from "./script"
import { db } from "./data"
import { scriptsData } from "./script-data"
import { exportAllScripts } from "./script-export"
import { editor } from "./editor"
import { EventEmitter } from "./event"
import { config } from "./config"
import { dlog, isMac } from "./util"
import { WindowSize } from "../common/messages"
function scrollIntoView(e :HTMLElement) {
if ((e as any).scrollIntoViewIfNeeded) {
;(e as any).scrollIntoViewIfNeeded()
} else {
e.scrollIntoView()
}
}
interface MenuEvents {
"visibility": boolean
}
class Menu extends EventEmitter<MenuEvents> {
readonly isVisible = false
_uiel = document.getElementById('menu')
_resolveMenuUIMountPromise :(()=>void)|null
menuUIMountPromise = new Promise<void>(resolve => {
this._resolveMenuUIMountPromise = resolve
})
closeOnSelection = false
toggle(closeOnSelection :bool = false) {
;(this as any).isVisible = this._uiel.classList.toggle("visible", !this.isVisible)
document.body.classList.toggle("menuVisible", this.isVisible)
this.closeOnSelection = closeOnSelection
if (this.isVisible) {
ReactDOM.render(<MenuUI />, this._uiel)
} else if (editor.editor) {
editor.editor.focus()
}
this.triggerEvent("visibility", this.isVisible)
if (editor.editor) {
editor.editor.layout()
}
config.menuVisible = this.isVisible
}
init() {
if (config.menuVisible) {
this.toggle()
}
}
scrollToActiveItem() {
function focusActiveItem() :boolean {
let activeItem = document.querySelector("#menu .active") as HTMLElement|null
if (!activeItem) {
return false
}
scrollIntoView(activeItem)
return true
}
if (!focusActiveItem()) {
requestAnimationFrame(focusActiveItem)
}
}
}
export const menu = new Menu()
interface MenuProps {}
interface MenuState {
scripts :Script[]
exampleScripts :{[category:string]:Script[]}
referenceScripts :Script[]
currentScriptId :number
configVersion :number
isExportingScripts :boolean
}
export class MenuUI extends React.Component<MenuProps,MenuState> {
constructor(props :MenuProps) {
super(props)
this.state = {
scripts: scriptsData.scripts,
exampleScripts: scriptsData.exampleScripts,
referenceScripts: scriptsData.referenceScripts,
currentScriptId: editor.currentScriptId,
configVersion: config.version,
isExportingScripts: false,
}
}
// onNewScript = () => {
// editor.newScript({ name: scriptsData.nextNewScriptName() })
// }
scriptsDataChangeCallback = () => {
this.setState({
scripts: scriptsData.scripts,
currentScriptId: editor.currentScriptId,
})
}
onEditorModelChange = () => {
this.setState({ currentScriptId: editor.currentScriptId })
}
onConfigChange = () => {
this.setState({ configVersion: config.version })
}
componentDidMount() {
// menu._setUI(this)
scriptsData.on("change", this.scriptsDataChangeCallback)
editor.on("modelchange", this.onEditorModelChange)
config.on("change", this.onConfigChange)
menu._resolveMenuUIMountPromise()
menu._resolveMenuUIMountPromise = null
}
componentWillUnmount() {
scriptsData.removeListener("change", this.scriptsDataChangeCallback)
editor.removeListener("modelchange", this.onEditorModelChange)
config.removeListener("change", this.onConfigChange)
// menu._setUI(null)
}
onChangeSettingBool = (ev :any) => {
ev.persist()
let input = ev.target as HTMLInputElement
const configPrefix = "config."
if (input.name.startsWith(configPrefix)) {
let value :any = input.type == "checkbox" ? input.checked : input.value
;(config as any)[input.name.substr(configPrefix.length)] = !!value
}
}
onChangeSettingBoolNeg = (ev :any) => {
ev.persist()
let input = ev.target as HTMLInputElement
const configPrefix = "config."
if (input.name.startsWith(configPrefix)) {
let value :any = input.type == "checkbox" ? input.checked : input.value
;(config as any)[input.name.substr(configPrefix.length)] = !value
}
}
onChangeSettingPercent = (ev :any) => {
ev.persist()
let input = ev.target as HTMLInputElement
const configPrefix = "config."
if (input.name.startsWith(configPrefix)) {
let value = parseFloat(input.value)
if (!isNaN(value)) {
;(config as any)[input.name.substr(configPrefix.length)] = (Math.round(value) / 100)
}
}
}
onChangeSettingNum = (ev :any) => {
ev.persist()
let input = ev.target as HTMLInputElement
const configPrefix = "config."
if (input.name.startsWith(configPrefix)) {
let value = parseFloat(input.value)
if (!isNaN(value)) {
;(config as any)[input.name.substr(configPrefix.length)] = value
}
}
}
onChangeWindowSize = (ev :any) => {
let s = ev.target.value.split(",")
if (s.length > 1) {
let ws :[WindowSize,WindowSize] = [
WindowSize[s[0]] as unknown as WindowSize,
WindowSize[s[1]] as unknown as WindowSize,
]
if (ws) {
config.windowSize = ws
}
}
}
onExportAllScripts = (ev :any) => {
dlog("onExportAllScripts")
this.setState({ isExportingScripts: true })
exportAllScripts().then(() => {
this.setState({ isExportingScripts: false })
}).catch(err => {
console.error(`failed to export scripts: ${err.stack||err}`)
this.setState({ isExportingScripts: false })
})
}
render() {
// TODO: consider adding a button to "Reset defaults..." that deletes the database.
const state = (this as any).state as MenuState // fix for IDE type issues
let currentScriptId = state.currentScriptId
let windowSizeVal = config.windowSize.map(v => WindowSize[v]).join(",")
let examples = <div className="examples">
{Object.keys(state.exampleScripts).map(cat =>
<div key={cat} className="category">
{cat ? <h4>{cat}</h4> : <h3>Examples</h3>}
<ul>
{state.exampleScripts[cat].map(s =>
<MenuItem key={s.id} script={s} isActive={currentScriptId == s.id} />
)}
</ul>
</div>
)}
</div>
return (
<div>
{state.scripts.length > 0 ?
<ul>
{state.scripts.map(s =>
<MenuItem key={s.id} script={s} isActive={currentScriptId == s.id} />
)}
</ul> :
null
}
{examples}
<h3>API reference</h3>
<ul>
{state.referenceScripts.map(s =>
<MenuItem key={s.id} script={s} isActive={currentScriptId == s.id} /> )}
</ul>
<h3>Settings</h3>
<div className="settings">
<label>
<input type="checkbox"
name="config.showLineNumbers"
checked={config.showLineNumbers}
onChange={this.onChangeSettingBool} />
Line numbers
</label>
<label>
<input type="checkbox"
name="config.wordWrap"
checked={config.wordWrap}
onChange={this.onChangeSettingBool} />
Word wrap
</label>
<label title="Use the font JetBrains Mono instead of iA Writer Quattro">
<input type="checkbox"
name="config.monospaceFont"
checked={config.monospaceFont}
onChange={this.onChangeSettingBool} />
Monospace font
</label>
<label
className={"dependant" + (config.monospaceFont ? "" : " disabled")}
title="Enables fancy ligatures of the monospace font JetBrains Mono, like special glyphs for => and ==">
<input type="checkbox"
name="config.fontLigatures"
checked={config.fontLigatures}
onChange={this.onChangeSettingBool} />
Font ligatures
</label>
<label title="Visualize otherwise-invisible characters like spaces and tabs">
<input type="checkbox"
name="config.showWhitespace"
checked={config.showWhitespace}
onChange={this.onChangeSettingBool} />
Show whitespace
</label>
<label title="Show vertical indentation guides">
<input type="checkbox"
name="config.indentGuides"
checked={config.indentGuides}
onChange={this.onChangeSettingBool} />
Indentation guides
</label>
<label title="Enables a minimap for navigating large scripts">
<input type="checkbox"
name="config.minimap"
checked={config.minimap}
onChange={this.onChangeSettingBool} />
Minimap
</label>
<label title="Enables information cards shown when hovering over code snippets">
<input type="checkbox"
name="config.hoverCards"
checked={config.hoverCards}
onChange={this.onChangeSettingBool} />
Hover cards
</label>
<label title="Enables suggestions as you type">
<input type="checkbox"
name="config.quickSuggestions"
checked={config.quickSuggestions}
onChange={this.onChangeSettingBool} />
Quick suggestions
</label>
<label className={"dependant" + (config.quickSuggestions ? "" : " disabled")}>
<div className="icon delay" title="Quick suggestions delay" />
<input type="number"
step="100"
min="0" max="10000"
readOnly={!config.quickSuggestions}
name="config.quickSuggestionsDelay"
value={config.quickSuggestionsDelay}
onChange={this.onChangeSettingNum} />
<span>ms</span>
</label>
<label title="Pressing the TAB key inserts SPACE characters instead of TAB">
<input type="checkbox"
name="config.useTabs"
checked={!config.useTabs}
onChange={this.onChangeSettingBoolNeg} />
TAB inserts spaces
</label>
<label>
Tab size:
<input type="number"
step="1"
min="1" max="8"
name="config.tabSize"
value={config.tabSize}
onChange={this.onChangeSettingNum} />
</label>
<label title="Size of Scripter window">
<div className="icon window" />
<select name="config.windowSize" value={windowSizeVal} onChange={this.onChangeWindowSize}>
<option disabled={true}>Window W×H</option>
<option value={"SMALL,SMALL"} >S×S window</option>
<option value={"SMALL,MEDIUM"} >S×M window</option>
<option value={"SMALL,LARGE"} >S×L window</option>
<option value={"SMALL,XLARGE"} >S×MAX window</option>
<option value={"MEDIUM,SMALL"} >M×S window</option>
<option value={"MEDIUM,MEDIUM"}>M×M window</option>
<option value={"MEDIUM,LARGE"} >M×L window</option>
<option value={"MEDIUM,XLARGE"}>M×MAX window</option>
<option value={"LARGE,SMALL"} >L×S window</option>
<option value={"LARGE,MEDIUM"} >L×M window</option>
<option value={"LARGE,LARGE"} >L×L window</option>
<option value={"LARGE,XLARGE"} >L×MAX window</option>
<option value={"XLARGE,SMALL"} >XL×S window</option>
<option value={"XLARGE,MEDIUM"} >XL×M window</option>
<option value={"XLARGE,LARGE"} >XL×L window</option>
<option value={"XLARGE,XLARGE"} >XL×MAX window</option>
</select>
</label>
<label
title={`Scale of the Scripter editor text size (${isMac ? "⌘+/-" : "Ctrl+/-"})`}
>
<div className="icon text-size" />
{/* Note: Sync min & max with values in app.ts uiScaleSteps */}
<input type="number"
step="10"
min="50" max="300"
name="config.uiScale"
value={Math.round(config.uiScale * 100)}
onChange={this.onChangeSettingPercent} />
<span>%</span>
</label>
<div className="group extra-actions">
<button disabled={state.isExportingScripts}
onClick={state.isExportingScripts ? ()=>{} : this.onExportAllScripts}
>{state.isExportingScripts ? "Exporting..." : "Export all scripts"}</button>
</div>
</div>
</div>
)
}
}
interface MenuItemProps {
script :Script
isActive :boolean
}
function MenuItem(props :MenuItemProps) :JSX.Element {
let s = props.script
const [isEditing, setIsEditing] = useState(false)
let attrs :{[k:string]:any} = {
// tabIndex: 0,
className: (
(props.isActive ? "active" : "") +
(s.id == 0 ? " unsaved" : "")
),
}
if (!isEditing) {
function onMouseDown(ev :Event) {
if (menu.closeOnSelection) {
menu.toggle()
}
dlog("menu/open-script", s)
editor.openScriptByGUID(s.guid)
scrollIntoView(ev.target as HTMLElement)
}
attrs.onMouseDown = onMouseDown
if (!s.isROLib && s.id >= 0) {
// allow renaming of editable files which are either unsaved (id==0) or saved (id>0).
// however, do not allow renaming of editable example files (id<0).
attrs.onDoubleClick = ev => {
setIsEditing(true)
ev.preventDefault()
ev.stopPropagation()
}
attrs.onContextMenu = ev => {
setIsEditing(true)
ev.preventDefault()
ev.stopPropagation()
}
attrs.title = `Last modified ${s.modifiedAt.toLocaleString()}`
}
}
function deleteScript() {
let confirmMessage = `Delete script "${s.name}"?`
if (s.isSavedInFigma()) {
confirmMessage =
`Remove script "${s.name}" from menu? You can open later again from Figma.`
}
if (s.id > 0 && confirm(confirmMessage)) {
// TODO: move this logic to editor or maybe script-data?
let otherScriptToOpen = scriptsData.scriptAfterOrBefore(s.guid)
if (!otherScriptToOpen) {
// deleted last script -- we must always have one script, so make a new one
editor.newScript()
} else {
editor.openScriptByGUID(otherScriptToOpen.guid)
}
s.delete()
}
}
let didCommitEditing = false
function commitEditing(newName :string) :void {
if (didCommitEditing) {
return
}
didCommitEditing = true
newName = newName.trim()
if (newName.length == 0) {
deleteScript()
} else {
// Note: Scripts which are unsaved are only created when the body is non-empty.
// This means that if we create a new script, which starts out empty, and then
// rename it, the name is saved only in memory and the script is not persisted
// until some edit is done to the body.
if (s.name != newName) {
s.name = newName
// even though setting the name implies scheduleSave, we save immediately
// so that the UI updates quickly (e.g. window title.)
s.save()
}
}
setIsEditing(false)
}
function cancelEditing() :void {
setIsEditing(false)
}
let valueProps :MenuItemValueProps = {
name: s.name,
isEditing,
commitEditing,
cancelEditing,
}
let buttons :JSX.Element[] = []
if (!isEditing && !s.isROLib) {
async function onClickPlayButton(ev :React.MouseEvent<HTMLDivElement>) {
ev.preventDefault()
ev.stopPropagation()
await editor.openScriptByID(s.id)
editor.runCurrentScript()
}
buttons = [
// U+2009 THIN SPACE offsets U+25B6 BLACK RIGHT-POINTING TRIANGLE
<MenuItemButton key="play" className="play" title={"\u2009▶"}
tooltip={props.isActive ? "Run script" : "Open & Run script"}
onClick={onClickPlayButton} />,
]
if (s.id > 0) {
async function onClickDeleteButton(ev :React.MouseEvent<HTMLDivElement>) {
deleteScript()
}
buttons.unshift(
<MenuItemButton key="delete" className="delete" title={"✗"}
tooltip="Delete script"
onClick={onClickDeleteButton} />
)
}
}
return (
<li {...attrs}>
<MenuItemValue {...valueProps} />
{buttons}
</li>
)
}
interface MenuItemButtonProps {
title :string
className :string
tooltip? :string
onClick :(e:React.MouseEvent<HTMLDivElement>)=>void
}
function MenuItemButton(props :MenuItemButtonProps) :JSX.Element {
return <div
className={"button " + props.className}
onClick={props.onClick}
title={props.tooltip}
>{props.title}</div>
}
interface MenuItemValueProps {
name :string
isEditing :boolean
commitEditing(newName :string) :void
cancelEditing() :void
}
function MenuItemValue(props :MenuItemValueProps) :JSX.Element {
const [editName, setEditName] = useState(props.name)
const [needsSelectAll, setNeedsSelectAll] = useState(true)
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (!props.isEditing) {
// reset edit-state values when not editing
if (editName !== props.name) { setEditName(props.name) }
if (!needsSelectAll) { setNeedsSelectAll(true) }
return
}
if (needsSelectAll && inputRef.current) {
inputRef.current.select()
setNeedsSelectAll(false)
}
})
if (!props.isEditing) {
return <span className="name">{props.name}</span>
}
function onChange(ev) {
setEditName(ev.target.value)
}
function onKeyDown(ev) {
if (ev.key == "Enter") {
props.commitEditing(editName)
ev.preventDefault()
ev.stopPropagation()
} else if (ev.key == "Escape") {
props.cancelEditing()
ev.preventDefault()
ev.stopPropagation()
}
}
function onBlur() {
props.commitEditing(editName)
}
return <input type="text" autoFocus
{...{value: editName, ref: inputRef, onChange, onBlur, onKeyDown }} />
} | the_stack |
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { AwsKmsMrkAwareSymmetricKeyringClass } from '../src/kms_mrk_keyring'
import {
NodeAlgorithmSuite,
AlgorithmSuiteIdentifier,
KeyringTraceFlag,
NodeDecryptionMaterial,
EncryptedDataKey,
Keyring,
Newable,
} from '@aws-crypto/material-management'
chai.use(chaiAsPromised)
const { expect } = chai
describe('AwsKmsMrkAwareSymmetricKeyring: _onDecrypt', () => {
describe('returns material', () => {
it('for configured MRK ARN', async () => {
const configuredKeyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const keyIdOtherRegion =
'arn:aws:kms:us-west-2:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function decrypt({
KeyId,
CiphertextBlob,
EncryptionContext,
GrantTokens,
}: any) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# When calling AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html), the keyring MUST call with a request constructed
//# as follows:
expect(KeyId).to.equal(configuredKeyId)
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
expect(Buffer.from(CiphertextBlob).toString('utf8')).to.equal(
keyIdOtherRegion
)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId,
}
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# To attempt to decrypt a particular encrypted data key
//# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS
//# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) with the configured AWS KMS client.
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: configuredKeyId,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyIdOtherRegion,
encryptedDataKey: Buffer.from(keyIdOtherRegion),
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# OnDecrypt MUST take decryption materials (structures.md#decryption-
//# materials) and a list of encrypted data keys
//# (structures.md#encrypted-data-key) as input.
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
[edk]
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# If the response does satisfies these requirements then OnDecrypt MUST
//# do the following with the response:
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(material.keyringTrace).to.have.lengthOf(1)
const [traceDecrypt] = material.keyringTrace
expect(traceDecrypt.keyNamespace).to.equal('aws-kms')
expect(traceDecrypt.keyName).to.equal(configuredKeyId)
expect(
traceDecrypt.flags & KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY)
expect(
traceDecrypt.flags & KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX
).to.equal(KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX)
})
it('for configured non-MRK ARN', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/1234abcd-12ab-34cd-56ef-1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function decrypt({
KeyId,
CiphertextBlob,
EncryptionContext,
GrantTokens,
}: any) {
expect(KeyId).to.equal(keyId)
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: Buffer.from(CiphertextBlob as Uint8Array).toString('utf8'),
}
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
[edk]
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(material.keyringTrace).to.have.lengthOf(1)
const [traceDecrypt] = material.keyringTrace
expect(traceDecrypt.keyNamespace).to.equal('aws-kms')
expect(traceDecrypt.keyName).to.equal(keyId)
expect(
traceDecrypt.flags & KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY)
expect(
traceDecrypt.flags & KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX
).to.equal(KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX)
})
})
it('do not process any EDKs if an unencrypted data key exists.', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/1234abcd-12ab-34cd-56ef-1234567890ab'
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const client: any = {}
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
})
const seedMaterial = new NodeDecryptionMaterial(
suite,
context
).setUnencryptedDataKey(new Uint8Array(suite.keyLengthBytes), {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
})
// The Provider info is malformed,
// if the keyring filters this,
// it should throw.
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: 'Not:an/arn',
encryptedDataKey: Buffer.from(keyId),
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# If the decryption materials (structures.md#decryption-materials)
//# already contained a valid plaintext data key OnDecrypt MUST
//# immediately return the unmodified decryption materials
//# (structures.md#decryption-materials).
const material = await testKeyring.onDecrypt(seedMaterial, [edk])
expect(material === seedMaterial).to.equal(true)
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# For each encrypted data key in the filtered set, one at a time, the
//# OnDecrypt MUST attempt to decrypt the data key.
it('decrypt errors should not halt', async () => {
const mrk =
'arn:aws:kms:us-west-1:123456789012:key/mrk-12345678123412341234123456789012'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let edkCount = 0
function decrypt({
KeyId,
// CiphertextBlob,
EncryptionContext,
GrantTokens,
}: any) {
if (edkCount === 0) {
edkCount += 1
throw new Error('failed to decrypt')
}
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId,
}
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: mrk,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: mrk,
encryptedDataKey: Buffer.from(mrk),
})
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: mrk,
encryptedDataKey: Buffer.from(mrk),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
[edk1, edk2]
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(material.keyringTrace).to.have.lengthOf(1)
})
describe('unexpected KMS response', () => {
const usEastMrkArn =
'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012'
const usWestMrkArn =
'arn:aws:kms:us-west-2:123456789012:key/mrk-12345678123412341234123456789012'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
it('keyId should should fail', async () => {
async function decrypt() {
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# * The "KeyId" field in the response MUST equal the configured AWS
//# KMS key identifier.
KeyId: 'Not the Encrypted ARN',
}
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: usEastMrkArn,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: usWestMrkArn,
encryptedDataKey: Buffer.from(usWestMrkArn),
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk1,
])
).to.rejectedWith(
/KMS Decryption key does not match the requested key id./
)
})
it('plaintext length should fail', async () => {
function decrypt() {
return {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# * The length of the response's "Plaintext" MUST equal the key
//# derivation input length (algorithm-suites.md#key-derivation-input-
//# length) specified by the algorithm suite (algorithm-suites.md)
//# included in the input decryption materials
//# (structures.md#decryption-materials).
Plaintext: new Uint8Array(suite.keyLengthBytes - 5),
KeyId: usEastMrkArn,
}
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: usEastMrkArn,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: usEastMrkArn,
encryptedDataKey: Buffer.from(usEastMrkArn),
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk1,
])
).to.eventually.rejectedWith(
/Key length does not agree with the algorithm specification/
)
})
})
it('does not attempt to decrypt non-matching EDKs', async () => {
const configuredKeyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const otherKeyArn =
'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let kmsCalled = false
function decrypt() {
kmsCalled = true
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: configuredKeyId,
}
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const edk1 = new EncryptedDataKey({
providerId: 'not aws kms edk',
providerInfo: configuredKeyId,
encryptedDataKey: Buffer.from(configuredKeyId),
})
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherKeyArn,
encryptedDataKey: Buffer.from(otherKeyArn),
})
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: configuredKeyId,
grantTokens,
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk1,
edk2,
])
).to.rejectedWith(Error, 'Unable to decrypt data key')
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# The set of encrypted data keys MUST first be filtered to match this
//# keyring's configuration.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# * Its provider ID MUST exactly match the value "aws-kms".
expect(kmsCalled).to.equal(false)
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# * The the function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-
//# for-decrypt.md#implementation) called with the configured AWS KMS
//# key identifier and the provider info MUST return "true".
it('does not attempt to decrypt if configured with an MRK and EDKs that do not satisfy an MRK match', async () => {
const usEastMrkArn =
'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let kmsCalled = false
function decrypt() {
kmsCalled = true
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: usEastMrkArn,
}
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const otherKeyArn =
'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherKeyArn,
encryptedDataKey: Buffer.from(otherKeyArn),
})
const otherMrkArn =
'arn:aws:kms:us-east-1:123456789012:key/mrk-00000000-0000-0000-0000-000000000000'
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherMrkArn,
encryptedDataKey: Buffer.from(otherMrkArn),
})
const otherPartitionMrkArn =
'arn:not-aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012'
const edk3 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherPartitionMrkArn,
encryptedDataKey: Buffer.from(otherPartitionMrkArn),
})
const otherAccountMrkArn =
'arn:aws:kms:us-east-1:098765432109:key/mrk-12345678123412341234123456789012'
const edk4 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherAccountMrkArn,
encryptedDataKey: Buffer.from(otherAccountMrkArn),
})
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: usEastMrkArn,
grantTokens,
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk1,
edk2,
edk3,
edk4,
])
).to.rejectedWith(Error, 'Unable to decrypt data key')
expect(kmsCalled).to.equal(false)
})
it('halts and throws an error if encounters aws-kms EDK ProviderInfo with non-valid ARN', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const client: any = {}
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
const invalidKeyId = 'Not:an/ARN'
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: invalidKeyId,
encryptedDataKey: Buffer.from(invalidKeyId),
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [edk1])
).to.rejectedWith(Error, 'Malformed arn')
const regionlessArn =
'arn:aws:kms::2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: regionlessArn,
encryptedDataKey: Buffer.from(regionlessArn),
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [edk2])
).to.rejectedWith(Error, 'Malformed arn')
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key-
//# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or
//# OnDecrypt MUST fail.
const aliasArn = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
const edk3 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: aliasArn,
encryptedDataKey: Buffer.from(aliasArn),
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [edk3])
).to.rejectedWith(Error, 'Unexpected EDK ProviderInfo for AWS KMS EDK')
})
describe('throws an error if does not successfully decrypt any EDK', () => {
it('because it encountered no EDKs to decrypt', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const client: any = {}
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
await expect(
new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
}).onDecrypt(new NodeDecryptionMaterial(suite, context), [])
).to.rejectedWith(Error, 'Unable to decrypt data key: No EDKs supplied.')
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# If this attempt
//# results in an error, then these errors MUST be collected.
it('and collects all errors encountered during decryption', async () => {
const usEastMrkArn =
'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012'
const usWestMrkArn =
'arn:aws:kms:us-west-1:123456789012:key/mrk-12345678123412341234123456789012'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let edkCount = 0
function decrypt() {
edkCount += 1
throw new Error(`Decrypt Error ${edkCount}`)
}
const client: any = { decrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: usEastMrkArn,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: usEastMrkArn,
encryptedDataKey: Buffer.from(usEastMrkArn),
})
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: usWestMrkArn,
encryptedDataKey: Buffer.from(usWestMrkArn),
})
const material = new NodeDecryptionMaterial(suite, context)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# If the response does not satisfies these requirements then an error
//# MUST be collected and the next encrypted data key in the filtered set
//# MUST be attempted.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=test
//# If OnDecrypt fails to successfully decrypt any encrypted data key
//# (structures.md#encrypted-data-key), then it MUST yield an error that
//# includes all the collected errors.
await expect(
testKeyring.onDecrypt(material, [edk1, edk2])
).to.rejectedWith(
Error,
/Unable to decrypt data key[\s\S]*Decrypt Error 1[\s\S]*Decrypt Error 2/
)
})
})
}) | the_stack |
import { EarthConstants, sphereProjection } from "@here/harp-geoutils";
import { Math2D } from "@here/harp-utils";
import * as THREE from "three";
import { CameraUtils } from "./CameraUtils";
import { MapViewUtils } from "./Utils";
const twoPi = Math.PI * 2;
// Keep counter clockwise order.
export enum CanvasSide {
Bottom,
Right,
Top,
Left
}
export function nextCanvasSide(side: CanvasSide): CanvasSide {
return (side + 1) % 4;
}
export function previousCanvasSide(side: CanvasSide): CanvasSide {
return (side + 3) % 4;
}
/**
* Class computing horizon tangent points and intersections with canvas for spherical projection.
*
* @remarks
*
* The horizon for a sphere is a circle formed by all intersections of tangent lines passing through
* the camera with said sphere. It lies on a plane perpendicular to the sphere normal at the camera
* and it's center is at the line segment joining the sphere center and the camera.
*
* The further the camera is, the nearer the horizon center gets to the sphere center, only reaching
* the sphere center when the camera is at infinity. In other words, the horizon observed from a
* finite distance is always smaller than a great circle (a circle with the sphere radius, dividing
* the sphere in two hemispheres, and therefore it's radius is smaller than the sphere's.
*
* @internal
*/
export class SphereHorizon {
private readonly m_matrix: THREE.Matrix4;
private readonly m_radius: number;
private readonly m_normalToTangentAngle: number;
private readonly m_distanceToHorizonCenter: number;
private readonly m_intersections: number[][] = [];
private m_isFullyVisible: boolean = true;
private readonly m_cameraPitch: number;
/**
* Constructs the SphereHorizon for the given camera.
*
* @param m_camera - The camera used as a reference to compute the horizon.
* @param m_cornerIntersects - Array with a boolean for each canvas corner telling whether it
* intersects with the world. Corners are in ccw-order starting with bottom left.
*/
constructor(
private readonly m_camera: THREE.PerspectiveCamera,
private readonly m_cornerIntersects: boolean[]
) {
//
// TL :,,,,,,,,,,,,,,,,,,,,,,,,,,,,! TR canvas corner (proj. on horizon plane)
// > +
// > +
// :: +
// + >
// > `::::::' !"
// > `:::" ':::, +
// + :!, .!!` +
// ,,:;` :+`>
// >T T# <-- Sphere radius to tangent angle (90 deg).
// !!> `+!(`
// =' + `.+ {:
// /. + `` > |:`
// /` :: .` > |:.
// /` > camZ '` `+ /`'`
// ;, + *,` ' !, ( `'
// ,^ + `.~ + ./ .`
// ) + ' ``` > !~ `.
// *` '~ ' ``.> ( .` tangentDistance
// `\ + `' ?`` '? `'
// /` + `. :. ``` ) `.
// `\ > `. > ``` .= .`
// |` + `` + ``` ( `.
// / "! .` + `?! '`
// ,+ !,,,,,!:,,,,,,,,,,,,, {.` `.
// /` BL ' BR ) ``` .`
// / ' >` `` `'
// / ' `* ``` .`
// ,: ' Sphere radius ) camZ``` `.
// ?` `. ) ``` `.
// / `. ) `.` '` camY
// / `` horizon radius / ````. ^
// / .` |<----------------------->/ ``.'` '
// / .` | /` `',' camX
// / O`````````````C`````````````````````````(,````````````````````````E-----*
// | | distanceToHorizonCenter |
// | |<------------------------------------------------->|
// | |
// |<--------------------------------------------------------------->|
// cameraHeight
// O -> Sphere center
// C -> Horizon center
// E -> Camera (eye)
// T -> Tangent points (also intersections with projected canvas)
const earthRadiusSq = EarthConstants.EQUATORIAL_RADIUS * EarthConstants.EQUATORIAL_RADIUS;
const xAxis = new THREE.Vector3().setFromMatrixColumn(m_camera.matrixWorld, 0).normalize();
const zAxis = m_camera.position.clone().normalize();
const yAxis = new THREE.Vector3().crossVectors(zAxis, xAxis);
const cameraHeight = m_camera.position.length();
this.m_normalToTangentAngle = Math.asin(EarthConstants.EQUATORIAL_RADIUS / cameraHeight);
const tangentDistance = Math.sqrt(cameraHeight * cameraHeight - earthRadiusSq);
this.m_distanceToHorizonCenter = tangentDistance * Math.cos(this.m_normalToTangentAngle);
const horizonCenterLength = cameraHeight - this.m_distanceToHorizonCenter;
this.m_radius = Math.sqrt(earthRadiusSq - horizonCenterLength * horizonCenterLength);
this.m_cameraPitch = MapViewUtils.extractAttitude(
{ projection: sphereProjection },
this.m_camera
).pitch;
const horizonCenter = new THREE.Vector3().copy(zAxis).setLength(horizonCenterLength);
this.m_matrix = new THREE.Matrix4()
.makeBasis(xAxis, yAxis, zAxis)
.setPosition(horizonCenter);
this.computeIntersections();
}
/**
* Gets the world coordinates of a point in the horizon corresponding to the given parameter.
*
* @param t - Parameter value in [0,1] corresponding to the point in the horizon circle at
* angle t*(arcEnd - arcStart)*2*pi counter clockwise.
* @param arcStart - Start of the arc covered by parameter t, corresponds to angle
* arcStart*2*pi.
* @param arcEnd - End of the arc covered by parameter t, corresponds to angle arcEnd*2*pi.
* @param target - Optional target where resulting world coordinates will be set.
* @returns the resulting point in world space.
*/
getPoint(
t: number,
arcStart: number = 0,
arcEnd: number = 1,
target: THREE.Vector3 = new THREE.Vector3()
): THREE.Vector3 {
const startAngle = arcStart * twoPi;
const endAngle = arcEnd >= arcStart ? arcEnd * twoPi : (arcEnd + 1) * twoPi;
const deltaAngle = endAngle - startAngle;
const angle = startAngle + t * deltaAngle;
target.set(this.m_radius * Math.cos(angle), this.m_radius * Math.sin(angle), 0);
target.applyMatrix4(this.m_matrix);
return target;
}
/**
* Subdivides and arc of the horizon circle, providing the world coordinates of the divisions.
*
* @param callback - Function called for every division point, getting the point world
* coordinates as parameter.
* @param tStart - Angular parameter of the arc's start point [0,1].
* @param tEnd - Angular parameter of the arc's end point [0,1].
* @param maxNumPoints - Number of division points for the whole horizon. Smaller arcs will
* be assigned a proportionally smaller number of points.
*/
getDivisionPoints(
callback: (point: THREE.Vector3) => void,
tStart: number = 0,
tEnd: number = 1,
maxNumPoints: number = 10
) {
const numPoints = Math.max(
Math.ceil(((tEnd < tStart ? 1 + tEnd : tEnd) - tStart) * maxNumPoints),
1
);
// Point corresponding to tEnd is omitted, hence the strict less condition in the loop.
for (let d = 0; d < numPoints; d++) {
callback(this.getPoint(d / numPoints, tStart, tEnd));
}
}
/**
* Indicates whether the horizon circle is fully visible.
* @returns 'True' if horizon is fully visible, false otherwise.
*/
get isFullyVisible(): boolean {
return this.m_isFullyVisible;
}
/**
* Gets the horizon intersections with the specified canvas side, specified in angular
* parameters [0,1].
* @returns the intersections with the canvas.
*/
getSideIntersections(side: CanvasSide): number[] {
return this.m_intersections[side];
}
private isTangentVisible(side: CanvasSide): boolean {
switch (side) {
case CanvasSide.Top: {
const eyeToTangentAngle = this.m_normalToTangentAngle - this.m_cameraPitch;
return CameraUtils.getTopFov(this.m_camera) >= Math.abs(eyeToTangentAngle);
}
case CanvasSide.Bottom: {
const eyeToTangentAngle = this.m_normalToTangentAngle + this.m_cameraPitch;
return CameraUtils.getBottomFov(this.m_camera) >= Math.abs(eyeToTangentAngle);
}
case CanvasSide.Left: {
const eyeToTangentAngle = this.m_normalToTangentAngle;
return (
CameraUtils.getLeftFov(this.m_camera) >= Math.abs(eyeToTangentAngle) &&
this.m_cameraPitch <= CameraUtils.getBottomFov(this.m_camera)
);
}
case CanvasSide.Right: {
const eyeToTangentAngle = this.m_normalToTangentAngle;
return (
CameraUtils.getRightFov(this.m_camera) >= Math.abs(eyeToTangentAngle) &&
this.m_cameraPitch <= CameraUtils.getBottomFov(this.m_camera)
);
}
}
}
private getTangentOnSide(side: CanvasSide): number {
switch (side) {
case CanvasSide.Bottom:
return 0.75;
case CanvasSide.Right:
return 0;
case CanvasSide.Top:
return 0.25;
case CanvasSide.Left:
return 0.5;
}
}
private computeIntersections() {
// Look for the intersections of the canvas sides projected in the horizon plane with the
// horizon circle.
// Top and bottom canvas sides are horizontal lines at plane coordinates yTop and yBottom
// respectively. Left and right sides are lines whose slope depends on the camera pitch.
//
// Front View (horizon plane):
//
// Top
// TL '{~~~~~~~~~~~~~~~~~~~~~~~~~~}. TR
// ( (
// ;" '!;!!!!!!!!!!!!;!' ::
// I>^^: :^^|I <--------- Canvas-Horizon intersection
// ~>+%. ,$+>,
// !|~ ( ( :|!
// ~/' L (----------C----------`) R ,/"
// /; `/ ^, )` ^|
// }' ( |` ( '}
// }` ,^ |` *. .}
// (' BL !::::::::|:::::::::: BR ,)
// ,{ |` Bottom }`
// } camZ|` `}
// } |` }
// } E----> camX }
// } } Horizon circle
// } `}
// ~{ }.
// {. '(
// }` `}
// `}. .}
// )! !/
// :/. '/:
// ^|' ,|^
// :>+. .+>:
// !^^;' ';^^!
// :;!!!!!!!!!!!!;!;:
//
// Top-down view (plane defined by camZ and camX):
//
// Top
// TL_______________________________ TR
// \ | /
// \ :;!!!!!!!!!!!!!!;!;: /
// I^;' | ';^^I
// :>+.\ | /.+>:
// ^|' \ | / ,|^ <--- Horizon
// :/. \ | / '/:
// } L--------C--------R_________}_________
// } \ ^camZ / } ^
// } \ | / } |
// :/. \ | / :/. |
// ^|' BL----B----BR_______ !|' |
// :>+. \ | / ^ | eyeToHorizon
// !^;' \ | / ';!| |
// :;!!!!!!\ | /!!;!;:! | eyeToBottom |
// \|/ | |
// E----> camX__v______________v
const yBottom =
this.m_distanceToHorizonCenter *
Math.tan(this.m_cameraPitch - CameraUtils.getBottomFov(this.m_camera));
let tTopRight: number | undefined;
let tBottomRight: number | undefined;
// Collect all intersections in counter-clockwise order.
for (let side = CanvasSide.Bottom; side < 4; side++) {
if (this.isTangentVisible(side)) {
this.m_intersections.push([this.getTangentOnSide(side)]);
continue;
}
const sideIntersections = new Array<number | undefined>();
this.m_isFullyVisible = false;
switch (side) {
case CanvasSide.Bottom: {
sideIntersections.push(...this.computeTBIntersections(yBottom));
break;
}
case CanvasSide.Right: {
const rightFov = CameraUtils.getRightFov(this.m_camera);
const intersections = this.computeLRIntersections(yBottom, rightFov);
if (intersections) {
[tTopRight, tBottomRight] = intersections;
sideIntersections.push(
tBottomRight !== undefined ? 1 + tBottomRight : undefined,
tTopRight
);
}
break;
}
case CanvasSide.Top: {
const yTop =
this.m_distanceToHorizonCenter *
Math.tan(this.m_cameraPitch + CameraUtils.getTopFov(this.m_camera));
sideIntersections.push(...this.computeTBIntersections(yTop).reverse());
break;
}
case CanvasSide.Left: {
const leftFov = CameraUtils.getLeftFov(this.m_camera);
if (leftFov === CameraUtils.getRightFov(this.m_camera)) {
// Left side intersections are symmetrical to right ones.
sideIntersections.push(
tTopRight !== undefined ? 0.5 - tTopRight : undefined,
tBottomRight !== undefined ? 0.5 - tBottomRight : undefined
);
} else {
const isections = this.computeLRIntersections(yBottom, leftFov);
if (isections) {
sideIntersections.push(
0.5 - isections[0], // top
isections[1] !== undefined ? 0.5 - isections[1] : undefined // bottom
);
}
}
break;
}
}
// Filter out undefined values and horizon intersections that are not visible because
// the canvas corner intersects the world (this may happen with off-center projections).
const hasCorners = [
this.m_cornerIntersects[side],
this.m_cornerIntersects[nextCanvasSide(side)]
];
this.m_intersections.push(
sideIntersections.filter(
(val, i) => val !== undefined && !hasCorners[i]
) as number[]
);
}
}
/**
* Computes horizon intersections with top or bottom canvas side.
*
* @returns positions of the intersections in the horizon circle, first left, then right
* Values are in range [0,1].
*/
private computeTBIntersections(y: number): [number, number] {
const radiusSq = this.m_radius * this.m_radius;
const x = Math.sqrt(radiusSq - y * y);
const t = Math.atan2(y, x) / twoPi;
return [0.5 - t, t > 0 ? t : 1 + t];
}
/**
* Computes horizon intersections with left or right canvas side.
*
* @returns positions of the intersections in the horizon circle, first top, then bottom
* (or undefined if not visible). Values are in range [-0.5,0.5].
*/
private computeLRIntersections(
yBottom: number,
sideFov: number
): [number, number?] | undefined {
// Define vertical canvas side line by finding the middle and bottom points of
// its projection on the horizon plane.
const eyeToHorizon = this.m_distanceToHorizonCenter / Math.cos(this.m_cameraPitch);
const yMiddle = this.m_distanceToHorizonCenter * Math.tan(this.m_cameraPitch);
const xMiddle = eyeToHorizon * Math.tan(sideFov);
const bottomFov = CameraUtils.getBottomFov(this.m_camera);
const eyeToBottom =
(this.m_distanceToHorizonCenter * Math.cos(bottomFov)) /
Math.cos(this.m_cameraPitch - bottomFov);
const xBottom = (xMiddle * eyeToBottom) / eyeToHorizon;
const intersections = Math2D.intersectLineAndCircle(
xBottom,
yBottom,
xMiddle,
yMiddle,
this.m_radius
);
if (!intersections) {
return undefined;
}
const yTopRight = intersections.y1;
const tTop = Math.atan2(yTopRight, intersections.x1) / twoPi;
// If there's a bottom intersection check if it's visible (its above the y
// coordinate of the bottom canvas side).
const hasBottomIntersection = -yTopRight >= yBottom && intersections.x2 !== undefined;
const tBottom = hasBottomIntersection
? Math.atan2(intersections.y2!, intersections.x2!) / twoPi
: undefined;
return [tTop, tBottom];
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsfp_surveyresponse_Information {
interface Header extends DevKit.Controls.IHeader {
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Priority of the activity. */
PriorityCode: DevKit.Controls.OptionSet;
/** Scheduled end time of the activity. */
ScheduledEnd: DevKit.Controls.DateTime;
/** Status of the activity. */
StateCode: DevKit.Controls.OptionSet;
}
interface tab__FE5BE043_870F_4D0F_B79F_195DCBA93F38_Sections {
_FE5BE043_870F_4D0F_B79F_195DCBA93F38_SECTION_4: DevKit.Controls.Section;
General: DevKit.Controls.Section;
QuestionResponses: DevKit.Controls.Section;
}
interface tab__FE5BE043_870F_4D0F_B79F_195DCBA93F38 extends DevKit.Controls.ITab {
Section: tab__FE5BE043_870F_4D0F_B79F_195DCBA93F38_Sections;
}
interface Tabs {
_FE5BE043_870F_4D0F_B79F_195DCBA93F38: tab__FE5BE043_870F_4D0F_B79F_195DCBA93F38;
}
interface Body {
Tab: Tabs;
/** Unique identifier of the user who created the activity. */
CreatedBy: DevKit.Controls.Lookup;
/** Person who the activity is from. */
From: DevKit.Controls.Lookup;
IFRAME_SurveyResponse: DevKit.Controls.IFrame;
/** Context data for the survey response. */
msfp_embedcontextparameters: DevKit.Controls.String;
/** Shows the language of the respondent. */
msfp_language: DevKit.Controls.String;
/** Shows the locale of the respondent. */
msfp_locale: DevKit.Controls.String;
/** The survey response name. */
msfp_name: DevKit.Controls.String;
/** Net Promoter Score of the response. */
msfp_npsscore: DevKit.Controls.Integer;
/** Other survey response properties in JSON format. */
msfp_otherproperties: DevKit.Controls.String;
/** List of question responses in JSON format. */
msfp_questionresponseslist: DevKit.Controls.String;
/** Name of the respondent. */
msfp_respondent: DevKit.Controls.String;
/** Email address of the respondent. */
msfp_respondentemailaddress: DevKit.Controls.String;
/** Satisfaction metric values for the survey response. */
msfp_satisfactionmetricvalue: DevKit.Controls.String;
/** Sentiment of the response. */
msfp_sentiment: DevKit.Controls.OptionSet;
/** Unique identifier for the survey in the source application. */
msfp_sourcesurveyidentifier: DevKit.Controls.String;
/** Stores the date when a response was submitted. */
msfp_submitdate: DevKit.Controls.Date;
/** Specifies the survey associated with the survey response. */
msfp_surveyid: DevKit.Controls.Lookup;
/** Specifies survey invitation associated with the survey response */
msfp_surveyinviteid: DevKit.Controls.Lookup;
/** Link to the survey response in Customer Voice. */
msfp_surveyresponseurl: DevKit.Controls.String;
/** Unique identifier of the object with which the activity is associated. */
RegardingObjectId: DevKit.Controls.Lookup;
/** Scheduled start time of the activity. */
ScheduledStart: DevKit.Controls.DateTime;
/** Subject associated with the activity. */
Subject: DevKit.Controls.String;
}
interface Grid {
QuestionResponses: DevKit.Controls.Grid;
}
}
class Formmsfp_surveyresponse_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msfp_surveyresponse_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msfp_surveyresponse_Information */
Body: DevKit.Formmsfp_surveyresponse_Information.Body;
/** The Header section of form msfp_surveyresponse_Information */
Header: DevKit.Formmsfp_surveyresponse_Information.Header;
/** The Grid of form msfp_surveyresponse_Information */
Grid: DevKit.Formmsfp_surveyresponse_Information.Grid;
}
class msfp_surveyresponseApi {
/**
* DynamicsCrm.DevKit msfp_surveyresponseApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Additional information provided by the external application as JSON. For internal use only. */
ActivityAdditionalParams: DevKit.WebApi.StringValue;
/** Unique identifier of the activity. */
ActivityId: DevKit.WebApi.GuidValue;
/** Actual duration of the activity in minutes. */
ActualDurationMinutes: DevKit.WebApi.IntegerValue;
/** Actual end time of the activity. */
ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Actual start time of the activity. */
ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */
Community: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the user who created the activity. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the activity was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the activitypointer. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the delivery of the activity was last attempted. */
DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of delivery of the activity to the email server. */
DeliveryPriorityCode: DevKit.WebApi.OptionSetValue;
/** Description of the activity. */
Description: DevKit.WebApi.StringValue;
/** The message id of activity which is returned from Exchange Server. */
ExchangeItemId: DevKit.WebApi.StringValue;
/** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the web link of Activity of type email. */
ExchangeWebLink: DevKit.WebApi.StringValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Type of instance of a recurring series. */
InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Information regarding whether the activity was billed as part of resolving a case. */
IsBilled: DevKit.WebApi.BooleanValue;
/** For internal use only. */
IsMapiPrivate: DevKit.WebApi.BooleanValue;
/** Information regarding whether the activity is a regular activity type or event type. */
IsRegularActivity: DevKit.WebApi.BooleanValueReadonly;
/** Information regarding whether the activity was created from a workflow rule. */
IsWorkflowCreated: DevKit.WebApi.BooleanValue;
/** Contains the date and time stamp of the last on hold time. */
LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Left the voice mail */
LeftVoiceMail: DevKit.WebApi.BooleanValue;
/** Unique identifier of user who last modified the activity. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when activity was last modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the activitypointer. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Context data for the survey response. */
msfp_embedcontextparameters: DevKit.WebApi.StringValue;
/** Specifies if individual question response records are generated. */
msfp_isquestionresponsegenerated: DevKit.WebApi.BooleanValue;
/** (Deprecated) Specifies if individual question response records are generated. */
msfp_isquestionresponsesgenerated: DevKit.WebApi.BooleanValue;
/** Shows the language of the respondent. */
msfp_language: DevKit.WebApi.StringValue;
/** Shows the locale of the respondent. */
msfp_locale: DevKit.WebApi.StringValue;
/** The survey response name. */
msfp_name: DevKit.WebApi.StringValue;
/** Net Promoter Score of the response. */
msfp_npsscore: DevKit.WebApi.IntegerValue;
/** Other survey response properties in JSON format. */
msfp_otherproperties: DevKit.WebApi.StringValue;
/** Parent survey response for the chained survey */
msfp_parentsurveyresponse: DevKit.WebApi.LookupValue;
/** List of question responses in JSON format. */
msfp_questionresponseslist: DevKit.WebApi.StringValue;
/** Name of the respondent. */
msfp_respondent: DevKit.WebApi.StringValue;
/** Email address of the respondent. */
msfp_respondentemailaddress: DevKit.WebApi.StringValue;
msfp_satisfactionmetriccalculated: DevKit.WebApi.BooleanValue;
/** Satisfaction metric values for the survey response. */
msfp_satisfactionmetricvalue: DevKit.WebApi.StringValue;
/** Sentiment of the response. */
msfp_sentiment: DevKit.WebApi.OptionSetValue;
/** Unique identifier for the response in the source application. */
msfp_sourceresponseidentifier: DevKit.WebApi.StringValue;
/** Unique identifier for the survey in the source application. */
msfp_sourcesurveyidentifier: DevKit.WebApi.StringValue;
/** Stores the date when a response was submitted. */
msfp_Startdate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Stores the date when a response was submitted. */
msfp_submitdate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Specifies the survey associated with the survey response. */
msfp_surveyid: DevKit.WebApi.LookupValue;
/** Specifies survey invitation associated with the survey response */
msfp_surveyinviteid: DevKit.WebApi.LookupValue;
/** Response to the survey. */
msfp_surveyresponse: DevKit.WebApi.StringValue;
/** Link to the survey response in Customer Voice. */
msfp_surveyresponseurl: DevKit.WebApi.StringValue;
/** Shows how long, in minutes, that the record was on hold. */
OnHoldTime: DevKit.WebApi.IntegerValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the business unit that owns the activity. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team that owns the activity. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user that owns the activity. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** For internal use only. */
PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of the activity. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the Process. */
ProcessId: DevKit.WebApi.GuidValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_account_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bookableresourcebooking_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bookableresourcebookingheader_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bulkoperation_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_campaign_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_campaignactivity_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_contact_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_contract_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_entitlement_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_entitlementtemplate_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_incident_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_new_interactionforemail_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_invoice_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_knowledgearticle_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_knowledgebaserecord_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_lead_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreement_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingdate_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingincident_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingservice_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingservicetask_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingsetup_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoicedate_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoiceproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoicesetup_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingalertstatus_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingrule_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingtimestamp_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_customerasset_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_fieldservicesetting_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypecharacteristic_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypeproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypeservice_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryadjustment_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryadjustmentproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryjournal_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventorytransfer_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_payment_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentdetail_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentmethod_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentterm_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_playbookinstance_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_postalbum_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_postalcode_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_processnotes_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_productinventory_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_projectteam_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorder_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderbill_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderreceipt_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderreceiptproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseordersubstatus_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingincident_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingservice_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingservicetask_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_resourceterritory_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rma_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmaproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmareceipt_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmareceiptproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmasubstatus_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtv_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtvproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtvsubstatus_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_shipvia_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_systemuserschedulersetting_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timegroup_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timegroupdetail_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timeoffrequest_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_warehouse_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorder_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workordercharacteristic_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderincident_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderproduct_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderresourcerestriction_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderservice_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderservicetask_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_opportunity_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_quote_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_salesorder_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_site_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_action_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_hostedapplication_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_nonhostedapplication_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_option_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_savedsession_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflow_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflowstep_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflow_workflowstep_mapping_msfp_surveyresponse: DevKit.WebApi.LookupValue;
RegardingObjectIdYomiName: DevKit.WebApi.StringValue;
/** Scheduled duration of the activity, specified in minutes. */
ScheduledDurationMinutes: DevKit.WebApi.IntegerValue;
/** Scheduled end time of the activity. */
ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Scheduled start time of the activity. */
ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the mailbox associated with the sender of the email message. */
SenderMailboxId: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the activity was sent. */
SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Uniqueidentifier specifying the id of recurring series of an instance. */
SeriesId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of an associated service. */
ServiceId: DevKit.WebApi.LookupValue;
/** Choose the service level agreement (SLA) that you want to apply to the case record. */
SLAId: DevKit.WebApi.LookupValue;
/** Last SLA that was applied to this case. This field is for internal use only. */
SLAInvokedId: DevKit.WebApi.LookupValueReadonly;
SLAName: DevKit.WebApi.StringValueReadonly;
/** Shows the date and time by which the activities are sorted. */
SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the Stage. */
StageId: DevKit.WebApi.GuidValue;
/** Status of the activity. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the activity. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Subject associated with the activity. */
Subject: DevKit.WebApi.StringValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the activitypointer. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** For internal use only. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the activity. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** The array of object that can cast object to ActivityPartyApi class */
ActivityParties: Array<any>;
}
}
declare namespace OptionSet {
namespace msfp_surveyresponse {
enum Community {
/** 5 */
Cortana,
/** 6 */
Direct_Line,
/** 8 */
Direct_Line_Speech,
/** 9 */
Email,
/** 1 */
Facebook,
/** 10 */
GroupMe,
/** 11 */
Kik,
/** 3 */
Line,
/** 7 */
Microsoft_Teams,
/** 0 */
Other,
/** 13 */
Skype,
/** 14 */
Slack,
/** 12 */
Telegram,
/** 2 */
Twitter,
/** 4 */
Wechat,
/** 15 */
WhatsApp
}
enum DeliveryPriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum InstanceTypeCode {
/** 0 */
Not_Recurring,
/** 3 */
Recurring_Exception,
/** 4 */
Recurring_Future_Exception,
/** 2 */
Recurring_Instance,
/** 1 */
Recurring_Master
}
enum msfp_sentiment {
/** 647390002 */
Negative,
/** 647390001 */
Neutral,
/** 647390000 */
Positive
}
enum PriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum StateCode {
/** 2 */
Canceled,
/** 1 */
Completed,
/** 0 */
Open,
/** 3 */
Scheduled
}
enum StatusCode {
/** 3 */
Canceled,
/** 2 */
Completed,
/** 1 */
Open,
/** 4 */
Scheduled
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {
CHAIN_ID_BSC,
CHAIN_ID_ETH,
createNonce,
hexToUint8Array,
nativeToHexString,
parseSequenceFromLogEth,
TokenImplementation__factory,
} from "@certusone/wormhole-sdk";
import { formatUnits, parseUnits } from "@ethersproject/units";
import {
Button,
Container,
makeStyles,
Paper,
Typography,
} from "@material-ui/core";
import Collapse from "@material-ui/core/Collapse";
import CheckCircleOutlineRoundedIcon from "@material-ui/icons/CheckCircleOutlineRounded";
import { ethers } from "ethers";
import { useCallback, useEffect, useMemo, useState } from "react";
import { SimpleDex__factory } from "../abi/factories/SimpleDex__factory";
import ButtonWithLoader from "../components/ButtonWithLoader";
import ChainSelectDialog from "../components/ChainSelectDialog";
import CircleLoader from "../components/CircleLoader";
import EthereumSignerKey from "../components/EthereumSignerKey";
import HoverIcon from "../components/HoverIcon";
import NumberTextField from "../components/NumberTextField";
import { useEthereumProvider } from "../contexts/EthereumProviderContext";
import useAllowance from "../hooks/useAllowance";
import useIsWalletReady from "../hooks/useIsWalletReady";
import useRestRelayer from "../hooks/useRestRelayer";
import Wormhole from "../icons/wormhole-network.svg";
import { COLORS } from "../muiTheme";
import {
CHAINS,
getBridgeAddressForChain,
getDefaultNativeCurrencySymbol,
getTokenBridgeAddressForChain,
} from "../utils/consts";
import getSwapPool from "../utils/getSwapPoolAddress";
const useStyles = makeStyles((theme) => ({
numberField: {
flexGrow: 1,
"& > * > .MuiInputBase-input": {
textAlign: "right",
height: "100%",
flexGrow: "1",
fontSize: "3rem",
fontFamily: "Roboto Mono, monospace",
caretShape: "block",
width: "0",
"&::-webkit-outer-spin-button, &::-webkit-inner-spin-button": {
"-webkit-appearance": "none",
"-moz-appearance": "none",
margin: 0,
},
"&[type=number]": {
"-webkit-appearance": "textfield",
"-moz-appearance": "textfield",
},
},
"& > * > input::-webkit-inner-spin-button": {
webkitAppearance: "none",
margin: "0",
},
},
sourceContainer: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
border: "3px solid #333333",
padding: ".6rem",
borderRadius: "30px",
"& > *": {
margin: ".5rem",
},
margin: "1rem 0rem 1rem 0rem",
},
centeredContainer: {
textAlign: "center",
width: "100%",
},
stepNum: {},
explainerText: {
marginBottom: "1rem",
},
spacer: {
height: "1rem",
},
mainPaper: {
padding: "2rem",
backgroundColor: COLORS.nearBlackWithMinorTransparency,
},
chainSelectorContainer: {},
downArrow: {
height: "5rem",
},
titleBar: {
marginTop: "10rem",
"& > *": {
margin: ".5rem",
alignSelf: "flex-end",
},
},
appBar: {
background: COLORS.nearBlackWithMinorTransparency,
"& > .MuiToolbar-root": {
margin: "auto",
width: "100%",
maxWidth: 1100,
},
},
link: {
...theme.typography.body1,
color: theme.palette.text.primary,
marginLeft: theme.spacing(6),
[theme.breakpoints.down("sm")]: {
marginLeft: theme.spacing(2.5),
},
[theme.breakpoints.down("xs")]: {
marginLeft: theme.spacing(1),
},
"&.active": {
color: theme.palette.primary.light,
},
},
bg: {
background:
"linear-gradient(160deg, rgba(69,74,117,.1) 0%, rgba(138,146,178,.1) 33%, rgba(69,74,117,.1) 66%, rgba(98,104,143,.1) 100%), linear-gradient(45deg, rgba(153,69,255,.1) 0%, rgba(121,98,231,.1) 20%, rgba(0,209,140,.1) 100%)",
display: "flex",
flexDirection: "column",
minHeight: "100vh",
},
actionArea: {
display: "grid",
placeItems: "center",
height: "10rem",
width: "100%",
},
content: {
margin: theme.spacing(2, 0),
[theme.breakpoints.up("md")]: {
margin: theme.spacing(4, 0),
},
},
brandLink: {
display: "inline-flex",
alignItems: "center",
"&:hover": {
textDecoration: "none",
},
},
iconButton: {
[theme.breakpoints.up("md")]: {
marginRight: theme.spacing(2.5),
},
[theme.breakpoints.down("sm")]: {
marginRight: theme.spacing(2.5),
},
[theme.breakpoints.down("xs")]: {
marginRight: theme.spacing(1),
},
},
gradientButton: {
backgroundImage: `linear-gradient(45deg, ${COLORS.blue} 0%, ${COLORS.nearBlack}20 50%, ${COLORS.blue}30 62%, ${COLORS.nearBlack}50 120%)`,
transition: "0.75s",
backgroundSize: "200% auto",
boxShadow: "0 0 20px #222",
"&:hover": {
backgroundPosition:
"right center" /* change the direction of the change here */,
},
width: "100%",
height: "3rem",
marginTop: "1rem",
},
disabled: {
background: COLORS.gray,
},
betaBanner: {
background: `linear-gradient(to left, ${COLORS.blue}40, ${COLORS.green}40);`,
padding: theme.spacing(1, 0),
},
loaderHolder: {
display: "flex",
justifyContent: "center",
flexDirection: "column",
alignItems: "center",
},
wormholeIcon: {
height: 60,
filter: "contrast(0)",
transition: "filter 0.5s",
"&:hover": {
filter: "contrast(1)",
},
verticalAlign: "middle",
margin: "1rem",
display: "inline-block",
},
successIcon: {
color: COLORS.green,
fontSize: "200px",
},
}));
function Home() {
const classes = useStyles();
const [transferHolderString, setTransferHolderString] = useState<string>("");
const [price, setPrice] = useState<BigInt | null>(null);
const [sequence, setSequence] = useState<string>("");
const [sourceChain, setSourceChain] = useState(CHAIN_ID_ETH);
const [targetChain, setTargetChain] = useState(CHAIN_ID_BSC);
const { swapPoolAddress, targetAsset } = useMemo(() => {
const holder = getSwapPool(sourceChain, targetChain) as any;
return {
swapPoolAddress: holder.poolAddress,
targetAsset: holder.tokenAddress,
};
}, [sourceChain, targetChain]);
const relayInfo = useRestRelayer(sourceChain, sequence, targetChain);
const allowanceInfo = useAllowance(
sourceChain,
swapPoolAddress,
targetAsset,
BigInt(100000000000000000000000),
false
);
console.log("allowance info", allowanceInfo);
console.log("relay info", relayInfo);
console.log("sequence", sequence);
console.log("price", price);
const { isReady: isEthWalletReady, walletAddress } = useIsWalletReady(
sourceChain,
true
);
const ethWallet = useEthereumProvider();
const handleSourceChange = useCallback(
(event) => {
const newSourceChain = event.target.value;
if (newSourceChain === targetChain) {
const newTargetChain = CHAINS.find(
(chain) => chain.id !== newSourceChain
);
setTargetChain(newTargetChain?.id || CHAIN_ID_ETH);
}
setSourceChain(newSourceChain);
setTransferHolderString("");
},
[targetChain]
);
const handleTargetChange = useCallback(
(event) => {
console.log(event.target.value, "value");
const newTargetChain = event.target.value;
if (newTargetChain === sourceChain) {
const newSourceChain = CHAINS.find(
(chain) => chain.id !== newTargetChain
);
setSourceChain(newSourceChain?.id || CHAIN_ID_ETH);
}
setTargetChain(newTargetChain);
setTransferHolderString("");
},
[sourceChain]
);
const swapChains = useCallback(() => {
setSourceChain(targetChain);
setTargetChain(sourceChain);
setTransferHolderString("");
}, [targetChain, sourceChain]);
const calcPrice = useCallback(async () => {
if (
!isEthWalletReady ||
!transferHolderString ||
!parseUnits(transferHolderString, 18)
) {
setPrice(null);
return;
}
const dex = SimpleDex__factory.connect(
swapPoolAddress,
ethWallet.provider as any
);
const token = TokenImplementation__factory.connect(
targetAsset,
ethWallet.provider as any
);
const tokensInPool = await token.balanceOf(swapPoolAddress);
const nativeInPool = await dex.totalLiquidity();
const price = await dex.price(
parseUnits(transferHolderString, 18),
nativeInPool,
tokensInPool
);
setPrice(price.toBigInt());
}, [
isEthWalletReady,
swapPoolAddress,
ethWallet.provider,
targetAsset,
transferHolderString,
]);
//calcPrice
//TODO debounce
useEffect(() => {
calcPrice();
}, [calcPrice]);
//TODO check that the user has enough balance
const sufficientPoolBalance =
price && transferHolderString && parseUnits(transferHolderString, "18");
const readyToGo =
isEthWalletReady &&
walletAddress &&
!isNaN(parseFloat(transferHolderString)) &&
parseFloat(transferHolderString) > 0 &&
allowanceInfo.sufficientAllowance &&
sufficientPoolBalance; //TODO check pool balances
const handleTransfer = useCallback(async () => {
if (!readyToGo || !walletAddress) {
return;
}
console.log(swapPoolAddress);
const dex = SimpleDex__factory.connect(
swapPoolAddress,
ethWallet.signer as any
);
const nonce = createNonce();
const receipt = await (
await dex.swapNGo(
getTokenBridgeAddressForChain(sourceChain),
targetChain,
hexToUint8Array(nativeToHexString(walletAddress, targetChain) as any),
"0",
nonce,
{ value: parseUnits(transferHolderString, 18) }
)
).wait();
console.log("transaction receipt", receipt);
const sequence = parseSequenceFromLogEth(
receipt,
getBridgeAddressForChain(sourceChain)
);
setSequence(sequence);
}, [
ethWallet.signer,
readyToGo,
sourceChain,
swapPoolAddress,
targetChain,
transferHolderString,
walletAddress,
]);
const handleAllowanceIncrease = useCallback(() => {
allowanceInfo.approveAmount(ethers.constants.MaxUint256.toBigInt());
}, [allowanceInfo]);
const handleAmountChange = useCallback((event) => {
setTransferHolderString(event.target.value);
}, []);
const handleReset = useCallback(() => {
setTransferHolderString("");
setSequence("");
}, []);
const sourceContent = (
<div className={classes.sourceContainer}>
<ChainSelectDialog
value={sourceChain}
onChange={handleSourceChange}
chains={CHAINS}
style2={true}
/>
<NumberTextField
className={classes.numberField}
value={transferHolderString}
onChange={handleAmountChange}
autoFocus={true}
InputProps={{ disableUnderline: true }}
/>
</div>
);
const middleButton = <HoverIcon onClick={swapChains} />; //TODO onclick
const targetContent = (
<div className={classes.sourceContainer}>
<ChainSelectDialog
value={targetChain}
onChange={handleTargetChange}
chains={CHAINS}
/>
<NumberTextField
className={classes.numberField}
value={
!!price
? parseFloat(formatUnits(price.toString(), 18)).toFixed(2)
: "0"
}
InputProps={{ disableUnderline: true }}
disabled={true}
/>
</div>
);
const walletButton = <EthereumSignerKey />;
const allowanceButton = (
<>
<ButtonWithLoader
onClick={handleAllowanceIncrease}
showLoader={allowanceInfo.isApproveProcessing}
disabled={allowanceInfo.isApproveProcessing || !isEthWalletReady}
>
Allow Wormhole Transfers
</ButtonWithLoader>
</>
);
const convertButton = (
<ButtonWithLoader
disabled={!readyToGo}
onClick={handleTransfer}
className={
classes.gradientButton + (!readyToGo ? " " + classes.disabled : "")
}
>
Convert
</ButtonWithLoader>
);
const buttonContent = !allowanceInfo.sufficientAllowance
? allowanceButton
: convertButton;
return (
<div className={classes.bg}>
<Container className={classes.centeredContainer} maxWidth="sm">
<div className={classes.titleBar}></div>
<Typography variant="h4" color="textSecondary">
{"Crypto Converter"}
</Typography>
<div className={classes.spacer} />
<Paper className={classes.mainPaper}>
<Collapse in={!!relayInfo.isComplete}>
<>
<CheckCircleOutlineRoundedIcon
fontSize={"inherit"}
className={classes.successIcon}
/>
<Typography>All Set!</Typography>
<Typography variant="h5">
{"You now have " +
parseFloat(formatUnits((price || 0).toString(), 18)).toFixed(
2
) +
" " +
getDefaultNativeCurrencySymbol(targetChain)}
</Typography>
<div className={classes.spacer} />
<div className={classes.spacer} />
<Button onClick={handleReset} variant="contained" color="primary">
Convert More Coins
</Button>
</>
</Collapse>
<div className={classes.loaderHolder}>
<Collapse in={!!relayInfo.isLoading && !relayInfo.isComplete}>
<div className={classes.loaderHolder}>
<CircleLoader />
<div className={classes.spacer} />
<div className={classes.spacer} />
<Typography variant="h5">
{"Your " +
getDefaultNativeCurrencySymbol(sourceChain) +
" is being converted to " +
getDefaultNativeCurrencySymbol(targetChain)}
</Typography>
<div className={classes.spacer} />
<Typography>{"Please wait a moment"}</Typography>
</div>
</Collapse>
</div>
<div className={classes.chainSelectorContainer}>
<Collapse
in={
!!ethWallet.provider &&
!relayInfo.isLoading &&
!relayInfo.isComplete &&
!sequence
}
>
{ethWallet.provider ? (
<>
{sourceContent}
{middleButton}
{targetContent}
<div className={classes.spacer} />
<div className={classes.spacer} />
</>
) : null}
{buttonContent}
</Collapse>
{!ethWallet.provider && walletButton}
</div>
</Paper>
<div className={classes.spacer} />
<Typography variant="subtitle1" color="textSecondary">
{"powered by wormhole"}
</Typography>
<img src={Wormhole} alt="Wormhole" className={classes.wormholeIcon} />
</Container>
</div>
);
}
export default Home; | the_stack |
import {Finding, Severity, Type} from './finding';
/**
* Content Security Policy object.
* List of valid CSP directives:
* - http://www.w3.org/TR/CSP2/#directives
* - https://www.w3.org/TR/upgrade-insecure-requests/
*/
export class Csp {
directives: Record<string, string[]|undefined> = {};
/**
* Clones a CSP object.
* @return clone of parsedCsp.
*/
clone(): Csp {
const clone = new Csp();
for (const [directive, directiveValues] of Object.entries(
this.directives)) {
if (directiveValues) {
clone.directives[directive] = [...directiveValues];
}
}
return clone;
}
/**
* Converts this CSP back into a string.
* @return CSP string.
*/
convertToString(): string {
let cspString = '';
for (const [directive, directiveValues] of Object.entries(
this.directives)) {
cspString += directive;
if (directiveValues !== undefined) {
for (let value, i = 0; (value = directiveValues[i]); i++) {
cspString += ' ';
cspString += value;
}
}
cspString += '; ';
}
return cspString;
}
/**
* Returns CSP as it would be seen by a UA supporting a specific CSP version.
* @param cspVersion CSP.
* @param optFindings findings about ignored directive values will be added
* to this array, if passed. (e.g. CSP2 ignores 'unsafe-inline' in
* presence of a nonce or a hash)
* @return The effective CSP.
*/
getEffectiveCsp(cspVersion: Version, optFindings?: Finding[]): Csp {
const findings = optFindings || [];
const effectiveCsp = this.clone();
const directive = effectiveCsp.getEffectiveDirective(Directive.SCRIPT_SRC);
const values = this.directives[directive] || [];
const effectiveCspValues = effectiveCsp.directives[directive];
if (effectiveCspValues &&
(effectiveCsp.policyHasScriptNonces() ||
effectiveCsp.policyHasScriptHashes())) {
if (cspVersion >= Version.CSP2) {
// Ignore 'unsafe-inline' in CSP >= v2, if a nonce or a hash is present.
if (values.includes(Keyword.UNSAFE_INLINE)) {
arrayRemove(effectiveCspValues, Keyword.UNSAFE_INLINE);
findings.push(new Finding(
Type.IGNORED,
'unsafe-inline is ignored if a nonce or a hash is present. ' +
'(CSP2 and above)',
Severity.NONE, directive, Keyword.UNSAFE_INLINE));
}
} else {
// remove nonces and hashes (not supported in CSP < v2).
for (const value of values) {
if (value.startsWith('\'nonce-') || value.startsWith('\'sha')) {
arrayRemove(effectiveCspValues, value);
}
}
}
}
if (effectiveCspValues && this.policyHasStrictDynamic()) {
// Ignore allowlist in CSP >= v3 in presence of 'strict-dynamic'.
if (cspVersion >= Version.CSP3) {
for (const value of values) {
// Because of 'strict-dynamic' all host-source and scheme-source
// expressions, as well as the "'unsafe-inline'" and "'self'
// keyword-sources will be ignored.
// https://w3c.github.io/webappsec-csp/#strict-dynamic-usage
if (!value.startsWith('\'') || value === Keyword.SELF ||
value === Keyword.UNSAFE_INLINE) {
arrayRemove(effectiveCspValues, value);
findings.push(new Finding(
Type.IGNORED,
'Because of strict-dynamic this entry is ignored in CSP3 and above',
Severity.NONE, directive, value));
}
}
} else {
// strict-dynamic not supported.
arrayRemove(effectiveCspValues, Keyword.STRICT_DYNAMIC);
}
}
if (cspVersion < Version.CSP3) {
// Remove CSP3 directives from pre-CSP3 policies.
// https://w3c.github.io/webappsec-csp/#changes-from-level-2
delete effectiveCsp.directives[Directive.REPORT_TO];
delete effectiveCsp.directives[Directive.WORKER_SRC];
delete effectiveCsp.directives[Directive.MANIFEST_SRC];
delete effectiveCsp.directives[Directive.TRUSTED_TYPES];
delete effectiveCsp.directives[Directive.REQUIRE_TRUSTED_TYPES_FOR];
}
return effectiveCsp;
}
/**
* Returns default-src if directive is a fetch directive and is not present in
* this CSP. Otherwise the provided directive is returned.
* @param directive CSP.
* @return The effective directive.
*/
getEffectiveDirective(directive: string): string {
// Only fetch directives default to default-src.
if (!(directive in this.directives) &&
FETCH_DIRECTIVES.includes(directive as Directive)) {
return Directive.DEFAULT_SRC;
}
return directive;
}
/**
* Returns the passed directives if present in this CSP or default-src
* otherwise.
* @param directives CSP.
* @return The effective directives.
*/
getEffectiveDirectives(directives: string[]): string[] {
const effectiveDirectives =
new Set(directives.map((val) => this.getEffectiveDirective(val)));
return [...effectiveDirectives];
}
/**
* Checks if this CSP is using nonces for scripts.
* @return true, if this CSP is using script nonces.
*/
policyHasScriptNonces(): boolean {
const directiveName = this.getEffectiveDirective(Directive.SCRIPT_SRC);
const values = this.directives[directiveName] || [];
return values.some((val) => isNonce(val));
}
/**
* Checks if this CSP is using hashes for scripts.
* @return true, if this CSP is using script hashes.
*/
policyHasScriptHashes(): boolean {
const directiveName = this.getEffectiveDirective(Directive.SCRIPT_SRC);
const values = this.directives[directiveName] || [];
return values.some((val) => isHash(val));
}
/**
* Checks if this CSP is using strict-dynamic.
* @return true, if this CSP is using CSP nonces.
*/
policyHasStrictDynamic(): boolean {
const directiveName = this.getEffectiveDirective(Directive.SCRIPT_SRC);
const values = this.directives[directiveName] || [];
return values.includes(Keyword.STRICT_DYNAMIC);
}
}
/**
* CSP directive source keywords.
*/
export enum Keyword {
SELF = '\'self\'',
NONE = '\'none\'',
UNSAFE_INLINE = '\'unsafe-inline\'',
UNSAFE_EVAL = '\'unsafe-eval\'',
WASM_EVAL = '\'wasm-eval\'',
WASM_UNSAFE_EVAL = '\'wasm-unsafe-eval\'',
STRICT_DYNAMIC = '\'strict-dynamic\'',
UNSAFE_HASHED_ATTRIBUTES = '\'unsafe-hashed-attributes\'',
UNSAFE_HASHES = '\'unsafe-hashes\'',
REPORT_SAMPLE = '\'report-sample\''
}
/**
* CSP directive source keywords.
*/
export enum TrustedTypesSink {
SCRIPT = '\'script\''
}
/**
* CSP v3 directives.
* List of valid CSP directives:
* - http://www.w3.org/TR/CSP2/#directives
* - https://www.w3.org/TR/upgrade-insecure-requests/
*
*/
export enum Directive {
// Fetch directives
CHILD_SRC = 'child-src',
CONNECT_SRC = 'connect-src',
DEFAULT_SRC = 'default-src',
FONT_SRC = 'font-src',
FRAME_SRC = 'frame-src',
IMG_SRC = 'img-src',
MEDIA_SRC = 'media-src',
OBJECT_SRC = 'object-src',
SCRIPT_SRC = 'script-src',
SCRIPT_SRC_ATTR = 'script-src-attr',
SCRIPT_SRC_ELEM = 'script-src-elem',
STYLE_SRC = 'style-src',
STYLE_SRC_ATTR = 'style-src-attr',
STYLE_SRC_ELEM = 'style-src-elem',
PREFETCH_SRC = 'prefetch-src',
MANIFEST_SRC = 'manifest-src',
WORKER_SRC = 'worker-src',
// Document directives
BASE_URI = 'base-uri',
PLUGIN_TYPES = 'plugin-types',
SANDBOX = 'sandbox',
DISOWN_OPENER = 'disown-opener',
// Navigation directives
FORM_ACTION = 'form-action',
FRAME_ANCESTORS = 'frame-ancestors',
// Reporting directives
REPORT_TO = 'report-to',
REPORT_URI = 'report-uri',
// Other directives
BLOCK_ALL_MIXED_CONTENT = 'block-all-mixed-content',
UPGRADE_INSECURE_REQUESTS = 'upgrade-insecure-requests',
REFLECTED_XSS = 'reflected-xss',
REFERRER = 'referrer',
REQUIRE_SRI_FOR = 'require-sri-for',
TRUSTED_TYPES = 'trusted-types',
// https://github.com/WICG/trusted-types
REQUIRE_TRUSTED_TYPES_FOR = 'require-trusted-types-for'
}
/**
* CSP v3 fetch directives.
* Fetch directives control the locations from which resources may be loaded.
* https://w3c.github.io/webappsec-csp/#directives-fetch
*
*/
export const FETCH_DIRECTIVES: Directive[] = [
Directive.CHILD_SRC, Directive.CONNECT_SRC, Directive.DEFAULT_SRC,
Directive.FONT_SRC, Directive.FRAME_SRC, Directive.IMG_SRC,
Directive.MANIFEST_SRC, Directive.MEDIA_SRC, Directive.OBJECT_SRC,
Directive.SCRIPT_SRC, Directive.SCRIPT_SRC_ATTR, Directive.SCRIPT_SRC_ELEM,
Directive.STYLE_SRC, Directive.STYLE_SRC_ATTR, Directive.STYLE_SRC_ELEM,
Directive.WORKER_SRC
];
/**
* CSP version.
*/
export enum Version {
CSP1 = 1,
CSP2,
CSP3
}
/**
* Checks if a string is a valid CSP directive.
* @param directive value to check.
* @return True if directive is a valid CSP directive.
*/
export function isDirective(directive: string): boolean {
return Object.values(Directive).includes(directive as Directive);
}
/**
* Checks if a string is a valid CSP keyword.
* @param keyword value to check.
* @return True if keyword is a valid CSP keyword.
*/
export function isKeyword(keyword: string): boolean {
return Object.values(Keyword).includes(keyword as Keyword);
}
/**
* Checks if a string is a valid URL scheme.
* Scheme part + ":"
* For scheme part see https://tools.ietf.org/html/rfc3986#section-3.1
* @param urlScheme value to check.
* @return True if urlScheme has a valid scheme.
*/
export function isUrlScheme(urlScheme: string): boolean {
const pattern = new RegExp('^[a-zA-Z][+a-zA-Z0-9.-]*:$');
return pattern.test(urlScheme);
}
/**
* A regex pattern to check nonce prefix and Base64 formatting of a nonce value.
*/
export const STRICT_NONCE_PATTERN =
new RegExp('^\'nonce-[a-zA-Z0-9+/_-]+[=]{0,2}\'$');
/** A regex pattern for checking if nonce prefix. */
export const NONCE_PATTERN = new RegExp('^\'nonce-(.+)\'$');
/**
* Checks if a string is a valid CSP nonce.
* See http://www.w3.org/TR/CSP2/#nonce_value
* @param nonce value to check.
* @param strictCheck Check if the nonce uses the base64 charset.
* @return True if nonce is has a valid CSP nonce.
*/
export function isNonce(nonce: string, strictCheck?: boolean): boolean {
const pattern = strictCheck ? STRICT_NONCE_PATTERN : NONCE_PATTERN;
return pattern.test(nonce);
}
/**
* A regex pattern to check hash prefix and Base64 formatting of a hash value.
*/
export const STRICT_HASH_PATTERN =
new RegExp('^\'(sha256|sha384|sha512)-[a-zA-Z0-9+/]+[=]{0,2}\'$');
/** A regex pattern to check hash prefix. */
export const HASH_PATTERN = new RegExp('^\'(sha256|sha384|sha512)-(.+)\'$');
/**
* Checks if a string is a valid CSP hash.
* See http://www.w3.org/TR/CSP2/#hash_value
* @param hash value to check.
* @param strictCheck Check if the hash uses the base64 charset.
* @return True if hash is has a valid CSP hash.
*/
export function isHash(hash: string, strictCheck?: boolean): boolean {
const pattern = strictCheck ? STRICT_HASH_PATTERN : HASH_PATTERN;
return pattern.test(hash);
}
/**
* Class to represent all generic CSP errors.
*/
export class CspError extends Error {
/**
* @param message An optional error message.
*/
constructor(message?: string) {
super(message);
}
}
/**
* Mutate the given array to remove the first instance of the given item
*/
function arrayRemove<T>(arr: T[], item: T): void {
if (arr.includes(item)) {
const idx = arr.findIndex(elem => item === elem);
arr.splice(idx, 1);
}
} | the_stack |
import * as tf from '@tensorflow/tfjs';
import { chunk, flatMapDeep } from 'lodash';
import * as types from '../../../types';
import { EmbeddingsModel } from '../embeddings/EmbeddingsModel';
import { TimeSeriesAttention } from '../TimeSeriesAttention';
export default class NerModel extends types.PipelineModel implements types.IPipelineModel {
private static setup(config: types.INerModelParams & types.IDefaultModelParams, datasetParams: types.IDatasetParams) {
const maxWords = datasetParams.maxWordsPerSentence;
const { addAttention, embeddingDimensions, numFilters, rnnUnits } = config;
const numSlotTypes = Object.keys(datasetParams.slotsToId).length;
const LEARNING_RATE = 0.0066; // use 1e-4 as default as alternative starting point
const ADAM_BETA_1 = 0.0025;
const ADAM_BETA_2 = 0.1;
const optimizer = tf.train.adam(LEARNING_RATE, ADAM_BETA_1, ADAM_BETA_2);
// WORD-NGRAMS LEVEL EMBEDDINGS
const embeddedSentencesInput = tf.input({
dtype: 'float32',
name: 'embedded_words',
shape: [maxWords, embeddingDimensions]
});
const convLayer1 = tf.layers
.conv1d({
activation: 'relu',
filters: numFilters[0],
inputShape: [maxWords, embeddingDimensions],
kernelInitializer: 'randomNormal',
kernelSize: 1,
name: 'nerConv1',
padding: 'valid'
})
.apply(embeddedSentencesInput) as tf.SymbolicTensor;
const convLayer2 = tf.layers
.conv1d({
activation: 'relu',
filters: numFilters[0],
kernelInitializer: 'randomNormal',
kernelSize: 1,
name: 'nerConv2',
padding: 'valid'
})
.apply(convLayer1) as tf.SymbolicTensor;
// CONCATENATE BOTH CNN ENCODERS (WORD AND CHAR) WITH THE INPUT AND THE CHAR CNN LAYER 1
const classLabelInput = tf.input({
dtype: 'float32',
name: 'embedded_intent',
shape: [datasetParams.intents.length]
});
const classLabelRepeated = tf.layers.repeatVector({ n: maxWords }).apply(classLabelInput) as tf.SymbolicTensor;
const concated = tf.layers.concatenate().apply([classLabelRepeated, embeddedSentencesInput, convLayer2]);
let finalHidden: tf.SymbolicTensor[] | tf.SymbolicTensor | null = null;
const lstmLayer = tf.layers.lstm({ units: rnnUnits, returnSequences: true, name: 'bidi_encoder' }) as tf.RNN;
if (addAttention) {
const biLstm = tf.layers.bidirectional({ layer: lstmLayer, mergeMode: null } as any).apply(concated) as tf.SymbolicTensor[];
const timeAttention = new TimeSeriesAttention({ name: 'attention_weight' }).apply(biLstm[0]) as tf.SymbolicTensor;
finalHidden = tf.layers.concatenate().apply([timeAttention, biLstm[0], biLstm[1]]) as tf.SymbolicTensor;
} else {
finalHidden = tf.layers.bidirectional({ layer: lstmLayer, mergeMode: 'concat' }).apply(concated) as tf.SymbolicTensor[];
}
const outputs = tf.layers.dense({ activation: 'softmax', units: numSlotTypes }).apply(finalHidden) as tf.SymbolicTensor;
const model = tf.model({ inputs: [classLabelInput, embeddedSentencesInput], outputs });
model.compile({ loss: 'categoricalCrossentropy', metrics: ['accuracy'], optimizer });
return model;
}
private config: types.INerModelParams & types.IDefaultModelParams;
private datasetParams: types.IDatasetParams;
private model: tf.LayersModel;
private embeddingsModel: EmbeddingsModel;
private logger: types.IPipelineModelLogger;
private nerTrainStatsHandler: types.ITrainStatsHandler['ner'] | undefined;
constructor(
config: types.INerModelParams & types.IDefaultModelParams,
datasetParams: types.IDatasetParams,
embeddingsModel: EmbeddingsModel,
logger: types.IPipelineModelLogger,
pretrainedModel?: tf.LayersModel,
nerTrainStatsHandler?: types.ITrainStatsHandler['ner']
) {
super();
this.config = config;
this.datasetParams = datasetParams;
this.embeddingsModel = embeddingsModel;
this.model = pretrainedModel ? pretrainedModel : NerModel.setup(this.config, this.datasetParams);
this.logger = logger;
this.nerTrainStatsHandler = nerTrainStatsHandler;
}
public tfModel = () => this.model;
public rawPrediction = (sentences: string[], classificationPred: types.IClassificationPred[]) => {
return tf.tidy(() => {
const { maxWordsPerSentence: maxWords, slotsToId } = this.datasetParams;
const slotTypesLength = Object.keys(slotsToId).length;
const embeddedSentences = this.embeddingsModel.embed(sentences);
const encodedIntent = classificationPred.map(p => {
const intentEncoded = new Array(this.datasetParams.intents.length).fill(0) as number[];
const idx = this.datasetParams.intents.indexOf(p.intent);
if (idx !== -1) {
intentEncoded[idx] = 1;
}
return intentEncoded;
});
const intentsFlat = flatMapDeep(encodedIntent);
const classLabel = tf.tensor2d(intentsFlat, [encodedIntent.length, this.datasetParams.intents.length]);
const output = this.model.predict([classLabel, embeddedSentences]) as tf.Tensor<tf.Rank>;
const flattenedPredictions = output.dataSync() as Float32Array;
output.dispose();
classLabel.dispose();
embeddedSentences.dispose();
// word predictions for each sentence in the form [sentence, word, slots scores]
const chunks = chunk(flattenedPredictions, maxWords * slotTypesLength).map(sp => chunk(sp, slotTypesLength));
return chunks.map(sentencePreds => {
return sentencePreds.map(wordTagPredictions => {
let highestIndex = 0;
let confidence = wordTagPredictions.length ? wordTagPredictions[highestIndex] : 0;
wordTagPredictions.forEach((tp, ti) => {
if (wordTagPredictions[highestIndex] < tp) {
highestIndex = ti;
confidence = tp;
}
});
return { highestIndex, confidence };
});
});
});
};
public predict = (sentences: string[], classificationPred: types.IClassificationPred[]) => {
const { lowConfidenceThreshold } = this.config;
const { slotsToId } = this.datasetParams;
const wordPredictionsChunk = this.rawPrediction(sentences, classificationPred);
return sentences.map((s, i) => {
const sentenceWordPredictionIds = wordPredictionsChunk[i];
const sentenceWords = this.embeddingsModel.tokenizer.splitSentenceToWords(s);
return sentenceWords.reduce(
(accumulator: types.ISlotReducer, w: string, currentIndex) => {
if (accumulator.current && accumulator.current.confidence === 0) {
accumulator.current.confidence = sentenceWordPredictionIds[currentIndex].confidence;
}
const currentSlotKey = Object.keys(slotsToId).find(
slotKey =>
sentenceWordPredictionIds[currentIndex] &&
slotsToId[slotKey] === sentenceWordPredictionIds[currentIndex].highestIndex
);
if (!currentSlotKey || !accumulator.current) {
return accumulator;
}
if (accumulator.current.key !== currentSlotKey) {
if (
accumulator.current.key &&
accumulator.current.key !== 'O' &&
accumulator.current.confidence >= lowConfidenceThreshold
) {
if (!accumulator.slots[accumulator.current.key]) {
accumulator.slots[accumulator.current.key] = [];
}
accumulator.slots[accumulator.current.key].push({
confidence: accumulator.current.confidence,
value: accumulator.current.value
});
}
accumulator.current = {
confidence: sentenceWordPredictionIds[currentIndex].confidence,
key: currentSlotKey,
value: w
};
} else {
// todo: add a join words handler for languages that tokenize differently
accumulator.current.value += ` ${w}`;
accumulator.current.confidence =
(sentenceWordPredictionIds[currentIndex].confidence + accumulator.current.confidence) / 2;
}
if (currentIndex + 1 === sentenceWords.length) {
if (accumulator.current.key !== 'O' && accumulator.current.confidence >= lowConfidenceThreshold) {
if (!accumulator.slots[accumulator.current.key]) {
accumulator.slots[accumulator.current.key] = [];
}
accumulator.slots[accumulator.current.key].push({
confidence: accumulator.current.confidence,
value: accumulator.current.value
});
}
return { sentence: s, slots: accumulator.slots };
}
return accumulator;
},
{ current: { key: '', value: '', confidence: 0 }, slots: {}, sentence: '' }
);
});
};
public train = async (trainDataset: types.ITrainingParams) => {
const trainY2Chunks = chunk(trainDataset.trainY2, this.config.batchSize);
const trainYChunks = chunk(trainDataset.trainY, this.config.batchSize);
const trainXChunks = chunk(trainDataset.trainX, this.config.batchSize);
const { epochs, trainingValidationSplit: validationSplit } = this.config;
const slotsLength = Object.keys(this.datasetParams.slotsToId).length;
this.logger.log('Start training NER model!');
let enoughAccuracyReached = false;
for (const [index, xChunk] of trainXChunks.entries()) {
if (enoughAccuracyReached) {
return;
}
// classification hot encoded labels as input
const intentLabels = tf.tidy(() =>
tf.oneHot(tf.tensor1d(trainYChunks[index], 'int32'), this.datasetParams.intents.length).asType('float32')
);
const embeddedSentenceWords = this.embeddingsModel.embed(xChunk);
// convert sentence-word-slots from the highest index format like [0,0,0,0,4,4,0,0,3,3] for a sentence
// to one hot encoded sentences with correct maxWords and batch sizes tensor sizes
const slotTags: tf.Tensor3D = tf.tidy(() => {
const y2sentences: tf.Tensor2D[] = [];
for (const wordsSlotId of trainY2Chunks[index]) {
const slotIds = tf
.tensor1d(wordsSlotId, 'int32')
.pad([[0, this.datasetParams.maxWordsPerSentence - wordsSlotId.length]]);
const ohe = tf.oneHot(slotIds, slotsLength).asType('float32') as tf.Tensor2D;
slotIds.dispose();
y2sentences.push(ohe);
}
const stack = tf.stack(y2sentences) as tf.Tensor3D;
y2sentences.forEach(s => s.dispose());
return stack;
});
await this.model.fit([intentLabels, embeddedSentenceWords], slotTags, {
// batchSize: this.config.batchSize,
callbacks: { onBatchEnd: tf.nextFrame },
epochs,
shuffle: true,
validationSplit
});
intentLabels.dispose();
embeddedSentenceWords.dispose();
await tf.nextFrame();
const h = this.model.history.history;
const c = h.val_loss.length - 1;
const epoch = this.model.history.epoch;
if (this.nerTrainStatsHandler) {
this.nerTrainStatsHandler({
batch: index + 1,
batchEpochs: epoch.length,
currentBatchSize: trainXChunks[index].length,
tensorsInMemory: tf.memory().numTensors,
totalBatches: trainXChunks.length,
trainingAccuracy: h.acc[c],
trainingLoss: h.loss[c],
validationAccuracy: h.val_acc[c],
validationLoss: h.val_loss[c]
});
}
this.logger.log(`Trained ${epoch.length} epochs on batch ${index + 1} of ${trainXChunks.length}`);
this.logger.log(`Training Loss: ${h.loss[c]} | Training Accuracy: ${h.acc[c]}`);
this.logger.log(`Validation Loss: ${h.val_loss[c]} | Validation Accuracy: ${h.val_acc[c]}`);
this.logger.warn(`(Memory) Number of tensors in memory at the end of batch: ${tf.memory().numTensors}`);
this.logger.log('==================================================================================================');
slotTags.dispose();
if (
this.config.lossThresholdToStopTraining &&
h.loss[c] < this.config.lossThresholdToStopTraining &&
h.val_loss[c] < this.config.lossThresholdToStopTraining
) {
enoughAccuracyReached = true;
this.logger.warn(`Enough accuracy reached! Ending training after batch ${index + 1} of ${trainXChunks.length}`);
this.logger.log('==================================================================================================');
}
}
};
public test = async (
testExamples: types.ITestingParams,
resultsHandler?: types.ITestPredictionsHandler
): Promise<types.IPredictionStats> => {
const handler = resultsHandler ? resultsHandler : this.defaultResultsLogger;
const stats: types.IPredictionStats = { correct: 0, wrong: 0 };
const batchSize = this.config.batchSize;
const testX = chunk(testExamples.testX, batchSize);
const testY = chunk(testExamples.testY, batchSize);
const testY2 = chunk(testExamples.testY2, batchSize);
for (const [i, sentences] of testX.entries()) {
const classifications = testY[i];
const encodedIntent = sentences.map(
(p, idx) =>
({
confidence: 1,
intent: this.datasetParams.intents[classifications[idx]],
sentence: p
} as types.IClassificationPred)
);
const predictions = this.rawPrediction(sentences, encodedIntent).map(sentence => sentence.map(s => s.highestIndex));
handler(sentences, testY2[i], predictions, stats);
await tf.nextFrame();
}
return stats;
};
private defaultResultsLogger = (
x: types.ITestingParams['testX'],
y2: types.ITestingParams['testY2'],
o: types.ITestingParams['testY2'],
stats: types.IPredictionStats
): types.IPredictionStats => {
x.forEach((s, sentenceIdx) => {
const expectedTags = y2[sentenceIdx];
const predictedTags = o[sentenceIdx];
let correct = true;
expectedTags.forEach((tag, idx) => {
if (predictedTags[idx] !== tag && correct) {
correct = false;
}
});
if (correct) {
stats.correct++;
this.logger.debug(`CORRECT - ${s} expected: ${expectedTags}, predicted: ${predictedTags}`);
} else {
stats.wrong++;
this.logger.error(`WRONG - ${s} expected: ${expectedTags}, predicted: ${predictedTags}`);
}
});
return stats;
};
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Azure resource
*/
export interface Resource extends BaseResource {
/**
* Specifies the resource ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Specifies the name of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Specifies the location of the resource.
*/
location: string;
/**
* Specifies the type of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Contains resource tags defined as key/value pairs.
*/
tags?: { [propertyName: string]: string };
}
/**
* Error detail information.
*/
export interface ErrorDetail {
/**
* Error code.
*/
code: string;
/**
* Error message.
*/
message: string;
}
/**
* Error response information.
*/
export interface ErrorResponse {
/**
* Error code.
*/
code: string;
/**
* Error message.
*/
message: string;
/**
* An array of error detail objects.
*/
details?: ErrorDetail[];
}
/**
* Wrapper for error response to follow ARM guidelines.
*/
export interface ErrorResponseWrapper {
/**
* The error response.
*/
error?: ErrorResponse;
}
/**
* Properties of Storage Account.
*/
export interface StorageAccountProperties {
/**
* ARM resource ID of the Azure Storage Account to store CLI specific files. If not provided one
* will be created. This cannot be changed once the cluster is created.
*/
resourceId?: string;
}
/**
* Properties of Azure Container Registry.
*/
export interface ContainerRegistryProperties {
/**
* ARM resource ID of the Azure Container Registry used to store Docker images for web services
* in the cluster. If not provided one will be created. This cannot be changed once the cluster
* is created.
*/
resourceId?: string;
}
/**
* The Azure service principal used by Kubernetes for configuring load balancers
*/
export interface ServicePrincipalProperties {
/**
* The service principal client ID
*/
clientId: string;
/**
* The service principal secret. This is not returned in response of GET/PUT on the resource. To
* see this please call listKeys.
*/
secret: string;
}
/**
* Kubernetes cluster specific properties
*/
export interface KubernetesClusterProperties {
/**
* The Azure Service Principal used by Kubernetes
*/
servicePrincipal?: ServicePrincipalProperties;
}
/**
* Information about a system service deployed in the cluster
*/
export interface SystemService {
/**
* The system service type. Possible values include: 'None', 'ScoringFrontEnd', 'BatchFrontEnd'
*/
systemServiceType: SystemServiceType;
/**
* The public IP address of the system service
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly publicIpAddress?: string;
/**
* The state of the system service
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly version?: string;
}
/**
* Information about the container service backing the cluster
*/
export interface AcsClusterProperties {
/**
* The FQDN of the cluster.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly clusterFqdn?: string;
/**
* Type of orchestrator. It cannot be changed once the cluster is created. Possible values
* include: 'Kubernetes', 'None'
*/
orchestratorType: OrchestratorType;
/**
* Orchestrator specific properties
*/
orchestratorProperties?: KubernetesClusterProperties;
/**
* The system services deployed to the cluster
*/
systemServices?: SystemService[];
/**
* The number of master nodes in the container service. Default value: 1.
*/
masterCount?: number;
/**
* The number of agent nodes in the Container Service. This can be changed to scale the cluster.
* Default value: 2.
*/
agentCount?: number;
/**
* The Azure VM size of the agent VM nodes. This cannot be changed once the cluster is created.
* This list is non exhaustive; refer to
* https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes for the possible VM
* sizes. Possible values include: 'Standard_A0', 'Standard_A1', 'Standard_A2', 'Standard_A3',
* 'Standard_A4', 'Standard_A5', 'Standard_A6', 'Standard_A7', 'Standard_A8', 'Standard_A9',
* 'Standard_A10', 'Standard_A11', 'Standard_D1', 'Standard_D2', 'Standard_D3', 'Standard_D4',
* 'Standard_D11', 'Standard_D12', 'Standard_D13', 'Standard_D14', 'Standard_D1_v2',
* 'Standard_D2_v2', 'Standard_D3_v2', 'Standard_D4_v2', 'Standard_D5_v2', 'Standard_D11_v2',
* 'Standard_D12_v2', 'Standard_D13_v2', 'Standard_D14_v2', 'Standard_G1', 'Standard_G2',
* 'Standard_G3', 'Standard_G4', 'Standard_G5', 'Standard_DS1', 'Standard_DS2', 'Standard_DS3',
* 'Standard_DS4', 'Standard_DS11', 'Standard_DS12', 'Standard_DS13', 'Standard_DS14',
* 'Standard_GS1', 'Standard_GS2', 'Standard_GS3', 'Standard_GS4', 'Standard_GS5'. Default value:
* 'Standard_D3_v2'.
*/
agentVmSize?: AgentVMSizeTypes;
}
/**
* Properties of App Insights.
*/
export interface AppInsightsProperties {
/**
* ARM resource ID of the App Insights.
*/
resourceId?: string;
}
/**
* SSL configuration. If configured data-plane calls to user services will be exposed over SSL
* only.
*/
export interface SslConfiguration {
/**
* SSL status. Allowed values are Enabled and Disabled. Possible values include: 'Enabled',
* 'Disabled'. Default value: 'Enabled'.
*/
status?: Status;
/**
* The SSL cert data in PEM format.
*/
cert?: string;
/**
* The SSL key data in PEM format. This is not returned in response of GET/PUT on the resource.
* To see this please call listKeys API.
*/
key?: string;
/**
* The CName of the certificate.
*/
cname?: string;
}
/**
* Global service auth configuration properties. These are the data-plane authorization keys and
* are used if a service doesn't define it's own.
*/
export interface ServiceAuthConfiguration {
/**
* The primary auth key hash. This is not returned in response of GET/PUT on the resource.. To
* see this please call listKeys API.
*/
primaryAuthKeyHash: string;
/**
* The secondary auth key hash. This is not returned in response of GET/PUT on the resource.. To
* see this please call listKeys API.
*/
secondaryAuthKeyHash: string;
}
/**
* AutoScale configuration properties.
*/
export interface AutoScaleConfiguration {
/**
* If auto-scale is enabled for all services. Each service can turn it off individually. Possible
* values include: 'Enabled', 'Disabled'. Default value: 'Disabled'.
*/
status?: Status;
/**
* The minimum number of replicas for each service. Default value: 1.
*/
minReplicas?: number;
/**
* The maximum number of replicas for each service. Default value: 100.
*/
maxReplicas?: number;
/**
* The target utilization.
*/
targetUtilization?: number;
/**
* Refresh period in seconds.
*/
refreshPeriodInSeconds?: number;
}
/**
* Global configuration for services in the cluster.
*/
export interface GlobalServiceConfiguration {
/**
* The configuration ETag for updates.
*/
etag?: string;
/**
* The SSL configuration properties
*/
ssl?: SslConfiguration;
/**
* Optional global authorization keys for all user services deployed in cluster. These are used
* if the service does not have auth keys.
*/
serviceAuth?: ServiceAuthConfiguration;
/**
* The auto-scale configuration
*/
autoScale?: AutoScaleConfiguration;
/**
* Describes unknown properties. The value of an unknown property can be of "any" type.
*/
[property: string]: any;
}
/**
* Instance of an Azure ML Operationalization Cluster resource.
*/
export interface OperationalizationCluster extends Resource {
/**
* The description of the cluster.
*/
description?: string;
/**
* The date and time when the cluster was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdOn?: Date;
/**
* The date and time when the cluster was last modified.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly modifiedOn?: Date;
/**
* The provision state of the cluster. Valid values are Unknown, Updating, Provisioning,
* Succeeded, and Failed. Possible values include: 'Unknown', 'Updating', 'Creating', 'Deleting',
* 'Succeeded', 'Failed', 'Canceled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: OperationStatus;
/**
* List of provisioning errors reported by the resource provider.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningErrors?: ErrorResponseWrapper[];
/**
* The cluster type. Possible values include: 'ACS', 'Local'
*/
clusterType: ClusterType;
/**
* Storage Account properties.
*/
storageAccount?: StorageAccountProperties;
/**
* Container Registry properties.
*/
containerRegistry?: ContainerRegistryProperties;
/**
* Parameters for the Azure Container Service cluster.
*/
containerService?: AcsClusterProperties;
/**
* AppInsights configuration.
*/
appInsights?: AppInsightsProperties;
/**
* Contains global configuration for the web services in the cluster.
*/
globalServiceConfiguration?: GlobalServiceConfiguration;
}
/**
* Parameters for PATCH operation on an operationalization cluster
*/
export interface OperationalizationClusterUpdateParameters {
/**
* Gets or sets a list of key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15 tags can be
* provided for a resource. Each tag must have a key no greater in length than 128 characters and
* a value no greater in length than 256 characters.
*/
tags?: { [propertyName: string]: string };
}
/**
* Access information for the storage account.
*/
export interface StorageAccountCredentials {
/**
* The ARM resource ID of the storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceId?: string;
/**
* The primary key of the storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryKey?: string;
/**
* The secondary key of the storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryKey?: string;
}
/**
* Information about the Azure Container Registry which contains the images deployed to the
* cluster.
*/
export interface ContainerRegistryCredentials {
/**
* The ACR login server name. User name is the first part of the FQDN.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly loginServer?: string;
/**
* The ACR primary password.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly password?: string;
/**
* The ACR secondary password.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly password2?: string;
/**
* The ACR login username.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly username?: string;
}
/**
* Information about the Azure Container Registry which contains the images deployed to the
* cluster.
*/
export interface ContainerServiceCredentials {
/**
* The ACS kube config file.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly acsKubeConfig?: string;
/**
* Service principal configuration used by Kubernetes.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly servicePrincipalConfiguration?: ServicePrincipalProperties;
/**
* The ACR image pull secret name which was created in Kubernetes.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly imagePullSecretName?: string;
}
/**
* AppInsights credentials.
*/
export interface AppInsightsCredentials {
/**
* The AppInsights application ID.
*/
appId?: string;
/**
* The AppInsights instrumentation key. This is not returned in response of GET/PUT on the
* resource. To see this please call listKeys API.
*/
instrumentationKey?: string;
}
/**
* Credentials to resources in the cluster.
*/
export interface OperationalizationClusterCredentials {
/**
* Credentials for the Storage Account.
*/
storageAccount?: StorageAccountCredentials;
/**
* Credentials for Azure Container Registry.
*/
containerRegistry?: ContainerRegistryCredentials;
/**
* Credentials for Azure Container Service.
*/
containerService?: ContainerServiceCredentials;
/**
* Credentials for Azure AppInsights.
*/
appInsights?: AppInsightsCredentials;
/**
* Global authorization keys for all user services deployed in cluster. These are used if the
* service does not have auth keys.
*/
serviceAuthConfiguration?: ServiceAuthConfiguration;
/**
* The SSL configuration for the services.
*/
sslConfiguration?: SslConfiguration;
}
/**
* Information about updates available for system services in a cluster.
*/
export interface CheckSystemServicesUpdatesAvailableResponse {
/**
* Yes if updates are available for the system services, No if not. Possible values include:
* 'Yes', 'No'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updatesAvailable?: UpdatesAvailable;
}
/**
* Response of the update system services API
*/
export interface UpdateSystemServicesResponse {
/**
* Update status. Possible values include: 'Unknown', 'Updating', 'Creating', 'Deleting',
* 'Succeeded', 'Failed', 'Canceled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updateStatus?: OperationStatus;
/**
* The date and time when the last system services update was started.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updateStartedOn?: Date;
/**
* The date and time when the last system services update completed.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updateCompletedOn?: Date;
}
/**
* Display of the operation.
*/
export interface ResourceOperationDisplay {
/**
* The resource provider name.
*/
provider?: string;
/**
* The resource name.
*/
resource?: string;
/**
* The operation.
*/
operation?: string;
/**
* The description of the operation.
*/
description?: string;
}
/**
* Resource operation.
*/
export interface ResourceOperation {
/**
* Name of this operation.
*/
name?: string;
/**
* Display of the operation.
*/
display?: ResourceOperationDisplay;
/**
* The operation origin.
*/
origin?: string;
}
/**
* Available operation list.
*/
export interface AvailableOperations {
/**
* An array of available operations.
*/
value?: ResourceOperation[];
}
/**
* Optional Parameters.
*/
export interface OperationalizationClustersDeleteMethodOptionalParams extends msRest.RequestOptionsBase {
/**
* If true, deletes all resources associated with this cluster.
*/
deleteAll?: boolean;
}
/**
* Optional Parameters.
*/
export interface OperationalizationClustersListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* Continuation token for pagination.
*/
skiptoken?: string;
}
/**
* Optional Parameters.
*/
export interface OperationalizationClustersListBySubscriptionIdOptionalParams extends msRest.RequestOptionsBase {
/**
* Continuation token for pagination.
*/
skiptoken?: string;
}
/**
* Optional Parameters.
*/
export interface OperationalizationClustersBeginDeleteMethodOptionalParams extends msRest.RequestOptionsBase {
/**
* If true, deletes all resources associated with this cluster.
*/
deleteAll?: boolean;
}
/**
* Optional Parameters.
*/
export interface OperationalizationClustersListByResourceGroupNextOptionalParams extends msRest.RequestOptionsBase {
/**
* Continuation token for pagination.
*/
skiptoken?: string;
}
/**
* Optional Parameters.
*/
export interface OperationalizationClustersListBySubscriptionIdNextOptionalParams extends msRest.RequestOptionsBase {
/**
* Continuation token for pagination.
*/
skiptoken?: string;
}
/**
* An interface representing MachineLearningComputeManagementClientOptions.
*/
export interface MachineLearningComputeManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* Defines headers for Delete operation.
*/
export interface OperationalizationClustersDeleteHeaders {
/**
* URI of the async operation.
*/
location: string;
}
/**
* Defines headers for UpdateSystemServices operation.
*/
export interface OperationalizationClustersUpdateSystemServicesHeaders {
/**
* URI of the async operation.
*/
location: string;
}
/**
* @interface
* Paginated list of operationalization clusters.
* @extends Array<OperationalizationCluster>
*/
export interface PaginatedOperationalizationClustersList extends Array<OperationalizationCluster> {
/**
* A continuation link (absolute URI) to the next page of results in the list.
*/
nextLink?: string;
}
/**
* Defines values for OperationStatus.
* Possible values include: 'Unknown', 'Updating', 'Creating', 'Deleting', 'Succeeded', 'Failed',
* 'Canceled'
* @readonly
* @enum {string}
*/
export type OperationStatus = 'Unknown' | 'Updating' | 'Creating' | 'Deleting' | 'Succeeded' | 'Failed' | 'Canceled';
/**
* Defines values for ClusterType.
* Possible values include: 'ACS', 'Local'
* @readonly
* @enum {string}
*/
export type ClusterType = 'ACS' | 'Local';
/**
* Defines values for OrchestratorType.
* Possible values include: 'Kubernetes', 'None'
* @readonly
* @enum {string}
*/
export type OrchestratorType = 'Kubernetes' | 'None';
/**
* Defines values for SystemServiceType.
* Possible values include: 'None', 'ScoringFrontEnd', 'BatchFrontEnd'
* @readonly
* @enum {string}
*/
export type SystemServiceType = 'None' | 'ScoringFrontEnd' | 'BatchFrontEnd';
/**
* Defines values for AgentVMSizeTypes.
* Possible values include: 'Standard_A0', 'Standard_A1', 'Standard_A2', 'Standard_A3',
* 'Standard_A4', 'Standard_A5', 'Standard_A6', 'Standard_A7', 'Standard_A8', 'Standard_A9',
* 'Standard_A10', 'Standard_A11', 'Standard_D1', 'Standard_D2', 'Standard_D3', 'Standard_D4',
* 'Standard_D11', 'Standard_D12', 'Standard_D13', 'Standard_D14', 'Standard_D1_v2',
* 'Standard_D2_v2', 'Standard_D3_v2', 'Standard_D4_v2', 'Standard_D5_v2', 'Standard_D11_v2',
* 'Standard_D12_v2', 'Standard_D13_v2', 'Standard_D14_v2', 'Standard_G1', 'Standard_G2',
* 'Standard_G3', 'Standard_G4', 'Standard_G5', 'Standard_DS1', 'Standard_DS2', 'Standard_DS3',
* 'Standard_DS4', 'Standard_DS11', 'Standard_DS12', 'Standard_DS13', 'Standard_DS14',
* 'Standard_GS1', 'Standard_GS2', 'Standard_GS3', 'Standard_GS4', 'Standard_GS5'
* @readonly
* @enum {string}
*/
export type AgentVMSizeTypes = 'Standard_A0' | 'Standard_A1' | 'Standard_A2' | 'Standard_A3' | 'Standard_A4' | 'Standard_A5' | 'Standard_A6' | 'Standard_A7' | 'Standard_A8' | 'Standard_A9' | 'Standard_A10' | 'Standard_A11' | 'Standard_D1' | 'Standard_D2' | 'Standard_D3' | 'Standard_D4' | 'Standard_D11' | 'Standard_D12' | 'Standard_D13' | 'Standard_D14' | 'Standard_D1_v2' | 'Standard_D2_v2' | 'Standard_D3_v2' | 'Standard_D4_v2' | 'Standard_D5_v2' | 'Standard_D11_v2' | 'Standard_D12_v2' | 'Standard_D13_v2' | 'Standard_D14_v2' | 'Standard_G1' | 'Standard_G2' | 'Standard_G3' | 'Standard_G4' | 'Standard_G5' | 'Standard_DS1' | 'Standard_DS2' | 'Standard_DS3' | 'Standard_DS4' | 'Standard_DS11' | 'Standard_DS12' | 'Standard_DS13' | 'Standard_DS14' | 'Standard_GS1' | 'Standard_GS2' | 'Standard_GS3' | 'Standard_GS4' | 'Standard_GS5';
/**
* Defines values for Status.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type Status = 'Enabled' | 'Disabled';
/**
* Defines values for UpdatesAvailable.
* Possible values include: 'Yes', 'No'
* @readonly
* @enum {string}
*/
export type UpdatesAvailable = 'Yes' | 'No';
/**
* Contains response data for the createOrUpdate operation.
*/
export type OperationalizationClustersCreateOrUpdateResponse = OperationalizationCluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationalizationCluster;
};
};
/**
* Contains response data for the get operation.
*/
export type OperationalizationClustersGetResponse = OperationalizationCluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationalizationCluster;
};
};
/**
* Contains response data for the update operation.
*/
export type OperationalizationClustersUpdateResponse = OperationalizationCluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationalizationCluster;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type OperationalizationClustersDeleteResponse = OperationalizationClustersDeleteHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: OperationalizationClustersDeleteHeaders;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type OperationalizationClustersListKeysResponse = OperationalizationClusterCredentials & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationalizationClusterCredentials;
};
};
/**
* Contains response data for the checkSystemServicesUpdatesAvailable operation.
*/
export type OperationalizationClustersCheckSystemServicesUpdatesAvailableResponse = CheckSystemServicesUpdatesAvailableResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CheckSystemServicesUpdatesAvailableResponse;
};
};
/**
* Contains response data for the updateSystemServices operation.
*/
export type OperationalizationClustersUpdateSystemServicesResponse = UpdateSystemServicesResponse & OperationalizationClustersUpdateSystemServicesHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: OperationalizationClustersUpdateSystemServicesHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: UpdateSystemServicesResponse;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type OperationalizationClustersListByResourceGroupResponse = PaginatedOperationalizationClustersList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PaginatedOperationalizationClustersList;
};
};
/**
* Contains response data for the listBySubscriptionId operation.
*/
export type OperationalizationClustersListBySubscriptionIdResponse = PaginatedOperationalizationClustersList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PaginatedOperationalizationClustersList;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type OperationalizationClustersBeginCreateOrUpdateResponse = OperationalizationCluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationalizationCluster;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type OperationalizationClustersListByResourceGroupNextResponse = PaginatedOperationalizationClustersList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PaginatedOperationalizationClustersList;
};
};
/**
* Contains response data for the listBySubscriptionIdNext operation.
*/
export type OperationalizationClustersListBySubscriptionIdNextResponse = PaginatedOperationalizationClustersList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PaginatedOperationalizationClustersList;
};
};
/**
* Contains response data for the listAvailableOperations operation.
*/
export type MachineLearningComputeListAvailableOperationsResponse = AvailableOperations & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AvailableOperations;
};
}; | the_stack |
import {mat4, ReadonlyVec3, vec3} from 'gl-matrix';
import {quatLookRotation} from '../../../utils/math/math';
import Camera3D from '../../../utils/render/camera/Camera3D';
import Renderer from '../../../utils/render/Renderer';
import ObjLoader from '../ObjLoader';
import {BodyPart} from './BodyPart';
import SkeletonModelNode from './SkeletonModelNode';
const ZERO: ReadonlyVec3 = [0, 0, 0];
export default class SkeletonModel {
root = new SkeletonModelNode();
[BodyPart.trunk] = this.root;
[BodyPart.head] = new SkeletonModelNode();
[BodyPart.leftUpperArm] = new SkeletonModelNode();
[BodyPart.leftLowerArm] = new SkeletonModelNode();
[BodyPart.leftHand] = new SkeletonModelNode();
[BodyPart.leftThigh] = new SkeletonModelNode();
[BodyPart.leftCalf] = new SkeletonModelNode();
[BodyPart.leftFoot] = new SkeletonModelNode();
[BodyPart.rightUpperArm] = new SkeletonModelNode();
[BodyPart.rightLowerArm] = new SkeletonModelNode();
[BodyPart.rightHand] = new SkeletonModelNode();
[BodyPart.rightThigh] = new SkeletonModelNode();
[BodyPart.rightCalf] = new SkeletonModelNode();
[BodyPart.rightFoot] = new SkeletonModelNode();
update(camera: Camera3D, node: SkeletonModelNode = this.root) {
const stack: SkeletonModelNode[] = [node];
for (; ;) {
const node = stack.pop();
if (!node) {
break;
}
stack.push(...node.children);
quatLookRotation(node.localRotation, node.forward, node.up);
mat4.fromRotationTranslation(node.localMatrix, node.localRotation, node.translation);
if (node.parent) {
mat4.mul(node.worldMatrix, node.parent.worldMatrix, node.localMatrix);
} else {
mat4.copy(node.worldMatrix, node.localMatrix);
}
vec3.transformMat4(node.originWorldPosition, ZERO, node.worldMatrix);
vec3.transformMat4(node.originViewPosition, node.originWorldPosition, camera.viewMatrix);
if (node.controlPoint) {
vec3.transformMat4(node.controlPointWorldPosition, node.controlPoint, node.worldMatrix);
vec3.transformMat4(node.controlPointViewPosition, node.controlPointWorldPosition, camera.viewMatrix);
vec3.transformMat4(node.controlPointScreenPosition, node.controlPointWorldPosition, camera.pvMatrix);
}
if (node.landmarks.length !== node.landmarksWorldPositions.length) {
node.landmarksWorldPositions = node.landmarks.map(_ => [0, 0, 0]);
node.landmarksViewPosition = node.landmarks.map(_ => [0, 0, 0]);
}
for (let i = 0, len = node.landmarks.length; i < len; ++i) {
vec3.transformMat4(node.landmarksWorldPositions[i], node.landmarks[i], node.worldMatrix);
vec3.transformMat4(node.landmarksViewPosition[i], node.landmarksWorldPositions[i], camera.viewMatrix);
}
}
}
render(renderer: Renderer) {
const stack: SkeletonModelNode[] = [this.root];
for (; ;) {
const node = stack.pop();
if (!node) {
break;
}
stack.push(...node.children);
node.render(renderer);
}
}
async init() {
// =============== load objs ===============
const headObjPromise = import('./obj/head.obj');
const trunkObjPromise = import('./obj/trunk.obj');
const leftUpperArmObjPromise = import('./obj/left-upper-arm.obj');
const leftLowerArmObjPromise = import('./obj/left-lower-arm.obj');
const leftHandObjPromise = import('./obj/left-hand.obj');
const rightUpperArmObjPromise = import('./obj/right-upper-arm.obj');
const rightLowerArmObjPromise = import('./obj/right-lower-arm.obj');
const rightHandObjPromise = import('./obj/right-hand.obj');
const leftThighObjPromise = import('./obj/left-thigh.obj');
const leftCalfObjPromise = import('./obj/left-calf.obj');
const leftFootObjPromise = import('./obj/left-foot.obj');
const rightThighObjPromise = import('./obj/right-thigh.obj');
const rightCalfObjPromise = import('./obj/right-calf.obj');
const rightFootObjPromise = import('./obj/right-foot.obj');
await Promise.all([
headObjPromise,
trunkObjPromise,
leftUpperArmObjPromise,
leftLowerArmObjPromise,
leftHandObjPromise,
rightUpperArmObjPromise,
rightLowerArmObjPromise,
rightHandObjPromise,
leftThighObjPromise,
leftCalfObjPromise,
leftFootObjPromise,
rightThighObjPromise,
rightCalfObjPromise,
rightFootObjPromise,
]);
const headVertices = new ObjLoader().load((await headObjPromise).default);
const trunkVertices = new ObjLoader().load((await trunkObjPromise).default);
const leftUpperArmVertices = new ObjLoader().load((await leftUpperArmObjPromise).default);
const leftLowerArmVertices = new ObjLoader().load((await leftLowerArmObjPromise).default);
const leftHandVertices = new ObjLoader().load((await leftHandObjPromise).default);
const rightUpperArmVertices = new ObjLoader().load((await rightUpperArmObjPromise).default);
const rightLowerArmVertices = new ObjLoader().load((await rightLowerArmObjPromise).default);
const rightHandVertices = new ObjLoader().load((await rightHandObjPromise).default);
const leftThighVertices = new ObjLoader().load((await leftThighObjPromise).default);
const leftCalfVertices = new ObjLoader().load((await leftCalfObjPromise).default);
const leftFootVertices = new ObjLoader().load((await leftFootObjPromise).default);
const rightThighVertices = new ObjLoader().load((await rightThighObjPromise).default);
const rightCalfVertices = new ObjLoader().load((await rightCalfObjPromise).default);
const rightFootVertices = new ObjLoader().load((await rightFootObjPromise).default);
// =============== move rotation origins to joint connection points ===============
const headOffset: [number, number, number] = [
0,
headVertices.lowerY + headVertices.yRange * 0.35,
headVertices.zRange * -0.1,
];
const leftUpperArmOffset: [number, number, number] = [
leftUpperArmVertices.lowerX + leftUpperArmVertices.xRange * 0.3,
leftUpperArmVertices.lowerY + leftUpperArmVertices.yRange * (1 - 0.075),
leftUpperArmVertices.zRange * -0.1,
];
const leftLowerArmOffset: [number, number, number] = [
leftLowerArmVertices.lowerX - leftUpperArmOffset[0] + leftLowerArmVertices.xRange * 0.5,
leftLowerArmVertices.lowerY - leftUpperArmOffset[1] + leftLowerArmVertices.yRange * (1 - 0.05),
leftLowerArmVertices.lowerZ - leftUpperArmOffset[2] + leftLowerArmVertices.zRange * 0.3,
];
const leftHandOffset: [number, number, number] = [
leftHandVertices.lowerX - leftLowerArmOffset[0] - leftUpperArmOffset[0] + leftHandVertices.xRange * 0.85,
leftHandVertices.lowerY - leftLowerArmOffset[1] - leftUpperArmOffset[1] + leftHandVertices.yRange * (1 - 0.05),
leftHandVertices.lowerZ - leftLowerArmOffset[2] - leftUpperArmOffset[2] + leftHandVertices.zRange * 0.65,
];
const leftThighOffset: [number, number, number] = [
leftThighVertices.lowerX + leftThighVertices.xRange * 0.5,
leftThighVertices.lowerY + leftThighVertices.yRange * (1 - 0.05),
leftThighVertices.zRange * 0.05,
];
const leftCalfOffset: [number, number, number] = [
leftCalfVertices.lowerX - leftThighOffset[0] + leftCalfVertices.xRange * 0.5,
leftCalfVertices.lowerY - leftThighOffset[1] + leftCalfVertices.yRange * (1 - 0.05),
leftCalfVertices.lowerZ - leftThighOffset[2] + leftCalfVertices.zRange * 0.65,
];
const leftFootOffset: [number, number, number] = [
leftFootVertices.lowerX - leftThighOffset[0] - leftCalfOffset[0] + leftFootVertices.xRange * 0.3,
leftFootVertices.lowerY - leftThighOffset[1] - leftCalfOffset[1] + leftFootVertices.yRange * (1 - 0.25),
leftFootVertices.lowerZ - leftThighOffset[2] - leftCalfOffset[2] + leftFootVertices.zRange * 0.25,
];
// =============== control points positions ===============
const trunkControlPoint: [number, number, number] = [0, trunkVertices.yRange * 0.75, 0];
const headControlPoint: [number, number, number] = [0, 0, headVertices.yRange * 0.5];
const leftUpperArmControlPoint: [number, number, number] = [
leftUpperArmVertices.xRange * 0.3,
leftUpperArmVertices.yRange * -0.85,
leftUpperArmVertices.zRange * -0.3,
];
const leftLowerArmControlPoint: [number, number, number] = [
0,
leftLowerArmVertices.yRange * -0.9,
leftLowerArmVertices.zRange * 0.4,
];
const leftHandControlPoint: [number, number, number] = [
leftHandVertices.xRange * -0.2,
leftHandVertices.yRange * -0.8,
leftHandVertices.zRange * -0.1,
];
const leftThighControlPoint: [number, number, number] = [
leftThighVertices.xRange * -0.15,
leftThighVertices.yRange * -0.87,
leftThighVertices.zRange * -0.25,
];
const leftCalfControlPoint: [number, number, number] = [
0,
leftCalfVertices.yRange * -0.85,
leftCalfVertices.zRange * -0.3,
];
const leftFootControlPoint: [number, number, number] = [
leftFootVertices.xRange * 0.25,
leftFootVertices.yRange * -0.5,
leftFootVertices.zRange * 0.6,
];
// =============== create nodes ===============
function mirror(vec: [number, number, number]): [number, number, number] {
return [-vec[0], vec[1], vec[2]];
}
const trunk = this.root;
trunkVertices.setGeometryVertices(trunk.geometry);
trunk.controlPoint = trunkControlPoint;
const head = this.addChild(this.root, this.head);
head.landmarks = [
// left ear
[-headVertices.lowerX, headVertices.yRange * .05, headVertices.zRange * .15],
// right ear
[-headVertices.upperX, headVertices.yRange * .05, headVertices.zRange * .15],
];
headVertices.translate(-headOffset[0], -headOffset[1], -headOffset[2]);
headVertices.setGeometryVertices(head.geometry);
head.translation = headOffset;
head.controlPoint = headControlPoint;
const leftUpperArm = this.addChild(this.root, this.leftUpperArm);
leftUpperArmVertices.translate(-leftUpperArmOffset[0], -leftUpperArmOffset[1], -leftUpperArmOffset[2]);
leftUpperArmVertices.setGeometryVertices(leftUpperArm.geometry);
leftUpperArm.translation = leftUpperArmOffset;
leftUpperArm.controlPoint = leftUpperArmControlPoint;
const rightUpperArm = this.addChild(this.root, this.rightUpperArm);
rightUpperArmVertices.translate(+leftUpperArmOffset[0], -leftUpperArmOffset[1], -leftUpperArmOffset[2]);
rightUpperArmVertices.setGeometryVertices(rightUpperArm.geometry);
rightUpperArm.translation = mirror(leftUpperArmOffset);
rightUpperArm.controlPoint = mirror(leftUpperArmControlPoint);
const leftLowerArm = this.addChild(leftUpperArm, this.leftLowerArm);
leftLowerArmVertices.translate(
-leftLowerArmOffset[0] - leftUpperArmOffset[0],
-leftLowerArmOffset[1] - leftUpperArmOffset[1],
-leftLowerArmOffset[2] - leftUpperArmOffset[2],
);
leftLowerArmVertices.setGeometryVertices(leftLowerArm.geometry);
leftLowerArm.translation = leftLowerArmOffset;
leftLowerArm.controlPoint = leftLowerArmControlPoint;
const rightLowerArm = this.addChild(rightUpperArm, this.rightLowerArm);
rightLowerArmVertices.translate(
+leftLowerArmOffset[0] + leftUpperArmOffset[0],
-leftLowerArmOffset[1] - leftUpperArmOffset[1],
-leftLowerArmOffset[2] - leftUpperArmOffset[2],
);
rightLowerArmVertices.setGeometryVertices(rightLowerArm.geometry);
rightLowerArm.translation = mirror(leftLowerArmOffset);
rightLowerArm.controlPoint = mirror(leftLowerArmControlPoint);
const leftHand = this.addChild(leftLowerArm, this.leftHand);
leftHandVertices.translate(
-leftHandOffset[0] - leftLowerArmOffset[0] - leftUpperArmOffset[0],
-leftHandOffset[1] - leftLowerArmOffset[1] - leftUpperArmOffset[1],
-leftHandOffset[2] - leftLowerArmOffset[2] - leftUpperArmOffset[2],
);
leftHandVertices.setGeometryVertices(leftHand.geometry);
leftHand.translation = leftHandOffset;
leftHand.controlPoint = leftHandControlPoint;
const rightHand = this.addChild(rightLowerArm, this.rightHand);
rightHandVertices.translate(
+leftHandOffset[0] + leftLowerArmOffset[0] + leftUpperArmOffset[0],
-leftHandOffset[1] - leftLowerArmOffset[1] - leftUpperArmOffset[1],
-leftHandOffset[2] - leftLowerArmOffset[2] - leftUpperArmOffset[2],
);
rightHandVertices.setGeometryVertices(rightHand.geometry);
rightHand.translation = mirror(leftHandOffset);
rightHand.controlPoint = mirror(leftHandControlPoint);
const leftThigh = this.addChild(trunk, this.leftThigh);
leftThighVertices.translate(
-leftThighOffset[0],
-leftThighOffset[1],
-leftThighOffset[2],
);
leftThighVertices.setGeometryVertices(leftThigh.geometry);
leftThigh.translation = leftThighOffset;
leftThigh.controlPoint = leftThighControlPoint;
const rightThigh = this.addChild(trunk, this.rightThigh);
rightThighVertices.translate(
+leftThighOffset[0],
-leftThighOffset[1],
-leftThighOffset[2],
);
rightThighVertices.setGeometryVertices(rightThigh.geometry);
rightThigh.translation = mirror(leftThighOffset);
rightThigh.controlPoint = mirror(leftThighControlPoint);
const leftCalf = this.addChild(leftThigh, this.leftCalf);
leftCalfVertices.translate(
-leftCalfOffset[0] - leftThighOffset[0],
-leftCalfOffset[1] - leftThighOffset[1],
-leftCalfOffset[2] - leftThighOffset[2],
);
leftCalfVertices.setGeometryVertices(leftCalf.geometry);
leftCalf.translation = leftCalfOffset;
leftCalf.controlPoint = leftCalfControlPoint;
const rightCalf = this.addChild(rightThigh, this.rightCalf);
rightCalfVertices.translate(
+leftCalfOffset[0] + leftThighOffset[0],
-leftCalfOffset[1] - leftThighOffset[1],
-leftCalfOffset[2] - leftThighOffset[2],
);
rightCalfVertices.setGeometryVertices(rightCalf.geometry);
rightCalf.translation = mirror(leftCalfOffset);
rightCalf.controlPoint = mirror(leftCalfControlPoint);
const leftFoot = this.addChild(leftCalf, this.leftFoot);
leftFootVertices.translate(
-leftFootOffset[0] - leftCalfOffset[0] - leftThighOffset[0],
-leftFootOffset[1] - leftCalfOffset[1] - leftThighOffset[1],
-leftFootOffset[2] - leftCalfOffset[2] - leftThighOffset[2],
);
leftFootVertices.setGeometryVertices(leftFoot.geometry);
leftFoot.translation = leftFootOffset;
leftFoot.controlPoint = leftFootControlPoint;
const rightFoot = this.addChild(rightCalf, this.rightFoot);
rightFootVertices.translate(
+leftFootOffset[0] + leftCalfOffset[0] + leftThighOffset[0],
-leftFootOffset[1] - leftCalfOffset[1] - leftThighOffset[1],
-leftFootOffset[2] - leftCalfOffset[2] - leftThighOffset[2],
);
rightFootVertices.setGeometryVertices(rightFoot.geometry);
rightFoot.translation = mirror(leftFootOffset);
rightFoot.controlPoint = mirror(leftFootControlPoint);
}
private addChild(parent: SkeletonModelNode, node?: SkeletonModelNode) {
node = node || new SkeletonModelNode();
parent.children.push(node);
node.parent = parent;
return node;
}
} | the_stack |
import {
DebugSession,
InitializedEvent,
TerminatedEvent,
StoppedEvent,
BreakpointEvent,
OutputEvent,
ThreadEvent,
Event,
Thread, StackFrame, Scope, Source, Handles, Breakpoint
} from 'vscode-debugadapter'
import { DebugProtocol } from 'vscode-debugprotocol'
import { readFileSync } from 'fs'
import { basename } from 'path'
import * as lldbmi from './lldbmi/index'
import FrontendBreakpoint = DebugProtocol.Breakpoint
import FrontendVariable = DebugProtocol.Variable
import LLDBMISession = lldbmi.DebugSession
import BackendBreakpoint = lldbmi.IBreakpointInfo
import BackendThread = lldbmi.IThreadInfo
import BackendStackFrame = lldbmi.IStackFrameInfo
import BackendVariable = lldbmi.IVariableInfo
// import BackendAllThreads = lldbmi.IMultiThreadInfo
/**
* This interface should always match the schema found in the mock-debug extension manifest.
*/
export interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
/** An absolute path to the program to debug. */
program: string;
// /** Automatically stop target after launch. If not specified, target does not stop. */
// stopOnEntry?: boolean;
enableTracing?: boolean;
}
class SDEDebugSessionAdapter extends DebugSession {
private lastBreakPoints = new Map<string, BackendBreakpoint[]>()
private variableHandles = new Handles<number | string>()
private debuggerLaunched = false
/**
* Creates a new debug adapter that is used for one debug session.
* We configure the default implementation of a debug adapter here.
*/
public constructor() {
super()
}
//override
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
this.sendEvent(new InitializedEvent());
this.initializeBackendDebugger();
response.body.supportsConfigurationDoneRequest = true;
// response.body.supportsEvaluateForHovers = true;
// response.body.supportsStepBack = true;
this.sendResponse(response);
this.trace("initializeRequest done.")
}
debugger: LLDBMISession = null;
private initializeBackendDebugger() {
this.debugger = lldbmi.startDebugSession(lldbmi.DebuggerType.LLDB);
this.debugger.on(lldbmi.EVENT_BREAKPOINT_HIT, (breakNotify: lldbmi.IBreakpointHitEvent) => {
this.sendEvent(new StoppedEvent("breakpoint", breakNotify.threadId));
this.trace(`EVENT_BREAKPOINT_HIT:[thread id: ${breakNotify.threadId}]`);
})
this.debugger.on(lldbmi.EVENT_STEP_FINISHED, (stepNotify: lldbmi.IStepFinishedEvent) => {
this.sendEvent(new StoppedEvent("step", stepNotify.threadId))
this.trace(`EVENT_STEP_FINISHED:[thread id: ${stepNotify.threadId}]`)
})
this.debugger.on(lldbmi.EVENT_FUNCTION_FINISHED, (stepNotify: lldbmi.IStepOutFinishedEvent) => {
this.sendEvent(new StoppedEvent("pause", stepNotify.threadId))//FIXME pause?step?
this.trace(`EVENT_FUNCTION_FINISHED:[thread id: ${stepNotify.threadId}]`)
})
this.debugger.on(lldbmi.EVENT_EXCEPTION_RECEIVED, (notification: lldbmi.IExceptionReceivedEvent) => {
this.sendEvent(new StoppedEvent("exception", notification.threadId, notification.exception))
this.trace(`EVENT_EXCEPTION_RECEIVED:[thread id: ${notification.threadId}]`)
})
this.debugger.on(lldbmi.EVENT_TARGET_STOPPED, (notification: lldbmi.ITargetStoppedEvent) => {
switch (notification.reason) {
case lldbmi.TargetStopReason.Exited:
case lldbmi.TargetStopReason.ExitedSignalled:
case lldbmi.TargetStopReason.ExitedNormally:
this.sendEvent(new TerminatedEvent())
this.trace(`EVENT_TARGET_STOPPED:[thread id: ${notification.threadId}]`)
break;
default:
}
})
// this.debugger.on(lldbmi.EVENT_THREAD_CREATED, (notification: lldbmi.IThreadCreatedEvent) => {
// this.sendEvent(new ThreadEvent("started", notification.id))//FIXME started? where the official docs?
// this.trace(`EVENT_THREAD_CREATED:[thread id: ${notification.id}]`)
// })
this.debugger.on(lldbmi.EVENT_THREAD_EXITED, (notification: lldbmi.IThreadExitedEvent) => {
this.sendEvent(new ThreadEvent("exited", notification.id));
this.trace(`EVENT_THREAD_EXITED:[thread id: ${notification.id}]`);
})
}
private enableTracing: boolean = false
//override
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
try {
if (args.enableTracing) {
this.enableTracing = args.enableTracing
}
this.debugger
.setExecutableFile(args.program)
.then(() => {
this.debuggerLaunched = true;
if (this.doSetBreakPoints) {
this.doSetBreakPoints()
} else {
this.debugger.startInferior()
}
this.trace("debugger Launched")
})
} catch (e) {
this.trace(e)
}
}
//override
private doSetBreakPoints: () => Promise<void> = undefined;
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
if (this.debuggerLaunched) {
this.invokeDefensively(() =>
this.setBreakPointsRequestAsync(response, args, false)
)
} else {
this.doSetBreakPoints = () =>
this.setBreakPointsRequestAsync(response, args, true)//only happen once?
}
}
private async setBreakPointsRequestAsync(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments,
notLaunched: boolean) {
var bbps: BackendBreakpoint[] = []
for (const line of args.lines) {
const bbp = await this.debugger.addBreakpoint(`${args.source.name}:${line}`)
bbps.push(bbp)
}
const oldbbps = this.lastBreakPoints.get(args.source.path)
if (oldbbps) {
let bids: number[] = []
for (const bbp of oldbbps) {
bids.push(bbp.id)
}
await this.debugger.removeBreakpoints(bids)
}
this.lastBreakPoints.set(args.source.path, bbps);
response.body = {
breakpoints: this.toFrontendBreakpoints(bbps)
};
this.sendResponse(response);
if (notLaunched) {
this.debugger.startInferior()//as the callback of launchRequest
}
this.trace("setBreakPointsRequestAsync done.")
}
private toFrontendBreakpoints(bbps: BackendBreakpoint[]): FrontendBreakpoint[] {
const rt: FrontendBreakpoint[] = [];
for (const bbp of bbps) {
if (bbp.locations) {
rt.push(<FrontendBreakpoint>new Breakpoint(true, bbp.locations[0].line))
}//FIXME handle pending
}
return rt
}
//override
//FIXME duplicated messages for threadsRequest. works but lower performance
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
this.threadsRequestAsync(response)
}
private async threadsRequestAsync(response: DebugProtocol.ThreadsResponse) {
const allThreads = await this.debugger.getThreads()
response.body = {
threads: allThreads.all.map(thread => {
return new Thread(thread.id, thread.name)
})
}
this.sendResponse(response);
this.trace("threadsRequestAsync done.")
}
//override
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
this.stackTraceRequestAsync(response, args)
}
private async stackTraceRequestAsync(
response: DebugProtocol.StackTraceResponse,
args: DebugProtocol.StackTraceArguments) {
args.startFrame
const frames: Array<BackendStackFrame> = await this.debugger.
getStackFrames({ threadId: args.threadId })
response.body = {
stackFrames: frames.map(frame => {
return new StackFrame(
frame.level,
`${frame.filename}@(${frame.address})`,
new Source(
frame.filename,
this.convertDebuggerPathToClient(frame.fullname)
),
frame.line,
0)
}),
totalFrames: frames.length
};
this.sendResponse(response);
this.trace("stackTraceRequestAsync done.")
}
//override
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
//FIXME all vars goto locals?
response.body = {
scopes: [
new Scope("Local", this.variableHandles.create(args.frameId), false),
// new Scope("Global", this.variableHandles.create(-1), false)
]
};
this.sendResponse(response);
this.trace("scopesRequest done.")
}
//override
protected variablesRequest(
response: DebugProtocol.VariablesResponse,
args: DebugProtocol.VariablesArguments): void {
this.variablesRequestAsync(response, args)
}
private async variablesRequestAsync(
response: DebugProtocol.VariablesResponse,
args: DebugProtocol.VariablesArguments) {
const v = this.variableHandles.get(args.variablesReference, 0)
let vars = [];
if (typeof v === 'number') {//Global scope
if (v == -1) {
//FIXME swift's global scope may be per app?but vscode's global scope is per stack frame...
vars = await this.debugger.getGlobalVariables()
} else {
vars = await this.debugger.getStackFrameVariables()
}
this.asFrontendVariables(vars, null)
} else {//typeof v === 'string'
vars = await this.debugger.getVariableContent(v)
this.asFrontendVariables(vars, v)
}
response.body = {
variables: vars
};
this.sendResponse(response);
this.trace("variablesRequestAsync done.")
}
asFrontendVariables(vars: FrontendVariable[], parentVarName: string) {
vars.forEach(v => {
if (typeof v.variablesReference === 'string') {
let vf: string = v.variablesReference
// this.trace(`parentVarName:${parentVarName}|vf: ${vf}`)
if (parentVarName) {
const lastDotIndex = vf.lastIndexOf(".")
const varName = vf.substr(lastDotIndex == -1 ? 0 : lastDotIndex + 1, vf.length)
if (varName.startsWith("[")) {
vf = parentVarName + varName
} else {
vf = `${parentVarName}.${varName}`
}
}
v.variablesReference = this.variableHandles.create(vf)
}
})
}
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this.debugger.resumeInferior()//FIXME specify thread?
this.sendResponse(response);//await?
}
// protected reverseContinueRequest(response: DebugProtocol.ReverseContinueResponse, args: DebugProtocol.ReverseContinueArguments): void {
// for (var ln = this._currentLine - 1; ln >= 0; ln--) {
// if (this.fireEventsForLine(response, ln)) {
// return;
// }
// }
// this.sendResponse(response);
// // no more lines: stop at first line
// this._currentLine = 0;
// this.sendEvent(new StoppedEvent("entry", SDEDebugSessionAdapter.THREAD_ID));
// }
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.debugger.stepOverLine({ threadId: args.threadId }).then(() => {
this.sendResponse(response)
})
this.trace("nextRequest done.")
}
// protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void {
// for (let ln = this._currentLine - 1; ln >= 0; ln--) {
// if (this.fireStepEvent(response, ln)) {
// return;
// }
// }
// this.sendResponse(response);
// // no more lines: stop at first line
// this._currentLine = 0;
// this.sendEvent(new StoppedEvent("entry", SDEDebugSessionAdapter.THREAD_ID));
// }
// protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void {
// response.body = {
// result: `evaluate(context: '${args.context}', '${args.expression}')`,
// variablesReference: 0
// };
// this.sendResponse(response);
// }
//===
private invokeDefensively(fn): void {
try {
fn()
} catch (e) {
this.trace(e)
}
}
private trace(msg: string) {
if (this.enableTracing) {
const e = new OutputEvent(`---[trace] ${msg}\n`);
this.sendEvent(e);
}
}
}
DebugSession.run(SDEDebugSessionAdapter); | the_stack |
import { errors } from '@tanker/core';
import type { Tanker, b64string } from '@tanker/core';
import { getPublicIdentity, createIdentity } from '@tanker/identity';
import { expect, uuid } from '@tanker/test-utils';
import type { AppHelper, AppProvisionalUser, TestArgs } from './helpers';
import { expectDecrypt } from './helpers';
export const generateGroupsTests = (args: TestArgs) => {
describe('groups', () => {
let aliceLaptop: Tanker;
let alicePublicIdentity: b64string;
let bobLaptop: Tanker;
let bobPublicIdentity: b64string;
let charlieLaptop: Tanker;
let charliePublicIdentity: b64string;
let unknownPublicIdentity: b64string;
let appHelper: AppHelper;
const clearText = "Two's company, three's a crowd";
before(async () => {
({ appHelper } = args);
const aliceIdentity = await appHelper.generateIdentity();
alicePublicIdentity = await getPublicIdentity(aliceIdentity);
aliceLaptop = args.makeTanker();
await aliceLaptop.start(aliceIdentity);
await aliceLaptop.registerIdentity({ passphrase: 'passphrase' });
const bobIdentity = await appHelper.generateIdentity();
bobPublicIdentity = await getPublicIdentity(bobIdentity);
bobLaptop = args.makeTanker();
await bobLaptop.start(bobIdentity);
await bobLaptop.registerIdentity({ passphrase: 'passphrase' });
const charlieIdentity = await args.appHelper.generateIdentity();
charliePublicIdentity = await getPublicIdentity(charlieIdentity);
charlieLaptop = args.makeTanker();
await charlieLaptop.start(charlieIdentity);
await charlieLaptop.registerIdentity({ passphrase: 'passphrase' });
unknownPublicIdentity = await getPublicIdentity(await appHelper.generateIdentity('galette'));
});
after(async () => {
await Promise.all([
aliceLaptop.stop(),
bobLaptop.stop(),
charlieLaptop.stop(),
]);
});
it('creates a group and encrypts for it', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId], shareWithSelf: false });
await expectDecrypt([aliceLaptop, bobLaptop], clearText, encrypted);
});
it('encrypts for two groups', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
const groupId2 = await aliceLaptop.createGroup([alicePublicIdentity, charliePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId, groupId2] });
await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted);
});
it('encrypts for a non-cached group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await charlieLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expectDecrypt([aliceLaptop], clearText, encrypted);
});
it('should create a group, encrypt and then share with it', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText);
const resourceId = await aliceLaptop.getResourceId(encrypted);
await aliceLaptop.share([resourceId], { shareWithGroups: [groupId] });
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('should encrypt and then share with two groups', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
const groupId2 = await aliceLaptop.createGroup([alicePublicIdentity, charliePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText);
const resourceId = await aliceLaptop.getResourceId(encrypted);
await aliceLaptop.share([resourceId], { shareWithGroups: [groupId, groupId2] });
await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted);
});
it('throws on groupCreation with empty users', async () => {
await expect(aliceLaptop.createGroup([]))
.to.be.rejectedWith(errors.InvalidArgument);
});
it('throws on groupCreation with identities from another trustchain', async () => {
const userId = uuid.v4();
const otherTrustchain = {
id: 'gOhJDFYKK/GNScGOoaZ1vLAwxkuqZCY36IwEo4jcnDE=',
sk: 'D9jiQt7nB2IlRjilNwUVVTPsYkfbCX0PelMzx5AAXIaVokZ71iUduWCvJ9Akzojca6lvV8u1rnDVEdh7yO6JAQ==',
};
const wrongIdentity = await createIdentity(otherTrustchain.id, otherTrustchain.sk, userId);
const wrongPublicIdentity = await getPublicIdentity(wrongIdentity);
await expect(aliceLaptop.createGroup([wrongPublicIdentity]))
.to.be.rejectedWith(errors.InvalidArgument, 'Invalid appId for identities');
});
it('should not keep the key if we are not part of the group', async () => {
const groupId = await aliceLaptop.createGroup([bobPublicIdentity]);
// eslint-disable-next-line no-underscore-dangle
if (!aliceLaptop._session)
throw new Error('_session cannot be null');
// We can't assert this with decrypt because the server will not send the
// key publish. This is the only way I have found to assert that.
// eslint-disable-next-line no-underscore-dangle
await expect(aliceLaptop._session._storage.groupStore._findGroupsByGroupId([groupId])).to.eventually.deep.equal([]);
});
it('should add a member to a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] });
// Also test resources shared after the group add
const encrypted2 = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expectDecrypt([bobLaptop], clearText, encrypted);
await expectDecrypt([bobLaptop], clearText, encrypted2);
});
it('should add two members to a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity, charliePublicIdentity] });
await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted);
});
it('throws on updateGroupMembers with identities from another trustchain', async () => {
const userId = uuid.v4();
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const otherTrustchain = {
id: 'gOhJDFYKK/GNScGOoaZ1vLAwxkuqZCY36IwEo4jcnDE=',
sk: 'D9jiQt7nB2IlRjilNwUVVTPsYkfbCX0PelMzx5AAXIaVokZ71iUduWCvJ9Akzojca6lvV8u1rnDVEdh7yO6JAQ==',
};
const wrongIdentity = await createIdentity(otherTrustchain.id, otherTrustchain.sk, userId);
const wrongPublicIdentity = await getPublicIdentity(wrongIdentity);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [wrongPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'Invalid appId for identities');
});
it('should remove a member from a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity, charliePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] })).to.be.fulfilled;
const encrypted2 = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
// Bob was removed, he can't decrypt or update the group anymore
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await expect(bobLaptop.decrypt(encrypted2)).to.be.rejectedWith(errors.InvalidArgument);
await expect(bobLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'You are not a member');
await expect(bobLaptop.updateGroupMembers(groupId, { usersToRemove: [charliePublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'You are not a member');
// Charlie was not removed, he should still be able to decrypt
await expectDecrypt([charlieLaptop], clearText, encrypted);
await expectDecrypt([charlieLaptop], clearText, encrypted2);
});
it('should remove two members from a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity, charliePublicIdentity]);
const encryptedData = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity, charliePublicIdentity] })).to.be.fulfilled;
await expect(bobLaptop.decrypt(encryptedData)).to.be.rejectedWith(errors.InvalidArgument);
await expect(charlieLaptop.decrypt(encryptedData)).to.be.rejectedWith(errors.InvalidArgument);
});
it('should allow access to resources when adding back a member', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] });
// Bob was removed, he can't decrypt anymore
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] });
// Bob was added back, he can decrypt
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('removes two group members', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity, charliePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] })).to.be.fulfilled;
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [charliePublicIdentity] })).to.be.fulfilled;
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await expect(charlieLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('should add a member to a group twice then remove it', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] })).to.be.fulfilled;
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] })).to.be.fulfilled;
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] })).to.be.fulfilled;
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('throws when removing a member from a group twice', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] })).to.be.fulfilled;
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] })).to.be.rejectedWith(errors.InvalidArgument, 'Some users are not part of this group');
});
it('should accept adding duplicate users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity, bobPublicIdentity] })).to.be.fulfilled;
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('should accept removing duplicate users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity, bobPublicIdentity] })).to.be.fulfilled;
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('throws when removing a member not in the group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [charliePublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'Some users are not part of this group');
});
it('throws on groupCreation with invalid user', async () => {
await expect(aliceLaptop.createGroup([alicePublicIdentity, unknownPublicIdentity]))
.to.be.rejectedWith(errors.InvalidArgument, unknownPublicIdentity);
});
it('throws on groupUpdate by adding invalid users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [unknownPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, unknownPublicIdentity);
});
it('throws on groupUpdate by removing invalid users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [unknownPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'Some users are not part of this group');
});
it('throws on groupUpdate with invalid group ID', async () => {
const badGroupID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=';
await expect(aliceLaptop.updateGroupMembers(badGroupID, { usersToAdd: [alicePublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, badGroupID);
});
it('throws on groupUpdate with mix valid/invalid users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity, unknownPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, unknownPublicIdentity);
});
it('throws on groupUpdate by adding and removing nobody', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [], usersToRemove: [] }))
.to.be.rejectedWith(errors.InvalidArgument, 'no members to add or remove');
});
it('throws on groupUpdate by removing the last member', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [alicePublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'removing all members');
});
it('throws when adding and removing the same user', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity], usersToRemove: [bobPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'both added to and removed');
});
it('should not be able to add a user to a group you are not in', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
await expect(bobLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'Current user is not a group member');
});
it('should not be able to remove a user from a group you are not in', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, bobPublicIdentity]);
await expect(charlieLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'Current user is not a group member');
});
describe('with email (+second phone) provisionals', () => {
let provisional: AppProvisionalUser;
let provisional2: AppProvisionalUser;
beforeEach(async () => {
provisional = await appHelper.generateEmailProvisionalIdentity();
provisional2 = await appHelper.generatePhoneNumberProvisionalIdentity();
});
it('creates a group with provisional members', async () => {
const groupId = await aliceLaptop.createGroup([provisional.publicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('adds provisional members to a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity] });
const encrypted2 = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expectDecrypt([bobLaptop], clearText, encrypted);
await expectDecrypt([bobLaptop], clearText, encrypted2);
});
it('adds two provisional members to a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity, provisional2.publicIdentity] });
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(charlieLaptop, provisional2);
await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted);
});
it('removes a provisional member from a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, charliePublicIdentity, provisional.publicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] });
const encrypted2 = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
// provisional was removed so Bob can't decrypt even after the claim
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await expect(bobLaptop.decrypt(encrypted2)).to.be.rejectedWith(errors.InvalidArgument);
await expect(bobLaptop.updateGroupMembers(groupId, { usersToAdd: [charliePublicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'You are not a member of this group');
// Charlie is still part of the group and can decrypt
await expectDecrypt([charlieLaptop], clearText, encrypted);
await expectDecrypt([charlieLaptop], clearText, encrypted2);
});
it('removes two provisional members from a group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity, provisional2.publicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity, provisional2.publicIdentity] });
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(bobLaptop, provisional2);
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('should allow access to resources when adding back a member as a provisional identity', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] });
// Bob was never added, he can't decrypt
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity] });
// Bob's provisional identity was added back, he can claim and decrypt
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('should allow access to resources when adding back a member as a permanent identity', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] });
// Bob was removed, he can't decrypt anymore
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [bobPublicIdentity] });
// Bob was added back, he can decrypt
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('should add a provisional member to a group twice then remove it', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity] })).to.be.fulfilled;
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity] })).to.be.fulfilled;
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] })).to.be.fulfilled;
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('should add duplicate provisional users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity, provisional.publicIdentity] })).to.be.fulfilled;
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expectDecrypt([bobLaptop], clearText, encrypted);
});
it('should remove duplicate provisional users', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity, provisional.publicIdentity] })).to.be.fulfilled;
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('throws when adding and removing the same provisional user', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity], usersToRemove: [provisional.publicIdentity] }))
.to.be.rejectedWith(errors.InvalidArgument, 'both added to and removed');
});
it('fails when creating a group with an already attached provisional identity with no share', async () => {
await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional);
await expect(bobLaptop.createGroup([provisional.publicIdentity])).to.be.rejectedWith(errors.IdentityAlreadyAttached);
});
it('fails when creating a group with an already attached provisional identity', async () => {
await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] })).to.be.fulfilled;
await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional);
await expect(bobLaptop.createGroup([provisional.publicIdentity])).to.be.rejectedWith(errors.IdentityAlreadyAttached);
});
it('fails when removing a claimed provisional user with the provisional identity', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await expect(aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] }))
.to.be.rejectedWith(errors.IdentityAlreadyAttached);
});
it('removes a member added by provisional identity after they have claimed it', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional);
await aliceLaptop.updateGroupMembers(groupId, { usersToRemove: [bobPublicIdentity] });
const encrypted = await aliceLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
await expect(bobLaptop.updateGroupMembers(groupId, { usersToAdd: [charliePublicIdentity] })).to.be.rejectedWith(errors.InvalidArgument, 'You are not a member of this group');
});
});
describe('with phone number provisionals', () => {
let provisional: AppProvisionalUser;
beforeEach(async () => {
provisional = await appHelper.generatePhoneNumberProvisionalIdentity();
});
it('fails when creating a group with an already attached provisional identity', async () => {
await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] })).to.be.fulfilled;
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional);
await expect(bobLaptop.createGroup([provisional.publicIdentity])).to.be.rejectedWith(errors.IdentityAlreadyAttached);
});
it('shares keys with added provisional group members', async () => {
const groupId = await bobLaptop.createGroup([bobPublicIdentity]);
await bobLaptop.updateGroupMembers(groupId, { usersToAdd: [provisional.publicIdentity] });
const encrypted = await bobLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional);
await expectDecrypt([aliceLaptop], clearText, encrypted);
});
it('should update group when claimed provisional users remove a member from group', async () => {
const groupId = await aliceLaptop.createGroup([alicePublicIdentity, provisional.publicIdentity]);
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(bobLaptop, provisional);
await bobLaptop.updateGroupMembers(groupId, { usersToRemove: [alicePublicIdentity] });
const encrypted = await bobLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await expect(aliceLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('should not share keys with removed provisional group members', async () => {
const groupId = await bobLaptop.createGroup([bobPublicIdentity, provisional.publicIdentity]);
const encrypted = await bobLaptop.encrypt(clearText, { shareWithGroups: [groupId] });
await bobLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] });
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional);
await expect(aliceLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument);
});
it('should fail when removing a claimed provisional user with the provisional identity', async () => {
const groupId = await bobLaptop.createGroup([bobPublicIdentity, provisional.publicIdentity]);
await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional);
await expect(bobLaptop.updateGroupMembers(groupId, { usersToRemove: [provisional.publicIdentity] }))
.to.be.rejectedWith(errors.IdentityAlreadyAttached);
});
});
});
}; | the_stack |
import { TokenReader, IRenderSettings, IRenderable, makeRenderSettings, ScriptLanguages, defaultRenderSettings } from "../../../helpers";
import { JSToken, stringToTokens } from "../../javascript";
import { ValueTypes } from "../value/value";
import { TypeSignature } from "../types/type-signature";
import { StatementTypes, ReturnStatement } from "../statements/statement";
import { Expression } from "../value/expression";
import { parseBlock, renderBlock } from "./block";
import { ClassDeclaration } from "./class";
import { VariableDeclaration, VariableContext } from "../statements/variable";
import { ObjectLiteral } from "../value/object";
import { Module } from "../module";
import { IFunctionDeclaration } from "../../../abstract-asts";
import { Decorator } from "../types/decorator";
export const functionPrefixes = [JSToken.Get, JSToken.Set, JSToken.Async];
// Parses a list of function parameters
export function parseFunctionParams(reader: TokenReader<JSToken>): Array<VariableDeclaration> {
const params: Array<VariableDeclaration> = [];
reader.expectNext(JSToken.OpenBracket);
while (reader.current.type !== JSToken.CloseBracket) {
if (reader.current.type === JSToken.Comment) reader.move();
const variable = VariableDeclaration.fromTokens(reader, { context: VariableContext.Parameter });
params.push(variable);
if (reader.current.type === JSToken.Comment) reader.move();
if (reader.current.type as JSToken === JSToken.CloseBracket) break;
reader.expectNext(JSToken.Comma);
}
reader.move();
return params;
}
export class ArgumentList implements IRenderable {
constructor(public args: ValueTypes[] = []) { }
render(settings: IRenderSettings = defaultRenderSettings): string {
const renderedArgs = this.args.map(arg => arg.render(settings, { inline: true }));
const totalWidth = renderedArgs.reduce((acc, cur) => acc + cur.length, 0);
// Prettifies function arguments with long arguments
if (totalWidth > settings.columnWidth && !settings.minify) {
const tabNewLine = "\n" + " ".repeat(settings.indent);
return `(${tabNewLine}${renderedArgs.map(arg => arg.replace(/\n/g, "\n" + " ".repeat(settings.indent))).join("," + tabNewLine)}\n)`;
} else {
return `(${renderedArgs.join(settings.minify ? "," : ", ")})`;
}
}
static fromTokens(reader: TokenReader<JSToken>): ArgumentList {
const args: Array<ValueTypes> = [];
reader.expectNext(JSToken.OpenBracket);
while (reader.current.type !== JSToken.CloseBracket) {
const arg = Expression.fromTokens(reader);
args.push(arg);
if (reader.current.type as JSToken === JSToken.CloseBracket) break;
reader.expectNext(JSToken.Comma);
}
reader.move();
return new ArgumentList(args);
}
}
export enum GetSet { Get, Set };
interface FunctionOptions {
parent: ClassDeclaration | ObjectLiteral | Module;
isAsync: boolean,
getSet?: GetSet,
bound: boolean, // If "this" refers to function scope
isGenerator: boolean,
isStatic: boolean,
decorators?: Array<Decorator>,
returnType?: TypeSignature,
isAbstract: boolean, // TODO implement on IClassMember
}
/**
* TODO should inline functions and functions as a statement be treated differently
*/
export class FunctionDeclaration implements IFunctionDeclaration, FunctionOptions {
name?: TypeSignature; // Null signifies anonymous function
returnType?: TypeSignature;
statements: Array<StatementTypes>;
parameters: Array<VariableDeclaration>;
parent: ClassDeclaration | ObjectLiteral | Module;
decorators?: Array<Decorator>;
bound: boolean = true; // If "this" returns to function context
getSet?: GetSet;
isAsync: boolean = false;
isGenerator: boolean = false;
isStatic: boolean = false;
isAbstract: boolean = false;
get actualName() {
return this.name?.name ?? null;
}
constructor(
name: TypeSignature | string | null = null,
parameters: string[] | VariableDeclaration[] = [],
statements: Array<StatementTypes> = [],
options: Partial<FunctionOptions> = {}
) {
if (name) {
if (typeof name === "string") {
this.name = new TypeSignature({ name });
} else {
this.name = name;
}
}
let params: VariableDeclaration[];
// If parameters array of string convert all there values to VariableDeclarations
if (typeof parameters[0] === "string") {
params = (parameters as string[]).map(param =>
new VariableDeclaration(param, { context: VariableContext.Parameter }));
} else {
params = parameters as VariableDeclaration[];
// Enforce each parameter has context of parameter
for (const param of params) {
param.context = VariableContext.Parameter;
}
}
this.parameters = params;
this.statements = statements;
Object.assign(this, options); // TODO not sure about this
}
/**
* Helper method for generating a argument list for calling this function. Basically implements named named parameters by generating a in order list of arguments
* @param argumentMap
*/
buildArgumentListFromArgumentsMap(argumentMap: Map<string, ValueTypes>): ArgumentList {
const args: Array<ValueTypes> = [];
for (const param of this.parameters) {
const arg = argumentMap.get(param.name);
// TODO or optional
if (!arg && !param.value) {
throw Error(`No argument found for parameter "${param.name}"`)
}
if (arg) {
args.push(arg);
}
}
return new ArgumentList(args);
}
render(settings: IRenderSettings = defaultRenderSettings): string {
settings = makeRenderSettings(settings);
let acc = "";
if (this.decorators && settings.scriptLanguage === ScriptLanguages.Typescript) {
const separator = settings.minify ? " " : "\n";
acc += this.decorators.map(decorator => decorator.render(settings)).join(separator) + separator;
}
if (this.isAbstract) {
if (settings.scriptLanguage !== ScriptLanguages.Typescript) return acc;
else acc += "abstract ";
}
if (this.isStatic) acc += "static ";
if (this.isAsync) acc += "async ";
// If not bound then it is considered an arrow function
if (!this.bound && !this.name) {
// If only one parameter and it is not destructuring use shorthand
if (
this.parameters.length === 1
&& this.parameters[0].name
&& !this.parameters[0].spread
&& settings.scriptLanguage === ScriptLanguages.Javascript // Cannot do shorthand with type signature
&& !this.isAsync
) {
acc += this.parameters[0].render(settings);
} else {
acc += "(";
for (const parameter of this.parameters) {
acc += parameter.render(settings);
if (parameter !== this.parameters[this.parameters.length - 1]) acc += settings.minify ? "," : ", ";
}
acc += ")";
}
acc += settings.minify ? "=>" : " => ";
// If single return statement use shorthand
if (
this.statements.length === 1
&& this.statements[0] instanceof ReturnStatement
&& (this.statements[0] as ReturnStatement).returnValue
) {
const { returnValue } = this.statements[0] as ReturnStatement;
// Parenthesize object literals to prevent mixup with block
if (returnValue instanceof ObjectLiteral) {
acc += `(${returnValue.render(settings)})`;
} else {
acc += returnValue!.render(settings);
}
} else {
acc += "{";
acc += renderBlock(this.statements, settings);
acc += "}";
}
return acc;
} else {
const asMember = this.parent instanceof ClassDeclaration || this.parent instanceof ObjectLiteral;
if (asMember) {
if (this.getSet === GetSet.Get) {
acc += "get ";
} else if (this.getSet === GetSet.Set) {
acc += "set ";
}
} else if (this.bound) {
acc += "function";
}
if (this.isGenerator) acc += "*";
if (this.name) {
if (!asMember) acc += " ";
if (settings.scriptLanguage === ScriptLanguages.Typescript) {
acc += this.name.render(settings);
} else {
acc += this.name.name;
}
}
acc += "(";
for (let i = 0; i < this.parameters.length; i++) {
// If the first parameter and name is "this" TypeScript uses it as a type annotation for "this"
// https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
const parameter = this.parameters[i];
if (i === 0 && parameter.name === "this" && settings.scriptLanguage !== ScriptLanguages.Typescript) continue;
acc += parameter.render(settings);
if (i < this.parameters.length - 1) {
acc += settings.minify ? "," : ", ";
}
}
acc += ")";
if (settings.scriptLanguage === ScriptLanguages.Typescript && this.returnType) {
acc += ": ";
acc += this.returnType.render(settings);
}
if (!settings.minify) {
acc += " ";
}
if (!(this.isAbstract && this.statements.length === 0)) {
acc += "{";
acc += renderBlock(this.statements, settings);
acc += "}";
}
return acc;
}
}
static fromTokens(
reader: TokenReader<JSToken>,
parent?: ClassDeclaration | ObjectLiteral,
modifiers?: Set<JSToken>,
): FunctionDeclaration {
let isAsync = false;
if (reader.current.type === JSToken.Async) {
isAsync = true;
reader.move();
}
let getSet: GetSet | undefined;
let isStatic = false
if (modifiers) {
for (const modifier of modifiers) {
switch (modifier) {
case JSToken.Get: getSet = GetSet.Get; break;
case JSToken.Set: getSet = GetSet.Set; break;
case JSToken.Static: isStatic = true; break;
}
}
}
if (reader.current.type === JSToken.Function || parent) {
if (reader.current.type === JSToken.Function) reader.move();
let generator: boolean = false;
if (reader.current.type === JSToken.Multiply) {
generator = true;
reader.move();
}
let name: TypeSignature | null = null;
if (reader.current.type !== JSToken.OpenBracket) {
name = TypeSignature.fromTokens(reader);
}
const parameters = parseFunctionParams(reader);
let returnType: TypeSignature | undefined;
if (reader.current.type === JSToken.Colon) {
reader.move();
returnType = TypeSignature.fromTokens(reader)
};
// Early return as abstract methods don't need bodies
if (modifiers && modifiers.has(JSToken.Abstract)) {
if (reader.current.type === JSToken.SemiColon) reader.move();
return new FunctionDeclaration(name, parameters, [], {
parent: parent,
bound: true,
isAbstract: true,
isGenerator: generator,
isStatic,
isAsync,
getSet,
returnType,
});
}
reader.expect(JSToken.OpenCurly);
const statements = parseBlock(reader);
return new FunctionDeclaration(name, parameters, statements, {
parent: parent,
bound: true,
isGenerator: generator,
isStatic,
isAsync,
getSet,
returnType
});
} else {
let params: VariableDeclaration[];
if (reader.current.type !== JSToken.OpenBracket) {
// TODO assert reader.current.value is not null here:
params = [new VariableDeclaration(reader.current.value!)];
reader.move();
} else {
params = parseFunctionParams(reader);
}
reader.expectNext(JSToken.ArrowFunction);
let statements: StatementTypes[];
if (reader.current.type as JSToken !== JSToken.OpenCurly) {
// If next token is void assume it is not meant to return
if (reader.peek()?.type === JSToken.Void) {
reader.move();
statements = [Expression.fromTokens(reader)];
} else {
statements = [new ReturnStatement(Expression.fromTokens(reader))];
}
} else {
statements = parseBlock(reader);
}
return new FunctionDeclaration(null, params, statements, { bound: false, isAsync });
}
}
static fromString(string: string): FunctionDeclaration {
const reader = stringToTokens(string);
const func = FunctionDeclaration.fromTokens(reader);
reader.expect(JSToken.EOF);
return func;
}
} | the_stack |
import * as support from "../support";
const opt = { err: true };
support.runTest("String Operators", {
$concat: [
[[null, "abc"], null],
[["a", "-", "c"], "a-c"],
],
$indexOfBytes: [
[["cafeteria", "e"], 3],
[["cafétéria", "é"], 3],
[["cafétéria", "e"], -1],
[["cafétéria", "t"], 4], // "5" is an error in MongoDB docs.
[["foo.bar.fi", ".", 5], 7],
[["vanilla", "ll", 0, 2], -1],
[
["vanilla", "ll", -1],
"$indexOfBytes third operand must resolve to a non-negative integer",
opt,
], // Error
[["vanilla", "ll", 12], -1],
[["vanilla", "ll", 5, 2], -1],
[["vanilla", "nilla", 3], -1],
[[null, "foo"], null],
],
$split: [
[[null, "/"], null],
[
["June-15-2013", "-"],
["June", "15", "2013"],
],
[
["banana split", "a"],
["b", "n", "n", " split"],
],
[
["Hello World", " "],
["Hello", "World"],
],
[
["astronomical", "astro"],
["", "nomical"],
],
[["pea green boat", "owl"], ["pea green boat"]],
[
["headphone jack", 7],
"$split requires an expression that evaluates to a string as a second argument, found: number",
opt,
],
[
["headphone jack", /jack/],
"$split requires an expression that evaluates to a string as a second argument, found: regex",
opt,
],
],
$strLenBytes: [
[{ $strLenBytes: "abcde" }, 5], // Each character is encoded using one byte.
[{ $strLenBytes: "Hello World!" }, 12], // Each character is encoded using one byte.
[{ $strLenBytes: "cafeteria" }, 9], // Each character is encoded using one byte.
[{ $strLenBytes: "cafétéria" }, 11], // é is encoded using two bytes.
[{ $strLenBytes: "" }, 0], //Empty strings return 0.
[{ $strLenBytes: { $literal: "$€λG" } }, 7], // € is encoded using three bytes. λ is encoded using two bytes.
[{ $strLenBytes: "寿司" }, 6], // Each character is encoded using three bytes.
],
$strLenCP: [
[{ $strLenCP: "abcde" }, 5],
[{ $strLenCP: "Hello World!" }, 12],
[{ $strLenCP: "cafeteria" }, 9],
[{ $strLenCP: "cafétéria" }, 9],
[{ $strLenCP: "" }, 0],
[{ $strLenCP: { $literal: "$€λG" } }, 4],
[{ $strLenCP: "寿司" }, 2],
],
$strcasecmp: [
[[null, undefined], 0],
[["13Q1", "13q4"], -1],
[["13Q4", "13q4"], 0],
[["14Q2", "13q4"], 1],
],
$substrCP: [
[[null, 2], ""],
[["hello", -1], ""],
[["hello", 1, -2], "ello"],
[{ $substrCP: ["abcde", 1, 2] }, "bc"],
[{ $substrCP: ["Hello World!", 6, 5] }, "World"],
[{ $substrCP: ["cafétéria", 0, 5] }, "cafét"],
[{ $substrCP: ["cafétéria", 5, 4] }, "éria"],
[{ $substrCP: ["cafétéria", 7, 3] }, "ia"],
[{ $substrCP: ["cafétéria", 3, 1] }, "é"],
],
$substrBytes: [
[{ $substrBytes: ["abcde", 1, 2] }, "bc"],
[{ $substrBytes: ["Hello World!", 6, 5] }, "World"],
[{ $substrBytes: ["cafétéria", 0, 5] }, "café"],
[{ $substrBytes: ["cafétéria", 5, 4] }, "tér"],
[{ $substrBytes: ["cafétéria", 7, 3] }, "invalid range", { err: 1 }],
[{ $substrBytes: ["cafétéria", 3, 1] }, "invalid range", { err: 1 }],
[["éclair", 0, 3], "éc"],
[["jalapeño", 0, 3], "jal"],
[["寿司sushi", 0, 3], "寿"],
],
$toLower: [["ABC123", "abc123"]],
$toUpper: [["abc123", "ABC123"]],
$trim: [
[{ $trim: { input: " \n good bye \t " } }, "good bye"],
[{ $trim: { input: " ggggoodbyeeeee", chars: "ge" } }, " ggggoodby"],
[{ $trim: { input: " ggggoodbyeeeee", chars: " ge" } }, "oodby"],
[{ $trim: { input: null } }, null],
],
$ltrim: [
[{ $ltrim: { input: " \n good bye \t " } }, "good bye \t "],
[{ $ltrim: { input: " ggggoodbyeeeee", chars: "ge" } }, " ggggoodbyeeeee"],
[{ $ltrim: { input: " ggggoodbyeeeee ", chars: " gd" } }, "oodbyeeeee "],
[{ $ltrim: { input: null } }, null],
],
$rtrim: [
[{ $rtrim: { input: " \n good bye \t " } }, " \n good bye"],
[{ $rtrim: { input: " ggggoodbyeeeee", chars: "ge" } }, " ggggoodby"],
[{ $rtrim: { input: " ggggoodbyeeeee ", chars: "e " } }, " ggggoodby"],
[{ $rtrim: { input: null } }, null],
],
});
const data = [
{ _id: 1, fname: "Carol", lname: "Smith", phone: "718-555-0113" },
{ _id: 2, fname: "Daryl", lname: "Doe", phone: "212-555-8832" },
{ _id: 3, fname: "Polly", lname: "Andrews", phone: "208-555-1932" },
{ _id: 4, fname: "Colleen", lname: "Duncan", phone: "775-555-0187" },
{ _id: 5, fname: "Luna", lname: "Clarke", phone: "917-555-4414" },
];
const productsData = [
{ _id: 1, description: "Single LINE description." },
{ _id: 2, description: "First lines\nsecond line" },
{ _id: 3, description: "Many spaces before line" },
{ _id: 4, description: "Multiple\nline descriptions" },
{ _id: 5, description: "anchors, links and hyperlinks" },
{ _id: 6, description: "métier work vocation" },
];
support.runTestPipeline("$regexMatch operators", [
{
message: "$regexMatch with option 's'",
input: productsData,
query: [
{
$addFields: {
returns: {
$regexMatch: {
input: "$description",
regex: /m.*line/,
options: "si",
},
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returns: false },
{ _id: 2, description: "First lines\nsecond line", returns: false },
{ _id: 3, description: "Many spaces before line", returns: true },
{ _id: 4, description: "Multiple\nline descriptions", returns: true },
{ _id: 5, description: "anchors, links and hyperlinks", returns: false },
{ _id: 6, description: "métier work vocation", returns: false },
],
},
]);
support.runTestPipeline("$regexFind operators", [
{
message: "can apply $regexFind",
input: [
{ _id: 1, category: "café" },
{ _id: 2, category: "cafe" },
{ _id: 3, category: "cafE" },
],
query: [
{
$addFields: {
resultObject: { $regexFind: { input: "$category", regex: /cafe/ } },
},
},
],
check: [
{ _id: 1, category: "café", resultObject: null },
{
_id: 2,
category: "cafe",
resultObject: { match: "cafe", idx: 0, captures: [] },
},
{ _id: 3, category: "cafE", resultObject: null },
],
},
{
message: "$regexFind with 'captures': 1",
input: data,
query: [
{
$project: {
returnObject: {
$regexFind: { input: "$fname", regex: /(C(ar)*)ol/ },
},
},
},
],
check: [
{
_id: 1,
returnObject: { match: "Carol", idx: 0, captures: ["Car", "ar"] },
},
{ _id: 2, returnObject: null },
{ _id: 3, returnObject: null },
{ _id: 4, returnObject: { match: "Col", idx: 0, captures: ["C", null] } },
{ _id: 5, returnObject: null },
],
},
{
message: "$regexFind with 'captures': 2",
input: data,
query: [
{
$project: {
nycContacts: {
$regexFind: {
input: "$phone",
regex: /^(718).*|^(212).*|^(917).*/,
},
},
},
},
],
check: [
{
_id: 1,
nycContacts: {
match: "718-555-0113",
idx: 0,
captures: ["718", null, null],
},
},
{
_id: 2,
nycContacts: {
match: "212-555-8832",
idx: 0,
captures: [null, "212", null],
},
},
{ _id: 3, nycContacts: null },
{ _id: 4, nycContacts: null },
{
_id: 5,
nycContacts: {
match: "917-555-4414",
idx: 0,
captures: [null, null, "917"],
},
},
],
},
{
message: "$regexFind without grouping",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFind: { input: "$description", regex: /line/ },
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: null },
{
_id: 2,
description: "First lines\nsecond line",
returnObject: { match: "line", idx: 6, captures: [] },
},
{
_id: 3,
description: "Many spaces before line",
returnObject: { match: "line", idx: 23, captures: [] },
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: { match: "line", idx: 9, captures: [] },
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: null,
},
{ _id: 6, description: "métier work vocation", returnObject: null },
],
},
{
message: "$regexFind with grouping",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFind: { input: "$description", regex: /lin(e|k)/ },
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: null },
{
_id: 2,
description: "First lines\nsecond line",
returnObject: { match: "line", idx: 6, captures: ["e"] },
},
{
_id: 3,
description: "Many spaces before line",
returnObject: { match: "line", idx: 23, captures: ["e"] },
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: { match: "line", idx: 9, captures: ["e"] },
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: { match: "link", idx: 9, captures: ["k"] },
},
{ _id: 6, description: "métier work vocation", returnObject: null },
],
},
{
message: "$regexFind 'idx' is codepoint",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFind: { input: "$description", regex: /tier/ },
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: null },
{ _id: 2, description: "First lines\nsecond line", returnObject: null },
{
_id: 3,
description: "Many spaces before line",
returnObject: null,
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: null,
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: null,
},
{
_id: 6,
description: "métier work vocation",
returnObject: { match: "tier", idx: 2, captures: [] },
},
],
},
{
message: "$regexFind with option 'i'",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFind: { input: "$description", regex: "line", options: "i" },
},
},
},
],
check: [
{
_id: 1,
description: "Single LINE description.",
returnObject: { match: "LINE", idx: 7, captures: [] },
},
{
_id: 2,
description: "First lines\nsecond line",
returnObject: { match: "line", idx: 6, captures: [] },
},
{
_id: 3,
description: "Many spaces before line",
returnObject: { match: "line", idx: 23, captures: [] },
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: { match: "line", idx: 9, captures: [] },
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: null,
},
{ _id: 6, description: "métier work vocation", returnObject: null },
],
},
{
message: "$regexFind with option 'm'",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFind: { input: "$description", regex: /^s/im },
},
},
},
],
check: [
{
_id: 1,
description: "Single LINE description.",
returnObject: { match: "S", idx: 0, captures: [] },
},
{
_id: 2,
description: "First lines\nsecond line",
returnObject: { match: "s", idx: 12, captures: [] },
},
{
_id: 3,
description: "Many spaces before line",
returnObject: null,
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: null,
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: null,
},
{ _id: 6, description: "métier work vocation", returnObject: null },
],
},
{
message: "$regexFind with option 's'",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFind: {
input: "$description",
regex: /m.*line/,
options: "si",
},
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: null },
{ _id: 2, description: "First lines\nsecond line", returnObject: null },
{
_id: 3,
description: "Many spaces before line",
returnObject: {
match: "Many spaces before line",
idx: 0,
captures: [],
},
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: { match: "Multiple\nline", idx: 0, captures: [] },
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: null,
},
{ _id: 6, description: "métier work vocation", returnObject: null },
],
},
// Not supported
// {
// message: "$regexFind with option 'x'",
// input: dataForOptions,
// query: [ { $addFields: { returnObject: { $regexFind: { input: "$description", regex: /lin(e|k) # matches line or link/, options: "x" } } } } ],
// check: [
// { "_id" : 1, "description" : "Single LINE description.", "returnObject" : null },
// { "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : null },
// { "_id" : 3, "description" : "Many spaces before line", "returnObject" : { "match" : "Many spaces before line", "idx" : 0, "captures" : [ ] } },
// { "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : { "match" : "Multiple\nline", "idx" : 0, "captures" : [ ] } },
// { "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : null },
// { "_id" : 6, "description" : "métier work vocation", "returnObject" : null }
// ]
// }
{
message: "$regexFind to Parse Email from String",
input: [
{
_id: 1,
comment:
"Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com",
},
{ _id: 2, comment: "I wanted to concatenate a string" },
{
_id: 3,
comment:
"I can't find how to convert a date to string. cam@mongodb.com",
},
{ _id: 4, comment: "It's just me. I'm testing. fred@MongoDB.com" },
],
query: [
{
$addFields: {
email: {
$regexFind: {
input: "$comment",
regex: /[a-z0-9_.+-]+@[a-z0-9_.+-]+\.[a-z0-9_.+-]+/i,
},
},
},
},
{ $set: { email: "$email.match" } },
],
check: [
{
_id: 1,
comment:
"Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com",
email: "aunt.arc.tica@example.com",
},
{ _id: 2, comment: "I wanted to concatenate a string" },
{
_id: 3,
comment:
"I can't find how to convert a date to string. cam@mongodb.com",
email: "cam@mongodb.com",
},
{
_id: 4,
comment: "It's just me. I'm testing. fred@MongoDB.com",
email: "fred@MongoDB.com",
},
],
},
{
message: "$regexFind to String Elements of an Array",
input: [
{
_id: 1,
name: "Aunt Arc Tikka",
details: ["+672-19-9999", "aunt.arc.tica@example.com"],
},
{
_id: 2,
name: "Belle Gium",
details: ["+32-2-111-11-11", "belle.gium@example.com"],
},
{
_id: 3,
name: "Cam Bo Dia",
details: ["+855-012-000-0000", "cam.bo.dia@example.com"],
},
{ _id: 4, name: "Fred", details: ["+1-111-222-3333"] },
],
query: [
{ $unwind: "$details" },
{
$addFields: {
regexemail: {
$regexFind: {
input: "$details",
regex: /^[a-z0-9_.+-]+@[a-z0-9_.+-]+\.[a-z0-9_.+-]+$/,
options: "i",
},
},
regexphone: {
$regexFind: {
input: "$details",
regex: /^[+]{0,1}[0-9]*-?[0-9_-]+$/,
},
},
},
},
{
$project: {
_id: 1,
name: 1,
details: { email: "$regexemail.match", phone: "$regexphone.match" },
},
},
{
$group: {
_id: "$_id",
name: { $first: "$name" },
details: { $mergeObjects: "$details" },
},
},
{ $sort: { _id: 1 } },
],
check: [
{
_id: 1,
name: "Aunt Arc Tikka",
details: { phone: "+672-19-9999", email: "aunt.arc.tica@example.com" },
},
{
_id: 2,
name: "Belle Gium",
details: { phone: "+32-2-111-11-11", email: "belle.gium@example.com" },
},
{
_id: 3,
name: "Cam Bo Dia",
details: {
phone: "+855-012-000-0000",
email: "cam.bo.dia@example.com",
},
},
{ _id: 4, name: "Fred", details: { phone: "+1-111-222-3333" } },
],
},
{
message: "$regexFind: Use Captured Groupings to Parse User Name",
input: [
{ _id: 1, name: "Aunt Arc Tikka", email: "aunt.tica@example.com" },
{ _id: 2, name: "Belle Gium", email: "belle.gium@example.com" },
{ _id: 3, name: "Cam Bo Dia", email: "cam.dia@example.com" },
{ _id: 4, name: "Fred" },
],
query: [
{
$addFields: {
username: {
$regexFind: {
input: "$email",
regex: /^([a-z0-9_.+-]+)@[a-z0-9_.+-]+\.[a-z0-9_.+-]+$/,
options: "i",
},
},
},
},
{ $set: { username: { $arrayElemAt: ["$username.captures", 0] } } },
],
check: [
{
_id: 1,
name: "Aunt Arc Tikka",
email: "aunt.tica@example.com",
username: "aunt.tica",
},
{
_id: 2,
name: "Belle Gium",
email: "belle.gium@example.com",
username: "belle.gium",
},
{
_id: 3,
name: "Cam Bo Dia",
email: "cam.dia@example.com",
username: "cam.dia",
},
{ _id: 4, name: "Fred", username: null },
],
},
]);
support.runTestPipeline("$regexFindAll operator", [
{
message: "can apply $regexFindAll",
input: [
{ _id: 1, category: "café" },
{ _id: 2, category: "cafe" },
{ _id: 3, category: "cafE" },
],
query: [
{
$addFields: {
resultObject: {
$regexFindAll: { input: "$category", regex: /cafe/ },
},
},
},
],
check: [
{ _id: 1, category: "café", resultObject: [] },
{
_id: 2,
category: "cafe",
resultObject: [{ match: "cafe", idx: 0, captures: [] }],
},
{ _id: 3, category: "cafE", resultObject: [] },
],
},
{
message: "$regexFindAll with 'captures': 1",
input: data,
query: [
{
$project: {
returnObject: {
$regexFindAll: { input: "$fname", regex: /(C(ar)*)ol/ },
},
},
},
],
check: [
{
_id: 1,
returnObject: [{ match: "Carol", idx: 0, captures: ["Car", "ar"] }],
},
{ _id: 2, returnObject: [] },
{ _id: 3, returnObject: [] },
{
_id: 4,
returnObject: [{ match: "Col", idx: 0, captures: ["C", null] }],
},
{ _id: 5, returnObject: [] },
],
},
{
message: "$regexFindAll with 'captures': 2",
input: data,
query: [
{
$project: {
nycContacts: {
$regexFindAll: {
input: "$phone",
regex: /^(718).*|^(212).*|^(917).*/,
},
},
},
},
],
check: [
{
_id: 1,
nycContacts: [
{ match: "718-555-0113", idx: 0, captures: ["718", null, null] },
],
},
{
_id: 2,
nycContacts: [
{ match: "212-555-8832", idx: 0, captures: [null, "212", null] },
],
},
{ _id: 3, nycContacts: [] },
{ _id: 4, nycContacts: [] },
{
_id: 5,
nycContacts: [
{ match: "917-555-4414", idx: 0, captures: [null, null, "917"] },
],
},
],
},
{
message: "$regexFindAll without grouping",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFindAll: { input: "$description", regex: /line/ },
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: [] },
{
_id: 2,
description: "First lines\nsecond line",
returnObject: [
{ match: "line", idx: 6, captures: [] },
{ match: "line", idx: 19, captures: [] },
],
},
{
_id: 3,
description: "Many spaces before line",
returnObject: [{ match: "line", idx: 23, captures: [] }],
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: [{ match: "line", idx: 9, captures: [] }],
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: [],
},
{ _id: 6, description: "métier work vocation", returnObject: [] },
],
},
{
message: "$regexFindAll with grouping",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFindAll: { input: "$description", regex: /lin(e|k)/ },
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: [] },
{
_id: 2,
description: "First lines\nsecond line",
returnObject: [
{ match: "line", idx: 6, captures: ["e"] },
{ match: "line", idx: 19, captures: ["e"] },
],
},
{
_id: 3,
description: "Many spaces before line",
returnObject: [{ match: "line", idx: 23, captures: ["e"] }],
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: [{ match: "line", idx: 9, captures: ["e"] }],
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: [
{ match: "link", idx: 9, captures: ["k"] },
{ match: "link", idx: 24, captures: ["k"] },
],
},
{ _id: 6, description: "métier work vocation", returnObject: [] },
],
},
{
message: "$regexFindAll 'idx' is codepoint",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFindAll: { input: "$description", regex: /tier/ },
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: [] },
{ _id: 2, description: "First lines\nsecond line", returnObject: [] },
{ _id: 3, description: "Many spaces before line", returnObject: [] },
{ _id: 4, description: "Multiple\nline descriptions", returnObject: [] },
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: [],
},
{
_id: 6,
description: "métier work vocation",
returnObject: [{ match: "tier", idx: 2, captures: [] }],
},
],
},
{
message: "$regexFindAll with option 'i'",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFindAll: {
input: "$description",
regex: "line",
options: "i",
},
},
},
},
],
check: [
{
_id: 1,
description: "Single LINE description.",
returnObject: [{ match: "LINE", idx: 7, captures: [] }],
},
{
_id: 2,
description: "First lines\nsecond line",
returnObject: [
{ match: "line", idx: 6, captures: [] },
{ match: "line", idx: 19, captures: [] },
],
},
{
_id: 3,
description: "Many spaces before line",
returnObject: [{ match: "line", idx: 23, captures: [] }],
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: [{ match: "line", idx: 9, captures: [] }],
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: [],
},
{ _id: 6, description: "métier work vocation", returnObject: [] },
],
},
{
message: "$regexFindAll with option 'm'",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFindAll: { input: "$description", regex: /^s/im },
},
},
},
],
check: [
{
_id: 1,
description: "Single LINE description.",
returnObject: [{ match: "S", idx: 0, captures: [] }],
},
{
_id: 2,
description: "First lines\nsecond line",
returnObject: [{ match: "s", idx: 12, captures: [] }],
},
{ _id: 3, description: "Many spaces before line", returnObject: [] },
{ _id: 4, description: "Multiple\nline descriptions", returnObject: [] },
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: [],
},
{ _id: 6, description: "métier work vocation", returnObject: [] },
],
},
{
message: "$regexFindAll with option 's'",
input: productsData,
query: [
{
$addFields: {
returnObject: {
$regexFindAll: {
input: "$description",
regex: /m.*line/,
options: "si",
},
},
},
},
],
check: [
{ _id: 1, description: "Single LINE description.", returnObject: [] },
{ _id: 2, description: "First lines\nsecond line", returnObject: [] },
{
_id: 3,
description: "Many spaces before line",
returnObject: [
{ match: "Many spaces before line", idx: 0, captures: [] },
],
},
{
_id: 4,
description: "Multiple\nline descriptions",
returnObject: [{ match: "Multiple\nline", idx: 0, captures: [] }],
},
{
_id: 5,
description: "anchors, links and hyperlinks",
returnObject: [],
},
{ _id: 6, description: "métier work vocation", returnObject: [] },
],
},
// Not supported
// {
// message: "$regexFindAll with option 'x'",
// input: dataForOptions,
// query: [ { $addFields: { returnObject: { $regexFindAll: { input: "$description", regex: /lin(e|k) # matches line or link/, options: "x" } } } } ],
// check: [
// { "_id" : 1, "description" : "Single LINE description.", "returnObject" : [] },
// { "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : [ { "match" : "line", "idx" : 6, "captures" : [ "e" ] }, { "match" : "line", "idx" : 19, "captures" : [ "e" ] } ] },
// { "_id" : 3, "description" : "Many spaces before line", "returnObject" : [ { "match" : "line", "idx" : 23, "captures" : [ "e" ] } ] },
// { "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : [ { "match" : "line", "idx" : 9, "captures" : [ "e" ] } ] },
// { "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : [ { "match" : "link", "idx" : 9, "captures" : [ "k" ] }, { "match" : "link", "idx" : 24, "captures" : [ "k" ] } ] },
// { "_id" : 6, "description" : "métier work vocation", "returnObject" : [] }
// ]
// }
{
message: "$regexFindAll to Parse Email from String",
input: [
{
_id: 1,
comment:
"Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com",
},
{ _id: 2, comment: "I wanted to concatenate a string" },
{
_id: 3,
comment:
"How do I convert a date to string? Contact me at either cam@mongodb.com or c.dia@mongodb.com",
},
{ _id: 4, comment: "It's just me. I'm testing. fred@MongoDB.com" },
],
query: [
{
$addFields: {
email: {
$regexFindAll: {
input: "$comment",
regex: /[a-z0-9_.+-]+@[a-z0-9_.+-]+\.[a-z0-9_.+-]+/i,
},
},
},
},
{ $set: { email: "$email.match" } },
],
check: [
{
_id: 1,
comment:
"Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com",
email: ["aunt.arc.tica@example.com"],
},
{ _id: 2, comment: "I wanted to concatenate a string", email: [] },
{
_id: 3,
comment:
"How do I convert a date to string? Contact me at either cam@mongodb.com or c.dia@mongodb.com",
email: ["cam@mongodb.com", "c.dia@mongodb.com"],
},
{
_id: 4,
comment: "It's just me. I'm testing. fred@MongoDB.com",
email: ["fred@MongoDB.com"],
},
],
},
{
message: "$regexFindAll: Use Captured Groupings to Parse User Name",
input: [
{
_id: 1,
comment:
"Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com",
},
{ _id: 2, comment: "I wanted to concatenate a string" },
{
_id: 3,
comment:
"How do I convert a date to string? Contact me at either cam@mongodb.com or c.dia@mongodb.com",
},
{ _id: 4, comment: "It's just me. I'm testing. fred@MongoDB.com" },
],
query: [
{
$addFields: {
names: {
$regexFindAll: {
input: "$comment",
regex: /([a-z0-9_.+-]+)@[a-z0-9_.+-]+\.[a-z0-9_.+-]+/i,
},
},
},
},
{
$set: {
names: {
$reduce: {
input: "$names.captures",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this"] },
},
},
},
},
],
check: [
{
_id: 1,
comment:
"Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com",
names: ["aunt.arc.tica"],
},
{ _id: 2, comment: "I wanted to concatenate a string", names: [] },
{
_id: 3,
comment:
"How do I convert a date to string? Contact me at either cam@mongodb.com or c.dia@mongodb.com",
names: ["cam", "c.dia"],
},
{
_id: 4,
comment: "It's just me. I'm testing. fred@MongoDB.com",
names: ["fred"],
},
],
},
]); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.