text stringlengths 2.5k 6.39M | kind stringclasses 3 values |
|---|---|
import * as React from 'react';
import { Button, ButtonProps } from '@mui/material';
import { Theme } from '@mui/material/styles';
import { createStyles, makeStyles } from '@mui/styles';
import Axios, { AxiosError } from 'axios';
import * as QueryString from 'query-string';
import { Link } from 'react-router-dom';
import { AuthMessageBox } from 'app/components';
import pixieAnalytics from 'app/utils/analytics';
import { isValidAnalytics } from 'app/utils/env';
import * as RedirectUtils from 'app/utils/redirect-utils';
import { BasePage } from './base';
import { AuthCallbackMode, parseRedirectArgs } from './callback-url';
import { Token } from './oauth-provider';
import { GetOAuthProvider } from './utils';
// Send token header to enable CORS check. Token is still allowed with Pixie CLI.
const redirectGet = async (url: string, data: { accessToken: string }) => (
Axios.get(url, { headers: { token: data.accessToken } })
);
type ErrorType = 'internal' | 'auth';
interface ErrorDetails {
errorType?: ErrorType;
errMessage?: string;
}
interface CallbackConfig {
mode?: AuthCallbackMode;
signup?: boolean;
token?: string;
loading?: boolean;
err?: ErrorDetails;
}
function trackAuthEvent(event: string, id: string, email: string): Promise<void> {
if (isValidAnalytics()) {
return Promise.race([
new Promise<void>((resolve) => { // Wait for analytics to be sent out before redirecting.
pixieAnalytics.track(event, () => {
pixieAnalytics.identify(id, { email }, {}, () => {
resolve();
});
});
}),
// Wait a maximum of 4s before redirecting. If it takes this long, it probably means that
// something in Segment failed to initialize/send.
new Promise((resolve) => setTimeout(resolve, 4000)),
]).then();
}
return Promise.resolve();
}
function getCtaDetails(config: CallbackConfig) {
let title: string;
let ctaMessage: string;
let ctaDestination: string;
let errorMessage: string;
let showDetails = true;
if (config.err.errorType === 'internal') {
if (config.signup) {
if (config.err.errMessage.match(/user.*already.*exists/ig)) {
errorMessage = 'Account already exists. Please login.';
ctaMessage = 'Go to Log In';
ctaDestination = '/auth/login';
showDetails = false;
} else {
errorMessage = 'We hit a snag in creating an account. Please try again later.';
ctaMessage = 'Back to Sign Up';
ctaDestination = '/auth/signup';
}
} else if (config.err.errMessage.match(/.*organization.*not.*found.*/g)
|| config.err.errMessage.match(/.*user.*not.*found.*/g)) {
errorMessage = 'We hit a snag trying to authenticate you. User not registered. Please sign up.';
// If user or organization not found, direct to sign up page first.
ctaMessage = 'Go to Sign Up';
ctaDestination = '/auth/signup';
} else if (config.err.errMessage.match(/verify.*your.*email/ig)) {
title = 'Please verify your email to continue';
errorMessage = 'Check your email for a verification link.';
ctaMessage = 'Go to Log In';
ctaDestination = '/auth/login';
showDetails = false;
} else {
errorMessage = 'We hit a snag trying to authenticate you. Please try again later.';
ctaMessage = 'Back to Log In';
ctaDestination = '/auth/login';
}
} else {
errorMessage = config.err.errMessage;
ctaMessage = 'Go Back';
ctaDestination = '/';
}
return {
title,
ctaMessage,
ctaDestination,
errorMessage,
showDetails,
};
}
const useStyles = makeStyles((theme: Theme) => createStyles({
ctaGutter: {
marginTop: theme.spacing(3),
paddingTop: theme.spacing(3),
borderTop: `1px solid ${theme.palette.foreground.grey1}`,
width: '80%',
},
}));
const CLICodeBox = React.memo<{ code: string }>(({ code }) => (
<AuthMessageBox
title='Pixie Auth Token'
message='Please copy this code, switch to the CLI and paste it there:'
code={code}
/>
));
CLICodeBox.displayName = 'CLICodeBox';
const CtaButton = React.memo<ButtonProps>(({ children, ...props }) => (
<Button color='primary' variant='contained' {...props}>{children}</Button>
));
CtaButton.displayName = 'CtaButton';
const ErrorMessage = React.memo<{ config: CallbackConfig }>(({ config }) => {
const classes = useStyles();
const title = config.signup ? 'Failed to Sign Up' : 'Failed to Log In';
const errorDetails = config.err.errorType === 'internal' ? config.err.errMessage : undefined;
const {
title: ctaTitle,
ctaMessage,
ctaDestination,
errorMessage,
showDetails,
} = getCtaDetails(config);
const cta = React.useMemo(() => (
<div className={classes.ctaGutter}>
<Link to={ctaDestination} component={CtaButton}>
{ctaMessage}
</Link>
</div>
), [classes.ctaGutter, ctaDestination, ctaMessage]);
return (
<AuthMessageBox
error='recoverable'
title={ctaTitle || title}
message={errorMessage}
errorDetails={showDetails ? errorDetails : ''}
cta={cta}
/>
);
});
ErrorMessage.displayName = 'ErrorMessage';
/**
* This is the main component to handle the callback from auth.
*
* This component gets the token from Auth0 and either sends it to the CLI or
* makes a request to Pixie cloud to perform a signup/login.
*/
export const AuthCallbackPage: React.FC = React.memo(() => {
const [config, setConfig] = React.useState<CallbackConfig>(null);
const setErr = React.useCallback((errType: ErrorType, errMsg: string) => {
setConfig((c) => ({
...c,
err: {
errorType: errType,
errMessage: errMsg,
},
loading: false,
}));
}, []);
const handleHTTPError = React.useCallback((err: AxiosError) => {
if (err.code === '401' || err.code === '403' || err.code === '404') {
setErr('auth', err.response.data);
} else {
setErr('internal', err.response.data);
}
}, [setErr]);
const performSignup = React.useCallback(async (accessToken: string, idToken: string, inviteToken: string) => {
let response = null;
try {
response = await Axios.post('/api/auth/signup', { accessToken, idToken, inviteToken });
} catch (err) {
pixieAnalytics.track('User signup failed', { error: err.response.data });
handleHTTPError(err as AxiosError);
return false;
}
await trackAuthEvent('User signed up', response.data.userInfo.userID, response.data.userInfo.email);
return true;
}, [handleHTTPError]);
const performUILogin = React.useCallback(async (accessToken: string, idToken: string, inviteToken: string) => {
let response = null;
try {
response = await Axios.post('/api/auth/login', {
accessToken,
idToken,
inviteToken,
});
} catch (err) {
pixieAnalytics.track('User login failed', { error: err.response.data });
handleHTTPError(err as AxiosError);
return false;
}
await trackAuthEvent('User logged in', response.data.userInfo.userID, response.data.userInfo.email);
return true;
}, [handleHTTPError]);
const sendTokenToCLI = React.useCallback(async (accessToken: string, idToken: string, redirectURI: string) => {
try {
const response = await redirectGet(redirectURI, { accessToken });
return response.status === 200 && response.data === 'OK';
} catch (error) {
handleHTTPError(error as AxiosError);
// If there's an error, we just return a failure.
return false;
}
}, [handleHTTPError]);
const doAuth = React.useCallback(async (
mode: AuthCallbackMode,
signup: boolean,
redirectURI: string,
accessToken: string,
idToken: string,
inviteToken: string,
) => {
let signupSuccess = false;
let loginSuccess = false;
if (signup) {
// We always need to perform signup, even if the mode is CLI.
signupSuccess = await performSignup(accessToken, idToken, inviteToken);
}
// eslint-disable-next-line default-case
switch (mode) {
case 'cli_get':
loginSuccess = await sendTokenToCLI(accessToken, idToken, redirectURI);
if (loginSuccess) {
setConfig((c) => ({
...c,
loading: false,
}));
RedirectUtils.redirect('/auth/cli-auth-complete', {});
return;
}
// Don't fallback to manual auth if there is an actual
// authentication error.
if (config.err?.errorType === 'auth') {
break;
}
// If it fails, switch to token auth.
setConfig((c) => ({
...c,
mode: 'cli_token',
}));
break;
case 'cli_token':
// Nothing to do, it will just render.
break;
case 'ui':
if (!signup) {
loginSuccess = await performUILogin(accessToken, idToken, inviteToken);
}
// We just need to redirect if in signup or login were successful since
// the cookies are installed.
if ((signup && signupSuccess) || loginSuccess) {
RedirectUtils.redirect(redirectURI || '/', {});
}
}
setConfig((c) => ({
...c,
loading: false,
}));
}, [config?.err?.errorType, performSignup, performUILogin, sendTokenToCLI]);
const handleAccessToken = React.useCallback((token: Token) => {
const args = parseRedirectArgs(QueryString.parse(window.location.search));
setConfig({
mode: args.mode,
signup: args.signup,
token: token?.accessToken,
loading: true,
});
if (!token?.accessToken) {
setConfig({
mode: args.mode,
signup: args.signup,
token: token?.accessToken,
loading: false,
});
return;
}
doAuth(
args.mode,
args.signup,
args.redirect_uri,
token?.accessToken,
token?.idToken,
args.invite_token,
).then();
}, [doAuth]);
React.useEffect(() => {
GetOAuthProvider().handleToken().then(handleAccessToken).catch((err) => {
setErr('internal', `${err}`);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const loadingMessage = React.useMemo(() => (
<AuthMessageBox
title='Authenticating'
message={
(config && config.signup) ? 'Signing up ...' : 'Logging in...'
|| '...'
}
/>
), [config]);
const normalMessage = React.useMemo(() => {
if (config?.mode === 'cli_token') {
return (
<CLICodeBox
code={config.token}
/>
);
}
return loadingMessage;
}, [config?.mode, config?.token, loadingMessage]);
const loading = !config || config.loading;
return (
<BasePage>
{loading && loadingMessage}
{!loading && (config.err ? <ErrorMessage config={config} /> : normalMessage)}
</BasePage>
);
});
AuthCallbackPage.displayName = 'AuthCallbackPage'; | the_stack |
import * as crypto from "crypto";
import * as debug_ from "debug";
import * as path from "path";
import { ok } from "readium-desktop/common/utils/assert";
import { httpGet } from "readium-desktop/main/network/http";
import {
getUniqueResourcesFromR2Publication, w3cPublicationManifestToReadiumPublicationManifest,
} from "readium-desktop/main/w3c/audiobooks/converter";
import {
findManifestFromHtmlEntryAndReturnBuffer,
} from "readium-desktop/main/w3c/audiobooks/entry";
import { findHtmlTocInRessources } from "readium-desktop/main/w3c/audiobooks/toc";
import { createWebpubZip, TResourcesFSCreateZip } from "readium-desktop/main/zip/create";
import { tryCatchSync } from "readium-desktop/utils/tryCatch";
import { SagaGenerator } from "typed-redux-saga";
import { call as callTyped } from "typed-redux-saga/macro";
import { TaJsonDeserialize, TaJsonSerialize } from "@r2-lcp-js/serializable";
import { Publication as R2Publication } from "@r2-shared-js/models/publication";
import { Link } from "@r2-shared-js/models/publication-link";
import { downloader } from "../../../downloader";
import { manifestContext } from "./context";
// Logger
const filename_ = "readium-desktop:main#saga/api/publication/packager/packageLink";
const debug = debug_(filename_);
const fetcher = (baseUrl: string) => async (href: string) => {
debug("fetcher", href);
// DEPRECATED API (watch for the inverse function parameter order!):
// url.resolve(baseUrl, href)
href = new URL(href, baseUrl).toString();
const res = await httpGet(href);
try {
ok(res.isSuccess, res.statusMessage);
return await res.response.buffer();
} catch (e) {
debug("error to fetch", e);
}
return undefined;
};
const copyAndSetHref = (lns: Link[], hrefMapToFind: TResources) =>
lns.map(
(ln) => {
const href = ln.Href;
const found = hrefMapToFind.find(([, searchValue]) => searchValue === href);
if (found) {
const [, , replaceValue] = found;
ln.Href = replaceValue;
}
if (Array.isArray(ln.Children) && ln.Children.length) {
ln.Children = copyAndSetHref(ln.Children, hrefMapToFind);
}
return ln;
});
const linksToArray = (lns: Link[]): string[] =>
lns.reduce(
(pv, cv) =>
cv.Href
? [
...pv,
cv.Href,
...(
Array.isArray(cv.Children) && cv.Children.length
? linksToArray(cv.Children)
: []
),
]
: pv,
new Array<string>());
type TResource = [fsPath: string, href: string, zipPath: string];
type TResources = TResource[];
function* downloadResources(
r2Publication: R2Publication,
title: string,
baseUrl: string,
): SagaGenerator<TResources> {
const uResources = getUniqueResourcesFromR2Publication(r2Publication);
debug(uResources);
const resourcesHref = [...new Set(linksToArray(uResources))];
debug(resourcesHref);
const resourcesType = resourcesHref.map((v) => {
// tslint:disable-next-line
try { new URL(v); return false; } catch {}
return true;
});
debug(resourcesType);
const resourcesHrefResolved = tryCatchSync(() => {
const baseUrlURL = new URL(baseUrl);
if (baseUrlURL.protocol === "file:") {
// new URL('file://C:/test/here')).pathname
// /C:/test/here
// WARNING: see code comment about isWindowsFilesystemPathRooted below!
const baseUrlLocal = baseUrl.slice("file://".length);
return resourcesHref.map((l) => path.join(baseUrlLocal, l));
}
// DEPRECATED API (watch for the inverse function parameter order!):
// url.resolve(baseUrl, l)
return resourcesHref
.map((l) => tryCatchSync(() => new URL(l, baseUrl).toString(), filename_))
.filter((v) => !!v);
}, filename_);
debug(resourcesHrefResolved);
const pathArrayFromDownloader = baseUrl.startsWith("file://")
? resourcesHrefResolved
: yield* callTyped(downloader, resourcesHrefResolved, title);
debug(pathArrayFromDownloader);
const pathArray = pathArrayFromDownloader.map<[string, boolean]>((v, i) => [v, resourcesType[i]]);
debug(pathArray);
const resourcesHrefMap = pathArray.map<TResource>(
([fsPath, isResourcesType], idx) => {
// fsPath can be undefined
if (!fsPath) {
return undefined;
}
// The following code block is not needed,
// as resourcesHrefResolved guarantees absolute filenames,
// removing file://
// and bypassing the URL(baseHref, href).toString() normalization.
// Reminder about URL(baseHref, href).toString():
// if the base URL is file://C:/etc. on Windows,
// the URL API adds a slash prefix: file:///C:/etc. to match Linux / MacOS absolute file path root syntax
//
// const isWindowsFilesystemPathRooted = path.sep === "\\" && /^\/[a-zA-Z]:\//.test(fsPath);
// const fsPath_ = isWindowsFilesystemPathRooted ?
// fsPath.substr(1).replace(/\//g, "\\") :
// fsPath;
// debug(isWindowsFilesystemPathRooted, fsPath);
let zipPath: string;
if (isResourcesType) {
zipPath = resourcesHref[idx];
} else {
const hash = crypto.createHash("sha1").update(resourcesHref[idx]).digest("hex");
zipPath = hash + "/" + path.basename(resourcesHrefResolved[idx]);
}
return [
fsPath,
resourcesHref[idx],
zipPath,
];
},
).filter((v) => !!v);
debug(resourcesHrefMap);
return resourcesHrefMap;
}
function updateManifest(
r2Publication: R2Publication,
resourcesHrefMap: TResources,
) {
{
const readingOrders = r2Publication.Spine;
if (Array.isArray(readingOrders)) {
r2Publication.Spine = copyAndSetHref(readingOrders, resourcesHrefMap);
}
}
{
const links = r2Publication.Links;
if (Array.isArray(links)) {
r2Publication.Links = copyAndSetHref(links, resourcesHrefMap);
}
}
{
const resources = r2Publication.Resources;
if (Array.isArray(resources)) {
r2Publication.Resources = copyAndSetHref(resources, resourcesHrefMap);
}
}
return r2Publication;
}
function* BufferManifestToR2Publication(r2PublicationBuffer: Buffer, href: string): SagaGenerator<R2Publication | undefined> {
let r2Publication: R2Publication;
const fetch = fetcher(href);
let r2PublicationJson: any;
try {
const r2PublicationStr = r2PublicationBuffer.toString("utf-8");
r2PublicationJson = JSON.parse(r2PublicationStr);
} catch (e) {
debug("error to parse manifest", e, r2PublicationBuffer);
return undefined;
}
const [isR2, isW3] = manifestContext(r2PublicationJson);
if (isW3) {
debug("w3cManifest found");
r2Publication = yield* callTyped(
w3cPublicationManifestToReadiumPublicationManifest,
r2PublicationJson,
async (resources: Link[]) => findHtmlTocInRessources(resources, fetch),
);
} else if (isR2) {
debug("readium manifest found");
r2Publication = TaJsonDeserialize(r2PublicationJson, R2Publication);
}
return r2Publication;
}
export function* packageFromLink(
href: string,
isHtml: boolean,
): SagaGenerator<string | undefined> {
const [manifest, manifestUrl] = yield* callTyped(packageGetManifestBuffer, href, isHtml);
if (!manifest) {
throw new Error("manifest not found from content link " + href);
}
return yield* callTyped(packageFromManifestBuffer, href, manifest, manifestUrl);
}
export function* packageFromManifestBuffer(
baseUrl: string, // 'file://' for local resources
manifest: Buffer,
manifestPath?: string,
) {
const r2Publication = yield* callTyped(BufferManifestToR2Publication, manifest, baseUrl);
if (!r2Publication) {
throw new Error("r2Publication parsing failed");
}
debug("ready to package the r2Publication");
debug(r2Publication);
// DEPRECATED API (watch for the inverse function parameter order!):
// url.resolve(baseUrl, manifestPath)
const manifestUrlAbsolutized = manifestPath ?
tryCatchSync(() => new URL(manifestPath, baseUrl).toString(), filename_) :
baseUrl;
debug("manifestUrl", manifestUrlAbsolutized, manifestPath, baseUrl);
const resourcesHrefMap = yield* callTyped(
downloadResources,
r2Publication,
baseUrl,
manifestUrlAbsolutized,
);
const r2PublicationUpdated = updateManifest(r2Publication, resourcesHrefMap);
debug(r2PublicationUpdated);
const manifestSerialize = TaJsonSerialize(r2PublicationUpdated);
const manifestString = JSON.stringify(manifestSerialize);
const manifestBuffer = Buffer.from(manifestString);
// create the .webpub zip package
const resourcesCreateZip: TResourcesFSCreateZip = resourcesHrefMap.map(([fsPath, , zipPath]) => [fsPath, zipPath]);
debug(resourcesCreateZip);
const webpubPath = yield* callTyped(createWebpubZip, manifestBuffer, resourcesCreateZip, [], "packager");
return webpubPath;
}
export function* packageGetManifestBuffer(
href: string,
isHtml: boolean,
): SagaGenerator<[Buffer, string]> {
let manifestBuffer: Buffer;
let manifestUrl: string;
const fetch = fetcher(href);
const data = yield* callTyped(httpGet, href);
const { response, isFailure } = data;
const rawData = yield* callTyped(() => response?.text());
if (isFailure) {
throw new Error("fetch error [" + href + "](" + response?.status + " " + response?.statusText + " " + rawData + "]");
// we can add a toast notification here like the downloader
}
if (rawData) {
if (isHtml) {
const htmlBuffer = Buffer.from(rawData);
[manifestBuffer, manifestUrl] = yield* callTyped(
findManifestFromHtmlEntryAndReturnBuffer,
htmlBuffer,
fetch,
);
} else {
manifestBuffer = Buffer.from(rawData);
}
}
return [manifestBuffer, manifestUrl];
} | the_stack |
import * as mockery from 'mockery';
import { mockElectron } from './electron';
import * as assert from 'assert';
import ofEvents from '../src/browser/of_events';
import route from '../src/common/route';
// tslint:disable-next-line
const sinon = require('sinon');
mockery.registerMock('electron', mockElectron);
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false
});
import { GlobalHotkey } from '../src/browser/api/global_hotkey';
describe('GlobalHotkey', () => {
afterEach(() => {
GlobalHotkey.unregisterAll({ uuid: 'test-uuid', name: 'test-uuid' });
GlobalHotkey.unregisterAll({ uuid: 'test-uuid2', name: 'test-uuid' });
});
it('Should be able to successully register an accelerator', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.calledOnce, 'Expected the global shortcut to be called');
});
it('Should allow multiple registrations for the same identity', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.register(identity, hotkey, spy);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.calledTwice, 'Expected the global shortcut to be called');
});
it('Should allow multiple registrations for the same uuid but different names', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
const cWinIdentity = { uuid: 'test-uuid', name: 'child-window' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.register(cWinIdentity, hotkey, spy);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.calledTwice, 'Expected the global shortcut to be called');
});
it('Should not allow multiple registrations from different identities', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
const identity2 = { uuid: 'test-uuid-2', name: 'test-uuid-2' };
GlobalHotkey.register(identity, hotkey, spy);
try {
GlobalHotkey.register(identity2, hotkey, spy);
} catch (err) {
assert.ok(err instanceof Error, 'Expected error thrown to be an instance of Error');
assert.equal(err.message, 'Failed to register Hotkey: CommandOrControl+X, already registered');
}
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.calledOnce, 'Expected the global shortcut to be called');
});
it('Should throw an error if the electron register fails', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
mockElectron.globalShortcut.failNextRegisterCall = true;
try {
GlobalHotkey.register(identity, hotkey, spy);
} catch (err) {
assert.ok(err instanceof Error, 'Expected error thrown to be an instance of Error');
assert.equal(err.message, 'Failed to register Hotkey: CommandOrControl+X, register call returned undefined');
}
});
it('Should successfully unregister', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.unregister(identity, hotkey);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.notCalled, 'Expected the global shortcut not to be called');
});
it('Should unregister a single hotkey', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const hotkey2 = 'CommandOrControl+Y';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.register(identity, hotkey2, spy);
GlobalHotkey.unregister(identity, hotkey);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
mockElectron.globalShortcut.mockRaiseEvent(hotkey2);
assert.ok(spy.calledOnce, 'Expected the global shortcut to be called');
});
it('Should unregister all hotkeys', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const hotkey2 = 'CommandOrControl+Y';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.register(identity, hotkey2, spy);
GlobalHotkey.unregisterAll(identity);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.notCalled, 'Expected the global shortcut not to be called');
});
it('Should unregister all for a given uuid', () => {
const spy = sinon.spy();
const spy2 = sinon.spy();
const hotkey = 'CommandOrControl+X';
const hotkey2 = 'CommandOrControl+Y';
const hotkey3 = 'CommandOrControl+C';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
const identity2 = { uuid: 'test-uuid2', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.register(identity, hotkey2, spy);
GlobalHotkey.register(identity2, hotkey3, spy2);
GlobalHotkey.unregisterAll(identity);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
mockElectron.globalShortcut.mockRaiseEvent(hotkey2);
mockElectron.globalShortcut.mockRaiseEvent(hotkey3);
assert.ok(spy.notCalled, 'Expected the global shortcut not to be called');
assert.ok(spy2.calledOnce, 'Expected the global shortcut not to be called');
});
it('Should return true for a registered hotkey', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
const isRegistered = GlobalHotkey.isRegistered(hotkey);
assert.deepStrictEqual(isRegistered, true, 'Expected hotkey to be registered');
});
it('Shuld return false for a unregistered hotkey', () => {
const hotkey = 'CommandOrControl+X';
const isRegistered = GlobalHotkey.isRegistered(hotkey);
assert.deepStrictEqual(isRegistered, false, 'Expected hotkey not to be registered');
});
it('Should return false for a recently unregistered hotkey', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.unregister(identity, hotkey);
const isRegistered = GlobalHotkey.isRegistered(hotkey);
assert.deepStrictEqual(isRegistered, false, 'Expected hotkey to not be registered');
});
it('Should unregister on a main window close event', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
//we simulate a window close.
ofEvents.emit(route.window('closed', identity.uuid, identity.name), identity);
const isRegistered = GlobalHotkey.isRegistered(hotkey);
assert.deepStrictEqual(isRegistered, false, 'Expected hotkey to not be registered');
});
it('Should unregister on a frame disconnected event', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'frame-one' };
GlobalHotkey.register(identity, hotkey, spy);
//we simulate a frame disconnected.
ofEvents.emit(route.frame('disconnected'), identity);
const isRegistered = GlobalHotkey.isRegistered(hotkey);
assert.deepStrictEqual(isRegistered, false, 'Expected hotkey to not be registered');
});
it('Should unregister on an external connection close event', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
GlobalHotkey.register(identity, hotkey, spy);
//we simulate a external connection closed.
ofEvents.emit(route('externalconn', 'closed'), identity);
const isRegistered = GlobalHotkey.isRegistered(hotkey);
assert.deepStrictEqual(isRegistered, false, 'Expected hotkey to not be registered');
});
it('Should not unregister if closing a child window if more windows have registered', () => {
const spy = sinon.spy();
const spy2 = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
const identity2 = { uuid: 'test-uuid', name: 'test-uuid-child' };
GlobalHotkey.register(identity, hotkey, spy);
GlobalHotkey.register(identity2, hotkey, spy2);
//we simulate a window close.
ofEvents.emit(route.window('closed', identity2.uuid, identity2.name), identity2);
mockElectron.globalShortcut.mockRaiseEvent(hotkey);
assert.ok(spy.calledOnce, 'Expected the global shortcut to be called');
assert.ok(spy2.notCalled, 'Expected the global shortcut to not be called');
});
it('Should emit registered events', () => {
const spy = sinon.spy();
const spy2 = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
//we simulate a window close.
ofEvents.on(route.globalHotkey('registered', identity.uuid), spy);
GlobalHotkey.register(identity, hotkey, spy2);
assert.ok(spy.calledOnce, 'Expected "registered" event to be fired once');
});
it('Should emit registered events once per hotkey', () => {
const spy = sinon.spy();
const spy2 = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
const identity2 = { uuid: 'test-uuid', name: 'test-uuid-child' };
//we simulate a window close.
ofEvents.on(route.globalHotkey('registered', identity.uuid), spy);
GlobalHotkey.register(identity, hotkey, spy2);
GlobalHotkey.register(identity2, hotkey, spy2);
assert.ok(spy.calledOnce, 'Expected "registered" event to be fired once');
});
it('Should emit unregistered events', () => {
const spy = sinon.spy();
const spy2 = sinon.spy();
const hotkey = 'CommandOrControl+X';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
//we simulate a window close.
ofEvents.on(route.globalHotkey('unregistered', identity.uuid), spy);
GlobalHotkey.register(identity, hotkey, spy2);
GlobalHotkey.unregister(identity, hotkey);
assert.ok(spy.calledOnce, 'Expected "unregistered" event to be fired once');
});
it('Should fail to register a reserved hotkey', () => {
const spy = sinon.spy();
const hotkey = 'CommandOrControl+0';
const identity = { uuid: 'test-uuid', name: 'test-uuid' };
mockElectron.globalShortcut.failNextRegisterCall = true;
try {
GlobalHotkey.register(identity, hotkey, spy);
} catch (err) {
assert.ok(err instanceof Error, 'Expected error thrown to be an instance of Error');
assert.equal(err.message, 'Failed to register Hotkey: CommandOrControl+0, is reserved');
}
});
}); | the_stack |
import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { equal } from '@wry/equality';
import { OperationVariables } from '../../core';
import { getApolloContext } from '../context';
import { ApolloError } from '../../errors';
import {
ApolloQueryResult,
NetworkStatus,
ObservableQuery,
DocumentNode,
TypedDocumentNode,
WatchQueryOptions,
} from '../../core';
import {
QueryHookOptions,
QueryResult,
} from '../types/types';
import { DocumentType, verifyDocumentType } from '../parser';
import { useApolloClient } from './useApolloClient';
export function useQuery<
TData = any,
TVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: QueryHookOptions<TData, TVariables>,
): QueryResult<TData, TVariables> {
const context = useContext(getApolloContext());
const client = useApolloClient(options?.client);
verifyDocumentType(query, DocumentType.Query);
const [obsQuery, setObsQuery] = useState(() => {
const watchQueryOptions = createWatchQueryOptions(query, options);
// See if there is an existing observable that was used to fetch the same
// data and if so, use it instead since it will contain the proper queryId
// to fetch the result set. This is used during SSR.
let obsQuery: ObservableQuery<TData, TVariables> | null = null;
if (context.renderPromises) {
obsQuery = context.renderPromises.getSSRObservable(watchQueryOptions);
}
if (!obsQuery) {
// Is it safe (StrictMode/memory-wise) to call client.watchQuery here?
obsQuery = client.watchQuery(watchQueryOptions);
if (context.renderPromises) {
context.renderPromises.registerSSRObservable(
obsQuery,
watchQueryOptions,
);
}
}
if (
context.renderPromises &&
options?.ssr !== false &&
!options?.skip &&
obsQuery.getCurrentResult().loading
) {
// TODO: This is a legacy API which could probably be cleaned up
context.renderPromises.addQueryPromise(
{
// The only options which seem to actually be used by the
// RenderPromises class are query and variables.
getOptions: () => createWatchQueryOptions(query, options),
fetchData: () => new Promise<void>((resolve) => {
const sub = obsQuery!.subscribe({
next(result) {
if (!result.loading) {
resolve()
sub.unsubscribe();
}
},
error() {
resolve();
sub.unsubscribe();
},
complete() {
resolve();
},
});
}),
},
// This callback never seemed to do anything
() => null,
);
}
return obsQuery;
});
let [result, setResult] = useState(() => {
const result = obsQuery.getCurrentResult();
if (!result.loading && options) {
if (result.error) {
options.onError?.(result.error);
} else if (result.data) {
options.onCompleted?.(result.data);
}
}
return result;
});
const ref = useRef({
client,
query,
options,
result,
previousData: void 0 as TData | undefined,
watchQueryOptions: createWatchQueryOptions(query, options),
});
// An effect to recreate the obsQuery whenever the client or query changes.
// This effect is also responsible for checking and updating the obsQuery
// options whenever they change.
useEffect(() => {
const watchQueryOptions = createWatchQueryOptions(query, options);
let nextResult: ApolloQueryResult<TData> | undefined;
if (ref.current.client !== client || !equal(ref.current.query, query)) {
const obsQuery = client.watchQuery(watchQueryOptions);
setObsQuery(obsQuery);
nextResult = obsQuery.getCurrentResult();
} else if (!equal(ref.current.watchQueryOptions, watchQueryOptions)) {
obsQuery.setOptions(watchQueryOptions).catch(() => {});
nextResult = obsQuery.getCurrentResult();
ref.current.watchQueryOptions = watchQueryOptions;
}
if (nextResult) {
const previousResult = ref.current.result;
if (previousResult.data) {
ref.current.previousData = previousResult.data;
}
setResult(ref.current.result = nextResult);
if (!nextResult.loading && options) {
if (!result.loading) {
if (result.error) {
options.onError?.(result.error);
} else if (result.data) {
options.onCompleted?.(result.data);
}
}
}
}
Object.assign(ref.current, { client, query });
}, [obsQuery, client, query, options]);
// An effect to subscribe to the current observable query
useEffect(() => {
if (context.renderPromises) {
return;
}
let subscription = obsQuery.subscribe(onNext, onError);
// We use `getCurrentResult()` instead of the callback argument because
// the values differ slightly. Specifically, loading results will have
// an empty object for data instead of `undefined` for some reason.
function onNext() {
const previousResult = ref.current.result;
const result = obsQuery.getCurrentResult();
// Make sure we're not attempting to re-render similar results
if (
previousResult &&
previousResult.loading === result.loading &&
previousResult.networkStatus === result.networkStatus &&
equal(previousResult.data, result.data)
) {
return;
}
if (previousResult.data) {
ref.current.previousData = previousResult.data;
}
setResult(ref.current.result = result);
if (!result.loading) {
ref.current.options?.onCompleted?.(result.data);
}
}
function onError(error: Error) {
const last = obsQuery["last"];
subscription.unsubscribe();
// Unfortunately, if `lastError` is set in the current
// `observableQuery` when the subscription is re-created,
// the subscription will immediately receive the error, which will
// cause it to terminate again. To avoid this, we first clear
// the last error/result from the `observableQuery` before re-starting
// the subscription, and restore it afterwards (so the subscription
// has a chance to stay open).
try {
obsQuery.resetLastResults();
subscription = obsQuery.subscribe(onNext, onError);
} finally {
obsQuery["last"] = last;
}
if (!error.hasOwnProperty('graphQLErrors')) {
// The error is not a GraphQL error
throw error;
}
const previousResult = ref.current.result;
if (
(previousResult && previousResult.loading) ||
!equal(error, previousResult.error)
) {
setResult(ref.current.result = {
data: previousResult.data,
error: error as ApolloError,
loading: false,
networkStatus: NetworkStatus.error,
});
ref.current.options?.onError?.(error as ApolloError);
}
}
return () => subscription.unsubscribe();
}, [obsQuery, context.renderPromises, client.disableNetworkFetches]);
let partial: boolean | undefined;
({ partial, ...result } = result);
{
// BAD BOY CODE BLOCK WHERE WE PUT SIDE-EFFECTS IN THE RENDER FUNCTION
//
// TODO: This code should be removed when the partialRefetch option is
// removed. I was unable to get this hook to behave reasonably in certain
// edge cases when this block was put in an effect.
if (
partial &&
options?.partialRefetch &&
!result.loading &&
(!result.data || Object.keys(result.data).length === 0) &&
obsQuery.options.fetchPolicy !== 'cache-only'
) {
result = {
...result,
loading: true,
networkStatus: NetworkStatus.refetch,
};
obsQuery.refetch();
}
// TODO: This is a hack to make sure useLazyQuery executions update the
// obsevable query options for ssr.
if (
context.renderPromises &&
options?.ssr !== false &&
!options?.skip &&
result.loading
) {
obsQuery.setOptions(createWatchQueryOptions(query, options)).catch(() => {});
}
// We assign options during rendering as a guard to make sure that
// callbacks like onCompleted and onError are not stale.
Object.assign(ref.current, { options });
}
if (
(context.renderPromises || client.disableNetworkFetches) &&
options?.ssr === false
) {
// If SSR has been explicitly disabled, and this function has been called
// on the server side, return the default loading state.
result = ref.current.result = {
loading: true,
data: void 0 as unknown as TData,
error: void 0,
networkStatus: NetworkStatus.loading,
};
} else if (options?.skip || options?.fetchPolicy === 'standby') {
// When skipping a query (ie. we're not querying for data but still want to
// render children), make sure the `data` is cleared out and `loading` is
// set to `false` (since we aren't loading anything).
//
// NOTE: We no longer think this is the correct behavior. Skipping should
// not automatically set `data` to `undefined`, but instead leave the
// previous data in place. In other words, skipping should not mandate that
// previously received data is all of a sudden removed. Unfortunately,
// changing this is breaking, so we'll have to wait until Apollo Client 4.0
// to address this.
result = {
loading: false,
data: void 0 as unknown as TData,
error: void 0,
networkStatus: NetworkStatus.ready,
};
}
if (result.errors && result.errors.length) {
// Until a set naming convention for networkError and graphQLErrors is
// decided upon, we map errors (graphQLErrors) to the error options.
// TODO: Is it possible for both result.error and result.errors to be
// defined here?
result = {
...result,
error: result.error || new ApolloError({ graphQLErrors: result.errors }),
};
}
const obsQueryFields = useMemo(() => ({
refetch: obsQuery.refetch.bind(obsQuery),
fetchMore: obsQuery.fetchMore.bind(obsQuery),
updateQuery: obsQuery.updateQuery.bind(obsQuery),
startPolling: obsQuery.startPolling.bind(obsQuery),
stopPolling: obsQuery.stopPolling.bind(obsQuery),
subscribeToMore: obsQuery.subscribeToMore.bind(obsQuery),
}), [obsQuery]);
return {
...obsQueryFields,
variables: createWatchQueryOptions(query, options).variables,
client,
called: true,
previousData: ref.current.previousData,
...result,
};
}
/**
* A function to massage options before passing them the ObservableQuery.
*/
function createWatchQueryOptions<TData, TVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: QueryHookOptions<TData, TVariables> = {},
): WatchQueryOptions<TVariables, TData> {
// TODO: For some reason, we pass context, which is the React Apollo Context,
// into observable queries, and test for that.
// removing hook specific options
const {
skip,
ssr,
onCompleted,
onError,
displayName,
...watchQueryOptions
} = options;
if (skip) {
watchQueryOptions.fetchPolicy = 'standby';
} else if (
watchQueryOptions.context?.renderPromises &&
(
watchQueryOptions.fetchPolicy === 'network-only' ||
watchQueryOptions.fetchPolicy === 'cache-and-network'
)
) {
// this behavior was added to react-apollo without explanation in this PR
// https://github.com/apollographql/react-apollo/pull/1579
watchQueryOptions.fetchPolicy = 'cache-first';
} else if (!watchQueryOptions.fetchPolicy) {
// cache-first is the default policy, but we explicitly assign it here so
// the cache policies computed based on options can be cleared
watchQueryOptions.fetchPolicy = 'cache-first';
}
if (!watchQueryOptions.variables) {
watchQueryOptions.variables = {} as TVariables;
}
return { query, ...watchQueryOptions };
} | the_stack |
import { MachineConfig, AnyEventObject, forwardTo, Machine } from "xstate"
import { IDataLayerContext } from "../data-layer/types"
import { IQueryRunningContext } from "../query-running/types"
import { IWaitingContext } from "../waiting/types"
import { buildActions } from "./actions"
import { developServices } from "./services"
import { IBuildContext } from "../../services"
const RECOMPILE_PANIC_LIMIT = 6
/**
* This is the top-level state machine for the `gatsby develop` command
*/
const developConfig: MachineConfig<IBuildContext, any, AnyEventObject> = {
id: `build`,
initial: `initializing`,
// These are mutation events, sent to this machine by the mutation listener
// in `services/listen-for-mutations.ts`
on: {
// These are deferred node mutations, mainly `createNode`
ADD_NODE_MUTATION: {
actions: `addNodeMutation`,
},
// Sent when webpack or chokidar sees a changed file
SOURCE_FILE_CHANGED: {
actions: `markSourceFilesDirty`,
},
// These are calls to the refresh endpoint. Also used by Gatsby Preview.
// Saves the webhook body from the event into context, then reloads data
WEBHOOK_RECEIVED: {
target: `reloadingData`,
actions: `assignWebhookBody`,
},
QUERY_RUN_REQUESTED: {
actions: `trackRequestedQueryRun`,
},
},
states: {
// Here we handle the initial bootstrap
initializing: {
on: {
// Ignore mutation events because we'll be running everything anyway
ADD_NODE_MUTATION: undefined,
SOURCE_FILE_CHANGED: undefined,
WEBHOOK_RECEIVED: undefined,
},
invoke: {
id: `initialize`,
src: `initialize`,
onDone: {
target: `initializingData`,
actions: [`assignStoreAndWorkerPool`, `spawnMutationListener`],
},
onError: {
actions: `panic`,
},
},
},
// Sourcing nodes, customising and inferring schema, then running createPages
initializingData: {
on: {
// We need to run mutations immediately when in this state
ADD_NODE_MUTATION: {
actions: `callApi`,
},
},
invoke: {
id: `initialize-data`,
src: `initializeData`,
data: ({
parentSpan,
store,
webhookBody,
}: IBuildContext): IDataLayerContext => {
return {
parentSpan,
store,
webhookBody,
shouldRunCreatePagesStatefully: true,
deferNodeMutation: true,
}
},
onDone: {
actions: [
`assignServiceResult`,
`clearWebhookBody`,
`finishParentSpan`,
],
target: `runningPostBootstrap`,
},
onError: {
actions: `logError`,
target: `waiting`,
},
},
},
runningPostBootstrap: {
invoke: {
id: `post-bootstrap`,
src: `postBootstrap`,
onDone: `runningQueries`,
},
},
// Running page and static queries and generating the SSRed HTML and page data
runningQueries: {
on: {
SOURCE_FILE_CHANGED: {
actions: [forwardTo(`run-queries`), `markSourceFilesDirty`],
},
ADD_NODE_MUTATION: {
actions: [`markNodesDirty`, `callApi`],
},
QUERY_RUN_REQUESTED: {
actions: forwardTo(`run-queries`),
},
},
invoke: {
id: `run-queries`,
src: `runQueries`,
// This is all the data that we're sending to the child machine
data: ({
program,
store,
parentSpan,
gatsbyNodeGraphQLFunction,
graphqlRunner,
websocketManager,
pendingQueryRuns,
}: IBuildContext): IQueryRunningContext => {
return {
program,
store,
parentSpan,
gatsbyNodeGraphQLFunction,
graphqlRunner,
websocketManager,
pendingQueryRuns,
}
},
onDone: [
{
// If we're at the recompile limit and nodes were mutated again then panic
target: `waiting`,
actions: `panicBecauseOfInfiniteLoop`,
cond: ({
nodesMutatedDuringQueryRun = false,
nodesMutatedDuringQueryRunRecompileCount = 0,
}: IBuildContext): boolean =>
nodesMutatedDuringQueryRun &&
nodesMutatedDuringQueryRunRecompileCount >= RECOMPILE_PANIC_LIMIT,
},
{
// Nodes were mutated while querying, so we need to re-run everything
target: `recreatingPages`,
cond: ({ nodesMutatedDuringQueryRun }: IBuildContext): boolean =>
!!nodesMutatedDuringQueryRun,
actions: [
`markNodesClean`,
`incrementRecompileCount`,
`clearPendingQueryRuns`,
],
},
{
// If we have no compiler (i.e. it's first run), then spin up the
// webpack and socket.io servers
target: `startingDevServers`,
actions: [`setQueryRunningFinished`, `clearPendingQueryRuns`],
cond: ({ compiler }: IBuildContext): boolean => !compiler,
},
{
// If source files have changed, then recompile the JS bundle
target: `recompiling`,
cond: ({ sourceFilesDirty }: IBuildContext): boolean =>
!!sourceFilesDirty,
actions: [`clearPendingQueryRuns`],
},
{
// ...otherwise just wait.
target: `waiting`,
actions: [`clearPendingQueryRuns`],
},
],
onError: {
actions: [`logError`, `clearPendingQueryRuns`],
target: `waiting`,
},
},
},
// Recompile the JS bundle
recompiling: {
// Important: mark source files as clean when recompiling starts
// Doing this `onDone` will wipe all file change events that occur **during** recompilation
// See https://github.com/gatsbyjs/gatsby/issues/27609
entry: [`setRecompiledFiles`, `markSourceFilesClean`],
invoke: {
src: `recompile`,
onDone: {
target: `waiting`,
},
onError: {
actions: `logError`,
target: `waiting`,
},
},
},
// Spin up webpack and socket.io
startingDevServers: {
invoke: {
src: `startWebpackServer`,
onDone: {
target: `waiting`,
actions: [
`assignServers`,
`spawnWebpackListener`,
`markSourceFilesClean`,
],
},
onError: {
actions: `panic`,
target: `waiting`,
},
},
},
// Idle, waiting for events that make us rebuild
waiting: {
always: [
{
target: `runningQueries`,
cond: ({ pendingQueryRuns }: IBuildContext): boolean =>
!!pendingQueryRuns && pendingQueryRuns.size > 0,
},
],
entry: [`saveDbState`, `resetRecompileCount`],
on: {
// Forward these events to the child machine, so it can handle batching
ADD_NODE_MUTATION: {
actions: forwardTo(`waiting`),
},
SOURCE_FILE_CHANGED: {
actions: [forwardTo(`waiting`), `markSourceFilesDirty`],
},
// This event is sent from the child
EXTRACT_QUERIES_NOW: {
target: `runningQueries`,
},
},
invoke: {
id: `waiting`,
src: `waitForMutations`,
// Send existing queued mutations to the child machine, which will execute them
data: ({
store,
nodeMutationBatch = [],
sourceFilesDirty,
}: IBuildContext): IWaitingContext => {
return {
store,
nodeMutationBatch,
sourceFilesDirty,
runningBatch: [],
}
},
// "done" means we need to rebuild
onDone: {
actions: `assignServiceResult`,
target: `recreatingPages`,
},
onError: {
actions: `panic`,
},
},
},
// Almost the same as initializing data, but skips various first-run stuff
reloadingData: {
on: {
// We need to run mutations immediately when in this state
ADD_NODE_MUTATION: {
actions: `callApi`,
},
},
invoke: {
src: `reloadData`,
data: ({
parentSpan,
store,
webhookBody,
webhookSourcePluginName,
}: IBuildContext): IDataLayerContext => {
return {
parentSpan,
store,
webhookBody,
webhookSourcePluginName,
refresh: true,
deferNodeMutation: true,
shouldRunCreatePagesStatefully: false,
}
},
onDone: {
actions: [
`assignServiceResult`,
`clearWebhookBody`,
`finishParentSpan`,
],
target: `runningQueries`,
},
onError: {
actions: `logError`,
target: `waiting`,
},
},
},
// Rebuild pages if a node has been mutated outside of sourceNodes
recreatingPages: {
on: {
// We need to run mutations immediately when in this state
ADD_NODE_MUTATION: {
actions: `callApi`,
},
},
invoke: {
id: `recreate-pages`,
src: `recreatePages`,
data: ({ parentSpan, store }: IBuildContext): IDataLayerContext => {
return {
parentSpan,
store,
deferNodeMutation: true,
shouldRunCreatePagesStatefully: false,
}
},
onDone: {
actions: `assignServiceResult`,
target: `runningQueries`,
},
onError: {
actions: `logError`,
target: `waiting`,
},
},
},
},
}
export const developMachine = Machine(developConfig, {
services: developServices,
actions: buildActions,
}) | the_stack |
import { Injectable } from '@angular/core';
import { Params } from '@angular/router';
import moment from 'moment';
import { CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import {
CoreCourse,
CoreCourseCompletionActivityStatus,
CoreCourseModuleWSCompletionData,
CoreCourseModuleContentFile,
CoreCourseProvider,
CoreCourseWSSection,
CoreCourseModuleCompletionTracking,
CoreCourseModuleCompletionStatus,
CoreCourseGetContentsWSModule,
} from './course';
import { CoreConstants } from '@/core/constants';
import { CoreLogger } from '@singletons/logger';
import { makeSingleton, Translate } from '@singletons';
import { CoreFilepool } from '@services/filepool';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreUtils, CoreUtilsOpenFileOptions } from '@services/utils/utils';
import {
CoreCourseAnyCourseData,
CoreCourseBasicData,
CoreCourses,
CoreCourseSearchedData,
CoreEnrolledCourseData,
} from '@features/courses/services/courses';
import { CoreArray } from '@singletons/array';
import { CoreIonLoadingElement } from '@classes/ion-loading';
import { CoreCourseOffline } from './course-offline';
import {
CoreCourseOptionsDelegate,
CoreCourseOptionsHandlerToDisplay,
CoreCourseOptionsMenuHandlerToDisplay,
} from './course-options-delegate';
import { CoreCourseModuleDelegate, CoreCourseModuleHandlerData } from './module-delegate';
import { CoreError } from '@classes/errors/error';
import {
CoreCourseModulePrefetchDelegate,
CoreCourseModulePrefetchHandler,
CoreCourseModulesStatus,
} from './module-prefetch-delegate';
import { CoreFileSizeSum } from '@services/plugin-file-delegate';
import { CoreFileHelper } from '@services/file-helper';
import { CoreApp } from '@services/app';
import { CoreSite } from '@classes/site';
import { CoreFile } from '@services/file';
import { CoreUrlUtils } from '@services/utils/url';
import { CoreTextUtils } from '@services/utils/text';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreFilterHelper } from '@features/filter/services/filter-helper';
import { CoreNetworkError } from '@classes/errors/network-error';
import { CoreSiteHome } from '@features/sitehome/services/sitehome';
import { CoreNavigationOptions, CoreNavigator } from '@services/navigator';
import { CoreSiteHomeHomeHandlerService } from '@features/sitehome/services/handlers/sitehome-home';
import { CoreStatusWithWarningsWSResponse } from '@services/ws';
/**
* Prefetch info of a module.
*/
export type CoreCourseModulePrefetchInfo = CoreCourseModulePackageLastDownloaded & {
size: number; // Downloaded size.
sizeReadable: string; // Downloadable size in a readable format.
status: string; // Module status.
statusIcon?: string; // Icon's name of the module status.
};
/**
* Prefetch info of a module.
*/
export type CoreCourseModulePackageLastDownloaded = {
downloadTime: number; // Time when the module was last downloaded.
downloadTimeReadable: string; // Download time in a readable format.
};
/**
* Progress of downloading a list of courses.
*/
export type CoreCourseCoursesProgress = {
/**
* Number of courses downloaded so far.
*/
count: number;
/**
* Toal of courses to download.
*/
total: number;
/**
* Whether the download has been successful so far.
*/
success: boolean;
/**
* Last downloaded course.
*/
courseId?: number;
};
export type CorePrefetchStatusInfo = {
status: string; // Status of the prefetch.
statusTranslatable: string; // Status translatable string.
icon: string; // Icon based on the status.
loading: boolean; // If it's a loading status.
badge?: string; // Progress badge string if any.
badgeA11yText?: string; // Description of the badge if any.
count?: number; // Amount of already downloaded courses.
total?: number; // Total of courses.
downloadSucceeded?: boolean; // Whether download has succeeded (in case it's downloaded).
};
/**
* Helper to gather some common course functions.
*/
@Injectable({ providedIn: 'root' })
export class CoreCourseHelperProvider {
protected courseDwnPromises: { [s: string]: { [id: number]: Promise<void> } } = {};
protected logger: CoreLogger;
constructor() {
this.logger = CoreLogger.getInstance('CoreCourseHelperProvider');
}
/**
* This function treats every module on the sections provided to load the handler data, treat completion
* and navigate to a module page if required. It also returns if sections has content.
*
* @param sections List of sections to treat modules.
* @param courseId Course ID of the modules.
* @param completionStatus List of completion status.
* @param courseName Not used since 4.0
* @param forCoursePage Whether the data will be used to render the course page.
* @return Whether the sections have content.
*/
async addHandlerDataForModules(
sections: CoreCourseWSSection[],
courseId: number,
completionStatus?: Record<string, CoreCourseCompletionActivityStatus>,
courseName?: string,
forCoursePage = false,
): Promise<{ hasContent: boolean; sections: CoreCourseSection[] }> {
let hasContent = false;
const formattedSections = await Promise.all(
sections.map<Promise<CoreCourseSection>>(async (courseSection) => {
const section = {
...courseSection,
hasContent: this.sectionHasContent(courseSection),
};
if (!section.hasContent) {
return section;
}
hasContent = true;
await Promise.all(section.modules.map(async (module) => {
module.handlerData = await CoreCourseModuleDelegate.getModuleDataFor(
module.modname,
module,
courseId,
section.id,
forCoursePage,
);
if (!module.completiondata && completionStatus && completionStatus[module.id] !== undefined) {
// Should not happen on > 3.6. Check if activity has completions and if it's marked.
const activityStatus = completionStatus[module.id];
module.completiondata = {
state: activityStatus.state,
timecompleted: activityStatus.timecompleted,
overrideby: activityStatus.overrideby || 0,
valueused: activityStatus.valueused,
tracking: activityStatus.tracking,
courseId,
cmid: module.id,
};
}
// Check if the module is stealth.
module.isStealth = CoreCourseHelper.isModuleStealth(module, section);
}));
return section;
}),
);
return { hasContent, sections: formattedSections };
}
/**
* Module is stealth.
*
* @param module Module to check.
* @param section Section to check.
* @return Wether the module is stealth.
*/
isModuleStealth(module: CoreCourseModuleData, section?: CoreCourseWSSection): boolean {
// visibleoncoursepage can be 1 for teachers when the section is hidden.
return !!module.visible && (!module.visibleoncoursepage || (!!section && !section.visible));
}
/**
* Module is visible by the user.
*
* @param module Module to check.
* @param section Section to check. Omitted if not defined.
* @return Wether the section is visible by the user.
*/
canUserViewModule(module: CoreCourseModuleData, section?: CoreCourseWSSection): boolean {
return module.uservisible !== false && (!section || CoreCourseHelper.canUserViewSection(section));
}
/**
* Section is stealth.
* This should not be true on Moodle 4.0 onwards.
*
* @param section Section to check.
* @return Wether section is stealth (accessible but not visible to students).
*/
isSectionStealth(section: CoreCourseWSSection): boolean {
return section.hiddenbynumsections === 1 || section.id === CoreCourseProvider.STEALTH_MODULES_SECTION_ID;
}
/**
* Section is visible by the user.
*
* @param section Section to check.
* @return Wether the section is visible by the user.
*/
canUserViewSection(section: CoreCourseWSSection): boolean {
return section.uservisible !== false;
}
/**
* Calculate completion data of a module.
*
* @deprecated since 4.0.
* @param module Module.
*/
calculateModuleCompletionData(module: CoreCourseModuleData): void {
if (!module.completiondata || !module.completion) {
return;
}
module.completiondata.courseId = module.course;
module.completiondata.tracking = module.completion;
module.completiondata.cmid = module.id;
}
/**
* Calculate the status of a section.
*
* @param section Section to calculate its status. It can't be "All sections".
* @param courseId Course ID the section belongs to.
* @param refresh True if it shouldn't use module status cache (slower).
* @param checkUpdates Whether to use the WS to check updates. Defaults to true.
* @return Promise resolved when the status is calculated.
*/
async calculateSectionStatus(
section: CoreCourseSection,
courseId: number,
refresh?: boolean,
checkUpdates: boolean = true,
): Promise<{statusData: CoreCourseModulesStatus; section: CoreCourseSectionWithStatus}> {
if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) {
throw new CoreError('Invalid section');
}
const sectionWithStatus = <CoreCourseSectionWithStatus> section;
// Get the status of this section.
const result = await CoreCourseModulePrefetchDelegate.getModulesStatus(
section.modules,
courseId,
section.id,
refresh,
true,
checkUpdates,
);
// Check if it's being downloaded.
const downloadId = this.getSectionDownloadId(section);
if (CoreCourseModulePrefetchDelegate.isBeingDownloaded(downloadId)) {
result.status = CoreConstants.DOWNLOADING;
}
sectionWithStatus.downloadStatus = result.status;
sectionWithStatus.canCheckUpdates = true;
// Set this section data.
if (result.status !== CoreConstants.DOWNLOADING) {
sectionWithStatus.isDownloading = false;
sectionWithStatus.total = 0;
} else {
// Section is being downloaded.
sectionWithStatus.isDownloading = true;
CoreCourseModulePrefetchDelegate.setOnProgress(downloadId, (data) => {
sectionWithStatus.count = data.count;
sectionWithStatus.total = data.total;
});
}
return { statusData: result, section: sectionWithStatus };
}
/**
* Calculate the status of a list of sections, setting attributes to determine the icons/data to be shown.
*
* @param sections Sections to calculate their status.
* @param courseId Course ID the sections belong to.
* @param refresh True if it shouldn't use module status cache (slower).
* @param checkUpdates Whether to use the WS to check updates. Defaults to true.
* @return Promise resolved when the states are calculated.
*/
async calculateSectionsStatus(
sections: CoreCourseSection[],
courseId: number,
refresh?: boolean,
checkUpdates: boolean = true,
): Promise<CoreCourseSectionWithStatus[]> {
let allSectionsSection: CoreCourseSectionWithStatus | undefined;
let allSectionsStatus = CoreConstants.NOT_DOWNLOADABLE;
const promises = sections.map(async (section: CoreCourseSectionWithStatus) => {
section.isCalculating = true;
if (section.id === CoreCourseProvider.ALL_SECTIONS_ID) {
// "All sections" section status is calculated using the status of the rest of sections.
allSectionsSection = section;
return;
}
try {
const result = await this.calculateSectionStatus(section, courseId, refresh, checkUpdates);
// Calculate "All sections" status.
allSectionsStatus = CoreFilepool.determinePackagesStatus(allSectionsStatus, result.statusData.status);
} finally {
section.isCalculating = false;
}
});
try {
await Promise.all(promises);
if (allSectionsSection) {
// Set "All sections" data.
allSectionsSection.downloadStatus = allSectionsStatus;
allSectionsSection.canCheckUpdates = true;
allSectionsSection.isDownloading = allSectionsStatus === CoreConstants.DOWNLOADING;
}
return sections;
} finally {
if (allSectionsSection) {
allSectionsSection.isCalculating = false;
}
}
}
/**
* Show a confirm and prefetch a course. It will retrieve the sections and the course options if not provided.
* This function will set the icon to "spinner" when starting and it will also set it back to the initial icon if the
* user cancels. All the other updates of the icon should be made when CoreEvents.COURSE_STATUS_CHANGED is received.
*
* @param data An object where to store the course icon and title: "prefetchCourseIcon", "title" and "downloadSucceeded".
* @param course Course to prefetch.
* @param options Other options.
* @return Promise resolved when the download finishes, rejected if an error occurs or the user cancels.
*/
async confirmAndPrefetchCourse(
data: CorePrefetchStatusInfo,
course: CoreCourseAnyCourseData,
options: CoreCoursePrefetchCourseOptions = {},
): Promise<void> {
const initialIcon = data.icon;
const initialStatus = data.status;
const initialStatusTranslatable = data.statusTranslatable;
const siteId = CoreSites.getCurrentSiteId();
data.downloadSucceeded = false;
data.icon = CoreConstants.ICON_DOWNLOADING;
data.status = CoreConstants.DOWNLOADING;
data.loading = true;
data.statusTranslatable = 'core.downloading';
try {
// Get the sections first if needed.
if (!options.sections) {
options.sections = await CoreCourse.getSections(course.id, false, true);
}
// Confirm the download.
await this.confirmDownloadSizeSection(course.id, undefined, options.sections, true);
// User confirmed, get the course handlers if needed.
if (!options.courseHandlers) {
options.courseHandlers = await CoreCourseOptionsDelegate.getHandlersToDisplay(course, false, options.isGuest);
}
if (!options.menuHandlers) {
options.menuHandlers = await CoreCourseOptionsDelegate.getMenuHandlersToDisplay(course, false, options.isGuest);
}
// Now we have all the data, download the course.
await this.prefetchCourse(course, options.sections, options.courseHandlers, options.menuHandlers, siteId);
// Download successful.
data.downloadSucceeded = true;
data.loading = false;
} catch (error) {
// User cancelled or there was an error.
data.icon = initialIcon;
data.status = initialStatus;
data.statusTranslatable = initialStatusTranslatable;
data.loading = false;
throw error;
}
}
/**
* Confirm and prefetches a list of courses.
*
* @param courses List of courses to download.
* @param options Other options.
* @return Resolved when downloaded, rejected if error or canceled.
*/
async confirmAndPrefetchCourses(
courses: CoreCourseAnyCourseData[],
options: CoreCourseConfirmPrefetchCoursesOptions = {},
): Promise<void> {
const siteId = CoreSites.getCurrentSiteId();
// Confirm the download without checking size because it could take a while.
await CoreDomUtils.showConfirm(Translate.instant('core.areyousure'), Translate.instant('core.courses.downloadcourses'));
const total = courses.length;
let count = 0;
const promises = courses.map(async (course) => {
const subPromises: Promise<void>[] = [];
let sections: CoreCourseWSSection[];
let handlers: CoreCourseOptionsHandlerToDisplay[] = [];
let menuHandlers: CoreCourseOptionsMenuHandlerToDisplay[] = [];
let success = true;
let isGuest = false;
if (options.canHaveGuestCourses) {
// Check if the user can only access as guest.
isGuest = await this.courseUsesGuestAccess(course.id, siteId);
}
// Get the sections and the handlers.
subPromises.push(CoreCourse.getSections(course.id, false, true).then((courseSections) => {
sections = courseSections;
return;
}));
subPromises.push(CoreCourseOptionsDelegate.getHandlersToDisplay(course, false, isGuest).then((cHandlers) => {
handlers = cHandlers;
return;
}));
subPromises.push(CoreCourseOptionsDelegate.getMenuHandlersToDisplay(course, false, isGuest).then((mHandlers) => {
menuHandlers = mHandlers;
return;
}));
return Promise.all(subPromises).then(() => this.prefetchCourse(course, sections, handlers, menuHandlers, siteId))
.catch((error) => {
success = false;
throw error;
}).finally(() => {
// Course downloaded or failed, notify the progress.
count++;
if (options.onProgress) {
options.onProgress({ count: count, total: total, courseId: course.id, success: success });
}
});
});
if (options.onProgress) {
// Notify the start of the download.
options.onProgress({ count: 0, total: total, success: true });
}
return CoreUtils.allPromises(promises);
}
/**
* Show confirmation dialog and then remove a module files.
*
* @param module Module to remove the files.
* @param courseId Course ID the module belongs to.
* @return Promise resolved when done.
* @deprecated since 4.0
*/
async confirmAndRemoveFiles(module: CoreCourseModuleData, courseId: number): Promise<void> {
let modal: CoreIonLoadingElement | undefined;
try {
await CoreDomUtils.showDeleteConfirm('addon.storagemanager.confirmdeletedatafrom', { name: module.name });
modal = await CoreDomUtils.showModalLoading();
await this.removeModuleStoredData(module, courseId);
} catch (error) {
if (error) {
CoreDomUtils.showErrorModal(error);
}
} finally {
modal?.dismiss();
}
}
/**
* Calculate the size to download a section and show a confirm modal if needed.
*
* @param courseId Course ID the section belongs to.
* @param section Section. If not provided, all sections.
* @param sections List of sections. Used when downloading all the sections.
* @param alwaysConfirm True to show a confirm even if the size isn't high, false otherwise.
* @return Promise resolved if the user confirms or there's no need to confirm.
*/
async confirmDownloadSizeSection(
courseId: number,
section?: CoreCourseWSSection,
sections?: CoreCourseWSSection[],
alwaysConfirm?: boolean,
): Promise<void> {
let hasEmbeddedFiles = false;
let sizeSum: CoreFileSizeSum = {
size: 0,
total: true,
};
// Calculate the size of the download.
if (section && section.id != CoreCourseProvider.ALL_SECTIONS_ID) {
sizeSum = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId);
// Check if the section has embedded files in the description.
hasEmbeddedFiles = CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0;
} else if (sections) {
await Promise.all(sections.map(async (section) => {
if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) {
return;
}
const sectionSize = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId);
sizeSum.total = sizeSum.total && sectionSize.total;
sizeSum.size += sectionSize.size;
// Check if the section has embedded files in the description.
if (!hasEmbeddedFiles && CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0) {
hasEmbeddedFiles = true;
}
}));
} else {
throw new CoreError('Either section or list of sections needs to be supplied.');
}
if (hasEmbeddedFiles) {
sizeSum.total = false;
}
// Show confirm modal if needed.
await CoreDomUtils.confirmDownloadSize(sizeSum, undefined, undefined, undefined, undefined, alwaysConfirm);
}
/**
* Check whether a course is accessed using guest access.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether course is accessed using guest access.
*/
async courseUsesGuestAccess(courseId: number, siteId?: string): Promise<boolean> {
try {
try {
// Check if user is enrolled. If enrolled, no guest access.
await CoreCourses.getUserCourse(courseId, false, siteId);
return false;
} catch {
// Ignore errors.
}
try {
// The user is not enrolled in the course. Use getCourses to see if it's an admin/manager and can see the course.
await CoreCourses.getCourse(courseId, siteId);
return false;
} catch {
// Ignore errors.
}
// Check if guest access is enabled.
const enrolmentMethods = await CoreCourses.getCourseEnrolmentMethods(courseId, siteId);
const method = enrolmentMethods.find((method) => method.type === 'guest');
if (!method) {
return false;
}
const info = await CoreCourses.getCourseGuestEnrolmentInfo(method.id);
if (!info.status) {
// Not active, reject.
return false;
}
// Don't allow guest access if it requires a password.
return !info.passwordrequired;
} catch {
return false;
}
}
/**
* Create and return a section for "All sections".
*
* @return Created section.
*/
createAllSectionsSection(): CoreCourseSection {
return {
id: CoreCourseProvider.ALL_SECTIONS_ID,
name: Translate.instant('core.course.allsections'),
hasContent: true,
summary: '',
summaryformat: 1,
modules: [],
};
}
/**
* Determine the status of a list of courses.
*
* @param courses Courses
* @return Promise resolved with the status.
*/
async determineCoursesStatus(courses: CoreCourseBasicData[]): Promise<string> {
// Get the status of each course.
const promises: Promise<string>[] = [];
const siteId = CoreSites.getCurrentSiteId();
courses.forEach((course) => {
promises.push(CoreCourse.getCourseStatus(course.id, siteId));
});
const statuses = await Promise.all(promises);
// Now determine the status of the whole list.
let status = statuses[0];
const filepool = CoreFilepool.instance;
for (let i = 1; i < statuses.length; i++) {
status = filepool.determinePackagesStatus(status, statuses[i]);
}
return status;
}
/**
* Convenience function to open a module main file, downloading the package if needed.
* This is meant for modules like mod_resource.
*
* @param module The module to download.
* @param courseId The course ID of the module.
* @param component The component to link the files to.
* @param componentId An ID to use in conjunction with the component.
* @param files List of files of the module. If not provided, use module.contents.
* @param siteId The site ID. If not defined, current site.
* @param options Options to open the file.
* @return Resolved on success.
*/
async downloadModuleAndOpenFile(
module: CoreCourseModuleData,
courseId: number,
component?: string,
componentId?: string | number,
files?: CoreCourseModuleContentFile[],
siteId?: string,
options: CoreUtilsOpenFileOptions = {},
): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
if (!files || !files.length) {
// Try to use module contents.
files = await CoreCourse.getModuleContents(module);
}
if (!files.length) {
throw new CoreError(Translate.instant('core.filenotfound'));
}
const mainFile = files[0];
if (!CoreFileHelper.isOpenableInApp(mainFile)) {
await CoreFileHelper.showConfirmOpenUnsupportedFile();
}
const site = await CoreSites.getSite(siteId);
// Check if the file should be opened in browser.
if (CoreFileHelper.shouldOpenInBrowser(mainFile)) {
return this.openModuleFileInBrowser(mainFile.fileurl, site, module, courseId, component, componentId, files, options);
}
// File shouldn't be opened in browser. Download the module if it needs to be downloaded.
const result = await this.downloadModuleWithMainFileIfNeeded(
module,
courseId,
component || '',
componentId,
files,
siteId,
options,
);
if (CoreUrlUtils.isLocalFileUrl(result.path)) {
return CoreUtils.openFile(result.path, options);
}
/* In iOS, if we use the same URL in embedded browser and background download then the download only
downloads a few bytes (cached ones). Add a hash to the URL so both URLs are different. */
result.path = result.path + '#moodlemobile-embedded';
try {
await CoreUtils.openOnlineFile(result.path);
} catch (error) {
// Error opening the file, some apps don't allow opening online files.
if (!CoreFile.isAvailable()) {
throw error;
} else if (result.status === CoreConstants.DOWNLOADING) {
throw new CoreError(Translate.instant('core.erroropenfiledownloading'));
}
let path: string | undefined;
if (result.status === CoreConstants.NOT_DOWNLOADED) {
// Not downloaded, download it now and return the local file.
await this.downloadModule(module, courseId, component, componentId, files, siteId);
path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl);
} else {
// File is outdated or stale and can't be opened in online, return the local URL.
path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl);
}
await CoreUtils.openFile(path, options);
}
}
/**
* Convenience function to open a module main file in case it needs to be opened in browser.
*
* @param fileUrl URL of the main file.
* @param site Site instance.
* @param module The module to download.
* @param courseId The course ID of the module.
* @param component The component to link the files to.
* @param componentId An ID to use in conjunction with the component.
* @param files List of files of the module. If not provided, use module.contents.
* @param options Options to open the file. Only used if not opened in browser.
* @return Resolved on success.
*/
protected async openModuleFileInBrowser(
fileUrl: string,
site: CoreSite,
module: CoreCourseModuleData,
courseId: number,
component?: string,
componentId?: string | number,
files?: CoreCourseModuleContentFile[],
options: CoreUtilsOpenFileOptions = {},
): Promise<void> {
if (!CoreApp.isOnline()) {
// Not online, get the offline file. It will fail if not found.
let path: string | undefined;
try {
path = await CoreFilepool.getInternalUrlByUrl(site.getId(), fileUrl);
} catch {
throw new CoreNetworkError();
}
return CoreUtils.openFile(path, options);
}
// Open in browser.
let fixedUrl = await site.checkAndFixPluginfileURL(fileUrl);
fixedUrl = fixedUrl.replace('&offline=1', '');
// Remove forcedownload when followed by another param.
fixedUrl = fixedUrl.replace(/forcedownload=\d+&/, '');
// Remove forcedownload when not followed by any param.
fixedUrl = fixedUrl.replace(/[?|&]forcedownload=\d+/, '');
CoreUtils.openInBrowser(fixedUrl);
if (CoreFile.isAvailable()) {
// Download the file if needed (file outdated or not downloaded).
// Download will be in background, don't return the promise.
this.downloadModule(module, courseId, component, componentId, files, site.getId());
}
}
/**
* Convenience function to download a module that has a main file and return the local file's path and other info.
* This is meant for modules like mod_resource.
*
* @param module The module to download.
* @param courseId The course ID of the module.
* @param component The component to link the files to.
* @param componentId An ID to use in conjunction with the component.
* @param files List of files of the module. If not provided, use module.contents.
* @param siteId The site ID. If not defined, current site.
* @param options Options to open the file.
* @return Promise resolved when done.
*/
async downloadModuleWithMainFileIfNeeded(
module: CoreCourseModuleData,
courseId: number,
component: string,
componentId?: string | number,
files?: CoreCourseModuleContentFile[],
siteId?: string,
options: CoreUtilsOpenFileOptions = {},
): Promise<{ fixedUrl: string; path: string; status?: string }> {
siteId = siteId || CoreSites.getCurrentSiteId();
if (!files || !files.length) {
// Module not valid, stop.
throw new CoreError('File list not supplied.');
}
const mainFile = files[0];
const site = await CoreSites.getSite(siteId);
const fixedUrl = await site.checkAndFixPluginfileURL(mainFile.fileurl);
if (!CoreFile.isAvailable()) {
return {
path: fixedUrl, // Use the online URL.
fixedUrl,
};
}
// The file system is available.
const status = await CoreFilepool.getPackageStatus(siteId, component, componentId);
let path = '';
if (status === CoreConstants.DOWNLOADING) {
// Use the online URL.
path = fixedUrl;
} else if (status === CoreConstants.DOWNLOADED) {
try {
// Get the local file URL.
path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl);
} catch (error){
// File not found, mark the module as not downloaded.
await CoreFilepool.storePackageStatus(siteId, CoreConstants.NOT_DOWNLOADED, component, componentId);
}
}
if (!path) {
try {
path = await this.downloadModuleWithMainFile(
module,
courseId,
fixedUrl,
files,
status,
component,
componentId,
siteId,
options,
);
} catch (error) {
if (status !== CoreConstants.OUTDATED) {
throw error;
}
// Use the local file even if it's outdated.
try {
path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl);
} catch {
throw error;
}
}
}
return {
path,
fixedUrl,
status,
};
}
/**
* Convenience function to download a module that has a main file and return the local file's path and other info.
* This is meant for modules like mod_resource.
*
* @param module The module to download.
* @param courseId The course ID of the module.
* @param fixedUrl Main file's fixed URL.
* @param files List of files of the module.
* @param status The package status.
* @param component The component to link the files to.
* @param componentId An ID to use in conjunction with the component.
* @param siteId The site ID. If not defined, current site.
* @param options Options to open the file.
* @return Promise resolved when done.
*/
protected async downloadModuleWithMainFile(
module: CoreCourseModuleData,
courseId: number,
fixedUrl: string,
files: CoreCourseModuleContentFile[],
status: string,
component?: string,
componentId?: string | number,
siteId?: string,
options: CoreUtilsOpenFileOptions = {},
): Promise<string> {
siteId = siteId || CoreSites.getCurrentSiteId();
const isOnline = CoreApp.isOnline();
const mainFile = files[0];
const timemodified = mainFile.timemodified || 0;
if (!isOnline && status === CoreConstants.NOT_DOWNLOADED) {
// Not downloaded and we're offline, reject.
throw new CoreNetworkError();
}
const shouldDownloadFirst = await CoreFilepool.shouldDownloadFileBeforeOpen(fixedUrl, mainFile.filesize, options);
if (shouldDownloadFirst) {
// Download and then return the local URL.
await this.downloadModule(module, courseId, component, componentId, files, siteId);
return CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl);
}
// Start the download if in wifi, but return the URL right away so the file is opened.
if (CoreApp.isWifi()) {
this.downloadModule(module, courseId, component, componentId, files, siteId);
}
if (!CoreFileHelper.isStateDownloaded(status) || isOnline) {
// Not downloaded or online, return the online URL.
return fixedUrl;
} else {
// Outdated but offline, so we return the local URL. Use getUrlByUrl so it's added to the queue.
return CoreFilepool.getUrlByUrl(
siteId,
mainFile.fileurl,
component,
componentId,
timemodified,
false,
false,
mainFile,
);
}
}
/**
* Convenience function to download a module.
*
* @param module The module to download.
* @param courseId The course ID of the module.
* @param component The component to link the files to.
* @param componentId An ID to use in conjunction with the component.
* @param files List of files of the module. If not provided, use module.contents.
* @param siteId The site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async downloadModule(
module: CoreCourseModuleData,
courseId: number,
component?: string,
componentId?: string | number,
files?: CoreCourseModuleContentFile[],
siteId?: string,
): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const prefetchHandler = CoreCourseModulePrefetchDelegate.getPrefetchHandlerFor(module.modname);
if (prefetchHandler) {
// Use the prefetch handler to download the module.
if (prefetchHandler.download) {
return await prefetchHandler.download(module, courseId);
}
return await prefetchHandler.prefetch(module, courseId, true);
}
// There's no prefetch handler for the module, just download the files.
files = files || module.contents || [];
await CoreFilepool.downloadOrPrefetchFiles(siteId, files, false, false, component, componentId);
}
/**
* Get a course. It will first check the user courses, and fallback to another WS if not enrolled.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the course.
*/
async getCourse(
courseId: number,
siteId?: string,
): Promise<{ enrolled: boolean; course: CoreEnrolledCourseData | CoreCourseSearchedData }> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Try with enrolled courses first.
try {
const course = await CoreCourses.getUserCourse(courseId, false, siteId);
return ({ enrolled: true, course: course });
} catch {
// Not enrolled or an error happened. Try to use another WebService.
}
const course = await CoreCourses.getCourseByField('id', courseId, siteId);
return ({ enrolled: false, course: course });
}
/**
* Get a course, wait for any course format plugin to load, and open the course page. It basically chains the functions
* getCourse and openCourse.
*
* @param courseId Course ID.
* @param params Other params to pass to the course page.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async getAndOpenCourse(courseId: number, params?: Params, siteId?: string): Promise<void> {
const modal = await CoreDomUtils.showModalLoading();
let course: CoreCourseAnyCourseData | { id: number };
try {
const data = await this.getCourse(courseId, siteId);
course = data.course;
} catch {
// Cannot get course, return a "fake".
course = { id: courseId };
}
modal?.dismiss();
return this.openCourse(course, { params , siteId });
}
/**
* Check if the course has a block with that name.
*
* @param courseId Course ID.
* @param name Block name to search.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with true if the block exists or false otherwise.
* @since 3.7
*/
async hasABlockNamed(courseId: number, name: string, siteId?: string): Promise<boolean> {
try {
const blocks = await CoreCourse.getCourseBlocks(courseId, siteId);
return blocks.some((block) => block.name == name);
} catch {
return false;
}
}
/**
* Initialize the prefetch icon for selected courses.
*
* @param courses Courses array to get info from.
* @param prefetch Prefetch information.
* @return Resolved with the prefetch information updated when done.
*/
async initPrefetchCoursesIcons(
courses: CoreCourseBasicData[],
prefetch: CorePrefetchStatusInfo,
): Promise<CorePrefetchStatusInfo> {
if (!courses || courses.length <= 0) {
// Not enough courses.
prefetch.icon = '';
return prefetch;
}
const status = await this.determineCoursesStatus(courses);
prefetch = this.getCoursesPrefetchStatusInfo(status);
if (prefetch.loading) {
// It seems all courses are being downloaded, show a download button instead.
prefetch.icon = CoreConstants.ICON_NOT_DOWNLOADED;
}
return prefetch;
}
/**
* Load offline completion into a list of sections.
* This should be used in 3.6 sites or higher, where the course contents already include the completion.
*
* @param courseId The course to get the completion.
* @param sections List of sections of the course.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async loadOfflineCompletion(courseId: number, sections: CoreCourseWSSection[], siteId?: string): Promise<void> {
const offlineCompletions = await CoreCourseOffline.getCourseManualCompletions(courseId, siteId);
if (!offlineCompletions || !offlineCompletions.length) {
// No offline completion.
return;
}
const totalOffline = offlineCompletions.length;
let loaded = 0;
const offlineCompletionsMap = CoreUtils.arrayToObject(offlineCompletions, 'cmid');
// Load the offline data in the modules.
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
if (!section.modules || !section.modules.length) {
// Section has no modules, ignore it.
continue;
}
for (let j = 0; j < section.modules.length; j++) {
const module = section.modules[j];
const offlineCompletion = offlineCompletionsMap[module.id];
if (offlineCompletion && module.completiondata !== undefined &&
offlineCompletion.timecompleted >= module.completiondata.timecompleted * 1000) {
// The module has offline completion. Load it.
module.completiondata.state = offlineCompletion.completed;
module.completiondata.offline = true;
// If all completions have been loaded, stop.
loaded++;
if (loaded == totalOffline) {
break;
}
}
}
}
}
/**
* Load offline completion for a certain module.
* This should be used in 3.6 sites or higher, where the course contents already include the completion.
*
* @param courseId The course to get the completion.
* @param mmodule The module.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async loadModuleOfflineCompletion(courseId: number, module: CoreCourseModuleData, siteId?: string): Promise<void> {
if (!module.completiondata) {
return;
}
const offlineCompletions = await CoreCourseOffline.getCourseManualCompletions(courseId, siteId);
const offlineCompletion = offlineCompletions.find(completion => completion.cmid == module.id);
if (offlineCompletion && offlineCompletion.timecompleted >= module.completiondata.timecompleted * 1000) {
// The module has offline completion. Load it.
module.completiondata.state = offlineCompletion.completed;
module.completiondata.offline = true;
}
}
/**
* Prefetch all the courses in the array.
*
* @param courses Courses array to prefetch.
* @param prefetch Prefetch information to be updated.
* @param options Other options.
* @return Promise resolved when done.
*/
async prefetchCourses(
courses: CoreCourseAnyCourseData[],
prefetch: CorePrefetchStatusInfo,
options: CoreCoursePrefetchCoursesOptions = {},
): Promise<void> {
prefetch.loading = true;
prefetch.icon = CoreConstants.ICON_DOWNLOADING;
prefetch.badge = '';
const prefetchOptions = {
...options,
onProgress: (progress) => {
prefetch.badge = progress.count + ' / ' + progress.total;
prefetch.badgeA11yText = Translate.instant('core.course.downloadcoursesprogressdescription', progress);
prefetch.count = progress.count;
prefetch.total = progress.total;
},
};
try {
await this.confirmAndPrefetchCourses(courses, prefetchOptions);
prefetch.icon = CoreConstants.ICON_OUTDATED;
} finally {
prefetch.loading = false;
prefetch.badge = '';
}
}
/**
* Get a course download promise (if any).
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Download promise, undefined if not found.
*/
getCourseDownloadPromise(courseId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
return this.courseDwnPromises[siteId] && this.courseDwnPromises[siteId][courseId];
}
/**
* Get a course status icon and the langkey to use as a title.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the icon name and the title key.
*/
async getCourseStatusIconAndTitle(courseId: number, siteId?: string): Promise<CorePrefetchStatusInfo> {
const status = await CoreCourse.getCourseStatus(courseId, siteId);
return this.getCoursePrefetchStatusInfo(status);
}
/**
* Get a course status icon and the langkey to use as a title from status.
*
* @param status Course status.
* @return Prefetch status info.
*/
getCoursePrefetchStatusInfo(status: string): CorePrefetchStatusInfo {
const prefetchStatus: CorePrefetchStatusInfo = {
status: status,
icon: this.getPrefetchStatusIcon(status, false),
statusTranslatable: '',
loading: false,
};
if (status == CoreConstants.DOWNLOADED) {
// Always show refresh icon, we cannot know if there's anything new in course options.
prefetchStatus.statusTranslatable = 'core.course.refreshcourse';
} else if (status == CoreConstants.DOWNLOADING) {
prefetchStatus.statusTranslatable = 'core.downloading';
prefetchStatus.loading = true;
} else {
prefetchStatus.statusTranslatable = 'core.course.downloadcourse';
}
return prefetchStatus;
}
/**
* Get a courses status icon and the langkey to use as a title from status.
*
* @param status Courses status.
* @return Prefetch status info.
*/
getCoursesPrefetchStatusInfo(status: string): CorePrefetchStatusInfo {
const prefetchStatus: CorePrefetchStatusInfo = {
status: status,
icon: this.getPrefetchStatusIcon(status, false),
statusTranslatable: '',
loading: false,
};
if (status == CoreConstants.DOWNLOADED) {
// Always show refresh icon, we cannot know if there's anything new in course options.
prefetchStatus.statusTranslatable = 'core.courses.refreshcourses';
} else if (status == CoreConstants.DOWNLOADING) {
prefetchStatus.statusTranslatable = 'core.downloading';
prefetchStatus.loading = true;
} else {
prefetchStatus.statusTranslatable = 'core.courses.downloadcourses';
}
return prefetchStatus;
}
/**
* Get the icon given the status and if trust the download status.
*
* @param status Status constant.
* @param trustDownload True to show download success, false to show an outdated status when downloaded.
* @return Icon name.
*/
getPrefetchStatusIcon(status: string, trustDownload: boolean = false): string {
if (status == CoreConstants.NOT_DOWNLOADED) {
return CoreConstants.ICON_NOT_DOWNLOADED;
}
if (status == CoreConstants.OUTDATED || (status == CoreConstants.DOWNLOADED && !trustDownload)) {
return CoreConstants.ICON_OUTDATED;
}
if (status == CoreConstants.DOWNLOADED && trustDownload) {
return CoreConstants.ICON_DOWNLOADED;
}
if (status == CoreConstants.DOWNLOADING) {
return CoreConstants.ICON_DOWNLOADING;
}
return CoreConstants.ICON_DOWNLOADING;
}
/**
* Get the course ID from a module instance ID, showing an error message if it can't be retrieved.
*
* @deprecated since 4.0.
* @param instanceId Instance ID.
* @param moduleName Name of the module. E.g. 'glossary'.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the module's course ID.
*/
async getModuleCourseIdByInstance(instanceId: number, moduleName: string, siteId?: string): Promise<number> {
try {
const cm = await CoreCourse.getModuleBasicInfoByInstance(
instanceId,
moduleName,
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
return cm.course;
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true);
throw error;
}
}
/**
* Get prefetch info for a module.
*
* @param module Module to get the info from.
* @param courseId Course ID the section belongs to.
* @param invalidateCache Invalidates the cache first.
* @param component Component of the module.
* @return Promise resolved with the info.
*/
async getModulePrefetchInfo(
module: CoreCourseModuleData,
courseId: number,
invalidateCache = false,
component = '',
): Promise<CoreCourseModulePrefetchInfo> {
if (invalidateCache) {
// Currently, some modules pass invalidateCache=false because they already invalidate data in downloadResourceIfNeeded.
// If this function is changed to do more actions if invalidateCache=true, please review those modules.
CoreCourseModulePrefetchDelegate.invalidateModuleStatusCache(module);
await CoreUtils.ignoreErrors(CoreCourseModulePrefetchDelegate.invalidateCourseUpdates(courseId));
}
const results = await Promise.all([
CoreCourseModulePrefetchDelegate.getModuleStoredSize(module, courseId),
CoreCourseModulePrefetchDelegate.getModuleStatus(module, courseId),
this.getModulePackageLastDownloaded(module, component),
]);
// Treat stored size.
const size = results[0];
const sizeReadable = CoreTextUtils.bytesToSize(results[0], 2);
// Treat module status.
const status = results[1];
let statusIcon: string | undefined;
switch (results[1]) {
case CoreConstants.NOT_DOWNLOADED:
statusIcon = CoreConstants.ICON_NOT_DOWNLOADED;
break;
case CoreConstants.DOWNLOADING:
statusIcon = CoreConstants.ICON_DOWNLOADING;
break;
case CoreConstants.OUTDATED:
statusIcon = CoreConstants.ICON_OUTDATED;
break;
case CoreConstants.DOWNLOADED:
break;
default:
statusIcon = '';
break;
}
const packageData = results[2];
return {
size,
sizeReadable,
status,
statusIcon,
downloadTime: packageData.downloadTime,
downloadTimeReadable: packageData.downloadTimeReadable,
};
}
/**
* Get prefetch info for a module.
*
* @param module Module to get the info from.
* @param component Component of the module.
* @return Promise resolved with the info.
*/
async getModulePackageLastDownloaded(
module: CoreCourseModuleData,
component = '',
): Promise<CoreCourseModulePackageLastDownloaded> {
const siteId = CoreSites.getCurrentSiteId();
const packageData = await CoreUtils.ignoreErrors(CoreFilepool.getPackageData(siteId, component, module.id));
// Treat download time.
if (!packageData || !packageData.downloadTime || !CoreFileHelper.isStateDownloaded(packageData.status || '')) {
// Not downloaded.
return {
downloadTime: 0,
downloadTimeReadable: '',
};
}
const now = CoreTimeUtils.timestamp();
const downloadTime = packageData.downloadTime;
let downloadTimeReadable = '';
if (now - downloadTime < 7 * 86400) {
downloadTimeReadable = moment(downloadTime * 1000).fromNow();
} else {
downloadTimeReadable = moment(downloadTime * 1000).calendar();
}
return {
downloadTime,
downloadTimeReadable,
};
}
/**
* Get the download ID of a section. It's used to interact with CoreCourseModulePrefetchDelegate.
*
* @param section Section.
* @return Section download ID.
*/
getSectionDownloadId(section: {id: number}): string {
return 'Section-' + section.id;
}
/**
* Navigate to a module using instance ID and module name.
*
* @param instanceId Activity instance ID.
* @param modName Module name of the activity.
* @param options Other options.
* @return Promise resolved when done.
*/
async navigateToModuleByInstance(
instanceId: number,
modName: string,
options: CoreCourseNavigateToModuleByInstanceOptions = {},
): Promise<void> {
const modal = await CoreDomUtils.showModalLoading();
try {
const module = await CoreCourse.getModuleBasicInfoByInstance(instanceId, modName, { siteId: options.siteId });
this.navigateToModule(
module.id,
{
...options,
courseId: module.course,
modName: options.useModNameToGetModule ? modName : undefined,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true);
} finally {
// Just in case. In fact we need to dismiss the modal before showing a toast or error message.
modal.dismiss();
}
}
/**
* Navigate to a module.
*
* @param moduleId Module's ID.
* @param options Other options.
* @return Promise resolved when done.
*/
async navigateToModule(
moduleId: number,
options: CoreCourseNavigateToModuleOptions = {},
): Promise<void> {
const siteId = options.siteId || CoreSites.getCurrentSiteId();
let courseId = options.courseId;
let sectionId = options.sectionId;
const modal = await CoreDomUtils.showModalLoading();
try {
if (!courseId || !sectionId) {
const module = await CoreCourse.getModuleBasicInfo(
moduleId,
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
courseId = module.course;
sectionId = module.section;
}
// Get the site.
const site = await CoreSites.getSite(siteId);
// Get the module.
const module = await CoreCourse.getModule(moduleId, courseId, sectionId, false, false, siteId, options.modName);
if (CoreSites.getCurrentSiteId() === site.getId()) {
// Try to use the module's handler to navigate cleanly.
module.handlerData = await CoreCourseModuleDelegate.getModuleDataFor(
module.modname,
module,
courseId,
sectionId,
false,
);
if (module.handlerData?.action) {
modal.dismiss();
return module.handlerData.action(new Event('click'), module, courseId, options.modNavOptions);
}
}
const params: Params = {
course: { id: courseId },
module,
sectionId,
modNavOptions: options.modNavOptions,
};
if (courseId == site.getSiteHomeId()) {
// Check if site home is available.
const isAvailable = await CoreSiteHome.isAvailable();
if (isAvailable) {
await CoreNavigator.navigateToSitePath(CoreSiteHomeHomeHandlerService.PAGE_NAME, { params, siteId });
return;
}
}
modal.dismiss();
await this.getAndOpenCourse(courseId, params, siteId);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true);
} finally {
modal.dismiss();
}
}
/**
* Open a module.
*
* @param module The module to open.
* @param courseId The course ID of the module.
* @param options Other options.
* @param True if module can be opened, false otherwise.
*/
async openModule(module: CoreCourseModuleData, courseId: number, options: CoreCourseOpenModuleOptions = {}): Promise<boolean> {
if (!module.handlerData) {
module.handlerData = await CoreCourseModuleDelegate.getModuleDataFor(
module.modname,
module,
courseId,
options.sectionId,
false,
);
}
if (module.handlerData?.action) {
module.handlerData.action(new Event('click'), module, courseId, {
animated: false,
...options.modNavOptions,
});
return true;
}
return false;
}
/**
* Prefetch all the activities in a course and also the course addons.
*
* @param course The course to prefetch.
* @param sections List of course sections.
* @param courseHandlers List of course options handlers.
* @param courseMenuHandlers List of course menu handlers.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the download finishes.
*/
async prefetchCourse(
course: CoreCourseAnyCourseData,
sections: CoreCourseWSSection[],
courseHandlers: CoreCourseOptionsHandlerToDisplay[],
courseMenuHandlers: CoreCourseOptionsMenuHandlerToDisplay[],
siteId?: string,
): Promise<void> {
const requiredSiteId = siteId || CoreSites.getRequiredCurrentSite().getId();
if (this.courseDwnPromises[requiredSiteId] && this.courseDwnPromises[requiredSiteId][course.id] !== undefined) {
// There's already a download ongoing for this course, return the promise.
return this.courseDwnPromises[requiredSiteId][course.id];
} else if (!this.courseDwnPromises[requiredSiteId]) {
this.courseDwnPromises[requiredSiteId] = {};
}
// First of all, mark the course as being downloaded.
this.courseDwnPromises[requiredSiteId][course.id] = CoreCourse.setCourseStatus(
course.id,
CoreConstants.DOWNLOADING,
requiredSiteId,
).then(async () => {
const promises: Promise<unknown>[] = [];
// Prefetch all the sections. If the first section is "All sections", use it. Otherwise, use a fake "All sections".
let allSectionsSection: CoreCourseWSSection = sections[0];
if (sections[0].id != CoreCourseProvider.ALL_SECTIONS_ID) {
allSectionsSection = this.createAllSectionsSection();
}
promises.push(this.prefetchSection(allSectionsSection, course.id, sections));
// Prefetch course options.
courseHandlers.forEach((handler) => {
if (handler.prefetch) {
promises.push(handler.prefetch(course));
}
});
courseMenuHandlers.forEach((handler) => {
if (handler.prefetch) {
promises.push(handler.prefetch(course));
}
});
// Prefetch other data needed to render the course.
promises.push(CoreCourses.getCoursesByField('id', course.id));
const sectionWithModules = sections.find((section) => section.modules && section.modules.length > 0);
if (!sectionWithModules || sectionWithModules.modules[0].completion === undefined) {
promises.push(CoreCourse.getActivitiesCompletionStatus(course.id));
}
promises.push(CoreFilterHelper.getFilters('course', course.id));
await CoreUtils.allPromises(promises);
// Download success, mark the course as downloaded.
return CoreCourse.setCourseStatus(course.id, CoreConstants.DOWNLOADED, requiredSiteId);
}).catch(async (error) => {
// Error, restore previous status.
await CoreCourse.setCoursePreviousStatus(course.id, requiredSiteId);
throw error;
}).finally(() => {
delete this.courseDwnPromises[requiredSiteId][course.id];
});
return this.courseDwnPromises[requiredSiteId][course.id];
}
/**
* Helper function to prefetch a module, showing a confirmation modal if the size is big
* and invalidating contents if refreshing.
*
* @param handler Prefetch handler to use.
* @param module Module to download.
* @param size Size to download.
* @param courseId Course ID of the module.
* @param refresh True if refreshing, false otherwise.
* @return Promise resolved when downloaded.
*/
async prefetchModule(
handler: CoreCourseModulePrefetchHandler,
module: CoreCourseModuleData,
size: CoreFileSizeSum,
courseId: number,
refresh?: boolean,
): Promise<void> {
// Show confirmation if needed.
await CoreDomUtils.confirmDownloadSize(size);
// Invalidate content if refreshing and download the data.
if (refresh) {
await CoreUtils.ignoreErrors(handler.invalidateContent(module.id, courseId));
}
await CoreCourseModulePrefetchDelegate.prefetchModule(module, courseId, true);
}
/**
* Prefetch one section or all the sections.
* If the section is "All sections" it will prefetch all the sections.
*
* @param section Section.
* @param courseId Course ID the section belongs to.
* @param sections List of sections. Used when downloading all the sections.
* @return Promise resolved when the prefetch is finished.
*/
async prefetchSection(
section: CoreCourseSectionWithStatus,
courseId: number,
sections?: CoreCourseSectionWithStatus[],
): Promise<void> {
if (section.id != CoreCourseProvider.ALL_SECTIONS_ID) {
try {
// Download only this section.
await this.prefetchSingleSectionIfNeeded(section, courseId);
} finally {
// Calculate the status of the section that finished.
await this.calculateSectionStatus(section, courseId, false, false);
}
return;
}
if (!sections) {
throw new CoreError('List of sections is required when downloading all sections.');
}
// Download all the sections except "All sections".
let allSectionsStatus = CoreConstants.NOT_DOWNLOADABLE;
section.isDownloading = true;
const promises = sections.map(async (section) => {
if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) {
return;
}
try {
await this.prefetchSingleSectionIfNeeded(section, courseId);
} finally {
// Calculate the status of the section that finished.
const result = await this.calculateSectionStatus(section, courseId, false, false);
// Calculate "All sections" status.
allSectionsStatus = CoreFilepool.determinePackagesStatus(allSectionsStatus, result.statusData.status);
}
});
try {
await CoreUtils.allPromises(promises);
// Set "All sections" data.
section.downloadStatus = allSectionsStatus;
section.canCheckUpdates = true;
section.isDownloading = allSectionsStatus === CoreConstants.DOWNLOADING;
} finally {
section.isDownloading = false;
}
}
/**
* Prefetch a certain section if it needs to be prefetched.
* If the section is "All sections" it will be ignored.
*
* @param section Section to prefetch.
* @param courseId Course ID the section belongs to.
* @return Promise resolved when the section is prefetched.
*/
protected async prefetchSingleSectionIfNeeded(section: CoreCourseSectionWithStatus, courseId: number): Promise<void> {
if (section.id == CoreCourseProvider.ALL_SECTIONS_ID || section.hiddenbynumsections) {
return;
}
const promises: Promise<void>[] = [];
const siteId = CoreSites.getCurrentSiteId();
section.isDownloading = true;
// Download the modules.
promises.push(this.syncModulesAndPrefetchSection(section, courseId));
// Download the files in the section description.
const introFiles = CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(section.summary);
promises.push(CoreUtils.ignoreErrors(
CoreFilepool.addFilesToQueue(siteId, introFiles, CoreCourseProvider.COMPONENT, courseId),
));
try {
await Promise.all(promises);
} finally {
section.isDownloading = false;
}
}
/**
* Sync modules in a section and prefetch them.
*
* @param section Section to prefetch.
* @param courseId Course ID the section belongs to.
* @return Promise resolved when the section is prefetched.
*/
protected async syncModulesAndPrefetchSection(section: CoreCourseSectionWithStatus, courseId: number): Promise<void> {
// Sync the modules first.
await CoreCourseModulePrefetchDelegate.syncModules(section.modules, courseId);
// Validate the section needs to be downloaded and calculate amount of modules that need to be downloaded.
const result = await CoreCourseModulePrefetchDelegate.getModulesStatus(section.modules, courseId, section.id);
if (result.status == CoreConstants.DOWNLOADED || result.status == CoreConstants.NOT_DOWNLOADABLE) {
// Section is downloaded or not downloadable, nothing to do.
return ;
}
await this.prefetchSingleSection(section, result, courseId);
}
/**
* Start or restore the prefetch of a section.
* If the section is "All sections" it will be ignored.
*
* @param section Section to download.
* @param result Result of CoreCourseModulePrefetchDelegate.getModulesStatus for this section.
* @param courseId Course ID the section belongs to.
* @return Promise resolved when the section has been prefetched.
*/
protected async prefetchSingleSection(
section: CoreCourseSectionWithStatus,
result: CoreCourseModulesStatus,
courseId: number,
): Promise<void> {
if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) {
return;
}
if (section.total && section.total > 0) {
// Already being downloaded.
return ;
}
// We only download modules with status notdownloaded, downloading or outdated.
const modules = result[CoreConstants.OUTDATED].concat(result[CoreConstants.NOT_DOWNLOADED])
.concat(result[CoreConstants.DOWNLOADING]);
const downloadId = this.getSectionDownloadId(section);
section.isDownloading = true;
// Prefetch all modules to prevent incoeherences in download count and to download stale data not marked as outdated.
await CoreCourseModulePrefetchDelegate.prefetchModules(downloadId, modules, courseId, (data) => {
section.count = data.count;
section.total = data.total;
});
}
/**
* Check if a section has content.
*
* @param section Section to check.
* @return Whether the section has content.
*/
sectionHasContent(section: CoreCourseWSSection): boolean {
if (!section.modules) {
return false;
}
if (section.hiddenbynumsections) {
return false;
}
return (section.availabilityinfo !== undefined && section.availabilityinfo != '') ||
section.summary != '' || (section.modules && section.modules.length > 0);
}
/**
* Wait for any course format plugin to load, and open the course page.
*
* If the plugin's promise is resolved, the course page will be opened. If it is rejected, they will see an error.
* If the promise for the plugin is still in progress when the user tries to open the course, a loader
* will be displayed until it is complete, before the course page is opened. If the promise is already complete,
* they will see the result immediately.
*
* @param course Course to open
* @param navOptions Navigation options that includes params to pass to the page.
* @return Promise resolved when done.
*/
async openCourse(
course: CoreCourseAnyCourseData | { id: number },
navOptions?: CoreNavigationOptions & { siteId?: string },
): Promise<void> {
const siteId = navOptions?.siteId;
if (!siteId || siteId == CoreSites.getCurrentSiteId()) {
// Current site, we can open the course.
return CoreCourse.openCourse(course, navOptions);
} else {
// We need to load the site first.
navOptions = navOptions || {};
navOptions.params = navOptions.params || {};
Object.assign(navOptions.params, { course: course });
await CoreNavigator.navigateToSitePath(`course/${course.id}`, navOptions);
}
}
/**
* Delete course files.
*
* @param courseId Course id.
* @return Promise to be resolved once the course files are deleted.
*/
async deleteCourseFiles(courseId: number): Promise<void> {
const sections = await CoreCourse.getSections(courseId);
const modules = CoreArray.flatten(sections.map((section) => section.modules));
await Promise.all(
modules.map((module) => this.removeModuleStoredData(module, courseId)),
);
await CoreCourse.setCourseStatus(courseId, CoreConstants.NOT_DOWNLOADED);
}
/**
* Remove module stored data.
*
* @param module Module to remove the files.
* @param courseId Course ID the module belongs to.
* @return Promise resolved when done.
*/
async removeModuleStoredData(module: CoreCourseModuleData, courseId: number): Promise<void> {
const promises: Promise<void>[] = [];
promises.push(CoreCourseModulePrefetchDelegate.removeModuleFiles(module, courseId));
const handler = CoreCourseModulePrefetchDelegate.getPrefetchHandlerFor(module.modname);
const site = CoreSites.getCurrentSite();
if (handler && site) {
promises.push(site.deleteComponentFromCache(handler.component, module.id));
}
await Promise.all(promises);
}
/**
* Completion clicked.
*
* @param completion The completion.
* @param event The click event.
* @return Promise resolved with the result.
*/
async changeManualCompletion(
completion: CoreCourseModuleCompletionData,
event?: Event,
): Promise<CoreStatusWithWarningsWSResponse | void> {
if (!completion) {
return;
}
if (completion.cmid === undefined ||
completion.tracking !== CoreCourseModuleCompletionTracking.COMPLETION_TRACKING_MANUAL) {
return;
}
event?.preventDefault();
event?.stopPropagation();
const modal = await CoreDomUtils.showModalLoading();
completion.state = completion.state === CoreCourseModuleCompletionStatus.COMPLETION_COMPLETE
? CoreCourseModuleCompletionStatus.COMPLETION_INCOMPLETE
: CoreCourseModuleCompletionStatus.COMPLETION_COMPLETE;
try {
const response = await CoreCourse.markCompletedManually(
completion.cmid,
completion.state === CoreCourseModuleCompletionStatus.COMPLETION_COMPLETE,
completion.courseId,
);
if (response.offline) {
completion.offline = true;
}
return response;
} catch (error) {
// Restore previous state.
completion.state = completion.state === CoreCourseModuleCompletionStatus.COMPLETION_COMPLETE
? CoreCourseModuleCompletionStatus.COMPLETION_INCOMPLETE
: CoreCourseModuleCompletionStatus.COMPLETION_COMPLETE;
CoreDomUtils.showErrorModalDefault(error, 'core.errorchangecompletion', true);
} finally {
modal.dismiss();
}
}
}
export const CoreCourseHelper = makeSingleton(CoreCourseHelperProvider);
/**
* Section with calculated data.
*/
export type CoreCourseSection = CoreCourseWSSection & {
hasContent?: boolean;
};
/**
* Section with data about prefetch.
*/
export type CoreCourseSectionWithStatus = CoreCourseSection & {
downloadStatus?: string; // Section status.
canCheckUpdates?: boolean; // Whether can check updates. @deprecated since app 4.0
isDownloading?: boolean; // Whether section is being downloaded.
total?: number; // Total of modules being downloaded.
count?: number; // Number of downloaded modules.
isCalculating?: boolean; // Whether status is being calculated.
};
/**
* Module with calculated data.
*/
export type CoreCourseModuleData = Omit<CoreCourseGetContentsWSModule, 'completiondata'> & {
course: number; // The course id.
isStealth?: boolean;
handlerData?: CoreCourseModuleHandlerData;
completiondata?: CoreCourseModuleCompletionData;
section: number;
};
/**
* Module with calculated data.
*
* @deprecated since 4.0. Use CoreCourseModuleData instead.
*/
export type CoreCourseModule = CoreCourseModuleData;
/**
* Module completion with calculated data.
*/
export type CoreCourseModuleCompletionData = CoreCourseModuleWSCompletionData & {
courseId: number;
tracking: CoreCourseModuleCompletionTracking;
cmid: number;
offline?: boolean;
};
/**
* Options for prefetch course function.
*/
export type CoreCoursePrefetchCourseOptions = {
sections?: CoreCourseWSSection[]; // List of course sections.
courseHandlers?: CoreCourseOptionsHandlerToDisplay[]; // List of course handlers.
menuHandlers?: CoreCourseOptionsMenuHandlerToDisplay[]; // List of course menu handlers.
isGuest?: boolean; // Whether the user is guest.
};
/**
* Options for prefetch courses function.
*/
export type CoreCoursePrefetchCoursesOptions = {
canHaveGuestCourses?: boolean; // Whether the list of courses can contain courses with only guest access.
};
/**
* Options for confirm and prefetch courses function.
*/
export type CoreCourseConfirmPrefetchCoursesOptions = CoreCoursePrefetchCoursesOptions & {
onProgress?: (data: CoreCourseCoursesProgress) => void;
};
/**
* Common options for navigate to module functions.
*/
type CoreCourseNavigateToModuleCommonOptions = {
courseId?: number; // Course ID. If not defined we'll try to retrieve it from the site.
sectionId?: number; // Section the module belongs to. If not defined we'll try to retrieve it from the site.
modNavOptions?: CoreNavigationOptions; // Navigation options to open the module, including params to pass to the module.
siteId?: string; // Site ID. If not defined, current site.
};
/**
* Options for navigate to module by instance function.
*/
export type CoreCourseNavigateToModuleByInstanceOptions = CoreCourseNavigateToModuleCommonOptions & {
// True to retrieve all instances with a single WS call. Not recommended if can return a lot of contents.
useModNameToGetModule?: boolean;
};
/**
* Options for navigate to module function.
*/
export type CoreCourseNavigateToModuleOptions = CoreCourseNavigateToModuleCommonOptions & {
modName?: string; // To retrieve all instances with a single WS call. Not recommended if can return a lot of contents.
};
/**
* Options for open module function.
*/
export type CoreCourseOpenModuleOptions = {
sectionId?: number; // Section the module belongs to.
modNavOptions?: CoreNavigationOptions; // Navigation options to open the module, including params to pass to the module.
}; | the_stack |
export const defaultOptions: ParseOptions;
/**
* May throw on error, and it may log warnings using `console.warn`.
* It only supports input consisting of a single YAML document;
* for multi-document support you should use `YAML.parseAllDocuments`
* @param str Should be a string with YAML formatting.
* @returns The value will match the type of the root value of the parsed YAML document,
* so Maps become objects, Sequences arrays, and scalars result in nulls, booleans, numbers and strings.
*/
export function parse(str: string, options?: ParseOptions): any;
/**
* @returns Will always include \n as the last character, as is expected of YAML documents.
*/
export function stringify(value: any, options?: ParseOptions): string;
/**
* Parses a single YAML.Document from the input str; used internally by YAML.parse.
* Will include an error if str contains more than one document.
*/
export function parseDocument(
str: string,
options?: ParseOptions
): ast.Document;
/**
* When parsing YAML, the input string str may consist of a stream of documents
* separated from each other by `...` document end marker lines.
* @returns An array of Document objects that allow these documents to be parsed and manipulated with more control.
*/
export function parseAllDocuments(
str: string,
options?: ParseOptions
): ast.Document[];
/**
* YAML.createNode recursively turns objects into Map and arrays to Seq collections.
* Its primary use is to enable attaching comments or other metadata to a value,
* or to otherwise exert more fine-grained control over the stringified output.
*
* Wraps plain values in Scalar objects.
*/
export function createNode(
value: any,
wrapScalars?: true,
tag?: string
): ast.MapBase | ast.SeqBase | ast.Scalar;
/**
* YAML.createNode recursively turns objects into Map and arrays to Seq collections.
* Its primary use is to enable attaching comments or other metadata to a value,
* or to otherwise exert more fine-grained control over the stringified output.
*
* Doesn't wrap plain values in Scalar objects.
*/
export function createNode(
value: any,
wrapScalars: false,
tag?: string
): ast.MapBase | ast.SeqBase | string | number | boolean | null;
export function parseCST(str: string): ParsedCST;
export interface ParsedCST extends Array<cst.Document> {
setOrigRanges(): boolean;
}
export const Document: ast.DocumentConstructor;
export interface ParseOptions {
/**
* Allow non-JSON JavaScript objects to remain in the `toJSON` output.
* Relevant with the YAML 1.1 `!!timestamp` and `!!binary` tags. By default `true`.
*/
keepBlobsInJSON?: boolean;
/**
* Include references in the AST to each node's corresponding CST node. By default `false`.
*/
keepCstNodes?: boolean;
/**
* Store the original node type when parsing documents. By default `true`.
*/
keepNodeTypes?: boolean;
/**
* When outputting JS, use Map rather than Object to represent mappings. By default `false`.
*/
mapAsMap?: boolean;
/**
* Enable support for `<<` merge keys.
*/
merge?: boolean;
/**
* The base schema to use. By default `"core"` for YAML 1.2 and `"yaml-1.1"` for earlier versions.
*/
schema?: "core" | "failsafe" | "json" | "yaml-1.1";
/**
* Array of additional (custom) tags to include in the schema.
*/
tags?: Tag[] | ((tags: Tag[]) => Tag[]);
/**
* The YAML version used by documents without a `%YAML` directive. By default `"1.2"`.
*/
version?: string;
}
export interface Tag {
/**
* A JavaScript class that should be matched to this tag, e.g. `Date` for `!!timestamp`.
*/
class?: new () => any;
/**
* An optional factory function, used e.g. by collections when wrapping JS objects as AST nodes.
*/
createNode?: (value: any) => ast.MapBase | ast.SeqBase | ast.Scalar;
/**
* If `true`, the tag should not be explicitly included when stringifying.
*/
default?: boolean;
/**
* If a tag has multiple forms that should be parsed and/or stringified differently, use `format` to identify them.
*/
format?: string;
/**
* The `Node` child class that implements this tag. Required for collections and tags that have overlapping JS representations.
*/
nodeClass?: new () => any;
/**
* Used by some tags to configure their stringification, where applicable.
*/
options?: object;
/**
* Should return an instance of a class extending `Node`.
* If test is set, will be called with the resulting match as arguments.
* Otherwise, will be called as `resolve(doc, cstNode)`.
*/
resolve(doc: ast.Document, cstNode: cst.Node): ast.Node;
resolve(...match: string[]): ast.Node;
/**
* @param item the node being stringified.
* @param ctx contains the stringifying context variables.
* @param onComment a function that should be called if the stringifier includes the item's comment in its output.
*/
stringify(
item: ast.Node,
ctx: StringifyContext,
onComment: () => void
): string;
/**
* The fully qualified name of the tag.
*/
tag: string;
/**
* Used to match string values of scalar nodes; captured parts will be passed as arguments of `resolve()`.
*/
test?: RegExp;
}
export interface StringifyContext {
[key: string]: any;
}
export type YAMLError =
| YAMLSyntaxError
| YAMLSemanticError
| YAMLReferenceError;
export interface YAMLSyntaxError extends SyntaxError {
name: "YAMLSyntaxError";
source: cst.Node;
}
export interface YAMLSemanticError extends SyntaxError {
name: "YAMLSemanticError";
source: cst.Node;
}
export interface YAMLReferenceError extends ReferenceError {
name: "YAMLReferenceError";
source: cst.Node;
}
export interface YAMLWarning extends Error {
name: "YAMLReferenceError";
source: cst.Node;
}
export namespace cst {
interface Range {
start: number;
end: number;
origStart?: number;
origEnd?: number;
isEmpty(): boolean;
}
interface ParseContext {
/** Node starts at beginning of line */
atLineStart: boolean;
/** true if currently in a collection context */
inCollection: boolean;
/** true if currently in a flow context */
inFlow: boolean;
/** Current level of indentation */
indent: number;
/** Start of the current line */
lineStart: number;
/** The parent of the node */
parent: Node;
/** Source of the YAML document */
src: string;
}
interface Node {
context: ParseContext | null;
/** if not null, indicates a parser failure */
error: YAMLSyntaxError | null;
/** span of context.src parsed into this node */
range: Range | null;
valueRange: Range | null;
/** anchors, tags and comments */
props: Range[];
/** specific node type */
type: string;
/** if non-null, overrides source value */
value: string | null;
readonly anchor: string | null;
readonly comment: string | null;
readonly hasComment: boolean;
readonly hasProps: boolean;
readonly jsonLike: boolean;
readonly rawValue: string | null;
readonly tag:
| null
| { verbatim: string }
| { handle: string; suffix: string };
readonly valueRangeContainsNewline: boolean;
}
interface Alias extends Node {
type: "ALIAS";
/** contain the anchor without the * prefix */
readonly rawValue: string;
}
type Scalar = BlockValue | PlainValue | QuoteValue;
interface BlockValue extends Node {
type: "BLOCK_FOLDED" | "BLOCK_LITERAL";
chomping: "CLIP" | "KEEP" | "STRIP";
blockIndent: number | null;
header: Range;
readonly strValue: string | null;
}
interface BlockFolded extends BlockValue {
type: "BLOCK_FOLDED";
}
interface BlockLiteral extends BlockValue {
type: "BLOCK_LITERAL";
}
interface PlainValue extends Node {
type: "PLAIN";
readonly strValue: string | null;
}
interface QuoteValue extends Node {
type: "QUOTE_DOUBLE" | "QUOTE_SINGLE";
readonly strValue:
| null
| string
| { str: string; errors: YAMLSyntaxError[] };
}
interface QuoteDouble extends QuoteValue {
type: "QUOTE_DOUBLE";
}
interface QuoteSingle extends QuoteValue {
type: "QUOTE_SINGLE";
}
interface Comment extends Node {
type: "COMMENT";
readonly anchor: null;
readonly comment: string;
readonly rawValue: null;
readonly tag: null;
}
interface BlankLine extends Node {
type: "BLANK_LINE";
}
interface MapItem extends Node {
type: "MAP_KEY" | "MAP_VALUE";
node: ContentNode | null;
}
interface MapKey extends MapItem {
type: "MAP_KEY";
}
interface MapValue extends MapItem {
type: "MAP_VALUE";
}
interface Map extends Node {
type: "MAP";
/** implicit keys are not wrapped */
items: Array<BlankLine | Comment | Alias | Scalar | MapItem>;
}
interface SeqItem extends Node {
type: "SEQ_ITEM";
node: ContentNode | null;
}
interface Seq extends Node {
type: "SEQ";
items: Array<BlankLine | Comment | SeqItem>;
}
interface FlowChar {
char: "{" | "}" | "[" | "]" | "," | "?" | ":";
offset: number;
origOffset?: number;
}
interface FlowCollection extends Node {
type: "FLOW_MAP" | "FLOW_SEQ";
items: Array<FlowChar | BlankLine | Comment | Alias | Scalar | FlowCollection>;
}
interface FlowMap extends FlowCollection {
type: "FLOW_MAP";
}
interface FlowSeq extends FlowCollection {
type: "FLOW_SEQ";
}
type ContentNode = Alias | Scalar | Map | Seq | FlowCollection;
interface Directive extends Node {
type: "DIRECTIVE";
name: string;
readonly anchor: null;
readonly parameters: string[];
readonly tag: null;
}
interface Document extends Node {
type: "DOCUMENT";
directives: Array<BlankLine | Comment | Directive>;
contents: Array<BlankLine | Comment | ContentNode>;
readonly anchor: null;
readonly comment: null;
readonly tag: null;
}
}
export namespace ast {
type AstNode = ScalarNode | MapNode | SeqNode | Alias;
type DocumentConstructor = new (options?: ParseOptions) => Document;
interface Document {
type: "DOCUMENT";
/**
* Anchors associated with the document's nodes;
* also provides alias & merge node creators.
*/
anchors: Anchors;
/**
* A comment at the very beginning of the document.
*/
commentBefore: null | string;
/**
* A comment at the end of the document.
*/
comment: null | string;
/**
* only available when `keepCstNodes` is set to `true`
*/
cstNode?: cst.Document;
/**
* The document contents.
*/
contents: AstNode | null;
/**
* Errors encountered during parsing.
*/
errors: YAMLError[];
/**
* The schema used with the document.
*/
schema: Schema;
/**
* the [start, end] range of characters of the source parsed
* into this node (undefined if not parsed)
*/
range: null | [number, number];
/**
* a blank line before this node and its commentBefore
*/
spaceBefore?: boolean;
/**
* Array of prefixes; each will have a string `handle` that
* starts and ends with `!` and a string `prefix` that the handle will be replaced by.
*/
tagPrefixes: Prefix[];
/**
* The parsed version of the source document;
* if true-ish, stringified output will include a `%YAML` directive.
*/
version?: string;
/**
* Warnings encountered during parsing.
*/
warnings: YAMLWarning[];
/**
* List the tags used in the document that are not in the default `tag:yaml.org,2002:` namespace.
*/
listNonDefaultTags(): string[];
/**
* Parse a CST into this document
*/
parse(cst: cst.Document): this;
/**
* Set `handle` as a shorthand string for the `prefix` tag namespace.
*/
setTagPrefix(handle: string, prefix: string): void;
/**
* A plain JavaScript representation of the document `contents`.
*/
toJSON(): any;
/**
* A YAML representation of the document.
*/
toString(): string;
}
interface Anchors {
/**
* Create a new `Alias` node, adding the required anchor for `node`.
* If `name` is empty, a new anchor name will be generated.
*/
createAlias(node: Node, name?: string): Alias;
/**
* Create a new `Merge` node with the given source nodes.
* Non-`Alias` sources will be automatically wrapped.
*/
createMergePair(...nodes: Node[]): Merge;
/**
* The anchor name associated with `node`, if set.
*/
getName(node: Node): undefined | string;
/**
* The node associated with the anchor `name`, if set.
*/
getNode(name: string): undefined | Node;
/**
* Find an available anchor name with the given `prefix` and a numerical suffix.
*/
newName(prefix: string): string;
/**
* Associate an anchor with `node`. If `name` is empty, a new name will be generated.
* To remove an anchor, use `setAnchor(null, name)`.
*/
setAnchor(node: Node | null, name?: string): void | string;
}
interface Schema {
merge: boolean;
name: string;
schema: Tag[];
}
interface Prefix {
handle: string;
prefix: string;
}
interface Node {
/**
* a comment on or immediately after this
*/
comment: null | string;
/**
* a comment before this
*/
commentBefore: null | string;
/**
* only available when `keepCstNodes` is set to `true`
*/
cstNode?: cst.Node;
/**
* the [start, end] range of characters of the source parsed
* into this node (undefined for pairs or if not parsed)
*/
range: null | [number, number];
/**
* a blank line before this node and its commentBefore
*/
spaceBefore?: boolean;
/**
* a fully qualified tag, if required
*/
tag: null | string;
/**
* a plain JS representation of this node
*/
toJSON(): any;
}
type ScalarConstructor = new (
value: null | boolean | number | string
) => Scalar;
interface Scalar extends Node {
type:
| "BLOCK_FOLDED"
| "BLOCK_LITERAL"
| "PLAIN"
| "QUOTE_DOUBLE"
| "QUOTE_SINGLE"
| undefined;
/**
* By default (undefined), numbers use decimal notation.
* The YAML 1.2 core schema only supports 'HEX' and 'OCT'.
*/
format: "BIN" | "HEX" | "OCT" | "TIME" | undefined;
value: null | boolean | number | string;
}
type ScalarNode =
| BlockFolded
| BlockLiteral
| PlainValue
| QuoteDouble
| QuoteSingle;
interface BlockFolded extends Scalar {
type: "BLOCK_FOLDED";
cstNode?: cst.BlockFolded;
}
interface BlockLiteral extends Scalar {
type: "BLOCK_LITERAL";
cstNode?: cst.BlockLiteral;
}
interface PlainValue extends Scalar {
type: "PLAIN";
cstNode?: cst.PlainValue;
}
interface QuoteDouble extends Scalar {
type: "QUOTE_DOUBLE";
cstNode?: cst.QuoteDouble;
}
interface QuoteSingle extends Scalar {
type: "QUOTE_SINGLE";
cstNode?: cst.QuoteSingle;
}
type PairConstructor = new (
key: AstNode | null,
value?: AstNode | null
) => Pair;
interface Pair extends Node {
type: "PAIR";
/**
* key is always Node or null when parsed, but can be set to anything.
*/
key: AstNode | null;
/**
* value is always Node or null when parsed, but can be set to anything.
*/
value: AstNode | null;
cstNode?: never; // no corresponding cstNode
}
type MapConstructor = new () => MapBase;
interface MapBase extends Node {
type: "FLOW_MAP" | "MAP" | undefined;
items: Array<Pair | Merge>;
}
type MapNode = FlowMap | Map;
interface FlowMap extends MapBase {
type: "FLOW_MAP";
cstNode?: cst.FlowMap;
}
interface Map extends MapBase {
type: "MAP";
cstNode?: cst.Map;
}
type SeqConstructor = new () => SeqBase;
interface SeqBase extends Node {
type: "FLOW_SEQ" | "SEQ" | undefined;
/**
* item is always Node or null when parsed, but can be set to anything.
*/
items: Array<AstNode | Pair | null>;
}
type SeqNode = FlowSeq | Seq;
interface FlowSeq extends SeqBase {
type: "FLOW_SEQ";
items: Array<AstNode | Pair>;
cstNode?: cst.FlowSeq;
}
interface Seq extends SeqBase {
type: "SEQ";
items: Array<AstNode | null>;
cstNode?: cst.Seq;
}
interface Alias extends Node {
type: "ALIAS";
source: AstNode;
cstNode?: cst.Alias;
}
interface Merge extends Node {
type: "MERGE_PAIR";
/**
* key is always Scalar('<<'), defined by the type specification
*/
key: PlainValue;
/**
* value is always Seq<Alias(Map)>, stringified as *A if length = 1
*/
value: SeqBase;
cstNode?: cst.PlainValue;
}
} | the_stack |
import { ColorReducer } from "./colorreductionmanagement";
import { delay, IMap, RGB } from "./common";
import { FacetCreator } from "./facetCreator";
import { Facet, FacetResult } from "./facetmanagement";
import { BooleanArray2D, Uint8Array2D } from "./structs/typedarrays";
export class FacetReducer {
/**
* Remove all facets that have a pointCount smaller than the given number.
*/
public static async reduceFacets(smallerThan: number, removeFacetsFromLargeToSmall: boolean, maximumNumberOfFacets: number, colorsByIndex: RGB[], facetResult: FacetResult, imgColorIndices: Uint8Array2D, onUpdate: ((progress: number) => void) | null = null) {
const visitedCache = new BooleanArray2D(facetResult.width, facetResult.height);
// build the color distance matrix, which describes the distance of each color to each other
const colorDistances: number[][] = ColorReducer.buildColorDistanceMatrix(colorsByIndex);
// process facets from large to small. This results in better consistency with the original image
// because the small facets act as boundary for the large merges keeping them mostly in place of where they should remain
// then afterwards the smaller ones are deleted which will just end up completely isolated and thus entirely replaced
// with the outer facet. But then again, what do I know, I'm just a comment.
const facetProcessingOrder = facetResult.facets.filter((f) => f != null).slice(0).sort((a, b) => b!.pointCount > a!.pointCount ? 1 : (b!.pointCount < a!.pointCount ? -1 : 0)).map((f) => f!.id);
if (!removeFacetsFromLargeToSmall) {
facetProcessingOrder.reverse();
}
let curTime = new Date().getTime();
for (let fidx: number = 0; fidx < facetProcessingOrder.length; fidx++) {
const f = facetResult.facets[facetProcessingOrder[fidx]];
// facets can be removed by merging by others due to a previous facet deletion
if (f != null && f.pointCount < smallerThan) {
FacetReducer.deleteFacet(f.id, facetResult, imgColorIndices, colorDistances, visitedCache);
if (new Date().getTime() - curTime > 500) {
curTime = new Date().getTime();
await delay(0);
if (onUpdate != null) {
onUpdate(0.5 * fidx / facetProcessingOrder.length);
}
}
}
}
let facetCount = facetResult.facets.filter(f => f != null).length;
if (facetCount > maximumNumberOfFacets) {
console.log(`There are still ${facetCount} facets, more than the maximum of ${maximumNumberOfFacets}. Removing the smallest facets`);
}
const startFacetCount = facetCount;
while (facetCount > maximumNumberOfFacets) {
// because facets can be merged, reevaluate the order of facets to make sure the smallest one is removed
// this is slower but more accurate
const facetProcessingOrder = facetResult.facets.filter((f) => f != null).slice(0)
.sort((a, b) => b!.pointCount > a!.pointCount ? 1 : (b!.pointCount < a!.pointCount ? -1 : 0))
.map((f) => f!.id)
.reverse();
const facetToRemove = facetResult.facets[facetProcessingOrder[0]];
FacetReducer.deleteFacet(facetToRemove!.id, facetResult, imgColorIndices, colorDistances, visitedCache);
facetCount = facetResult.facets.filter(f => f != null).length;
if (new Date().getTime() - curTime > 500) {
curTime = new Date().getTime();
await delay(0);
if (onUpdate != null) {
onUpdate(0.5 + 0.5 - (facetCount - maximumNumberOfFacets) / (startFacetCount - maximumNumberOfFacets));
}
}
}
// this.trimFacets(facetResult, imgColorIndices, colorDistances, visitedCache);
if (onUpdate != null) {
onUpdate(1);
}
}
// /**
// * Trims facets with narrow paths either horizontally or vertically, potentially splitting the facet into multiple facets
// */
// public static trimFacets(facetResult: FacetResult, imgColorIndices: Uint8Array2D, colorDistances: number[][], visitedArrayCache: BooleanArray2D) {
// for (const facet of facetResult.facets) {
// if (facet !== null) {
// const facetPointsToReallocate: Point[] = [];
// for (let y: number = facet.bbox.minY; y <= facet.bbox.maxY; y++) {
// for (let x: number = facet.bbox.minX; x <= facet.bbox.maxX; x++) {
// if (x > 0 && y > 0 && x < facetResult.width - 1 && y < facetResult.height - 1 &&
// facetResult.facetMap.get(x, y) === facet.id) {
// // check if isolated horizontally
// const top = facetResult.facetMap.get(x, y - 1);
// const bottom = facetResult.facetMap.get(x, y + 1);
// if (top !== facet.id && bottom !== facet.id) {
// // . ? .
// // . F .
// // . ? .
// // mark pixel of facet that it should be removed
// facetPointsToReallocate.push(new Point(x, y));
// const closestNeighbour = FacetReducer.getClosestNeighbourForPixel(facet, facetResult, x, y, colorDistances);
// // copy over color of closest neighbour
// imgColorIndices.set(x, y, facetResult.facets[closestNeighbour]!.color);
// console.log("Flagged " + x + "," + y + " to trim");
// }
// }
// }
// }
// if (facetPointsToReallocate.length > 0) {
// FacetReducer.rebuildForFacetChange(visitedArrayCache, facet, imgColorIndices, facetResult);
// }
// }
// }
// }
/**
* Deletes a facet. All points belonging to the facet are moved to the nearest neighbour facet
* based on the distance of the neighbour border points. This results in a voronoi like filling in of the
* void the deletion made
*/
private static deleteFacet(facetIdToRemove: number, facetResult: FacetResult, imgColorIndices: Uint8Array2D, colorDistances: number[][], visitedArrayCache: BooleanArray2D) {
const facetToRemove = facetResult.facets[facetIdToRemove];
if (facetToRemove === null) { // already removed
return;
}
if (facetToRemove.neighbourFacetsIsDirty) {
FacetCreator.buildFacetNeighbour(facetToRemove, facetResult);
}
if (facetToRemove.neighbourFacets!.length > 0) {
// there are many small facets, it's faster to just iterate over all points within its bounding box
// and seeing which belong to the facet than to keep track of the inner points (along with the border points)
// per facet, because that generates a lot of extra heap objects that need to be garbage collected each time
// a facet is rebuilt
for (let j: number = facetToRemove.bbox.minY; j <= facetToRemove.bbox.maxY; j++) {
for (let i: number = facetToRemove.bbox.minX; i <= facetToRemove.bbox.maxX; i++) {
if (facetResult.facetMap.get(i, j) === facetToRemove.id) {
const closestNeighbour = FacetReducer.getClosestNeighbourForPixel(facetToRemove, facetResult, i, j, colorDistances);
if (closestNeighbour !== -1) {
// copy over color of closest neighbour
imgColorIndices.set(i, j, facetResult.facets[closestNeighbour]!.color);
} else {
console.warn(`No closest neighbour found for point ${i},${j}`);
}
}
}
}
} else {
console.warn(`Facet ${facetToRemove.id} does not have any neighbours`);
}
// Rebuild all the neighbour facets that have been changed. While it could probably be faster by just adding the points manually
// to the facet map and determine if the border points are still valid, it's more complex than that. It's possible that due to the change in points
// that 2 neighbours of the same colors have become linked and need to merged as well. So it's easier to just rebuild the entire facet
FacetReducer.rebuildForFacetChange(visitedArrayCache, facetToRemove, imgColorIndices, facetResult);
// now mark the facet to remove as deleted
facetResult.facets[facetToRemove.id] = null;
}
private static rebuildForFacetChange(visitedArrayCache: BooleanArray2D, facet: Facet, imgColorIndices: Uint8Array2D, facetResult: FacetResult) {
FacetReducer.rebuildChangedNeighbourFacets(visitedArrayCache, facet, imgColorIndices, facetResult);
// sanity check: make sure that all points have been replaced by neighbour facets. It's possible that some points will have
// been left out because there is no continuity with the neighbour points
// this occurs for diagonal points to the neighbours and more often when the closest
// color is chosen when distances are equal.
// It's probably possible to enforce that this will never happen in the above code but
// this is a constraint that is expensive to enforce and doesn't happen all that much
// so instead try and merge if with any of its direct neighbours if possible
let needsToRebuild = false;
for (let y: number = facet.bbox.minY; y <= facet.bbox.maxY; y++) {
for (let x: number = facet.bbox.minX; x <= facet.bbox.maxX; x++) {
if (facetResult.facetMap.get(x, y) === facet.id) {
console.warn(`Point ${x},${y} was reallocated to neighbours for facet ${facet.id}`);
needsToRebuild = true;
if (x - 1 >= 0 && facetResult.facetMap.get(x - 1, y) !== facet.id && facetResult.facets[facetResult.facetMap.get(x - 1, y)] !== null) {
imgColorIndices.set(x, y, facetResult.facets[facetResult.facetMap.get(x - 1, y)]!.color);
} else if (y - 1 >= 0 && facetResult.facetMap.get(x, y - 1) !== facet.id && facetResult.facets[facetResult.facetMap.get(x, y - 1)] !== null) {
imgColorIndices.set(x, y, facetResult.facets[facetResult.facetMap.get(x, y - 1)]!.color);
} else if (x + 1 < facetResult.width && facetResult.facetMap.get(x + 1, y) !== facet.id && facetResult.facets[facetResult.facetMap.get(x + 1, y)] !== null) {
imgColorIndices.set(x, y, facetResult.facets[facetResult.facetMap.get(x + 1, y)]!.color);
} else if (y + 1 < facetResult.height && facetResult.facetMap.get(x, y + 1) !== facet.id && facetResult.facets[facetResult.facetMap.get(x, y + 1)] !== null) {
imgColorIndices.set(x, y, facetResult.facets[facetResult.facetMap.get(x, y + 1)]!.color);
} else {
console.error(`Unable to reallocate point ${x},${y}`);
}
}
}
}
// now we need to go through the thing again to build facets and update the neighbours
if (needsToRebuild) {
FacetReducer.rebuildChangedNeighbourFacets(visitedArrayCache, facet, imgColorIndices, facetResult);
}
}
/**
* Determines the closest neighbour for a given pixel of a facet, based on the closest distance to the neighbour AND the when tied, the closest color
*/
private static getClosestNeighbourForPixel(facetToRemove: Facet, facetResult: FacetResult, x: number, y: number, colorDistances: number[][]) {
let closestNeighbour = -1;
let minDistance = Number.MAX_VALUE;
let minColorDistance = Number.MAX_VALUE;
// ensure the neighbour facets is up to date if it was marked as dirty
if (facetToRemove.neighbourFacetsIsDirty) {
FacetCreator.buildFacetNeighbour(facetToRemove, facetResult);
}
// determine which neighbour will receive the current point based on the distance, and if there are more with the same
// distance, then take the neighbour with the closes color
for (const neighbourIdx of facetToRemove.neighbourFacets!) {
const neighbour = facetResult.facets[neighbourIdx];
if (neighbour != null) {
for (const bpt of neighbour.borderPoints) {
const distance = bpt.distanceToCoord(x, y);
if (distance < minDistance) {
minDistance = distance;
closestNeighbour = neighbourIdx;
minColorDistance = Number.MAX_VALUE; // reset color distance
} else if (distance === minDistance) {
// if the distance is equal as the min distance
// then see if the neighbour's color is closer to the current color
// note: this causes morepoints to be reallocated to different neighbours
// in the sanity check later, but still yields a better visual result
const colorDistance = colorDistances[facetToRemove.color][neighbour.color];
if (colorDistance < minColorDistance) {
minColorDistance = colorDistance;
closestNeighbour = neighbourIdx;
}
}
}
}
}
return closestNeighbour;
}
/**
* Rebuilds the given changed facets
*/
private static rebuildChangedNeighbourFacets(visitedArrayCache: BooleanArray2D, facetToRemove: Facet, imgColorIndices: Uint8Array2D, facetResult: FacetResult) {
const changedNeighboursSet: IMap<boolean> = {};
if (facetToRemove.neighbourFacetsIsDirty) {
FacetCreator.buildFacetNeighbour(facetToRemove, facetResult);
}
for (const neighbourIdx of facetToRemove.neighbourFacets!) {
const neighbour = facetResult.facets[neighbourIdx];
if (neighbour != null) {
// re-evaluate facet
// track all the facets that needs to have their neighbour list updated, which is also going to be all the neighbours of the neighbours that are being updated
changedNeighboursSet[neighbourIdx] = true;
if (neighbour.neighbourFacetsIsDirty) {
FacetCreator.buildFacetNeighbour(neighbour, facetResult);
}
for (const n of neighbour.neighbourFacets!) {
changedNeighboursSet[n] = true;
}
// rebuild the neighbour facet
const newFacet = FacetCreator.buildFacet(neighbourIdx, neighbour.color, neighbour.borderPoints[0].x, neighbour.borderPoints[0].y, visitedArrayCache, imgColorIndices, facetResult);
facetResult.facets[neighbourIdx] = newFacet;
// it's possible that any of the neighbour facets are now overlapping
// because if for example facet Red - Green - Red, Green is removed
// then it will become Red - Red and both facets will overlap
// this means the facet will have 0 points remaining
if (newFacet.pointCount === 0) {
// remove the empty facet as well
facetResult.facets[neighbourIdx] = null;
}
}
}
// reset the visited array for all neighbours
// while the visited array could be recreated per facet to remove, it's quite big and introduces
// a lot of allocation / cleanup overhead. Due to the size of the facets it's usually faster
// to just flag every point of the facet as false again
if (facetToRemove.neighbourFacetsIsDirty) {
FacetCreator.buildFacetNeighbour(facetToRemove, facetResult);
}
for (const neighbourIdx of facetToRemove.neighbourFacets!) {
const neighbour = facetResult.facets[neighbourIdx];
if (neighbour != null) {
for (let y: number = neighbour.bbox.minY; y <= neighbour.bbox.maxY; y++) {
for (let x: number = neighbour.bbox.minX; x <= neighbour.bbox.maxX; x++) {
if (facetResult.facetMap.get(x, y) === neighbour.id) {
visitedArrayCache.set(x, y, false);
}
}
}
}
}
// rebuild neighbour array for affected neighbours
for (const k of Object.keys(changedNeighboursSet)) {
if (changedNeighboursSet.hasOwnProperty(k)) {
const neighbourIdx = parseInt(k);
const f = facetResult.facets[neighbourIdx];
if (f != null) {
// it's a lot faster when deferring the neighbour array updates
// because a lot of facets that are deleted share the same facet neighbours
// and removing the unnecessary neighbour array checks until they it's needed
// speeds things up significantly
// FacetCreator.buildFacetNeighbour(f, facetResult);
f.neighbourFacets = null;
f.neighbourFacetsIsDirty = true;
}
}
}
}
} | the_stack |
import React from 'react';
import {Node} from '../../pathfinding/algorithms/Node';
import {Point} from '../../pathfinding/core/Components';
import AppSettings from "../../utils/AppSettings";
import {HashTable, stringify} from '../../pathfinding/structures/Hash';
const CLOSED_NODE = 'rgb(198, 237, 238)';
const OPEN_NODE = 'rgb(191, 248, 159)';
const ARROW_COLOR = 'rgb(153,153,153)';
const EMPTY_NODE = 'e';
const TILE_CLASS = 'tile';
const VIZ_TILE_CLASS = 'tile-viz';
const BASE_WIDTH = 27;
interface Arrow {
to: Point,
from: Point
}
interface IProps {
settings: AppSettings,
tileWidth: number,
width: number,
height: number
}
//scores and visualization are parallel arrays
interface IState {
visualization: string[][],
arrows: HashTable<Arrow> //arrows are uniquely defined by where they point to
}
/**
* Represents a visualization canvas for the background grid
* Can be mutated using functions to change the state of the current visualization
*/
class GridVisualization extends React.Component<IProps,IState>
{
private readonly tileWidth: number;
private tileClass: string = TILE_CLASS;
/**
* Constructs a GridVisualization with immutable height and width
* @param props
*/
constructor(props: IProps) {
super(props);
this.tileWidth = this.props.tileWidth;
this.state = {
visualization: this.createEmptyViz(),
arrows: new HashTable()
}
}
/**
* Checks if new width and height props have been passed in
* If so, the Grid must be resized by coping the visualization a new 2d array
* with a different size (some elements will be empty or cut off)
* @param prevProps
*/
componentDidUpdate(prevProps: Readonly<IProps>) {
if(this.props.width !== prevProps.width
|| this.props.height !== prevProps.height)
{
const visualization: string[][] = this.createEmptyViz();
for(let y = 0; y < this.props.height; y++) {
for(let x = 0; x < this.props.width; x++) {
if(y < prevProps.height && x < prevProps.width) {
visualization[y][x] = this.state.visualization[y][x];
}
}
}
this.setState({
visualization: visualization
});
}
}
/**
* Create a new empty visualization canvas
*/
createEmptyViz() {
const visualization: string[][] = [];
for(let y = 0; y < this.props.height; y++) {
const row: string[] = [];
for(let x = 0; x < this.props.width; x++) {
row.push(EMPTY_NODE);
}
visualization.push(row);
}
return visualization;
}
/**
* Clear the visualization canvas and update UI
*/
clear() {
this.setState({
visualization: this.createEmptyViz(),
arrows: new HashTable()
});
}
/**
* Perform a generation on a visualization array
* @param generation
* @param visualization
*/
static doVizGeneration(generation: Node, visualization: string[][]) {
for(const node of generation.children) {
const point = node.tile.point;
visualization[point.y][point.x] = OPEN_NODE;
}
const point = generation.tile.point;
visualization[point.y][point.x] = CLOSED_NODE;
return visualization;
}
/**
* Visualize generation and update UI
* @param generation
*/
visualizeGeneration(generation: Node) {
this.setState(prevState => ({
visualization: GridVisualization.doVizGeneration(
generation,
clone(prevState.visualization)
)
}));
}
enableAnimations() {
this.tileClass = VIZ_TILE_CLASS;
}
disableAnimations() {
this.tileClass = TILE_CLASS;
}
/**
* Visualize generation array and update UI
* @param generations
*/
visualizeGenerations(generations: Node[]) {
const visualization = this.createEmptyViz();
for(const generation of generations) {
GridVisualization.doVizGeneration(generation, visualization);
}
this.setState({
visualization: visualization
});
}
/**
* Perform an arrow generation on an arrow array
* @param generation
* @param arrows
*/
static doArrowGeneration(generation: Node, arrows: HashTable<Arrow>) {
const point = generation.tile.point;
for(const node of generation.children) {
const childPoint = node.tile.point;
const newArrow = {
from: point,
to: childPoint,
};
//remove a duplicate arrow to indicate replacement
//in A* for example, we could have re-discovered a better path to a tile
arrows.add(stringify(newArrow.to), newArrow);
}
return arrows;
}
/**
* Add arrow generation without updating UI
* @param generation
*/
addArrowGeneration(generation: Node) {
this.setState(prevState => ({
arrows: GridVisualization.doArrowGeneration(
generation,
prevState.arrows.clone()
)
}));
}
/**
* Add arrow generations and update UI
* @param generations
*/
addArrowGenerations(generations: Node[]) {
const arrows: HashTable<Arrow> = new HashTable();
for(const generation of generations) {
GridVisualization.doArrowGeneration(generation, arrows)
}
this.setState({
arrows: arrows
});
}
/**
* Visualize both generation and arrows and update UI
* @param generation
*/
visualizeGenerationAndArrows(generation: Node) {
this.setState(prevState => ({
visualization: GridVisualization.doVizGeneration(
generation,
clone(prevState.visualization)
),
arrows: GridVisualization.doArrowGeneration(
generation,
prevState.arrows.clone()
)
}));
}
/**
* Renders the visualization in the background with the arrows in front
* Arrows may or may not be rendered
*/
render() {
return (
<div>
<div className='bg'>
{this.renderViz()}
</div>
<svg
xmlns='http://www.w3.org/2000/svg'
className='bg-grid'
>
<defs>
<marker
id='arrowhead'
markerWidth='3'
markerHeight='3'
refX='0'
refY='1.5'
orient='auto'
fill={ARROW_COLOR}
>
<polygon points='0 0, 3 1.5, 0 3'/>
</marker>
</defs>
{this.props.settings.showArrows ?
this.renderArrows() :
[]
}
</svg>
</div>
);
}
/**
* Renders the arrows showing the tree of the visualization
* Can only be properly displayed in the svg canvas with the arrowhead marker
*/
renderArrows() {
const width = this.tileWidth;
const offset = width/2;
const arrows: JSX.Element[] = [];
const arrowList = this.state.arrows.values();
for(let i = 0; i < arrowList.length; i++) {
//calculate arrow position and dimensions
const arrow = arrowList[i];
const first = arrow.from;
const second = arrow.to;
const firstX = first.x * width;
const firstY = first.y * width;
const secondX = second.x * width;
const secondY = second.y * width;
const offsetX = (secondX - firstX)/4;
const offsetY = (secondY - firstY)/4;
arrows.push(
<line
key={'arrow ' + i}
x1={firstX + offset + offsetX}
y1={firstY + offset + offsetY}
x2={secondX + offset - offsetX}
y2={secondY + offset - offsetY}
stroke={ARROW_COLOR}
strokeWidth={2 * this.tileWidth/BASE_WIDTH}
className='line-arrow'
markerEnd='url(#arrowhead)'
/>
);
}
return arrows;
}
/**
* Renders the visualization as a 2d array of jsx elements
* It is possible for the height and width props to be out of sync with the
* visualization array if the resize called after new props are passed in hasn't
* finished before render is called again.
* If this happens, any any out of bound visualizations are just empty
*/
renderViz() {
const tiles: JSX.Element[][] = [];
for(let y = 0; y < this.props.height; y++) {
const row: JSX.Element[] = [];
for(let x = 0; x < this.props.width; x++) {
const inBounds = (this.state.visualization[y]||[])[x] !== undefined;
const viz = inBounds ? this.state.visualization[y][x] : EMPTY_NODE;
if(viz !== EMPTY_NODE) {
const point = {
x: x, y: y
};
row.push(
this.renderTile(point, viz)
);
}
}
tiles.push(row);
}
return tiles;
}
/**
* Renders a single tile, that may be animated depending on the state
* @param point
* @param color
*/
renderTile(point: Point, color: string) {
const width = this.tileWidth;
const top = point.y * width;
const left = point.x * width;
const style = {
backgroundColor: color,
width: width + 'px',
height: width + 'px',
top: top,
left: left,
fontSize: 10 * width/BASE_WIDTH
};
return (
<div
key={point.x + ',' + point.y}
style={style}
className={this.tileClass}
/>
);
}
}
function clone<T>(array: T[][]) {
return array.map(
(arr) => arr.slice()
);
}
export default GridVisualization; | the_stack |
import * as chai from 'chai';
import * as path from 'path';
import { getLogger, Logger } from "../../../common/log";
import { TrialJobApplicationForm, TrialJobStatus } from '../../../common/trainingService';
import { cleanupUnitTest, delay, prepareUnitTest, uniqueString } from '../../../common/utils';
import { INITIALIZED, KILL_TRIAL_JOB, NEW_TRIAL_JOB, SEND_TRIAL_JOB_PARAMETER, TRIAL_END, GPU_INFO } from '../../../core/commands';
import { TrialConfigMetadataKey } from '../../../training_service/common/trialConfigMetadataKey';
import { Command, CommandChannel } from '../../../training_service/reusable/commandChannel';
import { Channel, EnvironmentInformation, EnvironmentService } from "../../../training_service/reusable/environment";
import { TrialDetail } from '../../../training_service/reusable/trial';
import { TrialDispatcher } from "../../../training_service/reusable/trialDispatcher";
import { UtCommandChannel } from './utCommandChannel';
import { UtEnvironmentService } from "./utEnvironmentService";
import chaiAsPromised = require("chai-as-promised");
import { promises } from 'fs';
import { Deferred } from 'ts-deferred';
import { NNIErrorNames, NNIError, MethodNotImplementedError } from '../../../common/errors';
function createTrialForm(content: any = undefined): TrialJobApplicationForm {
if (content === undefined) {
content = {
"test": 1
};
}
const trialForm = {
sequenceId: 0,
hyperParameters: {
value: JSON.stringify(content),
index: 0
}
};
return trialForm;
}
async function waitResult<TResult>(callback: () => Promise<TResult | undefined>, waitMs: number = 1000, interval: number = 1, throwError: boolean = false): Promise<TResult | undefined> {
while (waitMs > 0) {
const result = await callback();
if (result !== undefined) {
return result;
}
await delay(interval);
waitMs -= interval;
};
if (throwError) {
throw new Error(`wait result timeout!\n${callback.toString()}`);
}
return undefined;
}
async function waitResultMust<TResult>(callback: () => Promise<TResult | undefined>, waitMs: number = 10000, interval: number = 1): Promise<TResult> {
const result = await waitResult(callback, waitMs, interval, true);
// this error should be thrown in waitResult already.
if (result === undefined) {
throw new Error(`wait result timeout!`);
}
return result;
}
async function newTrial(trialDispatcher: TrialDispatcher): Promise<TrialDetail> {
const trialDetail = await trialDispatcher.submitTrialJob(createTrialForm());
return trialDetail;
}
function newGpuInfo(gpuCount: Number = 2, nodeId: string | undefined = undefined): any {
let gpuInfos = [];
for (let index = 0; index < gpuCount; index++) {
gpuInfos.push({
index: index,
activeProcessNum: 0,
});
}
const gpuInfo = {
gpuInfos: gpuInfos,
gpuCount: gpuInfos.length,
node: nodeId
}
return gpuInfo;
}
async function verifyTrialRunning(commandChannel: UtCommandChannel, trialDetail: TrialDetail): Promise<Command> {
let command = await waitResultMust<Command>(async () => {
return await commandChannel.testReceiveCommandFromTrialDispatcher();
});
chai.assert.equal(command.command, NEW_TRIAL_JOB, "verifyTrialRunning command type");
chai.assert.equal(command.data["trialId"], trialDetail.id, "verifyTrialRunning trialDetail.id should be equal.");
return command;
}
async function verifyTrialResult(commandChannel: UtCommandChannel, trialDetail: TrialDetail, returnCode: number = 0): Promise<void> {
let trialResult = {
trial: trialDetail.id,
code: returnCode,
timestamp: Date.now(),
};
if (trialDetail.environment === undefined) {
throw new Error(`environment shouldn't be undefined.`)
}
await commandChannel.testSendCommandToTrialDispatcher(trialDetail.environment, TRIAL_END, trialResult);
await waitResultMust<boolean>(async () => {
return trialDetail.status !== 'RUNNING' ? true : undefined;
});
if (returnCode === 0) {
chai.assert.equal<TrialJobStatus>(trialDetail.status, 'SUCCEEDED', "trial should be succeeded");
} else {
chai.assert.equal<TrialJobStatus>(trialDetail.status, 'FAILED', "trial should be failed");
}
}
async function waitEnvironment(waitCount: number,
previousEnvironments: Map<string, EnvironmentInformation>,
environmentService: UtEnvironmentService, commandChannel: UtCommandChannel,
gpuCount: number = 2, nodeCount: number = 1,
callback: ((environment: EnvironmentInformation) => Promise<void>) | undefined = undefined): Promise<EnvironmentInformation> {
const waitRequestEnvironment = await waitResultMust<EnvironmentInformation>(async () => {
const environments = environmentService.testGetEnvironments();
if (environments.size === waitCount) {
for (const [id, environment] of environments) {
if (!previousEnvironments.has(id)) {
previousEnvironments.set(id, environment);
return environment;
}
}
}
return undefined;
});
if (waitRequestEnvironment === undefined) {
throw new Error(`waitRequestEnvironment is not defined.`);
}
const nodeIds = [];
waitRequestEnvironment.nodeCount = nodeCount;
if (nodeCount > 1) {
for (let index = 0; index < nodeCount; index++) {
nodeIds.push(uniqueString(5));
}
} else {
nodeIds.push(undefined);
}
for (const nodeId of nodeIds) {
// set runner is ready.
await commandChannel.testSendCommandToTrialDispatcher(waitRequestEnvironment, INITIALIZED, { node: nodeId });
if (gpuCount > 0) {
await commandChannel.testSendCommandToTrialDispatcher(waitRequestEnvironment, GPU_INFO, newGpuInfo(gpuCount, nodeId));
}
}
if (callback) {
await callback(waitRequestEnvironment);
}
// set env to running
environmentService.testSetEnvironmentStatus(waitRequestEnvironment, 'RUNNING');
await waitResultMust<boolean>(async () => {
return waitRequestEnvironment.isRunnerReady ? true : undefined;
});
return waitRequestEnvironment;
}
const config: any = {
searchSpace: { },
trialCommand: 'echo hi',
trialCodeDirectory: path.dirname(__filename),
trialConcurrency: 0,
nniManagerIp: '127.0.0.1',
trainingService: {
platform: 'local'
},
debug: true
};
describe('Unit Test for TrialDispatcher', () => {
let trialRunPromise: Promise<void>;
let trialDispatcher: TrialDispatcher;
let commandChannel: UtCommandChannel;
let environmentService: UtEnvironmentService;
let log: Logger;
let previousEnvironments: Map<string, EnvironmentInformation> = new Map<string, EnvironmentInformation>();
const currentDir = path.dirname(__filename);
before(() => {
chai.should();
chai.use(chaiAsPromised);
prepareUnitTest();
log = getLogger();
});
after(() => {
cleanupUnitTest();
});
beforeEach(async () => {
trialDispatcher = await TrialDispatcher.construct(config);
// set ut environment
let environmentServiceList: EnvironmentService[] = [];
environmentService = new UtEnvironmentService();
environmentServiceList.push(environmentService);
trialDispatcher.environmentServiceList = environmentServiceList;
// set ut command channel
environmentService.initCommandChannel(trialDispatcher.commandEmitter);
commandChannel = environmentService.getCommandChannel as UtCommandChannel;
trialDispatcher.commandChannelSet = new Set<CommandChannel>().add(environmentService.getCommandChannel);
trialDispatcher.environmentMaintenceLoopInterval = 1000;
trialRunPromise = trialDispatcher.run();
});
afterEach(async () => {
previousEnvironments.clear();
await trialDispatcher.cleanUp();
environmentService.testReset();
await trialRunPromise;
});
it('reuse env', async () => {
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
trialDetail = await newTrial(trialDispatcher);
await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, -1);
chai.assert.equal(environmentService.testGetEnvironments().size, 1, "as env reused, so only 1 env should be here.");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('not reusable env', async () => {
//trialDispatcher.setClusterMetadata(
// TrialConfigMetadataKey.TRIAL_CONFIG,
// JSON.stringify({
// reuseEnvironment: false,
// codeDir: currentDir,
// }));
//let trialDetail = await newTrial(trialDispatcher);
//let environment = await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
//await verifyTrialRunning(commandChannel, trialDetail);
//await verifyTrialResult(commandChannel, trialDetail, 0);
//await waitResultMust<true>(async () => {
// return environment.status === 'USER_CANCELED' ? true : undefined;
//});
//trialDetail = await newTrial(trialDispatcher);
//await waitEnvironment(2, previousEnvironments, environmentService, commandChannel);
//await verifyTrialRunning(commandChannel, trialDetail);
//await verifyTrialResult(commandChannel, trialDetail, -1);
//chai.assert.equal(environmentService.testGetEnvironments().size, 2, "as env not reused, so only 2 envs should be here.");
//const trials = await trialDispatcher.listTrialJobs();
//chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('no more env', async () => {
const trialDetail1 = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
// set to no more environment
environmentService.testSetNoMoreEnvironment(false);
const trialDetail2 = await newTrial(trialDispatcher);
await verifyTrialRunning(commandChannel, trialDetail1);
await verifyTrialResult(commandChannel, trialDetail1, 0);
await verifyTrialRunning(commandChannel, trialDetail2);
await verifyTrialResult(commandChannel, trialDetail2, -1);
chai.assert.equal(environmentService.testGetEnvironments().size, 1, "as env not reused, so only 1 envs should be here.");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('2trial2env', async () => {
let trialDetail1 = await newTrial(trialDispatcher);
let trialDetail2 = await newTrial(trialDispatcher);
await waitEnvironment(2, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail1);
await verifyTrialResult(commandChannel, trialDetail1, 0);
await verifyTrialRunning(commandChannel, trialDetail2);
await verifyTrialResult(commandChannel, trialDetail2, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 2, "2 envs should be here.");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('3trial2env', async () => {
let trialDetail1 = await newTrial(trialDispatcher);
let trialDetail2 = await newTrial(trialDispatcher);
await waitEnvironment(2, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail1);
await verifyTrialResult(commandChannel, trialDetail1, 0);
await verifyTrialRunning(commandChannel, trialDetail2);
await verifyTrialResult(commandChannel, trialDetail2, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 2, "2 envs should be here.");
let trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
let trialDetail3 = await newTrial(trialDispatcher);
await verifyTrialRunning(commandChannel, trialDetail3);
await verifyTrialResult(commandChannel, trialDetail3, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 2, "2 envs should be here.");
trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 3, "there should be 2 trials");
});
it('stop trial', async () => {
let trialDetail1 = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail1);
await trialDispatcher.cancelTrialJob(trialDetail1.id, false);
let command = await waitResultMust<Command>(async () => {
return await commandChannel.testReceiveCommandFromTrialDispatcher();
});
chai.assert.equal(command.command, KILL_TRIAL_JOB);
log.info(`command: ${JSON.stringify(command)}`);
chai.assert.equal(command.data, trialDetail1.id);
await waitResultMust<boolean>(async () => {
return trialDetail1.status !== 'RUNNING' ? true : undefined;
});
let trialDetail2 = await newTrial(trialDispatcher);
await verifyTrialRunning(commandChannel, trialDetail2);
await trialDispatcher.cancelTrialJob(trialDetail2.id, true);
command = await waitResultMust<Command>(async () => {
return await commandChannel.testReceiveCommandFromTrialDispatcher();
});
chai.assert.equal(command.command, KILL_TRIAL_JOB);
log.info(`command: ${JSON.stringify(command)}`);
chai.assert.equal(command.data, trialDetail2.id);
await waitResultMust<boolean>(async () => {
return trialDetail2.status !== 'RUNNING' ? true : undefined;
});
chai.assert.equal(environmentService.testGetEnvironments().size, 1, "only one trial, so one env");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 1 stopped trial only");
let trial = await trialDispatcher.getTrialJob(trialDetail1.id);
chai.assert.equal<TrialJobStatus>(trial.status, 'USER_CANCELED', `trial is canceled.`);
trial = await trialDispatcher.getTrialJob(trialDetail2.id);
chai.assert.equal<TrialJobStatus>(trial.status, 'EARLY_STOPPED', `trial is earlier stopped.`);
});
it('multi phase', async () => {
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail);
let content = {
test: 2,
}
await trialDispatcher.updateTrialJob(trialDetail.id, createTrialForm(content));
let command = await waitResultMust<Command>(async () => {
return await commandChannel.testReceiveCommandFromTrialDispatcher();
});
chai.assert.equal(command.command, SEND_TRIAL_JOB_PARAMETER);
chai.assert.equal(command.data["trialId"], trialDetail.id);
chai.assert.equal(command.data.parameters.index, 0);
chai.assert.equal(command.data.parameters.value, JSON.stringify(content));
content = {
test: 3,
}
await trialDispatcher.updateTrialJob(trialDetail.id, createTrialForm(content));
command = await waitResultMust<Command>(async () => {
return await commandChannel.testReceiveCommandFromTrialDispatcher();
});
chai.assert.equal(command.command, SEND_TRIAL_JOB_PARAMETER);
chai.assert.equal(command.data["trialId"], trialDetail.id);
chai.assert.equal(command.data.parameters.index, 0);
chai.assert.equal(command.data.parameters.value, JSON.stringify(content));
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 1, "only one trial, so one env");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 1, "there should be 1 stopped trial only");
});
it('multi node', async () => {
let trialDetail = await newTrial(trialDispatcher);
const environment = await waitEnvironment(1, previousEnvironments, environmentService, commandChannel, 2, 2);
log.debug(`environment ${JSON.stringify(environment)}`);
await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(environment.nodes.size, 2);
let command = await waitResultMust<Command>(async () => {
return await commandChannel.testReceiveCommandFromTrialDispatcher();
});
chai.assert.equal(command.command, KILL_TRIAL_JOB);
chai.assert.equal(environmentService.testGetEnvironments().size, 1, "only one trial, so one env");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 1, "there should be 1 stopped trial only");
});
it('env timeout', async () => {
let trialDetail = await newTrial(trialDispatcher);
let environment = await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
environmentService.testSetEnvironmentStatus(environment, 'SUCCEEDED');
await waitResultMust<boolean>(async () => {
return environment.status === 'SUCCEEDED' ? true : undefined;
});
trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(2, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(previousEnvironments.size, 2, "as an env timeout, so 2 envs should be here.");
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('env failed with trial', async () => {
let trialDetail = await newTrial(trialDispatcher);
let environment = await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
await verifyTrialRunning(commandChannel, trialDetail);
environmentService.testSetEnvironmentStatus(environment, 'FAILED');
await waitResultMust<boolean>(async () => {
return environment.status === 'FAILED' ? true : undefined;
});
await waitResultMust<boolean>(async () => {
return trialDetail.status === 'FAILED' ? true : undefined;
});
chai.assert.equal<TrialJobStatus>(trialDetail.status, 'FAILED', "env failed, so trial also failed.");
});
/* FIXME: setClusterMetadata
it('GPUScheduler disabled gpuNum === undefined', async () => {
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
const command = await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(command.data["gpuIndices"], undefined);
});
it('GPUScheduler disabled gpuNum === 0', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 0,
}));
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
const command = await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(command.data["gpuIndices"], "");
});
it('GPUScheduler enable no cluster gpu config', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 1,
}));
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
const command = await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(command.data["gpuIndices"], "0");
});
it('GPUScheduler skipped no GPU info', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
}));
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
const command = await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(command.data["gpuIndices"], undefined);
});
it('GPUScheduler disabled multi-node', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 0,
}));
let trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
const command = await verifyTrialRunning(commandChannel, trialDetail);
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(command.data["gpuIndices"], "");
});
it('GPUScheduler enabled 2 gpus 2 trial', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 1,
}));
const trialDetail1 = await newTrial(trialDispatcher);
const trialDetail2 = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
let command = await verifyTrialRunning(commandChannel, trialDetail1);
chai.assert.equal(command.data["gpuIndices"], "0");
command = await verifyTrialRunning(commandChannel, trialDetail2);
chai.assert.equal(command.data["gpuIndices"], "1");
await verifyTrialResult(commandChannel, trialDetail1, 0);
await verifyTrialResult(commandChannel, trialDetail2, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 1);
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('GPUScheduler enabled 4 gpus 2 trial(need 2 gpus)', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 2,
}));
const trialDetail1 = await newTrial(trialDispatcher);
const trialDetail2 = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel, 4);
let command = await verifyTrialRunning(commandChannel, trialDetail1);
chai.assert.equal(command.data["gpuIndices"], "0,1");
command = await verifyTrialRunning(commandChannel, trialDetail2);
chai.assert.equal(command.data["gpuIndices"], "2,3");
await verifyTrialResult(commandChannel, trialDetail1, 0);
await verifyTrialResult(commandChannel, trialDetail2, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 1);
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, "there should be 2 trials");
});
it('GPUScheduler enabled use 4 gpus but only 1 usable(4)', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 1,
}));
const trialDetail = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel, 4, 1, async (environment) => {
environment.usableGpus = [3];
});
let command = await verifyTrialRunning(commandChannel, trialDetail);
chai.assert.equal(command.data["gpuIndices"], "3");
await verifyTrialResult(commandChannel, trialDetail, 0);
chai.assert.equal(environmentService.testGetEnvironments().size, 1);
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 1);
});
it('GPUScheduler enabled TMP_NO_AVAILABLE_GPU, request new env', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 1,
}));
const trialDetail1 = await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel, 1);
let command = await verifyTrialRunning(commandChannel, trialDetail1);
chai.assert.equal(command.data["gpuIndices"], "0");
const trialDetail2 = await newTrial(trialDispatcher);
await waitEnvironment(2, previousEnvironments, environmentService, commandChannel, 1);
await verifyTrialResult(commandChannel, trialDetail1, 0);
command = await verifyTrialRunning(commandChannel, trialDetail2);
await verifyTrialResult(commandChannel, trialDetail2, 0);
chai.assert.equal(command.data["gpuIndices"], "0");
chai.assert.equal(environmentService.testGetEnvironments().size, 2, 'environments');
const trials = await trialDispatcher.listTrialJobs();
chai.assert.equal(trials.length, 2, 'trials');
});
it('GPUScheduler enabled REQUIRE_EXCEED_TOTAL, need fail', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 8,
}));
await newTrial(trialDispatcher);
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel);
await chai.expect(trialRunPromise).rejectedWith(NNIError, "REQUIRE_EXCEED_TOTAL");
const deferred = new Deferred<void>();
trialRunPromise = deferred.promise;
deferred.resolve();
});
it('GPUScheduler enabled maxTrialNumberPerGpu=2, 4 trials, 2 gpus', async () => {
trialDispatcher.setClusterMetadata(
TrialConfigMetadataKey.TRIAL_CONFIG,
JSON.stringify({
reuseEnvironment: false,
codeDir: currentDir,
gpuNum: 1,
}));
const trials = [];
// last two trials shouldn't be in first environment.
for (let index = 0; index < 6; index++) {
const trial = await newTrial(trialDispatcher);
trials.push(trial);
}
await waitEnvironment(1, previousEnvironments, environmentService, commandChannel, 2, 1, async (environment) => {
environment.maxTrialNumberPerGpu = 2;
});
await waitEnvironment(2, previousEnvironments, environmentService, commandChannel, 2, 1, async (environment) => {
environment.maxTrialNumberPerGpu = 2;
});
const gpuIndexMap = new Map<string, number>();
for (let index = 0; index < 6; index++) {
const trial = trials[index];
let command = await verifyTrialRunning(commandChannel, trial);
const gpuIndex = command.data["gpuIndices"];
const trialNumbers = gpuIndexMap.get(gpuIndex);
if (index < 4) {
if (undefined === trialNumbers) {
gpuIndexMap.set(gpuIndex, 1);
} else {
gpuIndexMap.set(gpuIndex, trialNumbers + 1);
}
}
}
chai.assert.equal(gpuIndexMap.size, 2);
chai.assert.equal(gpuIndexMap.get("0"), 2);
chai.assert.equal(gpuIndexMap.get("1"), 2);
for (let index = 0; index < 6; index++) {
const trial = trials[index];
await verifyTrialResult(commandChannel, trial, 0);
}
chai.assert.equal(environmentService.testGetEnvironments().size, 2);
const listedTrials = await trialDispatcher.listTrialJobs();
chai.assert.equal(listedTrials.length, 6);
});
*/
}); | the_stack |
import dynamicProto from "@microsoft/dynamicproto-js";
import {
removeInvalidElements,
walkUpDomChainWithElementValidation,
extend, isValueAssigned
} from "../common/Utils";
import { IDiagnosticLogger, eLoggingSeverity, getDocument, isNullOrUndefined, hasDocument, _throwInternal, _eInternalMessageId } from "@microsoft/applicationinsights-core-js";
import { IClickAnalyticsConfiguration, IContent, IContentHandler } from "../Interfaces/Datamodel";
const MAX_CONTENTNAME_LENGTH = 200;
export class DomContentHandler implements IContentHandler {
/**
* @param config - ClickAnalytics configuration object
* @param traceLogger - Trace logger to log to console.
*/
constructor(protected _config: IClickAnalyticsConfiguration, protected _traceLogger: IDiagnosticLogger) {
dynamicProto(DomContentHandler, this, (_self) => {
_self.getMetadata = (): { [name: string]: string } => {
let dataTags = (_self._config || {}).dataTags;
let metaTags = {};
if (hasDocument) {
metaTags = isValueAssigned(dataTags.metaDataPrefix) ? _getMetaDataFromDOM(dataTags.captureAllMetaDataContent, dataTags.metaDataPrefix, false) :
_getMetaDataFromDOM(dataTags.captureAllMetaDataContent ,"", false);
}
return metaTags;
};
_self.getElementContent = (element: Element): IContent => {
if (!element) {
return {};
}
let dataTags = (_self._config || {}).dataTags;
let elementContent: any = {};
let biBlobValue;
let parentDataTagPrefix;
const dataTagPrefix:string = dataTags.customDataPrefix;
const aiBlobAttributeTag:string = dataTagPrefix + dataTags.aiBlobAttributeTag;
if(isValueAssigned(dataTags.parentDataTag)) {
parentDataTagPrefix = dataTagPrefix + dataTags.parentDataTag;
}
if (!_isTracked(element, dataTagPrefix, aiBlobAttributeTag)) {
// capture blob from element or hierarchy
biBlobValue = element.getAttribute(aiBlobAttributeTag);
if (biBlobValue) {
try {
elementContent = JSON.parse(biBlobValue);
} catch (e) {
_throwInternal(_self._traceLogger,
eLoggingSeverity.CRITICAL,
_eInternalMessageId.CannotParseAiBlobValue, "Can not parse " + biBlobValue
);
}
} else {
// traverse up the DOM to find the closest parent with data-* tag defined
//contentElement = walkUpDomChainWithElementValidation(element, _self._isTracked, dataTagPrefix);
elementContent = extend(elementContent, _populateElementContent(element, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag));
}
} else {
elementContent = extend(elementContent, _populateElementContentwithDataTag(element, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag));
}
removeInvalidElements(elementContent);
if (parentDataTagPrefix) {
elementContent = extend(elementContent, _getParentDetails(element, elementContent, dataTagPrefix, aiBlobAttributeTag ));
}
return elementContent;
};
/**
* Capture current level Element content
*/
function _captureElementContentWithDataTag(contentElement: Element, elementContent: any, dataTagPrefix: string) {
for (var i = 0, attrib; i < contentElement.attributes.length; i++) {
attrib = contentElement.attributes[i];
if ( attrib.name.indexOf(dataTagPrefix) !== 0 ) {
continue;
}
var attribName = attrib.name.replace(dataTagPrefix, "");
elementContent[attribName] = attrib.value;
}
}
/**
* Walk Up the DOM to capture Element content
*/
function _walkUpDomChainCaptureData(el: Element, elementContent: any, dataTagPrefix: string, parentDataTagPrefix: string, aiBlobAttributeTag: string ): void {
let element = el;
let parentDataTagFound: boolean = false;
let elementLevelFlag: boolean = false; // Use this flag to capture 'id' only at the incoming html element level.
while(!isNullOrUndefined(element) && !isNullOrUndefined(element.attributes)) {
let attributes=element.attributes;
for (let i = 0; i < attributes.length; i++) {
const attrib = attributes[i];
if ( attrib.name.indexOf(dataTagPrefix) !== 0 ) {
continue;
}
if (attrib.name.indexOf(parentDataTagPrefix) === 0) {
parentDataTagFound = true;
}
// Todo handle blob data
if (attrib.name.indexOf(aiBlobAttributeTag) === 0) {
continue;
}
const attribName = attrib.name.replace(dataTagPrefix, "");
if (elementLevelFlag && attribName === "id") {
continue; // skip capturing id if not at the first level.
}
if (!isValueAssigned(elementContent[attribName])) {
elementContent[attribName] = attrib.value;
}
}
// break after current level;
if (parentDataTagFound) {
break;
}
elementLevelFlag = true; // after the initial level set this flag to true.
element = (element.parentNode as Element);
}
}
/**
* Capture Element content along with Data Tag attributes and values
*/
function _populateElementContent(element: Element, dataTagPrefix: string, parentDataTagPrefix: string, aiBlobAttributeTag: string) {
let elementContent: any = {};
if(!element) {
return elementContent;
}
let htmlContent = _getHtmlIdAndContentName(element);
elementContent = {
id: htmlContent.id || "",
contentName: htmlContent.contentName || ""
};
if(isValueAssigned(parentDataTagPrefix)) {
_walkUpDomChainCaptureData(element, elementContent, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag);
}
// Validate to ensure the minimum required field 'id' or 'contentName' is present.
// The content schema defines id, aN and sN as required fields. However,
// requiring these fields would result in majority of adopter's content from being collected.
// Just throw a warning and continue collection.
if (!elementContent.id && !elementContent.contentName) {
_throwInternal(_traceLogger,
eLoggingSeverity.WARNING,
_eInternalMessageId.InvalidContentBlob, "Invalid content blob. Missing required attributes (id, contentName. " +
" Content information will still be collected!"
)
}
return elementContent;
}
/**
* Capture Element content along with Data Tag attributes and values
*/
function _populateElementContentwithDataTag(element: Element, dataTagPrefix: string, parentDataTagPrefix: string, aiBlobAttributeTag: string) {
let dataTags = (_self._config || {}).dataTags;
let elementContent: any = {};
if(!element) {
return elementContent;
}
let htmlContent = _getHtmlIdAndContentName(element);
if(isValueAssigned(parentDataTagPrefix)) {
_walkUpDomChainCaptureData(element, elementContent, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag);
} else {
_captureElementContentWithDataTag(element, elementContent, dataTagPrefix);
}
if (dataTags.useDefaultContentNameOrId) {
if(!isValueAssigned(elementContent.id)) {
elementContent.id = htmlContent.id || "";
}
elementContent.contentName = htmlContent.contentName || "";
}
// Validate to ensure the minimum required field 'id' or 'contentName' is present.
// The content schema defines id, aN and sN as required fields. However,
// requiring these fields would result in majority of adopter's content from being collected.
// Just throw a warning and continue collection.
if (!elementContent.id && !elementContent.contentName) {
_throwInternal(_traceLogger,
eLoggingSeverity.WARNING,
_eInternalMessageId.InvalidContentBlob, "Invalid content blob. Missing required attributes (id, contentName. " +
" Content information will still be collected!"
)
}
return elementContent;
}
/**
* Retrieve a specified metadata tag value from the DOM.
* @param captureAllMetaDataContent - Flag to capture all metadata content
* @param prefix - Prefix to search the metatags with.
* @param removePrefix - Specifies if the prefix must be excluded from key names in the returned collection.
* @returns Metadata collection/property bag
*/
function _getMetaDataFromDOM(captureAllMetaDataContent:boolean, prefix: string, removePrefix: boolean): { [name: string]: string } {
var metaElements: any;
var metaData = {};
if (hasDocument) {
metaElements = document.querySelectorAll("meta");
for (var i = 0; i < metaElements.length; i++) {
var meta = metaElements[i];
if (meta.name) {
if(captureAllMetaDataContent || meta.name.indexOf(prefix) === 0) {
const name = removePrefix ? meta.name.replace(prefix, "") : meta.name;
metaData[name] = meta.content;
}
}
}
}
return metaData;
}
/**
* Gets the default content name.
* @param element - An html element
* @param useDefaultContentNameOrId -Flag indicating if an element is market PII.
* @returns Content name
*/
function _getDefaultContentName(element: any, useDefaultContentName: boolean) {
if (useDefaultContentName === false || !element.tagName) {
return "";
}
var doc = getDocument() || ({} as Document);
var contentName;
switch (element.tagName) {
case "A":
contentName = doc.all ? element.innerText || element.innerHTML : element.text || element.innerHTML;
break;
case "IMG":
case "AREA":
contentName = element.alt;
break;
default:
contentName = element.value || element.name || element.alt || element.innerText || element.id;
}
return contentName.substring(0, MAX_CONTENTNAME_LENGTH);
}
/**
* Check if the user wants to track the element, which means if the element has any tags with data-* or customDataPrefix
* @param element - An html element
* @returns true if any data-* exist, otherwise return false
*/
function _isTracked(element: Element, dataTag: string, aiBlobAttributeTag: string): boolean {
const attrs = element.attributes;
let dataTagFound = false;
for (let i = 0; i < attrs.length; i++) {
const attributeName = attrs[i].name;
if(attributeName === aiBlobAttributeTag) {
// ignore if the attribute name is equal to aiBlobAttributeTag
return false;
} else if (attributeName.indexOf(dataTag) === 0) {
dataTagFound = true;
}
}
return dataTagFound;
}
function _getHtmlIdAndContentName(element:Element) {
let dataTags = (_self._config || {}).dataTags;
let callback = (_self._config || {}).callback;
let htmlContent: any = {};
if(!element) {
return htmlContent;
}
if (dataTags.useDefaultContentNameOrId) {
const customizedContentName = callback.contentName ? callback.contentName(element, dataTags.useDefaultContentNameOrId) : "";
const defaultContentName = _getDefaultContentName(element, dataTags.useDefaultContentNameOrId);
htmlContent = {
id: element.id,
contentName: customizedContentName || defaultContentName || element.getAttribute("alt")
};
}
return htmlContent;
}
/**
* Computes the parentId of a given element.
* @param element - An html element
* @returns An object containing the closest parentId , can be empty if nothing was found
*/
function _getParentDetails(element: Element, elementContent: any, dataTagPrefix: string, aiBlobAttributeTag: string): IContent {
const parentId = elementContent["parentid"];
const parentName = elementContent["parentname"];
let parentInfo = {};
if (parentId || parentName || !element) {
return parentInfo;
}
return _populateParentInfo(element, dataTagPrefix, aiBlobAttributeTag);
}
/**
* Check if parent info already set up, if so take and put into content, if not walk up the DOM to find correct info
* @param element - An html element that the user wants to track
* @returns An object containing the parent info, can be empty if nothing was found
*/
function _populateParentInfo(element: Element, dataTagPrefix: string, aiBlobAttributeTag: string): IContent {
let parentInfo: IContent = {};
let parentId;
// if the user does not set up parent info, walk to the DOM, find the closest parent element (with tags) and populate the info
const closestParentElement = walkUpDomChainWithElementValidation(element.parentElement, _isTracked, dataTagPrefix);
if (closestParentElement) {
const dataAttr = closestParentElement.getAttribute(aiBlobAttributeTag) || element[aiBlobAttributeTag];
if (dataAttr) {
try {
var telemetryObject = JSON.parse(dataAttr);
} catch (e) {
_throwInternal(_traceLogger,
eLoggingSeverity.CRITICAL,
_eInternalMessageId.CannotParseAiBlobValue, "Can not parse " + dataAttr
);
}
if (telemetryObject) {
parentId = telemetryObject.id;
}
} else {
parentId = closestParentElement.getAttribute(dataTagPrefix+"id");
}
}
if (parentId) {
parentInfo["parentid"] = parentId;
} else {
let htmlContent= _getHtmlIdAndContentName(element.parentElement);
parentInfo["parentid"] = htmlContent.id;
parentInfo["parentname"] = htmlContent.contentName;
}
return parentInfo;
}
});
}
/**
* Collect metatags from DOM.
* Collect data from meta tags.
* @returns {object} - Metatags collection/property bag
*/
public getMetadata(): { [name: string]: string } {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
/**
* Collect data-* attributes for the given element.
* All attributes with data-* prefix or user provided customDataPrefix are collected.'data-*' prefix is removed from the key name.
* @param element - The element from which attributes need to be collected.
* @returns String representation of the Json array of element attributes
*/
public getElementContent(element: Element): IContent {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
} | the_stack |
import * as TE from 'fp-ts/lib/TaskEither';
import * as Q from '../../src/Query';
import * as S from '../../src/Strategy';
import { param, command } from '../../src/DSL';
import { observeShallow } from '../../src/observe';
import {
declareQueries,
WithQueries,
useQuery,
useQueries
} from '../../src/react';
import * as React from 'react';
import * as QR from '../../src/QueryResult';
import { invalidate } from '../../src/invalidate';
import { ProductA } from '../../src/util';
declare const af: (input: string) => TE.TaskEither<string, number>;
declare const as: S.Strategy<string, string, number>;
const a = Q.query(af)(as); // $ExpectType CachedQuery<string, string, number>
declare const bf: () => TE.TaskEither<string, number>;
// tslint:disable-next-line:invalid-void
declare const bs: S.Strategy<void, string, number>;
const b = Q.query(bf)(bs); // $ExpectType CachedQuery<void, string, number>
declare const cf: (input: number) => TE.TaskEither<string, boolean>;
declare const cs: S.Strategy<number, string, boolean>;
const c = Q.query(cf)(cs); // $ExpectType CachedQuery<number, string, boolean>
declare const df: (input: number) => TE.TaskEither<number, boolean>;
declare const ds: S.Strategy<number, number, boolean>;
const d = Q.query(df)(ds); // $ExpectType CachedQuery<number, number, boolean>
declare const ef: (input: string) => TE.TaskEither<number, boolean>;
declare const es: S.Strategy<string, number, boolean>;
const e = Q.query(ef)(es); // $ExpectType CachedQuery<string, number, boolean>
// $ExpectType Composition<string, string, boolean>
const composeac = Q.compose(a, c);
// $ExpectType Composition<string, string | number, boolean>
const composead = Q.compose(a, d);
const composeae = Q.compose(
a,
e // $ExpectError
);
// $expectType Composition<never, string, boolean>
const composebc = Q.compose(b, c);
interface Loc {
pathname: string;
search: Record<string, string>;
}
// tslint:disable-next-line:invalid-void
declare const location: Q.ObservableQuery<void, void, Loc>;
interface View {
view: string;
}
declare function locationToView(location: Loc): View;
// $ExpectType Composition<void, void, View>
const currentView = Q.compose(
location,
Q.queryStrict(
// tslint:disable-next-line:invalid-void
location => TE.taskEither.of<void, View>(locationToView(location)),
S.refetch
)
);
// $ExpectType Product<{} & { a: string; c: number; }, string, ProductP<{ a: CachedQuery<string, string, number>; c: CachedQuery<number, string, boolean>; }>>
const productac = Q.product({ a, c });
// tslint:disable-next-line:max-line-length
// $flaky-ExpectType Product<{} & { a: string; c: number; e: string; }, ProductL<{ a: CachedQuery<string, string, number>; c: CachedQuery<number, string, boolean>; e: CachedQuery<string, number, boolean>; }>, ProductP<{ a: CachedQuery<string, string, number>; c: CachedQuery<number, string, boolean>; e: CachedQuery<string, number, boolean>; }>>
const productace = Q.product({ a, c, e });
// $ExpectType Product<{ b?: undefined; } & { a: string; }, string, ProductP<{ a: CachedQuery<string, string, number>; b: CachedQuery<void, string, number>; }>>
const productab = Q.product({ a, b });
observeShallow(productab, { a: 'foo' });
// $ExpectError
observeShallow(productab, { b: 1, a: 'foo' });
// tslint:disable-next-line:invalid-void
declare function getToken(): TE.TaskEither<void, string>;
interface Post {
id: number;
content: { title: string; body: string };
}
type InvalidToken = 'invalid token';
type NotFound = 'not found';
declare function getPosts(input: {
token: string;
limit: number;
}): TE.TaskEither<InvalidToken, Post[]>;
type PostWithTags = Post & { tags: string[] };
const token = Q.queryShallow(getToken, S.available);
const postId = param<Post['id']>();
const limit = param<number>();
const posts = Q.compose(
Q.product({ token, limit }),
Q.queryShallow(getPosts, S.expire(2000))
);
declare function _addTags(input: {
token: string;
postId: number;
posts: Post[];
}): TE.TaskEither<InvalidToken | NotFound, PostWithTags>;
const addTags = Q.queryShallow(_addTags, S.expire(2000));
// tslint:disable-next-line:max-line-length
// $flaky-ExpectType Composition<{ token?: undefined; } & { postId: number; posts: { token?: undefined; } & { limit: number; }; }, void | "invalid token" | "not found", PostWithTags>
const postWithTags = Q.compose(Q.product({ token, postId, posts }), addTags);
const declareA = declareQueries({ a });
declareA.InputProps; // $ExpectType { queries: {} & { a: string; }; }
declareA.Props; // $ExpectType QueryOutputProps<string, ProductP<{ a: CachedQuery<string, string, number>; }>>
declare const CA: React.ComponentType<{
queries: QR.QueryResult<string, { a: number }>;
}>;
const DCA = declareA(CA);
<DCA queries={{ a: 'foo' }} />;
<DCA />; // $ExpectError
<DCA queries={{ a: 1 }} />; // $ExpectError
declare const CAA: React.ComponentType<{
queries: QR.QueryResult<string, { a: number }>;
foo: number;
}>;
const DCAA = declareA(CAA);
<DCAA queries={{ a: 'foo' }} foo={1} />;
<DCAA queries={{ a: 'foo' }} />; // $ExpectError
<DCAA foo={1} />; // $ExpectError
<DCAA queries={{ a: 1 }} foo={1} />; // $ExpectError
const declareB = declareQueries({ b });
declareB.InputProps; // $ExpectType {}
declareB.Props; // $ExpectType QueryOutputProps<string, ProductP<{ b: CachedQuery<void, string, number>; }>>
declare const CB: React.ComponentType<{
queries: QR.QueryResult<string, { b: number }>;
}>;
const DCB = declareB(CB);
<DCB queries={undefined} />; // $ExpectError
<DCB />;
declare const CBB: React.ComponentType<{
queries: QR.QueryResult<string, { b: number }>;
foo: number;
}>;
const DCBB = declareB(CBB);
<DCBB queries={{}} foo={1} />; // $ExpectError
<DCBB queries={{}} />; // $ExpectError
<DCBB foo={1} />;
const declareAB = declareQueries({ a, b });
declareAB.InputProps; // $ExpectType { queries: { b?: undefined; } & { a: string; }; }
declareAB.Props; // $ExpectType QueryOutputProps<string, ProductP<{ a: CachedQuery<string, string, number>; b: CachedQuery<void, string, number>; }>>
declare const AB: React.ComponentType<{
queries: QR.QueryResult<string, { a: number; b: number }>;
}>;
const DAB = declareAB(AB);
<DAB queries={{}} />; // $ExpectError
<DAB />; // $ExpectError
<DAB queries={{ a: 'foo' }} />;
invalidate({ a }, { a: 'foo' }); // $ExpectType TaskEither<string, ProductP<{ a: CachedQuery<string, string, number>; }>>
invalidate({ a }, {}); // $ExpectError
invalidate({ a }); // $ExpectError
invalidate({ b }, {}); // $ExpectError
invalidate({ b }); // $ExpectType TaskEither<string, ProductP<{ b: CachedQuery<void, string, number>; }>>
invalidate({ a, b }, {}); // $ExpectError
invalidate({ a, b }, { a: 'foo' }); // $ExpectType TaskEither<string, ProductP<{ a: CachedQuery<string, string, number>; b: CachedQuery<void, string, number>; }>>
declare const caf: (input: string) => TE.TaskEither<string, number>;
declare const cbf: (input: number) => TE.TaskEither<string, number>;
const cmdcaf = command(caf); // $ExpectType (a: string, ia?: undefined) => TaskEither<string, number>
cmdcaf('foo'); // $ExpectType TaskEither<string, number>
command(caf, {}); // $ExpectError
const cmda = command(caf, { a }); // $ExpectType (a: string, ia: {} & { a: string; }) => TaskEither<string, number>
cmda(1, { a: 'foo' }); // $ExpectError
cmda('foo', {}); // $ExpectError
cmda('foo'); // $ExpectError
cmda('foo', { a: 'foo' });
const cmdb = command(cbf, { b }); // $ExpectType (a: number, ia?: void | undefined) => TaskEither<string, number>
cmdb('foo', {}); // $ExpectError
cmdb('foo'); // $ExpectError
cmdb('foo', { b: 1 }); // $ExpectError
cmdb(1);
// tslint:disable-next-line:interface-over-type-literal
type RA = {
// tslint:disable-next-line:invalid-void
a: Q.ObservableQuery<string, void, number>;
// tslint:disable-next-line:invalid-void
b: Q.ObservableQuery<void, void, number>;
};
type PA = ProductA<RA>; // $ExpectType { b?: undefined; } & { a: string; }
// tslint:disable-next-line:interface-over-type-literal
type RB = {
// tslint:disable-next-line:invalid-void
a: Q.ObservableQuery<void, void, number>;
// tslint:disable-next-line:invalid-void
b: Q.ObservableQuery<void, void, number>;
};
type PB = ProductA<RB>; // $ExpectType void
// tslint:disable-next-line:interface-over-type-literal
type RC = {
// tslint:disable-next-line:invalid-void
a: Q.ObservableQuery<string, void, number>;
// tslint:disable-next-line:invalid-void
b: Q.ObservableQuery<number, void, number>;
};
type PC = ProductA<RC>; // $ExpectType {} & { a: string; b: number; }
declare const q1: Q.ObservableQuery<{ a: string }, string, string>;
declare const q2: Q.ObservableQuery<{ b: number }, string, string>;
declare const q3: Q.ObservableQuery<void, string, string>;
<WithQueries
queries={{ q1, q2 }}
params={{ q: { a: 'ciao' }, q2: { b: 2 } }} // $ExpectError
render={QR.fold(
() => null,
() => null,
({ q1, q2 }) => (
<span>{`${q1}: ${q2}`}</span>
)
)}
/>;
<WithQueries
queries={{ q1, q2 }}
params={{ q1: { a: 2 }, q2: { b: 2 } }} // $ExpectError
render={QR.fold(
() => null,
() => null,
({ q1, q2 }) => (
<span>{`${q1}: ${q2}`}</span>
)
)}
/>;
<WithQueries
queries={{ q2 }}
params={{ q2: { b: 2 } }}
render={QR.fold(
() => null,
() => null,
(
{ q } // $ExpectError
) => (
<span>{q}</span>
)
)}
/>;
<WithQueries
queries={{ q3 }}
params={{ q3: undefined }} // $ExpectError
render={QR.fold(
() => null,
() => null,
({ q3 }) => (
<span>{q3}</span>
)
)}
/>;
<WithQueries
queries={{ q3, q4: q3 }}
render={QR.fold(
() => null,
() => null,
({ q3, q4 }) => (
<span>{`${q3}-${q4}`}</span>
)
)}
/>;
useQuery(a); // $ExpectError
useQuery(b); // $ExpectType QueryResult<string, number>
useQuery(b, 3); // $ExpectError
useQuery(b, undefined); // $ExpectType QueryResult<string, number>
useQueries({ a }); // $ExpectError
useQueries({ b }); // $ExpectType QueryResult<string, ProductP<{ b: CachedQuery<void, string, number>; }>>
useQueries({ b }, { b: 3 }); // $ExpectError
useQueries({ b }, undefined); // $ExpectType QueryResult<string, ProductP<{ b: CachedQuery<void, string, number>; }>> | the_stack |
import * as path from 'path';
import { join as pathJoin } from 'path';
import { ConfigFile, Connection, fs, Logger, Org, SfdxError } from '@salesforce/core';
import { Dictionary, Optional } from '@salesforce/ts-types';
import { Duration, env, sleep, toNumber } from '@salesforce/kit';
import MetadataRegistry = require('./metadataRegistry');
type MemberRevision = {
serverRevisionCounter: number;
lastRetrievedFromServer: number;
memberType: string;
isNameObsolete: boolean;
};
type SourceMember = {
MemberType: string;
MemberName: string;
IsNameObsolete: boolean;
RevisionCounter: number;
};
export type ChangeElement = {
name: string;
type: string;
deleted?: boolean;
};
export namespace RemoteSourceTrackingService {
// Constructor Options for RemoteSourceTrackingService.
export interface Options extends ConfigFile.Options {
username: string;
}
}
/**
* This service handles source tracking of metadata between a local project and an org.
* Source tracking state is persisted to .sfdx/orgs/<username>/maxRevision.json.
* This JSON file keeps track of `SourceMember` objects and the `serverMaxRevisionCounter`,
* which is the highest `serverRevisionCounter` value of all the tracked elements.
*
* Each SourceMember object has 4 fields:
* serverRevisionCounter: the current RevisionCounter on the server for this object
* lastRetrievedFromServer: the RevisionCounter last retrieved from the server for this object
* memberType: the metadata name of the SourceMember
* isNameObsolete: `true` if this object has been deleted in the org
*
* ex.
```
{
serverMaxRevisionCounter: 3,
sourceMembers: {
ApexClass__MyClass: {
serverRevisionCounter: 3,
lastRetrievedFromServer: 2,
memberType: ApexClass,
isNameObsolete: false
},
CustomObject__Student__c: {
serverRevisionCounter: 1,
lastRetrievedFromServer: 1,
memberType: CustomObject,
isNameObsolete: false
}
}
}
```
* In this example, `ApexClass__MyClass` has been changed in the org because the `serverRevisionCounter` is different
* from the `lastRetrievedFromServer`. When a pull is performed, all of the pulled members will have their counters set
* to the corresponding `RevisionCounter` from the `SourceMember` of the org.
*/
// eslint-disable-next-line no-redeclare
export class RemoteSourceTrackingService extends ConfigFile<RemoteSourceTrackingService.Options> {
logger!: Logger;
private org: Org;
private readonly FIRST_REVISION_COUNTER_API_VERSION: string = '47.0';
private conn: Connection;
private currentApiVersion: string;
private static remoteSourceTrackingServiceDictionary: Dictionary<RemoteSourceTrackingService> = {};
private isSourceTrackedOrg = true;
// A short term cache (within the same process) of query results based on a revision.
// Useful for source:pull, which makes 3 of the same queries; during status, building manifests, after pull success.
private queryCache = new Map<number, SourceMember[]>();
//
// * * * * * P U B L I C M E T H O D S * * * * *
//
/**
* Get the singleton instance for a given user.
*
* @param {RemoteSourceTrackingService.Options} options that contain the org's username
* @returns {Promise<RemoteSourceTrackingService>} the remoteSourceTrackingService object for the given username
*/
public static async getInstance(options: RemoteSourceTrackingService.Options): Promise<RemoteSourceTrackingService> {
if (!this.remoteSourceTrackingServiceDictionary[options.username]) {
this.remoteSourceTrackingServiceDictionary[options.username] = await RemoteSourceTrackingService.create(options);
}
return this.remoteSourceTrackingServiceDictionary[options.username];
}
/**
* Returns the name of the file used for remote source tracking persistence.
*
* @override
*/
public static getFileName(): string {
return 'maxRevision.json';
}
/**
* Initializes the service with existing remote source tracking data, or sets
* the state to begin source tracking of metadata changes in the org.
*/
public async init() {
this.options.filePath = pathJoin('orgs', this.options.username);
this.options.filename = RemoteSourceTrackingService.getFileName();
this.org = await Org.create({ aliasOrUsername: this.options.username });
this.logger = await Logger.child(this.constructor.name);
this.conn = this.org.getConnection();
this.currentApiVersion = this.conn.getApiVersion();
try {
await super.init();
} catch (err) {
// This error is thrown when the legacy maxRevision.json is read. Transform to the new schema.
if (err.name === 'JsonDataFormatError') {
const filePath = path.join(process.cwd(), this.options.filePath, RemoteSourceTrackingService.getFileName());
const legacyRevision = await fs.readFile(filePath, 'utf-8');
this.logger.debug(`Converting legacy maxRevision.json with revision ${legacyRevision} to new schema`);
await fs.writeFile(
filePath,
JSON.stringify({ serverMaxRevisionCounter: parseInt(legacyRevision), sourceMembers: {} }, null, 4)
);
await super.init();
} else {
throw SfdxError.wrap(err);
}
}
const contents = this.getContents();
// Initialize a new maxRevision.json if the file doesn't yet exist.
if (!contents.serverMaxRevisionCounter && !contents.sourceMembers) {
try {
// To find out if the associated org has source tracking enabled, we need to make a query
// for SourceMembers. If a certain error is thrown during the query we won't try to do
// source tracking for this org. Calling querySourceMembersFrom() has the extra benefit
// of caching the query so we don't have to make an identical request in the same process.
await this.querySourceMembersFrom(0);
this.logger.debug('Initializing source tracking state');
contents.serverMaxRevisionCounter = 0;
contents.sourceMembers = {};
await this.write();
} catch (e) {
if (e.name === 'INVALID_TYPE' && e.message.includes("sObject type 'SourceMember' is not supported")) {
// non-source-tracked org E.G. DevHub or trailhead playground
this.isSourceTrackedOrg = false;
}
}
}
}
/**
* Returns the `ChangeElement` currently being tracked given a metadata key,
* or `undefined` if not found.
*
* @param key string of the form, `<type>__<name>` e.g.,`ApexClass__MyClass`
*/
public getTrackedElement(key: string): Optional<ChangeElement> {
const memberRevision = this.getSourceMembers()[key];
if (memberRevision) {
return RemoteSourceTrackingService.convertRevisionToChange(key, memberRevision);
}
}
/**
* Returns an array of `ChangeElements` currently being tracked.
*/
public getTrackedElements(): ChangeElement[] {
const sourceTrackedKeys = Object.keys(this.getSourceMembers());
return sourceTrackedKeys.map((key) => this.getTrackedElement(key));
}
/**
* Queries the org for any new, updated, or deleted metadata and updates
* source tracking state. All `ChangeElements` not in sync with the org
* are returned.
*/
public async retrieveUpdates(): Promise<ChangeElement[]> {
return this._retrieveUpdates();
}
/**
* Synchronizes local and remote source tracking with data from the associated org.
*
* When called without `ChangeElements` passed this will query all `SourceMember`
* objects from the last retrieval and update the tracked elements. This is
* typically called after retrieving all new, changed, or deleted metadata from
* the org. E.g., after a `source:pull` command.
*
* When called with `ChangeElements` passed this will poll the org for
* corresponding `SourceMember` data and update the tracked elements. This is
* typically called after deploying metadata from a local project to the org.
* E.g., after a `source:push` command.
*/
public async sync(metadataNames?: string[]) {
if (!metadataNames) {
// This is for a source:pull
await this._retrieveUpdates(true);
} else {
// This is for a source:push
if (metadataNames.length > 0) {
await this.pollForSourceTracking(metadataNames);
}
}
}
/**
* Resets source tracking state by first clearing all tracked data, then
* queries and synchronizes SourceMembers from the associated org.
*
* If a toRevision is passed, it will query for all `SourceMembers` with
* a `RevisionCounter` less than or equal to the provided revision number.
*
* When no toRevision is passed, it will query and sync all `SourceMembers`.
*
* @param toRevision The `RevisionCounter` number to sync to.
*/
public async reset(toRevision?: number) {
// Called during a source:tracking:reset
this.setServerMaxRevision(0);
this.initSourceMembers();
let members: SourceMember[];
if (toRevision != null) {
members = await this.querySourceMembersTo(toRevision);
} else {
members = await this.querySourceMembersFrom(0);
}
await this.trackSourceMembers(members, true);
}
//
// * * * * * P R I V A T E M E T H O D S * * * * *
//
private getServerMaxRevision(): number {
return this['contents'].serverMaxRevisionCounter;
}
private setServerMaxRevision(revision = 0) {
this['contents'].serverMaxRevisionCounter = revision;
}
private getSourceMembers(): Dictionary<MemberRevision> {
return this['contents'].sourceMembers;
}
private initSourceMembers() {
this['contents'].sourceMembers = {};
}
// Return a tracked element as MemberRevision data.
private getSourceMember(key: string): Optional<MemberRevision> {
return this.getSourceMembers()[key];
}
private setMemberRevision(key: string, sourceMember: MemberRevision) {
this.getContents().sourceMembers[key] = sourceMember;
}
// Adds the given SourceMembers to the list of tracked MemberRevisions, optionally updating
// the lastRetrievedFromServer field (sync), and persists the changes to maxRevision.json.
private async trackSourceMembers(sourceMembers: SourceMember[] = [], sync = false) {
let quiet = false;
if (sourceMembers.length > 100) {
this.logger.debug(`Upserting ${sourceMembers.length} SourceMembers to maxRevision.json`);
quiet = true;
}
// A sync with empty sourceMembers means "update all currently tracked elements".
// This is what happens during a source:pull
if (!sourceMembers.length && sync) {
const trackedRevisions = this.getSourceMembers();
for (const key in trackedRevisions) {
const member = trackedRevisions[key];
member.lastRetrievedFromServer = member.serverRevisionCounter;
trackedRevisions[key] = member;
}
await this.write();
return;
}
let serverMaxRevisionCounter = this.getServerMaxRevision();
sourceMembers.forEach((change) => {
// try accessing the sourceMembers object at the index of the change's name
// if it exists, we'll update the fields - if it doesn't, we'll create and insert it
const key = MetadataRegistry.getMetadataKey(change.MemberType, change.MemberName);
let sourceMember = this.getSourceMember(key);
if (sourceMember) {
// We are already tracking this element so we'll update it
if (!quiet) {
let msg = `Updating ${key} to RevisionCounter: ${change.RevisionCounter}`;
if (sync) {
msg += ' and syncing';
}
this.logger.debug(msg);
}
sourceMember.serverRevisionCounter = change.RevisionCounter;
sourceMember.isNameObsolete = change.IsNameObsolete;
} else {
// We are not yet tracking it so we'll insert a new record
if (!quiet) {
let msg = `Inserting ${key} with RevisionCounter: ${change.RevisionCounter}`;
if (sync) {
msg += ' and syncing';
}
this.logger.debug(msg);
}
sourceMember = {
serverRevisionCounter: change.RevisionCounter,
lastRetrievedFromServer: null,
memberType: change.MemberType,
isNameObsolete: change.IsNameObsolete,
};
}
// If we are syncing changes then we need to update the lastRetrievedFromServer field to
// match the RevisionCounter from the SourceMember.
if (sync) {
sourceMember.lastRetrievedFromServer = change.RevisionCounter;
}
// Keep track of the highest RevisionCounter for setting the serverMaxRevisionCounter
if (change.RevisionCounter > serverMaxRevisionCounter) {
serverMaxRevisionCounter = change.RevisionCounter;
}
// Update the state with the latest SourceMember data
this.setMemberRevision(key, sourceMember);
});
// Update the serverMaxRevisionCounter to the highest RevisionCounter
this.setServerMaxRevision(serverMaxRevisionCounter);
this.logger.debug(`Updating serverMaxRevisionCounter to ${serverMaxRevisionCounter}`);
await this.write();
}
private static convertRevisionToChange(memberKey: string, memberRevision: MemberRevision): ChangeElement {
return {
type: memberRevision.memberType,
name: memberKey.replace(`${memberRevision.memberType}__`, ''),
deleted: memberRevision.isNameObsolete,
};
}
// Internal implementation of the public `retrieveUpdates` function that adds the ability
// to sync the retrieved SourceMembers; meaning it will update the lastRetrievedFromServer
// field to the SourceMember's RevisionCounter, and update the serverMaxRevisionCounter
// to the highest RevisionCounter.
private async _retrieveUpdates(sync = false): Promise<ChangeElement[]> {
const returnElements: ChangeElement[] = [];
// Always track new SourceMember data, or update tracking when we sync.
const queriedSourceMembers = await this.querySourceMembersFrom();
if (queriedSourceMembers.length || sync) {
await this.trackSourceMembers(queriedSourceMembers, sync);
}
// Look for any changed that haven't been synced. I.e, the lastRetrievedFromServer
// does not match the serverRevisionCounter.
const trackedRevisions = this.getSourceMembers();
for (const key in trackedRevisions) {
const member = trackedRevisions[key];
if (member.serverRevisionCounter !== member.lastRetrievedFromServer) {
returnElements.push(RemoteSourceTrackingService.convertRevisionToChange(key, member));
}
}
if (returnElements.length) {
this.logger.debug(`Found ${returnElements.length} elements not synced with org`);
} else {
this.logger.debug('Remote source tracking is up to date');
}
return returnElements;
}
/**
* Polls the org for SourceMember objects matching the provided metadata member names,
* stopping when all members have been matched or the polling timeout is met or exceeded.
* NOTE: This can be removed when the Team Dependency (TD-0085369) for W-7737094 is delivered.
*
* @param memberNames Array of metadata names to poll
* @param pollingTimeout maximum amount of time in seconds to poll for SourceMembers
*/
private async pollForSourceTracking(memberNames: string[], pollingTimeout?: Duration.Unit.SECONDS): Promise<void> {
if (env.getBoolean('SFDX_DISABLE_SOURCE_MEMBER_POLLING', false)) {
this.logger.warn('Not polling for SourceMembers since SFDX_DISABLE_SOURCE_MEMBER_POLLING = true.');
return;
}
if (memberNames.length === 0) {
// Don't bother polling if we're not matching SourceMembers
return;
}
const overriddenTimeout = toNumber(env.getString('SFDX_SOURCE_MEMBER_POLLING_TIMEOUT', '0'));
if (overriddenTimeout > 0) {
this.logger.debug(`Overriding SourceMember polling timeout to ${overriddenTimeout}`);
pollingTimeout = overriddenTimeout;
}
// Calculate a polling timeout for SourceMembers based on the number of
// member names being polled plus a buffer of 5 seconds. This will
// wait 50s for each 1000 components, plus 5s.
if (!pollingTimeout) {
pollingTimeout = Math.ceil(memberNames.length * 0.05) + 5;
this.logger.debug(`Computed SourceMember polling timeout of ${pollingTimeout}s`);
}
const pollStartTime = Date.now();
let pollEndTime: number;
let totalPollTime: number;
const fromRevision = this.getServerMaxRevision();
this.logger.debug(
`Polling for ${memberNames.length} SourceMembers from revision ${fromRevision} with timeout of ${pollingTimeout}s`
);
let pollAttempts = 1;
const matches = new Set(memberNames);
const poll = async (): Promise<SourceMember[]> => {
const allMembers = await this.querySourceMembersFrom(fromRevision, pollAttempts !== 1, false);
for (const member of allMembers) {
matches.delete(member.MemberName);
}
this.logger.debug(
`[${pollAttempts}] Found ${memberNames.length - matches.size} of ${memberNames.length} SourceMembers`
);
pollEndTime = Date.now();
totalPollTime = Math.round((pollEndTime - pollStartTime) / 1000) || 1;
if (matches.size === 0 || totalPollTime >= pollingTimeout) {
return allMembers;
}
if (matches.size < 20) {
this.logger.debug(`Still looking for SourceMembers: ${[...matches]}`);
}
await this.sleep();
pollAttempts += 1;
return poll();
};
const sourceMembers = await poll();
if (matches.size === 0) {
this.logger.debug(`Retrieved all SourceMember data after ${totalPollTime}s and ${pollAttempts} attempts`);
} else {
this.logger.warn(`Polling for SourceMembers timed out after ${totalPollTime}s and ${pollAttempts} attempts`);
if (matches.size < 51) {
this.logger.debug(`Could not find ${matches.size} SourceMembers: ${[...matches]}`);
} else {
this.logger.debug(`Could not find SourceMembers for ${matches.size} components`);
}
}
// NOTE: we are updating tracking for every SourceMember returned by the query once we match all memberNames
// passed OR polling times out. This does not update SourceMembers of *only* the memberNames passed.
// This means if we ever want to support tracking on source:deploy or source:retrieve we would need
// to update tracking for only the matched SourceMembers. I.e., call trackSourceMembers() passing
// only the SourceMembers that match the memberNames.
await this.trackSourceMembers(sourceMembers, true);
}
private async querySourceMembersFrom(fromRevision?: number, quiet = false, useCache = true): Promise<SourceMember[]> {
const rev = fromRevision != null ? fromRevision : this.getServerMaxRevision();
if (useCache) {
// Check cache first and return if found.
const cachedQueryResult = this.queryCache.get(rev);
if (cachedQueryResult) {
this.logger.debug(`Using cache for SourceMember query for revision ${rev}`);
return cachedQueryResult;
}
}
// because `serverMaxRevisionCounter` is always updated, we need to select > to catch the most recent change
const query = `SELECT MemberType, MemberName, IsNameObsolete, RevisionCounter FROM SourceMember WHERE RevisionCounter > ${rev}`;
const queryResult = await this.query(query, quiet);
this.queryCache.set(rev, queryResult);
return queryResult;
}
private async querySourceMembersTo(toRevision: number, quiet = false): Promise<SourceMember[]> {
const query = `SELECT MemberType, MemberName, IsNameObsolete, RevisionCounter FROM SourceMember WHERE RevisionCounter <= ${toRevision}`;
return this.query(query, quiet);
}
private async sleep() {
await sleep(Duration.seconds(1));
}
private async query<T>(query: string, quiet = false) {
// to switch to using RevisionCounter - apiVersion > 46.0
// set the api version of the connection to 47.0, query, revert api version
if (!this.isSourceTrackedOrg) {
throw SfdxError.create('salesforce-alm', 'source', 'NonSourceTrackedOrgError');
}
if (!quiet) {
this.logger.debug(query);
}
let results;
if (parseFloat(this.currentApiVersion) < parseFloat(this.FIRST_REVISION_COUNTER_API_VERSION)) {
this.conn.setApiVersion(this.FIRST_REVISION_COUNTER_API_VERSION);
results = await this.conn.tooling.autoFetchQuery<T>(query);
this.conn.setApiVersion(this.currentApiVersion);
} else {
results = await this.conn.tooling.autoFetchQuery<T>(query);
}
return results.records;
}
} | the_stack |
"use strict";
import { assert } from "chai";
import { Strings } from "../../../src/helpers/strings";
import { GetInfo } from "../../../src/tfvc/commands/getinfo";
import { TfvcError, TfvcErrorCodes } from "../../../src/tfvc/tfvcerror";
import { IExecutionResult, IItemInfo } from "../../../src/tfvc/interfaces";
import { TeamServerContext } from "../../../src/contexts/servercontext";
import { CredentialInfo } from "../../../src/info/credentialinfo";
import { RepositoryInfo } from "../../../src/info/repositoryinfo";
describe("Tfvc-GetInfoCommand", function() {
const serverUrl: string = "http://server:8080/tfs";
const repoUrl: string = "http://server:8080/tfs/collection1/_git/repo1";
const collectionUrl: string = "http://server:8080/tfs/collection1";
const user: string = "user1";
const pass: string = "pass1";
let context: TeamServerContext;
beforeEach(function() {
context = new TeamServerContext(repoUrl);
context.CredentialInfo = new CredentialInfo(user, pass);
context.RepoInfo = new RepositoryInfo({
serverUrl: serverUrl,
collection: {
name: "collection1",
id: ""
},
repository: {
remoteUrl: repoUrl,
id: "",
name: "",
project: {
name: "project1"
}
}
});
});
it("should verify constructor", function() {
const localPaths: string[] = ["/path/to/workspace"];
new GetInfo(undefined, localPaths);
});
it("should verify constructor with context", function() {
const localPaths: string[] = ["/path/to/workspace"];
new GetInfo(context, localPaths);
});
it("should verify constructor - undefined args", function() {
assert.throws(() => new GetInfo(undefined, undefined), TfvcError, /Argument is required/);
});
it("should verify GetOptions", function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
assert.deepEqual(cmd.GetOptions(), {});
});
it("should verify GetExeOptions", function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
assert.deepEqual(cmd.GetExeOptions(), {});
});
it("should verify arguments", function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "info -noprompt " + localPaths[0]);
});
it("should verify arguments with context", function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(context, localPaths);
assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "info -noprompt -collection:" + collectionUrl + " ******** " + localPaths[0]);
});
it("should verify GetExeArguments", function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "info -noprompt " + localPaths[0]);
});
it("should verify GetExeArguments with context", function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(context, localPaths);
assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "info -noprompt -collection:" + collectionUrl + " ******** " + localPaths[0]);
});
it("should verify parse output - no output", async function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: undefined,
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseOutput(executionResult);
assert.equal(itemInfos.length, 0);
});
it("should verify parse output - single item", async function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "Local information:\n" +
"Local path: /path/to/file.txt\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 18, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1385\n",
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseOutput(executionResult);
assert.equal(itemInfos.length, 1);
assert.equal(itemInfos[0].localItem, "/path/to/file.txt");
assert.equal(itemInfos[0].serverItem, "$/TFVC_1/file.txt");
assert.equal(itemInfos[0].localVersion, "18");
assert.equal(itemInfos[0].change, "none");
assert.equal(itemInfos[0].type, "file");
assert.equal(itemInfos[0].serverVersion, "18");
assert.equal(itemInfos[0].deletionId, "0");
assert.equal(itemInfos[0].lock, "none");
assert.equal(itemInfos[0].lockOwner, "");
assert.equal(itemInfos[0].lastModified, "Nov 18, 2016 11:10:20 AM");
assert.equal(itemInfos[0].fileType, "windows-1252");
assert.equal(itemInfos[0].fileSize, "1385");
});
it("should verify parse output - multiple items", async function() {
const localPaths: string[] = ["/path/to/workspace/file.txt", "/path/to/workspace/file2.txt"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "Local information:\n" +
"Local path: /path/to/file.txt\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 18, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1385\n" +
"\n" +
"Local information:\n" +
"Local path: /path/to/file2.txt\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 19, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1386\n",
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseOutput(executionResult);
assert.equal(itemInfos.length, 2);
assert.equal(itemInfos[0].localItem, "/path/to/file.txt");
assert.equal(itemInfos[0].serverItem, "$/TFVC_1/file.txt");
assert.equal(itemInfos[0].localVersion, "18");
assert.equal(itemInfos[0].change, "none");
assert.equal(itemInfos[0].type, "file");
assert.equal(itemInfos[0].serverVersion, "18");
assert.equal(itemInfos[0].deletionId, "0");
assert.equal(itemInfos[0].lock, "none");
assert.equal(itemInfos[0].lockOwner, "");
assert.equal(itemInfos[0].lastModified, "Nov 18, 2016 11:10:20 AM");
assert.equal(itemInfos[0].fileType, "windows-1252");
assert.equal(itemInfos[0].fileSize, "1385");
assert.equal(itemInfos[1].localItem, "/path/to/file2.txt");
assert.equal(itemInfos[1].serverItem, "$/TFVC_1/file2.txt");
assert.equal(itemInfos[1].localVersion, "19");
assert.equal(itemInfos[1].change, "none");
assert.equal(itemInfos[1].type, "file");
assert.equal(itemInfos[1].serverVersion, "19");
assert.equal(itemInfos[1].deletionId, "0");
assert.equal(itemInfos[1].lock, "none");
assert.equal(itemInfos[1].lockOwner, "");
assert.equal(itemInfos[1].lastModified, "Nov 19, 2016 11:10:20 AM");
assert.equal(itemInfos[1].fileType, "windows-1252");
assert.equal(itemInfos[1].fileSize, "1386");
});
it("should verify parse output - multiple items with errors", async function() {
const localPaths: string[] = ["/path/to/workspace/file.txt", "nomatch", "/path/to/workspace/file2.txt"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "Local information:\n" +
"Local path: /path/to/file.txt\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 18, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1385\n" +
"\n" +
"No items match nomatch\n" +
"\n" +
"Local information:\n" +
"Local path: /path/to/file2.txt\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 19, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1386\n",
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseOutput(executionResult);
assert.equal(itemInfos.length, 3);
assert.equal(itemInfos[0].localItem, "/path/to/file.txt");
assert.equal(itemInfos[0].serverItem, "$/TFVC_1/file.txt");
assert.equal(itemInfos[0].localVersion, "18");
assert.equal(itemInfos[0].change, "none");
assert.equal(itemInfos[0].type, "file");
assert.equal(itemInfos[0].serverVersion, "18");
assert.equal(itemInfos[0].deletionId, "0");
assert.equal(itemInfos[0].lock, "none");
assert.equal(itemInfos[0].lockOwner, "");
assert.equal(itemInfos[0].lastModified, "Nov 18, 2016 11:10:20 AM");
assert.equal(itemInfos[0].fileType, "windows-1252");
assert.equal(itemInfos[0].fileSize, "1385");
assert.equal(itemInfos[1].localItem, undefined); // This indicates that the file could not be found, but other files could
assert.equal(itemInfos[2].localItem, "/path/to/file2.txt");
assert.equal(itemInfos[2].serverItem, "$/TFVC_1/file2.txt");
assert.equal(itemInfos[2].localVersion, "19");
assert.equal(itemInfos[2].change, "none");
assert.equal(itemInfos[2].type, "file");
assert.equal(itemInfos[2].serverVersion, "19");
assert.equal(itemInfos[2].deletionId, "0");
assert.equal(itemInfos[2].lock, "none");
assert.equal(itemInfos[2].lockOwner, "");
assert.equal(itemInfos[2].lastModified, "Nov 19, 2016 11:10:20 AM");
assert.equal(itemInfos[2].fileType, "windows-1252");
assert.equal(itemInfos[2].fileSize, "1386");
});
it("should verify parse output - all errors", async function() {
const localPaths: string[] = ["/path/to/workspace/file.txt", "/path/to/workspace/file2.txt"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "No items match /path/to/workspace/file.txt\n" +
"\n" +
"No items match /path/to/workspace/file2.txt\n",
stderr: undefined
};
try {
await cmd.ParseExeOutput(executionResult);
} catch (err) {
assert.isTrue(err.message.startsWith(Strings.NoMatchesFound));
assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NoItemsMatch);
}
});
/***********************************************************************************************
* The methods below are duplicates of the parse output methods but call the parseExeOutput.
***********************************************************************************************/
it("should verify parse EXE output - no output", async function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: undefined,
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseExeOutput(executionResult);
assert.equal(itemInfos.length, 0);
});
it("should verify parse EXE output - single item", async function() {
const localPaths: string[] = ["/path/to/workspace"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "Local information:\n" +
"Local path: /path/to/file.txt\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 18, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1385\n",
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseExeOutput(executionResult);
assert.equal(itemInfos.length, 1);
assert.equal(itemInfos[0].localItem, "/path/to/file.txt");
assert.equal(itemInfos[0].serverItem, "$/TFVC_1/file.txt");
assert.equal(itemInfos[0].localVersion, "18");
assert.equal(itemInfos[0].change, "none");
assert.equal(itemInfos[0].type, "file");
assert.equal(itemInfos[0].serverVersion, "18");
assert.equal(itemInfos[0].deletionId, "0");
assert.equal(itemInfos[0].lock, "none");
assert.equal(itemInfos[0].lockOwner, "");
assert.equal(itemInfos[0].lastModified, "Nov 18, 2016 11:10:20 AM");
assert.equal(itemInfos[0].fileType, "windows-1252");
assert.equal(itemInfos[0].fileSize, "1385");
});
it("should verify parse EXE output - multiple items", async function() {
const localPaths: string[] = ["/path/to/workspace/file.txt", "/path/to/workspace/file2.txt"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "Local information:\n" +
"Local path: /path/to/file.txt\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 18, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1385\n" +
"Local information:\n" +
"Local path: /path/to/file2.txt\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 19, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1386\n",
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseExeOutput(executionResult);
assert.equal(itemInfos.length, 2);
assert.equal(itemInfos[0].localItem, "/path/to/file.txt");
assert.equal(itemInfos[0].serverItem, "$/TFVC_1/file.txt");
assert.equal(itemInfos[0].localVersion, "18");
assert.equal(itemInfos[0].change, "none");
assert.equal(itemInfos[0].type, "file");
assert.equal(itemInfos[0].serverVersion, "18");
assert.equal(itemInfos[0].deletionId, "0");
assert.equal(itemInfos[0].lock, "none");
assert.equal(itemInfos[0].lockOwner, "");
assert.equal(itemInfos[0].lastModified, "Nov 18, 2016 11:10:20 AM");
assert.equal(itemInfos[0].fileType, "windows-1252");
assert.equal(itemInfos[0].fileSize, "1385");
assert.equal(itemInfos[1].localItem, "/path/to/file2.txt");
assert.equal(itemInfos[1].serverItem, "$/TFVC_1/file2.txt");
assert.equal(itemInfos[1].localVersion, "19");
assert.equal(itemInfos[1].change, "none");
assert.equal(itemInfos[1].type, "file");
assert.equal(itemInfos[1].serverVersion, "19");
assert.equal(itemInfos[1].deletionId, "0");
assert.equal(itemInfos[1].lock, "none");
assert.equal(itemInfos[1].lockOwner, "");
assert.equal(itemInfos[1].lastModified, "Nov 19, 2016 11:10:20 AM");
assert.equal(itemInfos[1].fileType, "windows-1252");
assert.equal(itemInfos[1].fileSize, "1386");
});
it("should verify parse EXE output - multiple items with errors", async function() {
const localPaths: string[] = ["/path/to/workspace/file.txt", "nomatch", "/path/to/workspace/file2.txt"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "Local information:\n" +
"Local path: /path/to/file.txt\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file.txt\n" +
"Changeset: 18\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 18, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1385\n" +
"No items match nomatch\n" +
"Local information:\n" +
"Local path: /path/to/file2.txt\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Change: none\n" +
"Type: file\n" +
"Server information:\n" +
"Server path: $/TFVC_1/file2.txt\n" +
"Changeset: 19\n" +
"Deletion ID: 0\n" +
"Lock: none\n" +
"Lock owner:\n" +
"Last modified: Nov 19, 2016 11:10:20 AM\n" +
"Type: file\n" +
"File type: windows-1252\n" +
"Size: 1386\n",
stderr: undefined
};
const itemInfos: IItemInfo[] = await cmd.ParseExeOutput(executionResult);
assert.equal(itemInfos.length, 3);
assert.equal(itemInfos[0].localItem, "/path/to/file.txt");
assert.equal(itemInfos[0].serverItem, "$/TFVC_1/file.txt");
assert.equal(itemInfos[0].localVersion, "18");
assert.equal(itemInfos[0].change, "none");
assert.equal(itemInfos[0].type, "file");
assert.equal(itemInfos[0].serverVersion, "18");
assert.equal(itemInfos[0].deletionId, "0");
assert.equal(itemInfos[0].lock, "none");
assert.equal(itemInfos[0].lockOwner, "");
assert.equal(itemInfos[0].lastModified, "Nov 18, 2016 11:10:20 AM");
assert.equal(itemInfos[0].fileType, "windows-1252");
assert.equal(itemInfos[0].fileSize, "1385");
assert.equal(itemInfos[1].localItem, undefined); // This indicates that the file could not be found, but other files could
assert.equal(itemInfos[2].localItem, "/path/to/file2.txt");
assert.equal(itemInfos[2].serverItem, "$/TFVC_1/file2.txt");
assert.equal(itemInfos[2].localVersion, "19");
assert.equal(itemInfos[2].change, "none");
assert.equal(itemInfos[2].type, "file");
assert.equal(itemInfos[2].serverVersion, "19");
assert.equal(itemInfos[2].deletionId, "0");
assert.equal(itemInfos[2].lock, "none");
assert.equal(itemInfos[2].lockOwner, "");
assert.equal(itemInfos[2].lastModified, "Nov 19, 2016 11:10:20 AM");
assert.equal(itemInfos[2].fileType, "windows-1252");
assert.equal(itemInfos[2].fileSize, "1386");
});
it("should verify parse EXE output - all errors", async function() {
const localPaths: string[] = ["/path/to/workspace/file.txt", "/path/to/workspace/file2.txt"];
const cmd: GetInfo = new GetInfo(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "No items match /path/to/workspace/file.txt\n" +
"No items match /path/to/workspace/file2.txt\n",
stderr: undefined
};
try {
await cmd.ParseExeOutput(executionResult);
} catch (err) {
assert.isTrue(err.message.startsWith(Strings.NoMatchesFound));
assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NoItemsMatch);
}
});
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
NetworkInterface,
NetworkInterfacesListCloudServiceRoleInstanceNetworkInterfacesOptionalParams,
NetworkInterfacesListCloudServiceNetworkInterfacesOptionalParams,
NetworkInterfacesListAllOptionalParams,
NetworkInterfacesListOptionalParams,
NetworkInterfacesListVirtualMachineScaleSetVMNetworkInterfacesOptionalParams,
NetworkInterfacesListVirtualMachineScaleSetNetworkInterfacesOptionalParams,
NetworkInterfaceIPConfiguration,
NetworkInterfacesListVirtualMachineScaleSetIpConfigurationsOptionalParams,
NetworkInterfacesGetCloudServiceNetworkInterfaceOptionalParams,
NetworkInterfacesGetCloudServiceNetworkInterfaceResponse,
NetworkInterfacesDeleteOptionalParams,
NetworkInterfacesGetOptionalParams,
NetworkInterfacesGetResponse,
NetworkInterfacesCreateOrUpdateOptionalParams,
NetworkInterfacesCreateOrUpdateResponse,
TagsObject,
NetworkInterfacesUpdateTagsOptionalParams,
NetworkInterfacesUpdateTagsResponse,
NetworkInterfacesGetEffectiveRouteTableOptionalParams,
NetworkInterfacesGetEffectiveRouteTableResponse,
NetworkInterfacesListEffectiveNetworkSecurityGroupsOptionalParams,
NetworkInterfacesListEffectiveNetworkSecurityGroupsResponse,
NetworkInterfacesGetVirtualMachineScaleSetNetworkInterfaceOptionalParams,
NetworkInterfacesGetVirtualMachineScaleSetNetworkInterfaceResponse,
NetworkInterfacesGetVirtualMachineScaleSetIpConfigurationOptionalParams,
NetworkInterfacesGetVirtualMachineScaleSetIpConfigurationResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a NetworkInterfaces. */
export interface NetworkInterfaces {
/**
* Gets information about all network interfaces in a role instance in a cloud service.
* @param resourceGroupName The name of the resource group.
* @param cloudServiceName The name of the cloud service.
* @param roleInstanceName The name of role instance.
* @param options The options parameters.
*/
listCloudServiceRoleInstanceNetworkInterfaces(
resourceGroupName: string,
cloudServiceName: string,
roleInstanceName: string,
options?: NetworkInterfacesListCloudServiceRoleInstanceNetworkInterfacesOptionalParams
): PagedAsyncIterableIterator<NetworkInterface>;
/**
* Gets all network interfaces in a cloud service.
* @param resourceGroupName The name of the resource group.
* @param cloudServiceName The name of the cloud service.
* @param options The options parameters.
*/
listCloudServiceNetworkInterfaces(
resourceGroupName: string,
cloudServiceName: string,
options?: NetworkInterfacesListCloudServiceNetworkInterfacesOptionalParams
): PagedAsyncIterableIterator<NetworkInterface>;
/**
* Gets all network interfaces in a subscription.
* @param options The options parameters.
*/
listAll(
options?: NetworkInterfacesListAllOptionalParams
): PagedAsyncIterableIterator<NetworkInterface>;
/**
* Gets all network interfaces in a resource group.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
list(
resourceGroupName: string,
options?: NetworkInterfacesListOptionalParams
): PagedAsyncIterableIterator<NetworkInterface>;
/**
* Gets information about all network interfaces in a virtual machine in a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param virtualMachineScaleSetName The name of the virtual machine scale set.
* @param virtualmachineIndex The virtual machine index.
* @param options The options parameters.
*/
listVirtualMachineScaleSetVMNetworkInterfaces(
resourceGroupName: string,
virtualMachineScaleSetName: string,
virtualmachineIndex: string,
options?: NetworkInterfacesListVirtualMachineScaleSetVMNetworkInterfacesOptionalParams
): PagedAsyncIterableIterator<NetworkInterface>;
/**
* Gets all network interfaces in a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param virtualMachineScaleSetName The name of the virtual machine scale set.
* @param options The options parameters.
*/
listVirtualMachineScaleSetNetworkInterfaces(
resourceGroupName: string,
virtualMachineScaleSetName: string,
options?: NetworkInterfacesListVirtualMachineScaleSetNetworkInterfacesOptionalParams
): PagedAsyncIterableIterator<NetworkInterface>;
/**
* Get the specified network interface ip configuration in a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param virtualMachineScaleSetName The name of the virtual machine scale set.
* @param virtualmachineIndex The virtual machine index.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
listVirtualMachineScaleSetIpConfigurations(
resourceGroupName: string,
virtualMachineScaleSetName: string,
virtualmachineIndex: string,
networkInterfaceName: string,
options?: NetworkInterfacesListVirtualMachineScaleSetIpConfigurationsOptionalParams
): PagedAsyncIterableIterator<NetworkInterfaceIPConfiguration>;
/**
* Get the specified network interface in a cloud service.
* @param resourceGroupName The name of the resource group.
* @param cloudServiceName The name of the cloud service.
* @param roleInstanceName The name of role instance.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
getCloudServiceNetworkInterface(
resourceGroupName: string,
cloudServiceName: string,
roleInstanceName: string,
networkInterfaceName: string,
options?: NetworkInterfacesGetCloudServiceNetworkInterfaceOptionalParams
): Promise<NetworkInterfacesGetCloudServiceNetworkInterfaceResponse>;
/**
* Deletes the specified network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes the specified network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesDeleteOptionalParams
): Promise<void>;
/**
* Gets information about the specified network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesGetOptionalParams
): Promise<NetworkInterfacesGetResponse>;
/**
* Creates or updates a network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param parameters Parameters supplied to the create or update network interface operation.
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
networkInterfaceName: string,
parameters: NetworkInterface,
options?: NetworkInterfacesCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<NetworkInterfacesCreateOrUpdateResponse>,
NetworkInterfacesCreateOrUpdateResponse
>
>;
/**
* Creates or updates a network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param parameters Parameters supplied to the create or update network interface operation.
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
networkInterfaceName: string,
parameters: NetworkInterface,
options?: NetworkInterfacesCreateOrUpdateOptionalParams
): Promise<NetworkInterfacesCreateOrUpdateResponse>;
/**
* Updates a network interface tags.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param parameters Parameters supplied to update network interface tags.
* @param options The options parameters.
*/
updateTags(
resourceGroupName: string,
networkInterfaceName: string,
parameters: TagsObject,
options?: NetworkInterfacesUpdateTagsOptionalParams
): Promise<NetworkInterfacesUpdateTagsResponse>;
/**
* Gets all route tables applied to a network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
beginGetEffectiveRouteTable(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesGetEffectiveRouteTableOptionalParams
): Promise<
PollerLike<
PollOperationState<NetworkInterfacesGetEffectiveRouteTableResponse>,
NetworkInterfacesGetEffectiveRouteTableResponse
>
>;
/**
* Gets all route tables applied to a network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
beginGetEffectiveRouteTableAndWait(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesGetEffectiveRouteTableOptionalParams
): Promise<NetworkInterfacesGetEffectiveRouteTableResponse>;
/**
* Gets all network security groups applied to a network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
beginListEffectiveNetworkSecurityGroups(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesListEffectiveNetworkSecurityGroupsOptionalParams
): Promise<
PollerLike<
PollOperationState<
NetworkInterfacesListEffectiveNetworkSecurityGroupsResponse
>,
NetworkInterfacesListEffectiveNetworkSecurityGroupsResponse
>
>;
/**
* Gets all network security groups applied to a network interface.
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
beginListEffectiveNetworkSecurityGroupsAndWait(
resourceGroupName: string,
networkInterfaceName: string,
options?: NetworkInterfacesListEffectiveNetworkSecurityGroupsOptionalParams
): Promise<NetworkInterfacesListEffectiveNetworkSecurityGroupsResponse>;
/**
* Get the specified network interface in a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param virtualMachineScaleSetName The name of the virtual machine scale set.
* @param virtualmachineIndex The virtual machine index.
* @param networkInterfaceName The name of the network interface.
* @param options The options parameters.
*/
getVirtualMachineScaleSetNetworkInterface(
resourceGroupName: string,
virtualMachineScaleSetName: string,
virtualmachineIndex: string,
networkInterfaceName: string,
options?: NetworkInterfacesGetVirtualMachineScaleSetNetworkInterfaceOptionalParams
): Promise<
NetworkInterfacesGetVirtualMachineScaleSetNetworkInterfaceResponse
>;
/**
* Get the specified network interface ip configuration in a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param virtualMachineScaleSetName The name of the virtual machine scale set.
* @param virtualmachineIndex The virtual machine index.
* @param networkInterfaceName The name of the network interface.
* @param ipConfigurationName The name of the ip configuration.
* @param options The options parameters.
*/
getVirtualMachineScaleSetIpConfiguration(
resourceGroupName: string,
virtualMachineScaleSetName: string,
virtualmachineIndex: string,
networkInterfaceName: string,
ipConfigurationName: string,
options?: NetworkInterfacesGetVirtualMachineScaleSetIpConfigurationOptionalParams
): Promise<NetworkInterfacesGetVirtualMachineScaleSetIpConfigurationResponse>;
} | the_stack |
* @module Quantity
*/
import { QuantityError, QuantityStatus } from "../Exception";
/** The regular expression to parse [format strings]($docs/bis/ec/kindofquantity.md#format-string)
* provided in serialized formats as well as the full name of an [[OverrideFormat]].
*
* `formatName(precision)[unitName|unitLabel][unitName|unitLabel][unitName|unitLabel][unitName|unitLabel]`
*
* Explanation of the regex:
* - ([\w.:]+)
* - Grabs the format full name
* - (\(([^\)]+)\))?
* - Grabs the precision part with and without the `()`.
* - The parentheses are needed to validate the entire string. (TODO: Need to check if this is true)
* - (\[([^\|\]]+)([\|])?([^\]]+)?\])?
* - 4 of these make up the rest of the regex, none of them are required so each end in `?`
* - Grabs the unit name and label including the `[]`
* - Grabs the unit name, `|` and label separately
* @internal
*/
export const formatStringRgx = /([\w.:]+)(\(([^\)]+)\))?(\[([^\|\]]+)([\|])?([^\]]+)?\])?(\[([^\|\]]+)([\|])?([^\]]+)?\])?(\[([^\|\]]+)([\|])?([^\]]+)?\])?(\[([^\|\]]+)([\|])?([^\]]+)?\])?/;
/** @internal */
export function* getItemNamesFromFormatString(formatString: string): Iterable<string> {
const match = formatString.split(formatStringRgx);
yield match[1]; // the Format Name
let index = 4;
while (index < match.length - 1) { // index 0 and 21 are empty strings
if (match[index] !== undefined)
yield match[index + 1]; // Unit Name
else
break;
index += 4;
}
}
/** @beta */
export enum FormatTraits {
Uninitialized = 0x0,
/** Show trailing zeroes to requested precision. */
TrailZeroes = 0x1,
/** Indicates that the fractional part of the number is required when the fraction is zero */
KeepSingleZero = 0x2,
/** Zero magnitude returns blank display value */
ZeroEmpty = 0x4,
/** Show decimal point when value to right of decimal is empty */
KeepDecimalPoint = 0x8,
/** Use the rounding factor. Not yet supported */
ApplyRounding = 0x10,
/** Show a dash between whole value and fractional value */
FractionDash = 0x20,
/** Append the quantity's unit label */
ShowUnitLabel = 0x40,
/** Prepend unit label. Not yet supported */
PrependUnitLabel = 0x80,
/** show a grouping in each group of 1000. */
Use1000Separator = 0x100,
/** Indicates that if an exponent value is positive to not include a `+`. By default a sign, `+` or `-`, is always shown. Not yet supported */
ExponentOnlyNegative = 0x200,
}
/** Precision for Fractional formatted value types. Range from Whole (1/1) through 1/256.
* @beta */
export enum FractionalPrecision {
One = 1,
Two = 2,
Four = 4,
Eight = 8,
Sixteen = 16,
ThirtyTwo = 32,
SixtyFour = 64,
OneHundredTwentyEight = 128,
TwoHundredFiftySix = 256,
}
/** Precision for Decimal, Scientific, and Station formatted value types. Range from 1/(10^0) through 1/(10^12).
* @beta */
export enum DecimalPrecision {
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
Eight = 8,
Nine = 9,
Ten = 10,
Eleven = 11,
Twelve = 12,
}
/** Supported format types
* @beta */
export enum FormatType {
/** Decimal display (ie 2.125) */
Decimal,
/** Fractional display (ie 2-1/8) */
Fractional,
/** Scientific Notation (ie 1.04e3) */
Scientific,
/** Civil Engineering Stationing (ie 1+00). */
Station,
}
/** required if type is scientific
* @beta */
export enum ScientificType {
/** Non-zero value left of decimal point (ie 1.2345e3) */
Normalized,
/** Zero value left of decimal point (ie 0.12345e4) */
ZeroNormalized,
}
/** Determines how the sign of values are displayed
* @beta */
export enum ShowSignOption {
/** Never show a sign even if the value is negative. */
NoSign,
/** Only show a sign when the value is negative. */
OnlyNegative,
/** Always show a sign whether the value is positive or negative. */
SignAlways,
/** Only show a sign when the value is negative but use parentheses instead of a negative sign. For example, -10 is formatted as `(10)`. */
NegativeParentheses,
}
// parse and toString methods
/** @beta */
export function parseScientificType(scientificType: string, formatName: string): ScientificType {
switch (scientificType.toLowerCase()) {
case "normalized": return ScientificType.Normalized;
case "zeronormalized": return ScientificType.ZeroNormalized;
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'scientificType' attribute.`);
}
}
/** @beta */
export function scientificTypeToString(scientificType: ScientificType): string {
return (scientificType === ScientificType.Normalized) ? "Normalized" : "ZeroNormalized";
}
/** @beta */
export function parseShowSignOption(showSignOption: string, formatName: string): ShowSignOption {
switch (showSignOption.toLowerCase()) {
case "nosign": return ShowSignOption.NoSign;
case "onlynegative": return ShowSignOption.OnlyNegative;
case "signalways": return ShowSignOption.SignAlways;
case "negativeparentheses": return ShowSignOption.NegativeParentheses;
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'showSignOption' attribute.`);
}
}
/** @beta */
export function showSignOptionToString(showSign: ShowSignOption): string {
switch (showSign) {
case ShowSignOption.NegativeParentheses: return "NegativeParentheses";
case ShowSignOption.NoSign: return "NoSign";
case ShowSignOption.OnlyNegative: return "OnlyNegative";
case ShowSignOption.SignAlways: return "SignAlways";
}
}
/** @beta */
export function parseFormatTrait(formatTraitsString: string, formatName: string): FormatTraits {
switch (formatTraitsString.toLowerCase()) {
case "trailzeroes": return FormatTraits.TrailZeroes;
case "keepsinglezero": return FormatTraits.KeepSingleZero;
case "zeroempty": return FormatTraits.ZeroEmpty;
case "keepdecimalpoint": return FormatTraits.KeepDecimalPoint;
case "applyrounding": return FormatTraits.ApplyRounding;
case "fractiondash": return FormatTraits.FractionDash;
case "showunitlabel": return FormatTraits.ShowUnitLabel;
case "prependunitlabel": return FormatTraits.PrependUnitLabel;
case "use1000separator": return FormatTraits.Use1000Separator;
case "exponentonlynegative": return FormatTraits.ExponentOnlyNegative;
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'formatTraits' attribute.`);
}
}
/** @beta */
export function getTraitString(trait: FormatTraits) {
switch (trait) {
case FormatTraits.TrailZeroes:
return "trailZeroes";
case FormatTraits.KeepSingleZero:
return "keepSingleZero";
case FormatTraits.ZeroEmpty:
return "zeroEmpty";
case FormatTraits.KeepDecimalPoint:
return "keepDecimalPoint";
case FormatTraits.ApplyRounding:
return "applyRounding";
case FormatTraits.FractionDash:
return "fractionDash";
case FormatTraits.ShowUnitLabel:
return "showUnitLabel";
case FormatTraits.PrependUnitLabel:
return "prependUnitLabel";
case FormatTraits.Use1000Separator:
return "use1000Separator";
case FormatTraits.ExponentOnlyNegative:
default:
return "exponentOnlyNegative";
}
}
/** @beta */
export function formatTraitsToArray(currentFormatTrait: FormatTraits): string[] {
const formatTraitsArr = Array<string>();
if ((currentFormatTrait & FormatTraits.TrailZeroes) === FormatTraits.TrailZeroes)
formatTraitsArr.push("TrailZeroes");
if ((currentFormatTrait & FormatTraits.KeepSingleZero) === FormatTraits.KeepSingleZero)
formatTraitsArr.push("KeepSingleZero");
if ((currentFormatTrait & FormatTraits.ZeroEmpty) === FormatTraits.ZeroEmpty)
formatTraitsArr.push("ZeroEmpty");
if ((currentFormatTrait & FormatTraits.KeepDecimalPoint) === FormatTraits.KeepDecimalPoint)
formatTraitsArr.push("KeepDecimalPoint");
if ((currentFormatTrait & FormatTraits.ApplyRounding) === FormatTraits.ApplyRounding)
formatTraitsArr.push("ApplyRounding");
if ((currentFormatTrait & FormatTraits.FractionDash) === FormatTraits.FractionDash)
formatTraitsArr.push("FractionDash");
if ((currentFormatTrait & FormatTraits.ShowUnitLabel) === FormatTraits.ShowUnitLabel)
formatTraitsArr.push("ShowUnitLabel");
if ((currentFormatTrait & FormatTraits.PrependUnitLabel) === FormatTraits.PrependUnitLabel)
formatTraitsArr.push("PrependUnitLabel");
if ((currentFormatTrait & FormatTraits.Use1000Separator) === FormatTraits.Use1000Separator)
formatTraitsArr.push("Use1000Separator");
if ((currentFormatTrait & FormatTraits.ExponentOnlyNegative) === FormatTraits.ExponentOnlyNegative)
formatTraitsArr.push("ExponentOnlyNegative");
return formatTraitsArr;
}
/** @beta */
export function parseFormatType(jsonObjType: string, formatName: string): FormatType {
switch (jsonObjType.toLowerCase()) {
case "decimal": return FormatType.Decimal;
case "scientific": return FormatType.Scientific;
case "station": return FormatType.Station;
case "fractional": return FormatType.Fractional;
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'type' attribute.`);
}
}
/** @beta */
export function formatTypeToString(type: FormatType): string {
switch (type) {
case FormatType.Decimal: return "Decimal";
case FormatType.Scientific: return "Scientific";
case FormatType.Station: return "Station";
case FormatType.Fractional: return "Fractional";
}
}
/** @beta */
export function parseDecimalPrecision(jsonObjPrecision: number, formatName: string): DecimalPrecision {
switch (jsonObjPrecision) {
case 0: return DecimalPrecision.Zero;
case 1: return DecimalPrecision.One;
case 2: return DecimalPrecision.Two;
case 3: return DecimalPrecision.Three;
case 4: return DecimalPrecision.Four;
case 5: return DecimalPrecision.Five;
case 6: return DecimalPrecision.Six;
case 7: return DecimalPrecision.Seven;
case 8: return DecimalPrecision.Eight;
case 9: return DecimalPrecision.Nine;
case 10: return DecimalPrecision.Ten;
case 11: return DecimalPrecision.Eleven;
case 12: return DecimalPrecision.Twelve;
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'precision' attribute.`);
}
}
/** @beta validates the input value, that is typically extracted for persisted JSON data, is a valid FractionalPrecision */
export function parseFractionalPrecision(jsonObjPrecision: number, formatName: string): FractionalPrecision {
switch (jsonObjPrecision) {
case 1: return FractionalPrecision.One;
case 2: return FractionalPrecision.Two;
case 4: return FractionalPrecision.Four;
case 8: return FractionalPrecision.Eight;
case 16: return FractionalPrecision.Sixteen;
case 32: return FractionalPrecision.ThirtyTwo;
case 64: return FractionalPrecision.SixtyFour;
case 128: return FractionalPrecision.OneHundredTwentyEight;
case 256: return FractionalPrecision.TwoHundredFiftySix;
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'precision' attribute.`);
}
}
/** @beta validates the input value, that is typically extracted for persisted JSON data, is a valid DecimalPrecision or FractionalPrecision. */
export function parsePrecision(precision: number, type: FormatType, formatName: string): DecimalPrecision | FractionalPrecision {
switch (type) { // type must be decimal, fractional, scientific, or station
case FormatType.Decimal:
case FormatType.Scientific:
case FormatType.Station:
return parseDecimalPrecision(precision, formatName);
case FormatType.Fractional:
return parseFractionalPrecision(precision, formatName);
default:
throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${formatName} has an invalid 'precision' attribute.`);
}
} | the_stack |
import { DirectiveForestHooks } from './hooks';
import { ElementPosition, ProfilerFrame, ElementProfile, DirectiveProfile, LifecycleProfile } from 'protocol';
import { runOutsideAngular, isCustomElement } from '../utils';
import { getDirectiveName } from '../highlighter';
import { ComponentTreeNode } from '../component-tree';
import { initializeOrGetDirectiveForestHooks } from '.';
import { Hooks } from './profiler';
let inProgress = false;
let inChangeDetection = false;
let eventMap: Map<any, DirectiveProfile>;
let frameDuration = 0;
let hooks: Partial<Hooks> = {};
export const start = (onFrame: (frame: ProfilerFrame) => void): void => {
if (inProgress) {
throw new Error('Recording already in progress');
}
eventMap = new Map<any, DirectiveProfile>();
inProgress = true;
hooks = getHooks(onFrame);
initializeOrGetDirectiveForestHooks().profiler.subscribe(hooks);
};
export const stop = (): ProfilerFrame => {
const directiveForestHooks = initializeOrGetDirectiveForestHooks();
const result = flushBuffer(directiveForestHooks);
initializeOrGetDirectiveForestHooks().profiler.unsubscribe(hooks);
hooks = {};
inProgress = false;
return result;
};
const startEvent = (map: Record<string, number>, directive: any, label: string) => {
const name = getDirectiveName(directive);
const key = `${name}#${label}`;
map[key] = performance.now();
};
const getEventStart = (map: Record<string, number>, directive: any, label: string) => {
const name = getDirectiveName(directive);
const key = `${name}#${label}`;
return map[key];
};
const getHooks = (onFrame: (frame: ProfilerFrame) => void): Partial<Hooks> => {
const timeStartMap: Record<string, number> = {};
return {
// We flush here because it's possible the current node to overwrite
// an existing removed node.
onCreate(directive: any, node: Node, _: number, isComponent: boolean, position: ElementPosition): void {
eventMap.set(directive, {
isElement: isCustomElement(node),
name: getDirectiveName(directive),
isComponent,
lifecycle: {},
outputs: {},
});
},
onChangeDetectionStart(component: any, node: Node): void {
startEvent(timeStartMap, component, 'changeDetection');
if (!inChangeDetection) {
inChangeDetection = true;
const source = getChangeDetectionSource();
runOutsideAngular(() => {
Promise.resolve().then(() => {
inChangeDetection = false;
onFrame(flushBuffer(initializeOrGetDirectiveForestHooks(), source));
});
});
}
if (!eventMap.has(component)) {
eventMap.set(component, {
isElement: isCustomElement(node),
name: getDirectiveName(component),
isComponent: true,
changeDetection: 0,
lifecycle: {},
outputs: {},
});
}
},
onChangeDetectionEnd(component: any): void {
const profile = eventMap.get(component);
if (profile) {
let current = profile.changeDetection;
if (current === undefined) {
current = 0;
}
const startTimestamp = getEventStart(timeStartMap, component, 'changeDetection');
if (startTimestamp === undefined) {
return;
}
const duration = performance.now() - startTimestamp;
profile.changeDetection = current + duration;
frameDuration += duration;
} else {
console.warn('Could not find profile for', component);
}
},
onDestroy(directive: any, node: Node, _: number, isComponent: boolean, __: ElementPosition): void {
// Make sure we reflect such directives in the report.
if (!eventMap.has(directive)) {
eventMap.set(directive, {
isElement: isComponent && isCustomElement(node),
name: getDirectiveName(directive),
isComponent,
lifecycle: {},
outputs: {},
});
}
},
onLifecycleHookStart(
directive: any,
hookName: keyof LifecycleProfile,
node: Node,
__: number,
isComponent: boolean
): void {
startEvent(timeStartMap, directive, hookName);
if (!eventMap.has(directive)) {
eventMap.set(directive, {
isElement: isCustomElement(node),
name: getDirectiveName(directive),
isComponent,
lifecycle: {},
outputs: {},
});
}
},
onLifecycleHookEnd(directive: any, hookName: keyof LifecycleProfile, _: Node, __: number, ___: boolean): void {
const dir = eventMap.get(directive);
const startTimestamp = getEventStart(timeStartMap, directive, hookName);
if (startTimestamp === undefined) {
return;
}
if (!dir) {
console.warn('Could not find directive in onLifecycleHook callback', directive, hookName);
return;
}
const duration = performance.now() - startTimestamp;
dir.lifecycle[hookName] = (dir.lifecycle[hookName] || 0) + duration;
frameDuration += duration;
},
onOutputStart(componentOrDirective: any, outputName: string, node: Node, isComponent: boolean): void {
startEvent(timeStartMap, componentOrDirective, outputName);
if (!eventMap.has(componentOrDirective)) {
eventMap.set(componentOrDirective, {
isElement: isCustomElement(node),
name: getDirectiveName(componentOrDirective),
isComponent,
lifecycle: {},
outputs: {},
});
}
},
onOutputEnd(componentOrDirective: any, outputName: string): void {
const name = outputName;
const entry = eventMap.get(componentOrDirective);
const startTimestamp = getEventStart(timeStartMap, componentOrDirective, name);
if (startTimestamp === undefined) {
return;
}
if (!entry) {
console.warn('Could not find directive or component in onOutputEnd callback', componentOrDirective, outputName);
return;
}
const duration = performance.now() - startTimestamp;
entry.outputs[name] = (entry.outputs[name] || 0) + duration;
frameDuration += duration;
},
};
};
const insertOrMerge = (lastFrame: ElementProfile, profile: DirectiveProfile) => {
let exists = false;
lastFrame.directives.forEach((d) => {
if (d.name === profile.name) {
exists = true;
let current = d.changeDetection;
if (current === undefined) {
current = 0;
}
d.changeDetection = current + (profile.changeDetection ?? 0);
for (const key of Object.keys(profile.lifecycle)) {
if (!d.lifecycle[key]) {
d.lifecycle[key] = 0;
}
d.lifecycle[key] += profile.lifecycle[key];
}
for (const key of Object.keys(profile.outputs)) {
if (!d.outputs[key]) {
d.outputs[key] = 0;
}
d.outputs[key] += profile.outputs[key];
}
}
});
if (!exists) {
lastFrame.directives.push(profile);
}
};
const insertElementProfile = (frames: ElementProfile[], position: ElementPosition, profile?: DirectiveProfile) => {
if (!profile) {
return;
}
const original = frames;
for (let i = 0; i < position.length - 1; i++) {
const pos = position[i];
if (!frames[pos]) {
// TODO(mgechev): consider how to ensure we don't hit this case
console.warn('Unable to find parent node for', profile, original);
return;
}
frames = frames[pos].children;
}
const lastIdx = position[position.length - 1];
let lastFrame: ElementProfile = {
children: [],
directives: [],
};
if (frames[lastIdx]) {
lastFrame = frames[lastIdx];
} else {
frames[lastIdx] = lastFrame;
}
insertOrMerge(lastFrame, profile);
};
const prepareInitialFrame = (source: string, duration: number) => {
const frame: ProfilerFrame = {
source,
duration,
directives: [],
};
const directiveForestHooks = initializeOrGetDirectiveForestHooks();
const directiveForest = directiveForestHooks.getIndexedDirectiveForest();
const traverse = (node: ComponentTreeNode, children = frame.directives) => {
let position: ElementPosition | undefined;
if (node.component) {
position = directiveForestHooks.getDirectivePosition(node.component.instance);
} else {
position = directiveForestHooks.getDirectivePosition(node.directives[0].instance);
}
if (position === undefined) {
return;
}
const directives = node.directives.map((d) => {
return {
isComponent: false,
isElement: false,
name: getDirectiveName(d.instance),
outputs: {},
lifecycle: {},
};
});
if (node.component) {
directives.push({
isElement: node.component.isElement,
isComponent: true,
lifecycle: {},
outputs: {},
name: getDirectiveName(node.component.instance),
});
}
const result = {
children: [],
directives,
};
children[position[position.length - 1]] = result;
node.children.forEach((n) => traverse(n, result.children));
};
directiveForest.forEach((n) => traverse(n));
return frame;
};
const flushBuffer = (directiveForestHooks: DirectiveForestHooks, source: string = '') => {
const items = Array.from(eventMap.keys());
const positions: ElementPosition[] = [];
const positionDirective = new Map<ElementPosition, any>();
items.forEach((dir) => {
const position = directiveForestHooks.getDirectivePosition(dir);
if (position === undefined) {
return;
}
positions.push(position);
positionDirective.set(position, dir);
});
positions.sort(lexicographicOrder);
const result = prepareInitialFrame(source, frameDuration);
frameDuration = 0;
positions.forEach((position) => {
const dir = positionDirective.get(position);
insertElementProfile(result.directives, position, eventMap.get(dir));
});
eventMap = new Map<any, DirectiveProfile>();
return result;
};
const getChangeDetectionSource = () => {
const zone = (window as any).Zone;
if (!zone || !zone.currentTask) {
return '';
}
return zone.currentTask.source;
};
const lexicographicOrder = (a: ElementPosition, b: ElementPosition) => {
if (a.length < b.length) {
return -1;
}
if (a.length > b.length) {
return 1;
}
for (let i = 0; i < a.length; i++) {
if (a[i] < b[i]) {
return -1;
}
if (a[i] > b[i]) {
return 1;
}
}
return 0;
}; | the_stack |
import { CONFIG } from './Config'
import Core from './gameUnits/Core'
import Formations from './utils/Formations'
import { common } from './Common'
import { IGameUnit } from './gameUnits/IGameUnit'
import Ground from './Ground'
import Lobby from './hud/Lobby'
import MathHelpers from './MathHelpers'
import { CenterOfMassMarker } from './gameUnits/CenterOfMassMarker'
let PickingInfo = BABYLON.PickingInfo
let Vector3 = BABYLON.Vector3
let FreeCamera = BABYLON.FreeCamera
import './styles/index'
export class Game {
startingNumberOfCores: number = 7
// lobby: Lobby = new Lobby()
canvas: HTMLCanvasElement
engine: BABYLON.Engine = new BABYLON.Engine(document.getElementById('glcanvas') as HTMLCanvasElement, true)
scene: BABYLON.Scene = new BABYLON.Scene(this.engine)
gameUnits: Array<IGameUnit>
camera: BABYLON.FreeCamera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 15, -40), this.scene)
// todo move to remote Users
enemyUnits: IGameUnit[] = []
selectionPrgress = false
ground: Ground
centerOfMass: CenterOfMassMarker
get selectedUnits () {
return this.gameUnits.filter(unit => unit.isSelected)
}
constructor () {
this.canvas = this.engine.getRenderingCanvas()
this.initScene()
this.adjustCanvasDimensions()
this.addListeners()
this.gameUnits = this.createInitialPlayerUnits()
let formation = Formations.circularGrouping(this.gameUnits.length, new Vector3(0, 0, 0))
for (let i = 0; i < this.gameUnits.length; i++) {
this.gameUnits[i].mesh.position = formation[i]
}
this.camera.detachControl(this.canvas)
this.centerOfMass = new CenterOfMassMarker(this.scene, true)
this.centerOfMass.mesh.position = Formations.getCentroid(this.gameUnits)
this.engine.runRenderLoop(() => {
this.centerOfMass.mesh.position = Formations.getCentroid(this.gameUnits)
this.scene.render()
})
}
/**
* We need this to get proper scaling of the 2d overlay canvas
*/
adjustCanvasDimensions () {
var width = this.context.canvas.clientWidth;
var height = this.context.canvas.clientHeight;
this.canvas2D.width = width
this.canvas2D.height = height
this.canvas2D.height = height
}
addListeners () {
window.addEventListener('resize', () => {
//todo some logic
this.engine.resize()
this.adjustCanvasDimensions()
})
this.scene.onPointerUp = this.onScenePointerDown.bind(this)
/**
* Creates events related to the 2d overlay
*/
let onPointerMove = (evt: PointerEvent) => {
this.endPos = { x: this.scene.pointerX, y: this.scene.pointerY }
console.log('pointer move')
let x = Math.min(this.startPos.x, this.endPos.x)
let y = Math.min(this.startPos.y, this.endPos.y)
let w = Math.abs(this.startPos.x - this.endPos.x)
let h = Math.abs(this.startPos.y - this.endPos.y)
this.context.clearRect(0, 0, this.canvas2D.width, this.canvas2D.height)
if (CONFIG.SELECTION_CONFIG.Stroke) {
this.context.strokeStyle = "#28ff26"
this.context.strokeRect(x, y, w, h)
}
if (CONFIG.SELECTION_CONFIG.Fill) {
this.context.globalAlpha = 0.2;
this.context.fillRect(x, y, w, h)
this.context.globalAlpha = 1;
}
// ignore accedental mouse select moves
if (!(w < 4 && h < 4)) {
this.selectionPrgress = true
}
console.log("select progres" + this.selectionPrgress)
}
// variable here because we want to remove it on mouse up
let onPointerMoveB = onPointerMove.bind(this)
window.addEventListener('mousedown', (evt: PointerEvent) => {
/*
if (evt.button !== common.MOUSE.LEFT) {
return
}
*/
console.log('pointer down')
this.startPos = { x: this.scene.pointerX, y: this.scene.pointerY }
window.addEventListener('mousemove', onPointerMoveB)
})
// todo is this better/possible combined with the scene pointer down
window.addEventListener('mouseup', (evt: PointerEvent) => {
/* if (evt.button !== common.MOUSE.LEFT) {
return
}*/
window.removeEventListener('mousemove', onPointerMoveB)
console.log('pointer up')
if (!this.selectionPrgress) {
return
}
this.selectionPrgress = false
console.log("select progres" + this.selectionPrgress)
this.context.clearRect(0, 0, this.canvas2D.width, this.canvas2D.height)
if (!this.endPos) {
return
}
let x = Math.min(this.startPos.x, this.endPos.x)
let y = Math.min(this.startPos.y, this.endPos.y)
let w = Math.abs(this.startPos.x - this.endPos.x)
let h = Math.abs(this.startPos.y - this.endPos.y)
// no need to select anything in this case
if (w === 0 || h === 0) {
return
}
this.OnSelectionEnd(x, y, w, h)
}
)
}
/**
* Allows drawing over to select units and shows health points of units. Also shows selection rectangle when user
* clicks and drags over units.
*/
private canvas2D: HTMLCanvasElement = document.getElementById('gameOverlay') as HTMLCanvasElement
private context: CanvasRenderingContext2D = this.canvas2D.getContext('2d')
private startPos
private endPos
onScenePointerDown (evt, pickResult: BABYLON.PickingInfo) {
console.log("scene pointer down")
// ignore if not click
if (evt.button !== 0 || this.selectionPrgress) {
return
}
// make the pickResult y = 1 to stop things moving vertically
pickResult.pickedPoint.y = common.defaultY
let isOwnUnitHit = this.gameUnits.some((el: IGameUnit) => {
return pickResult.pickedMesh === el.mesh
})
if (isOwnUnitHit) {
if (evt.shiftKey) {
return // the unit will select itself in the events manager
}
// deselection of of other units if selected without shift key
this.gameUnits.filter((el: IGameUnit) => {
return pickResult.pickedMesh !== el.mesh
}).forEach((el: IGameUnit) => {
el.deselect()
})
return
}
// check for enemy targeted
for (let i = 0; i < this.enemyUnits.length; i++) {
if (pickResult.pickedMesh === this.enemyUnits[i].mesh) {
this.gameUnits.filter((el: IGameUnit) => {
return el.isSelected
}).forEach((el: IGameUnit) => {
el.weapon.fire(el, this.enemyUnits[i], this.scene)
})
return
}
}
// check for ground hit
if (pickResult.pickedMesh === this.ground.mesh) {
//ground hit, now check if any units selected
if (this.gameUnits.filter((item: IGameUnit) => {return item.isSelected}).length) {
this.addMoveCommand(pickResult.pickedPoint)
}
} else {
}
}
initScene () {
// This targets the camera to scene origin
this.camera.setTarget(BABYLON.Vector3.Zero())
// This attaches the camera to the canvas
this.camera.attachControl(this.canvas, true)
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
let light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), this.scene)
// Default intensity is 1. Let's dim the light a small amount
light.intensity = 0.7
// Move the sphere upward 1/2 its height
// Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
this.ground = new Ground(this.scene)
// Skybox
let skybox = BABYLON.Mesh.CreateBox('skyBox', 750.0, this.scene)
let skyboxMaterial = new BABYLON.StandardMaterial('skyBox', this.scene)
skyboxMaterial.backFaceCulling = false
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0)
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0)
skyboxMaterial.emissiveColor = new BABYLON.Color3(0, 0.0, 0.0)
skybox.material = skyboxMaterial
this.setUpDummyEnemys()
}
addMoveCommand (pickResult: BABYLON.Vector3) {
let selectedUnits = this.gameUnits.filter((unit: IGameUnit) => {
return unit.isSelected
})
let formation = Formations.circularGrouping(selectedUnits.length, pickResult)
for (let i = 0; i < selectedUnits.length; i++) {
let unit = selectedUnits[i]
// use pythagoras to work out the realtive speed for the units to arrive at roughly the same time
let distance = Math.sqrt(Math.pow(pickResult.x - unit.mesh.position.x, 2)
+ Math.pow(pickResult.z - unit.mesh.position.z, 2))
let framesNeeded = Math.round((distance / common.MEDIUM_SPEED) * common.ANIMATIONS_FPS)
// console.log('dist: ' + distance + ' frames' + framesNeeded)
let animationBezierTorus = new BABYLON.Animation('animationCore', 'position',
common.ANIMATIONS_FPS,
BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT)
let keysBezierTorus = []
keysBezierTorus.push({ frame: 0, value: unit.mesh.position })
keysBezierTorus.push({
frame: framesNeeded,
value: unit.mesh.position = formation[i]
})
animationBezierTorus.setKeys(keysBezierTorus)
unit.mesh.animations.push(animationBezierTorus)
this.scene.beginAnimation(unit.mesh, 0, framesNeeded, true) // todo move animation to server side
}
}
createInitialPlayerUnits () {
let cores: IGameUnit[] = []
for (let i = 0; i < this.startingNumberOfCores; i++) {
let core = new Core(this.scene, true)
core.mesh.position.y = common.defaultY
cores.push(core)
}
return cores
}
setUpDummyEnemys () {
for (let i = 0; i < 5; i++) {
let newCore = new Core(this.scene, false)
let newCore2 = new Core(this.scene, false)
newCore.mesh.position = new Vector3(10 + 2 * i, common.defaultY, 10 + 2 * i)
newCore2.mesh.position = new Vector3(14 + 2 * i, common.defaultY, 10 + 2 * i)
this.enemyUnits.push(newCore)
this.enemyUnits.push(newCore2)
}
}
deselectAllUnits () {
this.gameUnits.forEach(unit => {unit.deselect()})
}
OnSelectionEnd (x: number, y: number, w: number, h: number) {
let area: Array<BABYLON.Vector3> = new Array<BABYLON.Vector3>(4)
let units: Array<BABYLON.AbstractMesh>
// Translate points to world coordinates
area[0] = this.scene.pick(x, y).pickedPoint
area[1] = this.scene.pick(x + w, y).pickedPoint
area[2] = this.scene.pick(x + w, y + h).pickedPoint
area[3] = this.scene.pick(x, y + h).pickedPoint
// this._selectedUnits = this._players[this._localPlayer].units.filter(
let toBeSelected: IGameUnit[] = this.gameUnits.filter(
(unit: IGameUnit) => {
return MathHelpers.isPointInPolyBabylon(area, unit.mesh.position) // helper is up
})
if (!toBeSelected.length) {
return
}
// todo option for appending selection
this.deselectAllUnits()
toBeSelected.forEach(
(unit: IGameUnit) => {
if (MathHelpers.isPointInPolyBabylon(area, unit.mesh.position)) {
unit.select()
}
})
console.log(this.selectedUnits)
}
/**
* this show health and stuff on 2d canvas
* @param units
*/
showUnitsStatus (units: Array<IGameUnit>) {
units.forEach((unit: IGameUnit) => {
// let info:BoundingInfo = unit.mesh.getpic
// this.context2D.fillText(info.toString(),info.x)
})
}
} | the_stack |
module android.text {
import Canvas = android.graphics.Canvas;
import Paint = android.graphics.Paint;
import Path = android.graphics.Path;
import ParagraphStyle = android.text.style.ParagraphStyle;
import Layout = android.text.Layout;
import Spanned = android.text.Spanned;
import TextDirectionHeuristic = android.text.TextDirectionHeuristic;
import TextDirectionHeuristics = android.text.TextDirectionHeuristics;
import TextLine = android.text.TextLine;
import TextPaint = android.text.TextPaint;
import TextUtils = android.text.TextUtils;
/**
* A BoringLayout is a very simple Layout implementation for text that
* fits on a single line and is all left-to-right characters.
* You will probably never want to make one of these yourself;
* if you do, be sure to call {@link #isBoring} first to make sure
* the text meets the criteria.
* <p>This class is used by widgets to control text layout. You should not need
* to use this class directly unless you are implementing your own widget
* or custom display object, in which case
* you are encouraged to use a Layout instead of calling
* {@link android.graphics.Canvas#drawText(java.lang.CharSequence, int, int, float, float, android.graphics.Paint)
* Canvas.drawText()} directly.</p>
*/
export class BoringLayout extends Layout implements TextUtils.EllipsizeCallback {
static make(source:String, paint:TextPaint, outerwidth:number, align:Layout.Alignment, spacingmult:number, spacingadd:number,
metrics:BoringLayout.Metrics, includepad:boolean, ellipsize:TextUtils.TruncateAt=null, ellipsizedWidth:number=outerwidth):BoringLayout {
return new BoringLayout(source, paint, outerwidth, align, spacingmult, spacingadd, metrics, includepad, ellipsize, ellipsizedWidth);
}
/**
* Returns a BoringLayout for the specified text, potentially reusing
* this one if it is already suitable. The caller must make sure that
* no one is still using this Layout.
*/
replaceOrMake(source:String, paint:TextPaint, outerwidth:number, align:Layout.Alignment, spacingmult:number, spacingadd:number,
metrics:BoringLayout.Metrics, includepad:boolean, ellipsize:TextUtils.TruncateAt=null, ellipsizedWidth:number=outerwidth):BoringLayout {
let trust:boolean;
if (ellipsize == null || ellipsize == TextUtils.TruncateAt.MARQUEE) {
this.replaceWith(source, paint, outerwidth, align, spacingmult, spacingadd);
this.mEllipsizedWidth = outerwidth;
this.mEllipsizedStart = 0;
this.mEllipsizedCount = 0;
trust = true;
} else {
this.replaceWith(TextUtils.ellipsize(source, paint, ellipsizedWidth, ellipsize, true, this), paint, outerwidth, align, spacingmult, spacingadd);
this.mEllipsizedWidth = ellipsizedWidth;
trust = false;
}
this.init(this.getText(), paint, outerwidth, align, spacingmult, spacingadd, metrics, includepad, trust);
return this;
}
constructor( source:String, paint:TextPaint, outerwidth:number, align:Layout.Alignment, spacingmult:number, spacingadd:number,
metrics:BoringLayout.Metrics, includepad:boolean, ellipsize:TextUtils.TruncateAt=null, ellipsizedWidth:number=outerwidth) {
/*
* It is silly to have to call super() and then replaceWith(),
* but we can't use "this" for the callback until the call to
* super() finishes.
*/
super(source, paint, outerwidth, align, TextDirectionHeuristics.FIRSTSTRONG_LTR, spacingmult, spacingadd);
let trust:boolean;
if (ellipsize == null || ellipsize == TextUtils.TruncateAt.MARQUEE) {
this.mEllipsizedWidth = outerwidth;
this.mEllipsizedStart = 0;
this.mEllipsizedCount = 0;
trust = true;
} else {
this.replaceWith(TextUtils.ellipsize(source, paint, ellipsizedWidth, ellipsize, true, this), paint, outerwidth, align, spacingmult, spacingadd);
this.mEllipsizedWidth = ellipsizedWidth;
trust = false;
}
this.init(this.getText(), paint, outerwidth, align, spacingmult, spacingadd, metrics, includepad, trust);
}
/* package */
init(source:String, paint:TextPaint, outerwidth:number, align:Layout.Alignment, spacingmult:number,
spacingadd:number, metrics:BoringLayout.Metrics, includepad:boolean, trustWidth:boolean):void {
let spacing:number;
if (Object.getPrototypeOf(source) === String.prototype && align == Layout.Alignment.ALIGN_NORMAL) {
this.mDirect = source.toString();
} else {
this.mDirect = null;
}
this.mPaint = paint;
if (includepad) {
spacing = metrics.bottom - metrics.top;
} else {
spacing = metrics.descent - metrics.ascent;
}
if (spacingmult != 1 || spacingadd != 0) {
spacing = Math.floor((spacing * spacingmult + spacingadd + 0.5));
}
this.mBottom = spacing;
if (includepad) {
this.mDesc = spacing + metrics.top;
} else {
this.mDesc = spacing + metrics.ascent;
}
if (trustWidth) {
this.mMax = metrics.width;
} else {
/*
* If we have ellipsized, we have to actually calculate the
* width because the width that was passed in was for the
* full text, not the ellipsized form.
*/
let line:TextLine = TextLine.obtain();
line.set(paint, source, 0, source.length, Layout.DIR_LEFT_TO_RIGHT, Layout.DIRS_ALL_LEFT_TO_RIGHT, false, null);
this.mMax = Math.floor(Math.ceil(line.metrics(null)));
TextLine.recycle(line);
}
if (includepad) {
this.mTopPadding = metrics.top - metrics.ascent;
this.mBottomPadding = metrics.bottom - metrics.descent;
}
}
/**
* Returns null if not boring; the width, ascent, and descent in the
* provided Metrics object (or a new one if the provided one was null)
* if boring.
* @hide
*/
static isBoring(text:String, paint:TextPaint, textDir:TextDirectionHeuristic=TextDirectionHeuristics.FIRSTSTRONG_LTR,
metrics:BoringLayout.Metrics=null):BoringLayout.Metrics {
let temp:string;
let length:number = text.length;
let boring:boolean = true;
outer: for (let i:number = 0; i < length; i += 500) {
let j:number = i + 500;
if (j > length) j = length;
temp = text.substring(i, j);
let n:number = j - i;
for (let a:number = 0; a < n; a++) {
let c:string = temp[a];
if (c == '\n' || c == '\t') { // || c.codePointAt(0) >= BoringLayout.FIRST_RIGHT_TO_LEFT) {
boring = false;
break outer;
}
}
if (textDir != null && textDir.isRtl(temp, 0, n)) {
boring = false;
break outer;
}
}
//TextUtils.recycle(temp);
if (boring && Spanned.isImplements(text) ) {
let sp:Spanned = <Spanned> text;
let styles:any[] = sp.getSpans(0, length, ParagraphStyle.type);
if (styles.length > 0) {
boring = false;
}
}
if (boring) {
let fm:BoringLayout.Metrics = metrics;
if (fm == null) {
fm = new BoringLayout.Metrics();
}
let line:TextLine = TextLine.obtain();
line.set(paint, text, 0, length, Layout.DIR_LEFT_TO_RIGHT, Layout.DIRS_ALL_LEFT_TO_RIGHT, false, null);
fm.width = Math.floor(Math.ceil(line.metrics(fm)));
TextLine.recycle(line);
return fm;
} else {
return null;
}
}
getHeight():number {
return this.mBottom;
}
getLineCount():number {
return 1;
}
getLineTop(line:number):number {
if (line == 0)
return 0;
else
return this.mBottom;
}
getLineDescent(line:number):number {
return this.mDesc;
}
getLineStart(line:number):number {
if (line == 0)
return 0;
else
return this.getText().length;
}
getParagraphDirection(line:number):number {
return BoringLayout.DIR_LEFT_TO_RIGHT;
}
getLineContainsTab(line:number):boolean {
return false;
}
getLineMax(line:number):number {
return this.mMax;
}
getLineDirections(line:number):Layout.Directions {
return Layout.DIRS_ALL_LEFT_TO_RIGHT;
}
getTopPadding():number {
return this.mTopPadding;
}
getBottomPadding():number {
return this.mBottomPadding;
}
getEllipsisCount(line:number):number {
return this.mEllipsizedCount;
}
getEllipsisStart(line:number):number {
return this.mEllipsizedStart;
}
getEllipsizedWidth():number {
return this.mEllipsizedWidth;
}
// Override draw so it will be faster.
draw(c:Canvas, highlight:Path, highlightpaint:Paint, cursorOffset:number):void {
if (this.mDirect != null && highlight == null) {
c.drawText(this.mDirect, 0, this.mBottom - this.mDesc, this.mPaint);
} else {
super.draw(c, highlight, highlightpaint, cursorOffset);
}
}
/**
* Callback for the ellipsizer to report what region it ellipsized.
*/
ellipsized(start:number, end:number):void {
this.mEllipsizedStart = start;
this.mEllipsizedCount = end - start;
}
private static FIRST_RIGHT_TO_LEFT = ''.codePointAt(0);
private mDirect:string;
//private mPaint:Paint;
/* package */
// for Direct
mBottom:number = 0;
mDesc:number = 0;
private mTopPadding:number = 0
private mBottomPadding:number = 0;
private mMax:number = 0;
private mEllipsizedWidth:number = 0;
private mEllipsizedStart:number = 0;
private mEllipsizedCount:number = 0;
private static sTemp:TextPaint = new TextPaint();
}
export module BoringLayout{
export class Metrics extends Paint.FontMetricsInt {
width:number = 0;
toString():string {
return super.toString() + " width=" + this.width;
}
}
}
} | the_stack |
import {CursorPos} from 'app/client/components/Cursor';
import {GristDoc} from 'app/client/components/GristDoc';
import {ViewFieldRec, ViewSectionRec} from 'app/client/models/DocModel';
import {reportError} from 'app/client/models/errors';
import {delay} from 'app/common/delay';
import {waitObs} from 'app/common/gutil';
import {TableData} from 'app/common/TableData';
import {BaseFormatter, createFormatter} from 'app/common/ValueFormatter';
import {Disposable, Observable} from 'grainjs';
import debounce = require('lodash/debounce');
/**
* SearchModel used to maintain the state of the search UI.
*/
export interface SearchModel {
value: Observable<string>; // string in the search input
isOpen: Observable<boolean>; // indicates whether the search bar is expanded to show the input
noMatch: Observable<boolean>; // indicates if there are no search matches
isEmpty: Observable<boolean>; // indicates whether the value is empty
isRunning: Observable<boolean>; // indicates that matching is in progress
multiPage: Observable<boolean>; // if true will search across all pages
findNext(): Promise<void>; // find next match
findPrev(): Promise<void>; // find previous match
}
interface SearchPosition {
pageIndex: number;
sectionIndex: number;
rowIndex: number;
fieldIndex: number;
}
/**
* Stepper is an helper class that is used to implement stepping through all the cells of a
* document. Fields belongs to rows, rows belongs to section and sections to pages. So this is four
* steppers that must be used together, one for each level (field, rows, section and pages). When a
* stepper reaches the end of its array, this is the `nextArrayFunc` callback, passed to the
* `next()`, that is responsible for both taking a step at the higher level and updating the
* stepper's array.
*/
class Stepper<T> {
public array: ReadonlyArray<T> = [];
public index: number = 0;
public inRange() {
return this.index >= 0 && this.index < this.array.length;
}
// Doing await at every step adds a ton of overhead; we can optimize by returning and waiting on
// Promises only when needed.
public next(step: number, nextArrayFunc: () => Promise<void>|void): Promise<void>|void {
this.index += step;
if (!this.inRange()) {
// If index reached the end of the array, take a step at a higher level to get a new array.
// For efficiency, only wait asynchronously if the callback returned a promise.
const p = nextArrayFunc();
if (p) {
return p.then(() => this.setStart(step));
} else {
this.setStart(step);
}
}
}
public setStart(step: number) {
this.index = step > 0 ? 0 : this.array.length - 1;
}
public get value(): T { return this.array[this.index]; }
}
/**
* Interface that represents an ongoing search job which stops on the first match found.
*/
interface IFinder {
matchFound: boolean; // true if a match was found
startPosition: SearchPosition; // position at which to stop searching for a new match
abort(): void; // abort current search
matchNext(step: number): Promise<void>; // next match
nextField(step: number): Promise<void>|void; // move the current position
getCurrentPosition(): SearchPosition; // get the current position
}
// A callback to opening a page: useful to switch to next page during an ongoing search.
type DocPageOpener = (viewId: number) => Promise<void>;
/**
* An implementation of an IFinder.
*/
class FinderImpl implements IFinder {
public matchFound = false;
public startPosition: SearchPosition;
private _searchRegexp: RegExp;
private _pageStepper = new Stepper<any>();
private _sectionStepper = new Stepper<ViewSectionRec>();
private _sectionTableData: TableData;
private _rowStepper = new Stepper<number>();
private _fieldStepper = new Stepper<ViewFieldRec>();
private _fieldFormatters: BaseFormatter[];
private _pagesSwitched: number = 0;
private _aborted = false;
private _clearCursorHighlight: (() => void)|undefined;
constructor(private _gristDoc: GristDoc, value: string, private _openDocPageCB: DocPageOpener,
public multiPage: Observable<boolean>) {
this._searchRegexp = makeRegexp(value);
}
public abort() {
this._aborted = true;
if (this._clearCursorHighlight) { this._clearCursorHighlight(); }
}
public getCurrentPosition(): SearchPosition {
return {
pageIndex: this._pageStepper.index,
sectionIndex: this._sectionStepper.index,
rowIndex: this._rowStepper.index,
fieldIndex: this._fieldStepper.index,
};
}
// Initialize the steppers. Returns false if anything goes wrong.
public init(): boolean {
const pages: any[] = this._gristDoc.docModel.visibleDocPages.peek();
this._pageStepper.array = pages;
this._pageStepper.index = pages.findIndex(t => t.viewRef() === this._gristDoc.activeViewId.get());
if (this._pageStepper.index < 0) { return false; }
const view = this._pageStepper.value.view.peek();
const sections: any[] = view.viewSections().peek();
this._sectionStepper.array = sections;
this._sectionStepper.index = sections.findIndex(s => s.getRowId() === view.activeSectionId());
if (this._sectionStepper.index < 0) { return false; }
this._initNewSectionShown();
// Find the current cursor position in the current section.
const viewInstance = this._sectionStepper.value.viewInstance.peek()!;
const pos = viewInstance.cursor.getCursorPos();
this._rowStepper.index = pos.rowIndex!;
this._fieldStepper.index = pos.fieldIndex!;
return true;
}
public async matchNext(step: number): Promise<void> {
let count = 0;
let lastBreak = Date.now();
this._pagesSwitched = 0;
while (!this._matches() || ((await this._loadSection(step)) && !this._matches())) {
// If search was aborted, simply returns.
if (this._aborted) { return; }
// To avoid hogging the CPU for too long, check time periodically, and if we've been running
// for long enough, take a brief break. We choose a 5ms break every 20ms; and only check
// time every 100 iterations, to avoid excessive overhead purely due to time checks.
if ((++count) % 100 === 0 && Date.now() >= lastBreak + 20) {
await delay(5);
lastBreak = Date.now();
}
const p = this.nextField(step);
if (p) { await p; }
// Detect when we get back to the start position; this is where we break on no match.
if (this._isCurrentPosition(this.startPosition) && !this._matches()) {
console.log("SearchBar: reached start position without finding anything");
this.matchFound = false;
return;
}
// A fail-safe to prevent certain bugs from causing infinite loops; break also if we scan
// through pages too many times.
// TODO: test it by disabling the check above.
if (this._pagesSwitched > this._pageStepper.array.length) {
console.log("SearchBar: aborting search due to too many page switches");
this.matchFound = false;
return;
}
}
console.log("SearchBar: found a match at %s", JSON.stringify(this.getCurrentPosition()));
this.matchFound = true;
await this._highlight();
}
public nextField(step: number): Promise<void>|void {
return this._fieldStepper.next(step, () => this._nextRow(step));
}
private _nextRow(step: number) {
return this._rowStepper.next(step, () => this._nextSection(step));
}
private async _nextSection(step: number) {
// Switching sections is rare enough that we don't worry about optimizing away `await` calls.
await this._sectionStepper.next(step, () => this._nextPage(step));
await this._initNewSectionAny();
}
// TODO There are issues with filtering. A section may have filters applied, and it may be
// auto-filtered (linked sections). If a tab is shown, we have the filtered list of rowIds; if
// the tab is not shown, it takes work to apply explicit filters. For linked sections, the
// sensible behavior seems to scan through ALL values, then once a match is found, set the
// cursor that determines the linking to include the matched row. And even that may not always
// be possible. So this is an open question.
private _initNewSectionCommon() {
const section = this._sectionStepper.value;
const tableModel = this._gristDoc.getTableModel(section.table.peek().tableId.peek());
this._sectionTableData = tableModel.tableData;
this._fieldStepper.array = section.viewFields().peek();
this._fieldFormatters = this._fieldStepper.array.map(
f => createFormatter(f.displayColModel().type(), f.widgetOptionsJson(), f.documentSettings()));
return tableModel;
}
private _initNewSectionShown() {
this._initNewSectionCommon();
const viewInstance = this._sectionStepper.value.viewInstance.peek()!;
this._rowStepper.array = viewInstance.sortedRows.getKoArray().peek() as number[];
}
private async _initNewSectionAny() {
const tableModel = this._initNewSectionCommon();
const viewInstance = this._sectionStepper.value.viewInstance.peek();
if (viewInstance) {
this._rowStepper.array = viewInstance.sortedRows.getKoArray().peek() as number[];
} else {
// If we are searching through another page (not currently loaded), we will NOT have a
// viewInstance, but we use the unsorted unfiltered row list, and if we find a match, the
// _loadSection() method will load the page and we'll repeat the search with a viewInstance.
await tableModel.fetch();
this._rowStepper.array = this._sectionTableData.getRowIds();
}
}
private async _nextPage(step: number) {
if (!this.multiPage.get()) { return; }
await this._pageStepper.next(step, () => undefined);
this._pagesSwitched++;
const view = this._pageStepper.value.view.peek();
this._sectionStepper.array = view.viewSections().peek();
}
private _matches(): boolean {
if (this._pageStepper.index < 0 || this._sectionStepper.index < 0 ||
this._rowStepper.index < 0 || this._fieldStepper.index < 0) {
console.warn("match outside");
return false;
}
const field = this._fieldStepper.value;
const formatter = this._fieldFormatters[this._fieldStepper.index];
const rowId = this._rowStepper.value;
const displayCol = field.displayColModel.peek();
const value = this._sectionTableData.getValue(rowId, displayCol.colId.peek());
// TODO: Note that formatting dates is now the bulk of the performance cost.
const text = formatter.format(value);
return this._searchRegexp.test(text);
}
private async _loadSection(step: number): Promise<boolean> {
// If we found a match in a section for which we don't have a valid BaseView instance, we need
// to load the BaseView and start searching the section again, since the match we found does
// not take into account sort or filters. So we switch to the right page, wait for the
// viewInstance to be created, reset the section info, and return true to continue searching.
const section = this._sectionStepper.value;
if (!section.viewInstance.peek()) {
const view = this._pageStepper.value.view.peek();
await this._openDocPage(view.getRowId());
console.log("SearchBar: loading view %s section %s", view.getRowId(), section.getRowId());
const viewInstance: any = await waitObs(section.viewInstance);
await viewInstance.getLoadingDonePromise();
this._initNewSectionShown();
this._rowStepper.setStart(step);
this._fieldStepper.setStart(step);
console.log("SearchBar: loaded view %s section %s", view.getRowId(), section.getRowId());
return true;
}
return false;
}
// Highlights the cell at the current position.
private async _highlight() {
if (this._aborted) { return; }
const section = this._sectionStepper.value;
const sectionId = section.getRowId();
const cursorPos: CursorPos = {
sectionId,
rowId: this._rowStepper.value,
fieldIndex: this._fieldStepper.index,
};
await this._gristDoc.recursiveMoveToCursorPos(cursorPos, true).catch(reportError);
if (this._aborted) { return; }
// Highlight the selected cursor, after giving it a chance to update. We find the cursor in
// this ad-hoc way rather than use observables, to avoid the overhead of *every* cell
// depending on an additional observable.
await delay(0);
const viewInstance = await waitObs<any>(section.viewInstance);
await viewInstance.getLoadingDonePromise();
if (this._aborted) { return; }
const cursor = viewInstance.viewPane.querySelector('.selected_cursor');
if (cursor) {
cursor.classList.add('search-match');
this._clearCursorHighlight = () => {
cursor.classList.remove('search-match');
clearTimeout(timeout);
this._clearCursorHighlight = undefined;
};
const timeout = setTimeout(this._clearCursorHighlight, 20);
}
}
private _isCurrentPosition(pos: SearchPosition): boolean {
return (
this._pageStepper.index === pos.pageIndex &&
this._sectionStepper.index === pos.sectionIndex &&
this._rowStepper.index === pos.rowIndex &&
this._fieldStepper.index === pos.fieldIndex
);
}
private _openDocPage(viewId: number) {
if (this._aborted) { return; }
return this._openDocPageCB(viewId);
}
}
/**
* Implementation of SearchModel used to construct the search UI.
*/
export class SearchModelImpl extends Disposable implements SearchModel {
public readonly value = Observable.create(this, '');
public readonly isOpen = Observable.create(this, false);
public readonly isRunning = Observable.create(this, false);
public readonly noMatch = Observable.create(this, true);
public readonly isEmpty = Observable.create(this, true);
public readonly multiPage = Observable.create(this, false);
private _isRestartNeeded = false;
private _finder: IFinder|null = null;
constructor(private _gristDoc: GristDoc) {
super();
// Listen to input value changes (debounced) to activate searching.
const findFirst = debounce((_value: string) => this._findFirst(_value), 100);
this.autoDispose(this.value.addListener(v => { this.isRunning.set(true); void findFirst(v); }));
// Set this.noMatch to false when multiPage gets turned ON.
this.autoDispose(this.multiPage.addListener(v => { if (v) { this.noMatch.set(false); } }));
// Schedule a search restart when user changes pages (otherwise search would resume from the
// previous page that is not shown anymore). Also revert noMatch flag when in single page mode.
this.autoDispose(this._gristDoc.activeViewId.addListener(() => {
if (!this.multiPage.get()) { this.noMatch.set(false); }
this._isRestartNeeded = true;
}));
}
public async findNext() {
if (this.isRunning.get() || this.noMatch.get()) { return; }
if (this._isRestartNeeded) { return this._findFirst(this.value.get()); }
await this._run(async (finder) => {
await finder.nextField(1);
await finder.matchNext(1);
});
}
public async findPrev() {
if (this.isRunning.get() || this.noMatch.get()) { return; }
if (this._isRestartNeeded) { return this._findFirst(this.value.get()); }
await this._run(async (finder) => {
await finder.nextField(-1);
await finder.matchNext(-1);
});
}
private async _findFirst(value: string) {
this._isRestartNeeded = false;
this.isEmpty.set(!value);
this._updateFinder(value);
if (!value || !this._finder) { this.noMatch.set(true); return; }
await this._run(async (finder) => {
await finder.matchNext(1);
});
}
private _updateFinder(value: string) {
if (this._finder) { this._finder.abort(); }
const impl = new FinderImpl(this._gristDoc, value, this._openDocPage.bind(this), this.multiPage);
const isValid = impl.init();
this._finder = isValid ? impl : null;
}
// Internal helper that runs cb, passing it the current `this._finder` as first argument and sets
// this.isRunning to true until the call resolves. It also takes care of updating this.noMatch.
private async _run(cb: (finder: IFinder) => Promise<void>) {
const finder = this._finder;
if (!finder) { throw new Error("SearchModel: finder is not defined"); }
try {
this.isRunning.set(true);
finder.startPosition = finder.getCurrentPosition();
await cb(finder);
} finally {
this.isRunning.set(false);
this.noMatch.set(!finder.matchFound);
}
}
// Opens doc page without triggering a restart.
private async _openDocPage(viewId: number) {
await this._gristDoc.openDocPage(viewId);
this._isRestartNeeded = false;
}
}
function makeRegexp(value: string) {
// From https://stackoverflow.com/a/3561711/328565
const escaped = value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(escaped, 'i');
} | the_stack |
import * as path from 'path';
import * as ts from 'typescript';
import * as base from './base';
import {Transpiler} from './main';
type CallHandler = (c: ts.CallExpression, context: ts.Expression) => void;
type PropertyHandler = (c: ts.PropertyAccessExpression) => void;
type Set = {
[s: string]: boolean
};
const FACADE_DEBUG = false;
const DEFAULT_LIB_MARKER = '__ts2dart_default_lib';
const PROVIDER_IMPORT_MARKER = '__ts2dart_has_provider_import';
const TS2DART_PROVIDER_COMMENT = '@ts2dart_Provider';
function merge(...args: {[key: string]: any}[]): {[key: string]: any} {
let returnObject: {[key: string]: any} = {};
for (let arg of args) {
for (let key of Object.getOwnPropertyNames(arg)) {
returnObject[key] = arg[key];
}
}
return returnObject;
}
export class FacadeConverter extends base.TranspilerBase {
private tc: ts.TypeChecker;
private defaultLibLocation: string;
private candidateProperties: {[propertyName: string]: boolean} = {};
private candidateTypes: {[typeName: string]: boolean} = {};
private genericMethodDeclDepth = 0;
constructor(transpiler: Transpiler) {
super(transpiler);
this.extractPropertyNames(this.callHandlers, this.candidateProperties);
this.extractPropertyNames(this.propertyHandlers, this.candidateProperties);
this.extractPropertyNames(this.tsToDartTypeNames, this.candidateTypes);
}
initializeTypeBasedConversion(
tc: ts.TypeChecker, opts: ts.CompilerOptions, host: ts.CompilerHost) {
this.tc = tc;
this.defaultLibLocation = ts.getDefaultLibFilePath(opts).replace(/\.d\.ts$/, '');
this.resolveModuleNames(opts, host, this.callHandlers);
this.resolveModuleNames(opts, host, this.propertyHandlers);
this.resolveModuleNames(opts, host, this.tsToDartTypeNames);
this.resolveModuleNames(opts, host, this.callHandlerReplaceNew);
}
private extractPropertyNames(m: ts.Map<ts.Map<any>>, candidates: {[k: string]: boolean}) {
for (let fileName of Object.keys(m)) {
const file = m[fileName];
Object.keys(file)
.map((propName) => propName.substring(propName.lastIndexOf('.') + 1))
.forEach((propName) => candidates[propName] = true);
}
}
private resolveModuleNames(
opts: ts.CompilerOptions, host: ts.CompilerHost, m: ts.Map<ts.Map<any>>) {
for (let mn of Object.keys(m)) {
let actual: string;
let absolute: string;
if (mn === DEFAULT_LIB_MARKER) {
actual = this.defaultLibLocation;
} else {
let resolved = ts.resolveModuleName(mn, '', opts, host);
if (!resolved.resolvedModule) continue;
actual = resolved.resolvedModule.resolvedFileName.replace(/(\.d)?\.ts$/, '');
// TypeScript's resolution returns relative paths here, but uses absolute ones in
// SourceFile.fileName later. Make sure to hit both use cases.
absolute = path.resolve(actual);
}
if (FACADE_DEBUG) console.log('Resolved module', mn, '->', actual);
m[actual] = m[mn];
if (absolute) m[absolute] = m[mn];
}
}
/**
* To avoid strongly referencing the Provider class (which could bloat binary size), Angular 2
* write providers as object literals. However the Dart transformers don't recognize this, so
* ts2dart translates the special syntax `/* @ts2dart_Provider * / {provide: Class, param1: ...}`
* into `const Provider(Class, param1: ...)`.
*/
maybeHandleProvider(ole: ts.ObjectLiteralExpression): boolean {
if (!this.hasMarkerComment(ole, TS2DART_PROVIDER_COMMENT)) return false;
let classParam: ts.Expression;
let remaining = ole.properties.filter((e) => {
if (e.kind !== ts.SyntaxKind.PropertyAssignment) {
this.reportError(e, TS2DART_PROVIDER_COMMENT + ' elements must be property assignments');
}
if ('provide' === base.ident(e.name)) {
classParam = (e as ts.PropertyAssignment).initializer;
return false;
}
return true; // include below.
});
if (!classParam) {
this.reportError(ole, 'missing provide: element');
return false;
}
this.emit('const Provider(');
this.visit(classParam);
if (remaining.length > 0) {
this.emit(',');
for (let i = 0; i < remaining.length; i++) {
let e = remaining[i];
if (e.kind !== ts.SyntaxKind.PropertyAssignment) this.visit(e.name);
this.emit(base.ident(e.name));
this.emit(':');
this.visit((e as ts.PropertyAssignment).initializer);
if ((i + 1) < remaining.length) this.emit(',');
}
this.emit(')');
}
return true;
}
maybeHandleCall(c: ts.CallExpression): boolean {
if (!this.tc) return false;
let {context, symbol} = this.getCallInformation(c);
if (!symbol) {
// getCallInformation returns a symbol if we understand this call.
return false;
}
let handler = this.getHandler(c, symbol, this.callHandlers);
return handler && !handler(c, context);
}
handlePropertyAccess(pa: ts.PropertyAccessExpression): boolean {
if (!this.tc) return;
let ident = pa.name.text;
if (!this.candidateProperties.hasOwnProperty(ident)) return false;
let symbol = this.tc.getSymbolAtLocation(pa.name);
if (!symbol) {
this.reportMissingType(pa, ident);
return false;
}
let handler = this.getHandler(pa, symbol, this.propertyHandlers);
return handler && !handler(pa);
}
/**
* Searches for type references that require extra imports and emits the imports as necessary.
*/
emitExtraImports(sourceFile: ts.SourceFile) {
let libraries = <ts.Map<string>>{
'XMLHttpRequest': 'dart:html',
'KeyboardEvent': 'dart:html',
'Uint8Array': 'dart:typed_arrays',
'ArrayBuffer': 'dart:typed_arrays',
'Promise': 'dart:async',
};
let emitted: Set = {};
this.emitImports(sourceFile, libraries, emitted, sourceFile);
}
private emitImports(
n: ts.Node, libraries: ts.Map<string>, emitted: Set, sourceFile: ts.SourceFile): void {
if (n.kind === ts.SyntaxKind.TypeReference) {
let type = base.ident((<ts.TypeReferenceNode>n).typeName);
if (libraries.hasOwnProperty(type)) {
let toEmit = libraries[type];
if (!emitted[toEmit]) {
this.emit(`import "${toEmit}";`);
emitted[toEmit] = true;
}
}
}
// Support for importing "Provider" in case /* @ts2dart_Provider */ comments are present.
if (n.kind === ts.SyntaxKind.ImportDeclaration) {
// See if there is already code importing 'Provider' from angular2/core.
let id = n as ts.ImportDeclaration;
if ((id.moduleSpecifier as ts.StringLiteral).text === 'angular2/core') {
if (id.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports) {
let ni = id.importClause.namedBindings as ts.NamedImports;
for (let nb of ni.elements) {
if (base.ident(nb.name) === 'Provider') {
emitted[PROVIDER_IMPORT_MARKER] = true;
break;
}
}
}
}
}
if (!emitted[PROVIDER_IMPORT_MARKER] && this.hasMarkerComment(n, TS2DART_PROVIDER_COMMENT)) {
// if 'Provider' has not been imported yet, and there's a @ts2dart_Provider, add it.
this.emit(`import "package:angular2/core.dart" show Provider;`);
emitted[PROVIDER_IMPORT_MARKER] = true;
}
n.getChildren(sourceFile)
.forEach((child: ts.Node) => this.emitImports(child, libraries, emitted, sourceFile));
}
pushTypeParameterNames(n: ts.FunctionLikeDeclaration) {
if (!n.typeParameters) return;
this.genericMethodDeclDepth++;
}
popTypeParameterNames(n: ts.FunctionLikeDeclaration) {
if (!n.typeParameters) return;
this.genericMethodDeclDepth--;
}
resolvePropertyTypes(tn: ts.TypeNode): ts.Map<ts.PropertyDeclaration> {
let res: ts.Map<ts.PropertyDeclaration> = {};
if (!tn || !this.tc) return res;
let t = this.tc.getTypeAtLocation(tn);
for (let sym of this.tc.getPropertiesOfType(t)) {
let decl = sym.valueDeclaration || (sym.declarations && sym.declarations[0]);
if (decl.kind !== ts.SyntaxKind.PropertyDeclaration &&
decl.kind !== ts.SyntaxKind.PropertySignature) {
let msg = this.tc.getFullyQualifiedName(sym) +
' used for named parameter definition must be a property';
this.reportError(decl, msg);
continue;
}
res[sym.name] = <ts.PropertyDeclaration>decl;
}
return res;
}
/**
* The Dart Development Compiler (DDC) has a syntax extension that uses comments to emulate
* generic methods in Dart. ts2dart has to hack around this and keep track of which type names
* in the current scope are actually DDC type parameters and need to be emitted in comments.
*
* TODO(martinprobst): Remove this once the DDC hack has made it into Dart proper.
*/
private isGenericMethodTypeParameterName(name: ts.EntityName): boolean {
// Avoid checking this unless needed.
if (this.genericMethodDeclDepth === 0 || !this.tc) return false;
// Check if the type of the name is a TypeParameter.
let t = this.tc.getTypeAtLocation(name);
if (!t || (t.flags & ts.TypeFlags.TypeParameter) === 0) return false;
// Check if the symbol we're looking at is the type parameter.
let symbol = this.tc.getSymbolAtLocation(name);
if (symbol !== t.symbol) return false;
// Check that the Type Parameter has been declared by a function declaration.
return symbol.declarations.some(
// Constructors are handled separately.
d => d.parent.kind === ts.SyntaxKind.FunctionDeclaration ||
d.parent.kind === ts.SyntaxKind.MethodDeclaration ||
d.parent.kind === ts.SyntaxKind.MethodSignature);
}
visitTypeName(typeName: ts.EntityName) {
if (typeName.kind !== ts.SyntaxKind.Identifier) {
this.visit(typeName);
return;
}
let ident = base.ident(typeName);
if (this.isGenericMethodTypeParameterName(typeName)) {
// DDC generic methods hack - all names that are type parameters to generic methods have to be
// emitted in comments.
this.emit('dynamic/*=');
this.emit(ident);
this.emit('*/');
return;
}
if (this.candidateTypes.hasOwnProperty(ident) && this.tc) {
let symbol = this.tc.getSymbolAtLocation(typeName);
if (!symbol) {
this.reportMissingType(typeName, ident);
return;
}
let fileAndName = this.getFileAndName(typeName, symbol);
if (fileAndName) {
let fileSubs = this.tsToDartTypeNames[fileAndName.fileName];
if (fileSubs && fileSubs.hasOwnProperty(fileAndName.qname)) {
this.emit(fileSubs[fileAndName.qname]);
return;
}
}
}
this.emit(ident);
}
shouldEmitNew(c: ts.CallExpression): boolean {
if (!this.tc) return true;
let ci = this.getCallInformation(c);
let symbol = ci.symbol;
// getCallInformation returns a symbol if we understand this call.
if (!symbol) return true;
let loc = this.getFileAndName(c, symbol);
if (!loc) return true;
let {fileName, qname} = loc;
let fileSubs = this.callHandlerReplaceNew[fileName];
if (!fileSubs) return true;
return !fileSubs[qname];
}
private getCallInformation(c: ts.CallExpression): {context?: ts.Expression, symbol?: ts.Symbol} {
let symbol: ts.Symbol;
let context: ts.Expression;
let ident: string;
let expr = c.expression;
if (expr.kind === ts.SyntaxKind.Identifier) {
// Function call.
ident = base.ident(expr);
if (!this.candidateProperties.hasOwnProperty(ident)) return {};
symbol = this.tc.getSymbolAtLocation(expr);
if (!symbol) {
this.reportMissingType(c, ident);
return {};
}
context = null;
} else if (expr.kind === ts.SyntaxKind.PropertyAccessExpression) {
// Method call.
let pa = <ts.PropertyAccessExpression>expr;
ident = base.ident(pa.name);
if (!this.candidateProperties.hasOwnProperty(ident)) return {};
symbol = this.tc.getSymbolAtLocation(pa);
// Error will be reported by PropertyAccess handling below.
if (!symbol) return {};
context = pa.expression;
}
return {context, symbol};
}
private getHandler<T>(n: ts.Node, symbol: ts.Symbol, m: ts.Map<ts.Map<T>>): T {
let loc = this.getFileAndName(n, symbol);
if (!loc) return null;
let {fileName, qname} = loc;
let fileSubs = m[fileName];
if (!fileSubs) return null;
return fileSubs[qname];
}
private getFileAndName(n: ts.Node, originalSymbol: ts.Symbol): {fileName: string, qname: string} {
let symbol = originalSymbol;
while (symbol.flags & ts.SymbolFlags.Alias) symbol = this.tc.getAliasedSymbol(symbol);
let decl = symbol.valueDeclaration;
if (!decl) {
// In the case of a pure declaration with no assignment, there is no value declared.
// Just grab the first declaration, hoping it is declared once.
if (!symbol.declarations || symbol.declarations.length === 0) {
this.reportError(n, 'no declarations for symbol ' + originalSymbol.name);
return null;
}
decl = symbol.declarations[0];
}
const canonicalFileName = decl.getSourceFile().fileName.replace(/(\.d)?\.ts$/, '');
let qname = this.tc.getFullyQualifiedName(symbol);
// Some Qualified Names include their file name. Might be a bug in TypeScript,
// for the time being just special case.
if (symbol.flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Function | ts.SymbolFlags.Variable)) {
qname = symbol.getName();
}
if (FACADE_DEBUG) console.error('cfn:', canonicalFileName, 'qn:', qname);
return {fileName: canonicalFileName, qname};
}
private isNamedDefaultLibType(node: ts.Node, qname: string): boolean {
let symbol = this.tc.getTypeAtLocation(node).getSymbol();
if (!symbol) return false;
let actual = this.getFileAndName(node, symbol);
return actual.fileName === this.defaultLibLocation && qname === actual.qname;
}
private reportMissingType(n: ts.Node, ident: string) {
this.reportError(
n, `Untyped property access to "${ident}" which could be ` +
`a special ts2dart builtin. ` +
`Please add type declarations to disambiguate.`);
}
private static DECLARATIONS: {[k: number]: boolean} = {
[ts.SyntaxKind.ClassDeclaration]: true,
[ts.SyntaxKind.FunctionDeclaration]: true,
[ts.SyntaxKind.InterfaceDeclaration]: true,
[ts.SyntaxKind.MethodDeclaration]: true,
[ts.SyntaxKind.PropertyDeclaration]: true,
[ts.SyntaxKind.PropertyDeclaration]: true,
[ts.SyntaxKind.VariableDeclaration]: true,
};
isInsideConstExpr(node: ts.Node): boolean {
while (node.parent) {
if (node.parent.kind === ts.SyntaxKind.Parameter &&
(node.parent as ts.ParameterDeclaration).initializer === node) {
// initializers of parameters must be const in Dart.
return true;
}
if (this.isConstExpr(node)) return true;
node = node.parent;
if (FacadeConverter.DECLARATIONS[node.kind]) {
// Stop walking upwards when hitting a declaration - @ts2dart_const should only propagate
// to the immediate declaration it applies to (but should be transitive in expressions).
return false;
}
}
return false;
}
isConstClass(decl: base.ClassLike) {
return this.hasConstComment(decl) || this.hasAnnotation(decl.decorators, 'CONST') ||
(<ts.NodeArray<ts.Declaration>>decl.members).some((m) => {
if (m.kind !== ts.SyntaxKind.Constructor) return false;
return this.hasAnnotation(m.decorators, 'CONST');
});
}
/**
* isConstExpr returns true if the passed in expression itself is a const expression. const
* expressions are marked by the special comment @ts2dart_const (expr), or by the special
* function call CONST_EXPR.
*/
isConstExpr(node: ts.Node): boolean {
if (!node) return false;
if (this.hasConstComment(node)) {
return true;
}
return node.kind === ts.SyntaxKind.CallExpression &&
base.ident((<ts.CallExpression>node).expression) === 'CONST_EXPR';
}
hasConstComment(node: ts.Node): boolean { return this.hasMarkerComment(node, '@ts2dart_const'); }
private hasMarkerComment(node: ts.Node, markerText: string): boolean {
let text = node.getFullText();
let comments = ts.getLeadingCommentRanges(text, 0);
if (!comments) return false;
for (let c of comments) {
let commentText = text.substring(c.pos, c.end);
if (commentText.indexOf(markerText) !== -1) {
return true;
}
}
return false;
}
private emitMethodCall(name: string, args?: ts.Expression[]) {
this.emit('.');
this.emitCall(name, args);
}
private emitCall(name: string, args?: ts.Expression[]) {
this.emit(name);
this.emit('(');
if (args) this.visitList(args);
this.emit(')');
}
private stdlibTypeReplacements: ts.Map<string> = {
'Date': 'DateTime',
'Array': 'List',
'XMLHttpRequest': 'HttpRequest',
'Uint8Array': 'Uint8List',
'ArrayBuffer': 'ByteBuffer',
'Promise': 'Future',
// Dart has two different incompatible DOM APIs
// https://github.com/angular/angular/issues/2770
'Node': 'dynamic',
'Text': 'dynamic',
'Element': 'dynamic',
'Event': 'dynamic',
'HTMLElement': 'dynamic',
'HTMLAnchorElement': 'dynamic',
'HTMLStyleElement': 'dynamic',
'HTMLInputElement': 'dynamic',
'HTMLDocument': 'dynamic',
'History': 'dynamic',
'Location': 'dynamic',
};
private tsToDartTypeNames: ts.Map<ts.Map<string>> = {
[DEFAULT_LIB_MARKER]: this.stdlibTypeReplacements,
'angular2/src/facade/lang': {'Date': 'DateTime'},
'rxjs/Observable': {'Observable': 'Stream'},
'es6-promise/es6-promise': {'Promise': 'Future'},
'es6-shim/es6-shim': {'Promise': 'Future'},
};
private es6Promises: ts.Map<CallHandler> = {
'Promise.catch': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emit('.catchError(');
this.visitList(c.arguments);
this.emit(')');
},
'Promise.then': (c: ts.CallExpression, context: ts.Expression) => {
// then() in Dart doesn't support 2 arguments.
this.visit(context);
this.emit('.then(');
this.visit(c.arguments[0]);
this.emit(')');
if (c.arguments.length > 1) {
this.emit('.catchError(');
this.visit(c.arguments[1]);
this.emit(')');
}
},
'Promise': (c: ts.CallExpression, context: ts.Expression) => {
if (c.kind !== ts.SyntaxKind.NewExpression) return true;
this.assert(c, c.arguments.length === 1, 'Promise construction must take 2 arguments.');
this.assert(
c, c.arguments[0].kind === ts.SyntaxKind.ArrowFunction ||
c.arguments[0].kind === ts.SyntaxKind.FunctionExpression,
'Promise argument must be a function expression (or arrow function).');
let callback: ts.FunctionLikeDeclaration;
if (c.arguments[0].kind === ts.SyntaxKind.ArrowFunction) {
callback = <ts.FunctionLikeDeclaration>(<ts.ArrowFunction>c.arguments[0]);
} else if (c.arguments[0].kind === ts.SyntaxKind.FunctionExpression) {
callback = <ts.FunctionLikeDeclaration>(<ts.FunctionExpression>c.arguments[0]);
}
this.assert(
c, callback.parameters.length > 0 && callback.parameters.length < 3,
'Promise executor must take 1 or 2 arguments (resolve and reject).');
const completerVarName = this.uniqueId('completer');
this.assert(
c, callback.parameters[0].name.kind === ts.SyntaxKind.Identifier,
'First argument of the Promise executor is not a straight parameter.');
let resolveParameterIdent = <ts.Identifier>(callback.parameters[0].name);
this.emit('(() {'); // Create a new scope.
this.emit(`Completer ${completerVarName} = new Completer();`);
this.emit('var');
this.emit(resolveParameterIdent.text);
this.emit(`= ${completerVarName}.complete;`);
if (callback.parameters.length === 2) {
this.assert(
c, callback.parameters[1].name.kind === ts.SyntaxKind.Identifier,
'First argument of the Promise executor is not a straight parameter.');
let rejectParameterIdent = <ts.Identifier>(callback.parameters[1].name);
this.emit('var');
this.emit(rejectParameterIdent.text);
this.emit(`= ${completerVarName}.completeError;`);
}
this.emit('(()');
this.visit(callback.body);
this.emit(')();');
this.emit(`return ${completerVarName}.future;`);
this.emit('})()');
},
};
private es6Collections: ts.Map<CallHandler> = {
'Map.set': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emit('[');
this.visit(c.arguments[0]);
this.emit(']');
this.emit('=');
this.visit(c.arguments[1]);
},
'Map.get': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emit('[');
this.visit(c.arguments[0]);
this.emit(']');
},
'Map.has': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('containsKey', c.arguments);
},
'Map.delete': (c: ts.CallExpression, context: ts.Expression) => {
// JS Map.delete(k) returns whether k was present in the map,
// convert to:
// (Map.containsKey(k) && (Map.remove(k) !== null || true))
// (Map.remove(k) !== null || true) is required to always returns true
// when Map.containsKey(k)
this.emit('(');
this.visit(context);
this.emitMethodCall('containsKey', c.arguments);
this.emit('&& (');
this.visit(context);
this.emitMethodCall('remove', c.arguments);
this.emit('!= null || true ) )');
},
'Map.forEach': (c: ts.CallExpression, context: ts.Expression) => {
let cb: any;
let params: any;
switch (c.arguments[0].kind) {
case ts.SyntaxKind.FunctionExpression:
cb = <ts.FunctionExpression>(c.arguments[0]);
params = cb.parameters;
if (params.length !== 2) {
this.reportError(c, 'Map.forEach callback requires exactly two arguments');
return;
}
this.visit(context);
this.emit('. forEach ( (');
this.visit(params[1]);
this.emit(',');
this.visit(params[0]);
this.emit(')');
this.visit(cb.body);
this.emit(')');
break;
case ts.SyntaxKind.ArrowFunction:
cb = <ts.ArrowFunction>(c.arguments[0]);
params = cb.parameters;
if (params.length !== 2) {
this.reportError(c, 'Map.forEach callback requires exactly two arguments');
return;
}
this.visit(context);
this.emit('. forEach ( (');
this.visit(params[1]);
this.emit(',');
this.visit(params[0]);
this.emit(')');
if (cb.body.kind !== ts.SyntaxKind.Block) {
this.emit('=>');
}
this.visit(cb.body);
this.emit(')');
break;
default:
this.visit(context);
this.emit('. forEach ( ( k , v ) => (');
this.visit(c.arguments[0]);
this.emit(') ( v , k ) )');
break;
}
},
'Array.find': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emit('. firstWhere (');
this.visit(c.arguments[0]);
this.emit(', orElse : ( ) => null )');
},
};
private stdlibHandlers: ts.Map<CallHandler> = merge(this.es6Promises, this.es6Collections, {
'Array.push': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('add', c.arguments);
},
'Array.pop': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('removeLast');
},
'Array.shift': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emit('. removeAt ( 0 )');
},
'Array.unshift': (c: ts.CallExpression, context: ts.Expression) => {
this.emit('(');
this.visit(context);
if (c.arguments.length === 1) {
this.emit('.. insert ( 0,');
this.visit(c.arguments[0]);
this.emit(') ) . length');
} else {
this.emit('.. insertAll ( 0, [');
this.visitList(c.arguments);
this.emit(']) ) . length');
}
},
'Array.map': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('map', c.arguments);
this.emitMethodCall('toList');
},
'Array.filter': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('where', c.arguments);
this.emitMethodCall('toList');
},
'Array.some': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('any', c.arguments);
},
'Array.slice': (c: ts.CallExpression, context: ts.Expression) => {
this.emitCall('ListWrapper.slice', [context, ...c.arguments]);
},
'Array.splice': (c: ts.CallExpression, context: ts.Expression) => {
this.emitCall('ListWrapper.splice', [context, ...c.arguments]);
},
'Array.concat': (c: ts.CallExpression, context: ts.Expression) => {
this.emit('( new List . from (');
this.visit(context);
this.emit(')');
c.arguments.forEach(arg => {
if (!this.isNamedDefaultLibType(arg, 'Array')) {
this.reportError(arg, 'Array.concat only takes Array arguments');
}
this.emit('.. addAll (');
this.visit(arg);
this.emit(')');
});
this.emit(')');
},
'Array.join': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
if (c.arguments.length) {
this.emitMethodCall('join', c.arguments);
} else {
this.emit('. join ( "," )');
}
},
'Array.reduce': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
if (c.arguments.length >= 2) {
this.emitMethodCall('fold', [c.arguments[1], c.arguments[0]]);
} else {
this.emit('. fold ( null ,');
this.visit(c.arguments[0]);
this.emit(')');
}
},
'ArrayConstructor.isArray': (c: ts.CallExpression, context: ts.Expression) => {
this.emit('( (');
this.visitList(c.arguments); // Should only be 1.
this.emit(')');
this.emit('is List');
this.emit(')');
},
'Console.log': (c: ts.CallExpression, context: ts.Expression) => {
this.emit('print(');
if (c.arguments.length === 1) {
this.visit(c.arguments[0]);
} else {
this.emit('[');
this.visitList(c.arguments);
this.emit('].join(" ")');
}
this.emit(')');
},
'RegExp.exec': (c: ts.CallExpression, context: ts.Expression) => {
if (context.kind !== ts.SyntaxKind.RegularExpressionLiteral) {
// Fail if the exec call isn't made directly on a regexp literal.
// Multiple exec calls on the same global regexp have side effects
// (each return the next match), which we can't reproduce with a simple
// Dart RegExp (users should switch to some facade / wrapper instead).
this.reportError(
c, 'exec is only supported on regexp literals, ' +
'to avoid side-effect of multiple calls on global regexps.');
}
if (c.parent.kind === ts.SyntaxKind.ElementAccessExpression) {
// The result of the exec call is used for immediate indexed access:
// this use-case can be accommodated by RegExp.firstMatch, which returns
// a Match instance with operator[] which returns groups (special index
// 0 returns the full text of the match).
this.visit(context);
this.emitMethodCall('firstMatch', c.arguments);
} else {
// In the general case, we want to return a List. To transform a Match
// into a List of its groups, we alias it in a local closure that we
// call with the Match value. We are then able to use the group method
// to generate a List large enough to hold groupCount groups + the
// full text of the match at special group index 0.
this.emit('((match) => new List.generate(1 + match.groupCount, match.group))(');
this.visit(context);
this.emitMethodCall('firstMatch', c.arguments);
this.emit(')');
}
},
'RegExp.test': (c: ts.CallExpression, context: ts.Expression) => {
this.visit(context);
this.emitMethodCall('hasMatch', c.arguments);
},
'String.substr': (c: ts.CallExpression, context: ts.Expression) => {
this.reportError(
c, 'substr is unsupported, use substring (but beware of the different semantics!)');
this.visit(context);
this.emitMethodCall('substr', c.arguments);
},
});
private callHandlerReplaceNew: ts.Map<ts.Map<boolean>> = {
[DEFAULT_LIB_MARKER]: {'Promise': true},
};
private callHandlers: ts.Map<ts.Map<CallHandler>> = {
[DEFAULT_LIB_MARKER]: this.stdlibHandlers,
'angular2/manual_typings/globals': this.es6Collections,
'angular2/src/facade/collection': {
'Map': (c: ts.CallExpression, context: ts.Expression): boolean => {
// The actual Map constructor is special cased for const calls.
if (!this.isInsideConstExpr(c)) return true;
if (c.arguments.length) {
this.reportError(c, 'Arguments on a Map constructor in a const are unsupported');
}
if (c.typeArguments) {
this.emit('<');
this.visitList(c.typeArguments);
this.emit('>');
}
this.emit('{ }');
return false;
},
},
'angular2/src/core/di/forward_ref': {
'forwardRef': (c: ts.CallExpression, context: ts.Expression) => {
// The special function forwardRef translates to an unwrapped value in Dart.
const callback = <ts.FunctionExpression>c.arguments[0];
if (callback.kind !== ts.SyntaxKind.ArrowFunction) {
this.reportError(c, 'forwardRef takes only arrow functions');
return;
}
this.visit(callback.body);
},
},
'angular2/src/facade/lang': {
'CONST_EXPR': (c: ts.CallExpression, context: ts.Expression) => {
// `const` keyword is emitted in the array literal handling, as it needs to be transitive.
this.visitList(c.arguments);
},
'normalizeBlank': (c: ts.CallExpression, context: ts.Expression) => {
// normalizeBlank is a noop in Dart, so erase it.
this.visitList(c.arguments);
},
},
};
private es6CollectionsProp: ts.Map<PropertyHandler> = {
'Map.size': (p: ts.PropertyAccessExpression) => {
this.visit(p.expression);
this.emit('.');
this.emit('length');
},
};
private es6PromisesProp: ts.Map<PropertyHandler> = {
'PromiseConstructor.resolve': (p: ts.PropertyAccessExpression) => {
this.emit('new ');
this.visit(p.expression);
this.emit('.value');
},
'PromiseConstructor.reject': (p: ts.PropertyAccessExpression) => {
this.emit('new ');
this.visit(p.expression);
this.emit('.error');
},
};
private propertyHandlers: ts.Map<ts.Map<PropertyHandler>> = {
[DEFAULT_LIB_MARKER]: merge(this.es6CollectionsProp, this.es6PromisesProp),
};
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreLogger } from '@singletons/logger';
import { CoreSites } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { CoreCourses } from '@features/courses/services/courses';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreStatusWithWarningsWSResponse, CoreWSExternalWarning } from '@services/ws';
import { makeSingleton } from '@singletons';
import { CoreError } from '@classes/errors/error';
const ROOT_CACHE_KEY = 'mmaCourseCompletion:';
/**
* Service to handle course completion.
*/
@Injectable({ providedIn: 'root' })
export class AddonCourseCompletionProvider {
protected logger: CoreLogger;
constructor() {
this.logger = CoreLogger.getInstance('AddonCourseCompletion');
}
/**
* Returns whether or not the user can mark a course as self completed.
* It can if it's configured in the course and it hasn't been completed yet.
*
* @param userId User ID.
* @param completion Course completion.
* @return True if user can mark course as self completed, false otherwise.
*/
canMarkSelfCompleted(userId: number, completion: AddonCourseCompletionCourseCompletionStatus): boolean {
if (CoreSites.getCurrentSiteUserId() != userId) {
return false;
}
let selfCompletionActive = false;
let alreadyMarked = false;
completion.completions.forEach((criteria) => {
if (criteria.type === 1) {
// Self completion criteria found.
selfCompletionActive = true;
alreadyMarked = criteria.complete;
}
});
return selfCompletionActive && !alreadyMarked;
}
/**
* Get completed status text. The language code returned is meant to be translated.
*
* @param completion Course completion.
* @return Language code of the text to show.
*/
getCompletedStatusText(completion: AddonCourseCompletionCourseCompletionStatus): string {
if (completion.completed) {
return 'addon.coursecompletion.completed';
}
// Let's calculate status.
const hasStarted = completion.completions.some((criteria) => criteria.timecompleted || criteria.complete);
if (hasStarted) {
return 'addon.coursecompletion.inprogress';
}
return 'addon.coursecompletion.notyetstarted';
}
/**
* Get course completion status for a certain course and user.
*
* @param courseId Course ID.
* @param userId User ID. If not defined, use current user.
* @param preSets Presets to use when calling the WebService.
* @param siteId Site ID. If not defined, use current site.
* @return Promise to be resolved when the completion is retrieved.
*/
async getCompletion(
courseId: number,
userId?: number,
preSets: CoreSiteWSPreSets = {},
siteId?: string,
): Promise<AddonCourseCompletionCourseCompletionStatus> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
this.logger.debug('Get completion for course ' + courseId + ' and user ' + userId);
const data: AddonCourseCompletionGetCourseCompletionStatusWSParams = {
courseid: courseId,
userid: userId,
};
preSets.cacheKey = this.getCompletionCacheKey(courseId, userId);
preSets.updateFrequency = preSets.updateFrequency || CoreSite.FREQUENCY_SOMETIMES;
preSets.cacheErrors = ['notenroled'];
const result: AddonCourseCompletionGetCourseCompletionStatusWSResponse =
await site.read('core_completion_get_course_completion_status', data, preSets);
if (result.completionstatus) {
return result.completionstatus;
}
throw new CoreError('Cannot fetch course completion status');
}
/**
* Get cache key for get completion WS calls.
*
* @param courseId Course ID.
* @param useIid User ID.
* @return Cache key.
*/
protected getCompletionCacheKey(courseId: number, userId: number): string {
return ROOT_CACHE_KEY + 'view:' + courseId + ':' + userId;
}
/**
* Invalidates view course completion WS call.
*
* @param courseId Course ID.
* @param userId User ID. If not defined, use current user.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved when the list is invalidated.
*/
async invalidateCourseCompletion(courseId: number, userId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCompletionCacheKey(courseId, userId));
}
/**
* Returns whether or not the view course completion plugin is enabled for the current site.
*
* @return True if plugin enabled, false otherwise.
*/
isPluginViewEnabled(): boolean {
return CoreSites.isLoggedIn();
}
/**
* Returns whether or not the view course completion plugin is enabled for a certain course.
*
* @param courseId Course ID.
* @param preferCache True if shouldn't call WS if data is cached, false otherwise.
* @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise.
*/
async isPluginViewEnabledForCourse(courseId?: number, preferCache: boolean = true): Promise<boolean> {
if (!courseId) {
return false;
}
const course = await CoreCourses.getUserCourse(courseId, preferCache);
if (course) {
if (typeof course.enablecompletion != 'undefined' && !course.enablecompletion) {
// Completion not enabled for the course.
return false;
}
if (typeof course.completionhascriteria != 'undefined' && !course.completionhascriteria) {
// No criteria, cannot view completion.
return false;
}
}
return true;
}
/**
* Returns whether or not the view course completion plugin is enabled for a certain user.
*
* @param courseId Course ID.
* @param userId User ID. If not defined, use current user.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise.
*/
async isPluginViewEnabledForUser(courseId: number, userId?: number, siteId?: string): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
const currentUserId = site.getUserId();
// Check if user wants to view his own completion.
try {
if (!userId || userId == currentUserId) {
// Viewing own completion. Get the course to check if it has completion criteria.
const course = await CoreCourses.getUserCourse(courseId, true);
// If the site is returning the completionhascriteria then the user can view his own completion.
// We already checked the value in isPluginViewEnabledForCourse.
if (course && typeof course.completionhascriteria != 'undefined') {
return true;
}
}
} catch {
// Ignore errors.
}
// User not viewing own completion or the site doesn't tell us if the course has criteria.
// The only way to know if completion can be viewed is to call the WS.
// Disable emergency cache to be able to detect that the plugin has been disabled (WS will fail).
const preSets: CoreSiteWSPreSets = {
emergencyCache: false,
};
try {
await this.getCompletion(courseId, userId, preSets);
return true;
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// The WS returned an error, plugin is not enabled.
return false;
}
}
try {
// Not a WS error. Check if we have a cached value.
preSets.omitExpires = true;
await this.getCompletion(courseId, userId, preSets);
return true;
} catch {
return false;
}
}
/**
* Mark a course as self completed.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved on success.
*/
async markCourseAsSelfCompleted(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonCourseCompletionMarkCourseSelfCompletedWSParams = {
courseid: courseId,
};
const response = await site.write<CoreStatusWithWarningsWSResponse>('core_completion_mark_course_self_completed', params);
if (!response.status) {
throw new CoreError('Cannot mark course as self completed');
}
}
}
export const AddonCourseCompletion = makeSingleton(AddonCourseCompletionProvider);
/**
* Completion status returned by core_completion_get_course_completion_status.
*/
export type AddonCourseCompletionCourseCompletionStatus = {
completed: boolean; // True if the course is complete, false otherwise.
aggregation: number; // Aggregation method 1 means all, 2 means any.
completions: {
type: number; // Completion criteria type.
title: string; // Completion criteria Title.
status: string; // Completion status (Yes/No) a % or number.
complete: boolean; // Completion status (true/false).
timecompleted: number; // Timestamp for criteria completetion.
details: {
type: string; // Type description.
criteria: string; // Criteria description.
requirement: string; // Requirement description.
status: string; // Status description, can be anything.
}; // Details.
}[];
};
/**
* Params of core_completion_get_course_completion_status WS.
*/
export type AddonCourseCompletionGetCourseCompletionStatusWSParams = {
courseid: number; // Course ID.
userid: number; // User ID.
};
/**
* Data returned by core_completion_get_course_completion_status WS.
*/
export type AddonCourseCompletionGetCourseCompletionStatusWSResponse = {
completionstatus: AddonCourseCompletionCourseCompletionStatus; // Course status.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of core_completion_mark_course_self_completed WS.
*/
export type AddonCourseCompletionMarkCourseSelfCompletedWSParams = {
courseid: number; // Course ID.
}; | the_stack |
import _ from "lodash"
import * as action from "../../src/action/common"
import Session, { dispatch, getState } from "../../src/common/session"
import { getNumLabels, getShapes } from "../../src/functional/state_util"
import { Size2D } from "../../src/math/size2d"
import { IdType, PathPoint2DType } from "../../src/types/state"
import { checkPolygon } from "../util/shape"
import { findNewLabels, findNewLabelsFromState } from "../util/state"
import {
drawPolygon,
drawPolygonByDragging,
initializeTestingObjects,
keyClick,
keyDown,
keyUp,
mouseClick,
mouseDown,
mouseMove,
mouseMoveClick,
mouseUp
} from "./util"
describe("Draw 2d polygons to label2d list", () => {
// Samples polygon vertices to use for tests
const vertices: number[][][] = [
[
[10, 10],
[100, 100],
[200, 100],
[100, 0]
],
[
[500, 500],
[600, 400],
[700, 700]
]
]
test("Draw polygon with a mix of clicking and dragging", () => {
const itemIndex = 0
const [label2dHandler] = initializeTestingObjects()
const canvasSize = new Size2D(1000, 1000)
dispatch(action.changeSelect({ labelType: 1 }))
// Draw the first points by clicking
mouseMoveClick(label2dHandler, 10, 10, canvasSize, -1, 0)
mouseMoveClick(label2dHandler, 100, 100, canvasSize, -1, 0)
mouseMoveClick(label2dHandler, 200, 100, canvasSize, -1, 0)
// Check that polygon isn't added to state until it's finished
expect(getNumLabels(getState(), itemIndex)).toEqual(0)
// Drag when drawing the last point
mouseMove(label2dHandler, 200, 10, canvasSize, -1, 0)
mouseDown(label2dHandler, 200, 10, -1, 0)
mouseMove(label2dHandler, 100, 0, canvasSize, -1, 0)
mouseUp(label2dHandler, 100, 0, -1, 0)
mouseMoveClick(label2dHandler, 10, 10, canvasSize, -1, 1)
const labelId = findNewLabelsFromState(getState(), itemIndex, [])[0]
checkPolygon(labelId, vertices[0])
})
test("Draw multiple polygons", () => {
const [label2dHandler] = initializeTestingObjects()
const canvasSize = new Size2D(1000, 1000)
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
labelIds.push(drawPolygon(label2dHandler, canvasSize, vertices[0]))
checkPolygon(labelIds[0], vertices[0])
labelIds.push(
drawPolygonByDragging(label2dHandler, canvasSize, vertices[1])
)
checkPolygon(labelIds[1], vertices[1])
expect(Session.label2dList.labelList.length).toEqual(2)
})
test("Draw polygons with interrupting actions", () => {
const [label2dHandler] = initializeTestingObjects()
const canvasSize = new Size2D(1000, 1000)
const interrupt = true
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
labelIds.push(
drawPolygon(label2dHandler, canvasSize, vertices[0], interrupt)
)
checkPolygon(labelIds[0], vertices[0])
labelIds.push(
drawPolygonByDragging(label2dHandler, canvasSize, vertices[1], interrupt)
)
checkPolygon(labelIds[1], vertices[1])
expect(Session.label2dList.labelList.length).toEqual(2)
})
})
test("2d polygons highlighted and selected", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw first polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[120, 120],
[210, 210],
[310, 260],
[410, 210],
[210, 110]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
*/
let selected = Session.label2dList.selectedLabels
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
expect(selected[0].labelId).toEqual(labelIds[0])
// Draw second polygon
drawPolygon(label2dHandler, canvasSize, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
// Change highlighted label
mouseMove(label2dHandler, 130, 130, canvasSize, 0, 0)
let highlighted = label2dHandler.highlightedLabel
selected = Session.label2dList.selectedLabels
expect(Session.label2dList.labelList.length).toEqual(2)
expect(Session.label2dList.labelList[1].labelId).toEqual(labelIds[1])
expect(highlighted).not.toBeNull()
if (highlighted !== null) {
expect(highlighted.labelId).toEqual(labelIds[0])
}
expect(selected[0].labelId).toEqual(labelIds[1])
// Change selected label
mouseDown(label2dHandler, 130, 130, 0, 0)
mouseMove(label2dHandler, 140, 140, canvasSize, 0, 0)
mouseUp(label2dHandler, 140, 140, 0, 0)
highlighted = label2dHandler.highlightedLabel
selected = Session.label2dList.selectedLabels
expect(highlighted).not.toBeNull()
if (highlighted !== null) {
expect(highlighted.labelId).toEqual(labelIds[0])
}
expect(selected[0].labelId).toEqual(labelIds[0])
})
test("validation check for polygon2d", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw a valid polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[120, 120],
[210, 210],
[310, 260],
[410, 210],
[210, 110]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
// Draw one invalid polygon
drawPolygon(
label2dHandler,
canvasSize,
[
[200, 100],
[400, 300],
[300, 200],
[300, 0]
],
false,
false
)
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
* polygon 2: (200, 100) (400, 300) (300, 200) (300, 0) invalid
*/
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
// Drag the polygon to an invalid shape
mouseMove(label2dHandler, 310, 260, canvasSize, 0, 5)
mouseDown(label2dHandler, 310, 260, 0, 5)
mouseMove(label2dHandler, 310, 0, canvasSize, 0, 5)
mouseUp(label2dHandler, 310, 0, 0, 5)
/**
* polygon 1: (120, 120) (210, 210) (310, 0) (410, 210) (210, 110)
* polygon 1 is an invalid shape
*/
state = getState()
const points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[2]).toMatchObject({ x: 310, y: 260, pointType: "line" })
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, [])[0])
// Draw a too small polygon
drawPolygon(
label2dHandler,
canvasSize,
[
[0, 0],
[1, 0],
[0, 1]
],
false,
false
)
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
* polygon 2: (0, 0) (1, 0) (0, 1) too small, invalid
*/
state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
})
test("2d polygons drag vertices, midpoints and edges", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw a polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100],
[100, 0]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100) (100, 0)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
// Drag a vertex
mouseMove(label2dHandler, 200, 100, canvasSize, 0, 5)
mouseDown(label2dHandler, 200, 100, 0, 5)
mouseMove(label2dHandler, 300, 100, canvasSize, 0, 5)
mouseUp(label2dHandler, 300, 100, 0, 5)
let state = getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[2]).toMatchObject({ x: 300, y: 100, pointType: "line" })
/**
* polygon 1: (10, 10) (100, 100) (300, 100) (100, 0)
*/
// Drag midpoints
mouseMove(label2dHandler, 200, 100, canvasSize, 0, 4)
mouseDown(label2dHandler, 200, 100, 0, 4)
mouseMove(label2dHandler, 200, 150, canvasSize, 0, 5)
mouseUp(label2dHandler, 200, 150, 0, 5)
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[2]).toMatchObject({ x: 200, y: 150, pointType: "line" })
/**
* polygon 1: (10, 10) (100, 100) (200, 150) (300, 100) (100, 0)
*/
// Drag edges
mouseMove(label2dHandler, 20, 20, canvasSize, 0, 0)
mouseDown(label2dHandler, 20, 20, 0, 0)
mouseMove(label2dHandler, 120, 120, canvasSize, 0, 0)
mouseUp(label2dHandler, 120, 120, 0, 0)
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[0]).toMatchObject({ x: 110, y: 110, pointType: "line" })
/**
* polygon 1: (110, 110) (200, 200) (300, 250) (400, 200) (200, 100)
*/
})
test("2d polygons delete vertex and draw bezier curve", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw a polygon and delete vertex when drawing
const canvasSize = new Size2D(1000, 1000)
mouseMoveClick(label2dHandler, 200, 100, canvasSize, -1, 0)
keyClick(label2dHandler, "d")
mouseMoveClick(label2dHandler, 250, 100, canvasSize, -1, 0)
mouseMoveClick(label2dHandler, 300, 0, canvasSize, -1, 0)
mouseMoveClick(label2dHandler, 350, 100, canvasSize, -1, 0)
mouseMoveClick(label2dHandler, 300, 200, canvasSize, -1, 0)
mouseMove(label2dHandler, 320, 130, canvasSize, -1, 0)
keyClick(label2dHandler, "d")
mouseClick(label2dHandler, 320, 130, -1, 0)
mouseMoveClick(label2dHandler, 300, 150, canvasSize, -1, 0)
mouseMoveClick(label2dHandler, 250, 100, canvasSize, -1, 1)
/**
* polygon: (250, 100) (300, 0) (350, 100) (320, 130) (300, 150)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[0]).toMatchObject({ x: 250, y: 100, pointType: "line" })
expect(points[1]).toMatchObject({ x: 300, y: 0, pointType: "line" })
expect(points[2]).toMatchObject({ x: 350, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 320, y: 130, pointType: "line" })
expect(points[4]).toMatchObject({ x: 300, y: 150, pointType: "line" })
// Delete vertex when closed
keyDown(label2dHandler, "d")
mouseMoveClick(label2dHandler, 275, 125, canvasSize, 0, 10)
mouseMoveClick(label2dHandler, 300, 150, canvasSize, 0, 9)
keyUp(label2dHandler, "d")
/**
* polygon: (250, 100) (300, 0) (350, 100) (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(4)
expect(points[3]).toMatchObject({ x: 320, y: 130, pointType: "line" })
// Draw bezier curve
keyDown(label2dHandler, "c")
mouseMoveClick(label2dHandler, 335, 115, canvasSize, 0, 6)
keyUp(label2dHandler, "c")
/**
* polygon: (250, 100) (300, 0) (350, 100)
* [ (340, 110) (330, 120) <bezier curve control points>]
* (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(6)
expect(points[3]).toMatchObject({ x: 340, y: 110, pointType: "bezier" })
expect(points[4]).toMatchObject({ x: 330, y: 120, pointType: "bezier" })
// Drag bezier curve control points
mouseMove(label2dHandler, 340, 110, canvasSize, 0, 6)
mouseDown(label2dHandler, 340, 110, 0, 6)
mouseMove(label2dHandler, 340, 90, canvasSize, 0, 6)
mouseUp(label2dHandler, 340, 90, 0, 6)
/**
* polygon: (250, 100) (300, 0) (350, 100)
* [ (340, 90) (330, 120) <bezier curve control points>]
* (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(6)
expect(points[2]).toMatchObject({ x: 350, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 340, y: 90, pointType: "bezier" })
expect(points[4]).toMatchObject({ x: 330, y: 120, pointType: "bezier" })
// Delete vertex on bezier curve
keyDown(label2dHandler, "d")
mouseMoveClick(label2dHandler, 350, 100, canvasSize, 0, 5)
keyUp(label2dHandler, "d")
/**
* polygon: (250, 100) (300, 0) (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(3)
})
test("2d polygon select and moving", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw first polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
// Select label 1
mouseMoveClick(label2dHandler, 50, 50, canvasSize, 0, 0)
state = getState()
expect(state.user.select.labels[0].length).toEqual(1)
expect(state.user.select.labels[0][0]).toEqual(labelIds[0])
const label2dlist = Session.label2dList
expect(label2dlist.selectedLabels.length).toEqual(1)
expect(label2dlist.selectedLabels[0].labelId).toEqual(labelIds[0])
mouseMove(label2dHandler, 20, 20, canvasSize, 0, 0)
mouseDown(label2dHandler, 20, 20, 0, 0)
mouseMove(label2dHandler, 60, 60, canvasSize, 0, 0)
mouseMove(label2dHandler, 120, 120, canvasSize, 0, 0)
mouseUp(label2dHandler, 120, 120, 0, 0)
state = getState()
const points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 110, y: 110 })
})
test("2d polygons multi-select and multi-label moving", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw first polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
// Draw second polygon
drawPolygon(label2dHandler, canvasSize, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
// Draw third polygon
drawPolygon(label2dHandler, canvasSize, [
[250, 250],
[300, 250],
[350, 350]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
// Select label 1
mouseMoveClick(label2dHandler, 600, 600, canvasSize, 1, 0)
state = getState()
expect(state.user.select.labels[0].length).toEqual(1)
expect(state.user.select.labels[0][0]).toEqual(labelIds[1])
expect(Session.label2dList.selectedLabels.length).toEqual(1)
expect(Session.label2dList.selectedLabels[0].labelId).toEqual(labelIds[1])
// Select label 1, 2, 3
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 300, 250, canvasSize, 2, 2)
mouseMoveClick(label2dHandler, 50, 50, canvasSize, 0, 0)
keyUp(label2dHandler, "Meta")
state = getState()
expect(state.user.select.labels[0].length).toEqual(3)
expect(Session.label2dList.selectedLabels.length).toEqual(3)
// Unselect label 3
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 300, 250, canvasSize, 2, 2)
keyUp(label2dHandler, "Meta")
state = getState()
expect(state.user.select.labels[0].length).toEqual(2)
expect(Session.label2dList.selectedLabels.length).toEqual(2)
// Select three labels
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 300, 250, canvasSize, 2, 2)
keyUp(label2dHandler, "Meta")
state = getState()
expect(state.user.select.labels[0].length).toEqual(3)
expect(Session.label2dList.selectedLabels.length).toEqual(3)
// Move
mouseMove(label2dHandler, 20, 20, canvasSize, 0, 0)
mouseDown(label2dHandler, 20, 20, 0, 0)
mouseMove(label2dHandler, 60, 60, canvasSize, 0, 0)
mouseMove(label2dHandler, 120, 120, canvasSize, 0, 0)
mouseUp(label2dHandler, 120, 120, 0, 0)
/**
* polygon 1: (110, 110) (200, 200) (300, 200)
* polygon 2: (600, 600) (700, 500) (800, 800)
* polygon 3: (350, 350) (400, 350) (450, 450)
*/
state = getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 110, y: 110 })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 600, y: 600 })
points = getShapes(state, 0, labelIds[2]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 350, y: 350 })
})
test("2d polygons linking labels and moving", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
const labelIds: IdType[] = []
// Draw first polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
// Draw second polygon
drawPolygon(label2dHandler, canvasSize, [
[500, 500],
[600, 400],
[700, 700]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
// Draw third polygon
drawPolygon(label2dHandler, canvasSize, [
[250, 250],
[300, 250],
[350, 350]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
// Select label 2 and 0
mouseMoveClick(label2dHandler, 300, 300, canvasSize, 2, 0)
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 100, 100, canvasSize, 0, 2)
keyUp(label2dHandler, "Meta")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
state = getState()
expect(state.user.select.labels[0].length).toEqual(2)
expect(state.user.select.labels[0][0]).toEqual(labelIds[2])
expect(state.user.select.labels[0][1]).toEqual(labelIds[0])
expect(Session.label2dList.selectedLabels.length).toEqual(2)
expect(Session.label2dList.selectedLabels[0].labelId).toEqual(labelIds[2])
expect(Session.label2dList.selectedLabels[1].labelId).toEqual(labelIds[0])
// Select label 1 and 2
mouseMoveClick(label2dHandler, 600, 600, canvasSize, 1, 0)
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 50, 50, canvasSize, 0, 0)
keyUp(label2dHandler, "Meta")
// Link label 1 and 2
keyClick(label2dHandler, "l")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: 1, 2
*/
state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(4)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
expect(Session.label2dList.labelList[0].color).toEqual(
Session.label2dList.labelList[1].color
)
// Reselect label 1 and 2
mouseMoveClick(label2dHandler, 300, 250, canvasSize, 2, 2)
mouseMoveClick(label2dHandler, 50, 50, canvasSize, 0, 0)
state = getState()
expect(state.user.select.labels[0].length).toEqual(2)
expect(Session.label2dList.selectedLabels.length).toEqual(2)
// Moving group 1
mouseMove(label2dHandler, 20, 20, canvasSize, 0, 0)
mouseDown(label2dHandler, 20, 20, 0, 0)
mouseMove(label2dHandler, 60, 60, canvasSize, 0, 0)
mouseMove(label2dHandler, 120, 120, canvasSize, 0, 0)
mouseUp(label2dHandler, 120, 120, 0, 0)
/**
* polygon 1: (110, 110) (200, 200) (300, 200)
* polygon 2: (600, 600) (700, 500) (800, 800)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: 1, 2
*/
state = getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 110, y: 110 })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 600, y: 600 })
points = getShapes(state, 0, labelIds[2]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 250, y: 250 })
// Reshape for one label in group
mouseMove(label2dHandler, 110, 110, canvasSize, 0, 1)
mouseDown(label2dHandler, 110, 110, 0, 1)
mouseMove(label2dHandler, 100, 100, canvasSize, 0, 1)
mouseUp(label2dHandler, 100, 100, 0, 1)
/**
* polygon 1: (100, 100) (200, 200) (300, 200)
* polygon 2: (600, 600) (700, 500) (800, 800)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: 1, 2
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 100, y: 100 })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 600, y: 600 })
points = getShapes(state, 0, labelIds[2]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 250, y: 250 })
})
test("2d polygons unlinking", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 1 }))
// Draw first polygon
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
// Draw second polygon
drawPolygon(label2dHandler, canvasSize, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
// Draw third polygon
drawPolygon(label2dHandler, canvasSize, [
[250, 250],
[300, 250],
[350, 350]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
// Select polygon 1 and 3
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 100, 100, canvasSize, 0, 2)
keyUp(label2dHandler, "Meta")
// Link polygon 1 and 3
keyClick(label2dHandler, "l")
state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(4)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
expect(Session.label2dList.labelList[0].color).toEqual(
Session.label2dList.labelList[2].color
)
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: polygon 1, 3
*/
// Select polygon 1, 2, 3
mouseMoveClick(label2dHandler, 550, 550, canvasSize, 1, 0)
keyDown(label2dHandler, "Meta")
mouseMoveClick(label2dHandler, 100, 100, canvasSize, 0, 2)
keyUp(label2dHandler, "Meta")
// Unlink polygon 1 and 3
keyClick(label2dHandler, "L")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
// Unselect polygon 1
keyDown(label2dHandler, "Meta")
mouseMove(label2dHandler, 100, 100, canvasSize, 0, 2)
mouseDown(label2dHandler, 100, 100, 0, 2)
mouseUp(label2dHandler, 100, 100, 0, 2)
keyUp(label2dHandler, "Meta")
// Link polygon 2 and 3
keyClick(label2dHandler, "l")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: polygon 2, 3
*/
state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(4)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
expect(Session.label2dList.labelList[1].color).toEqual(
Session.label2dList.labelList[2].color
)
})
test("2d polyline creating", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 3 }))
const labelIds: IdType[] = []
// Draw first polyline
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polyline 1: (10, 10) (100, 100) (200, 100)
*/
// Draw second polyline
drawPolygon(label2dHandler, canvasSize, [
[500, 500],
[600, 400],
[700, 700]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polyline 1: (10, 10) (100, 100) (200, 100)
* polyline 2: (500, 500) (600, 400) (700, 700)
*/
// Draw third polyline
drawPolygon(label2dHandler, canvasSize, [
[250, 250],
[300, 250],
[350, 350]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polyline 1: (10, 10) (100, 100) (200, 100)
* polyline 2: (500, 500) (600, 400) (700, 700)
* polyline 3: (250, 250) (300, 250) (350, 350)
*/
const state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(3)
expect(points[0]).toMatchObject({ x: 10, y: 10, pointType: "line" })
expect(points[1]).toMatchObject({ x: 100, y: 100, pointType: "line" })
expect(points[2]).toMatchObject({ x: 200, y: 100, pointType: "line" })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points.length).toEqual(3)
expect(points[0]).toMatchObject({ x: 500, y: 500, pointType: "line" })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points.length).toEqual(3)
expect(points[0]).toMatchObject({ x: 500, y: 500, pointType: "line" })
})
test("2d polylines drag vertices, midpoints and edges", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 3 }))
const labelIds: IdType[] = []
// Draw a polyline
const canvasSize = new Size2D(1000, 1000)
drawPolygon(label2dHandler, canvasSize, [
[10, 10],
[100, 100],
[200, 100],
[100, 0]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polyline 1: (10, 10) (100, 100) (200, 100) (100, 0)
*/
// Drag a vertex
mouseMove(label2dHandler, 200, 100, canvasSize, 0, 5)
mouseDown(label2dHandler, 200, 100, 0, 5)
mouseMove(label2dHandler, 300, 100, canvasSize, 0, 5)
mouseUp(label2dHandler, 300, 100, 0, 5)
mouseMove(label2dHandler, 10, 10, canvasSize, 0, 1)
mouseDown(label2dHandler, 10, 10, 0, 1)
mouseMove(label2dHandler, 50, 50, canvasSize, 0, 1)
mouseUp(label2dHandler, 50, 50, 0, 1)
let state = getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 50, y: 50 })
expect(points[2]).toMatchObject({ x: 300, y: 100 })
expect(points[3]).toMatchObject({ x: 100, y: 0 })
/**
* polyline 1: (50, 50) (100, 100) (300, 100) (100, 0)
*/
// Drag midpoints
mouseMove(label2dHandler, 200, 100, canvasSize, 0, 4)
mouseDown(label2dHandler, 200, 100, 0, 4)
mouseMove(label2dHandler, 200, 150, canvasSize, 0, 5)
mouseUp(label2dHandler, 200, 150, 0, 5)
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[2]).toMatchObject({ x: 200, y: 150, pointType: "line" })
/**
* polyline 1: (50, 50) (100, 100) (200, 150) (300, 100) (100, 0)
*/
// Drag edges
mouseMove(label2dHandler, 70, 70, canvasSize, 0, 0)
mouseDown(label2dHandler, 70, 70, 0, 0)
mouseMove(label2dHandler, 170, 170, canvasSize, 0, 0)
mouseUp(label2dHandler, 170, 170, 0, 0)
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[0]).toMatchObject({ x: 150, y: 150, pointType: "line" })
/**
* polyline 1: (150, 150) (200, 200) (300, 250) (400, 200) (200, 100)
*/
})
test("2d polylines delete vertex and draw bezier curve", () => {
const [label2dHandler] = initializeTestingObjects()
dispatch(action.changeSelect({ labelType: 3 }))
const labelIds: IdType[] = []
// Draw a polyline and delete vertex when drawing
const canvasSize = new Size2D(1000, 1000)
mouseMove(label2dHandler, 200, 100, canvasSize, -1, 0)
mouseUp(label2dHandler, 200, 100, -1, 0)
mouseDown(label2dHandler, 200, 100, -1, 0)
keyClick(label2dHandler, "d")
drawPolygon(label2dHandler, canvasSize, [
[250, 100],
[300, 0],
[350, 100],
[320, 130],
[300, 150]
])
labelIds.push(findNewLabels(getState().task.items[0].labels, labelIds)[0])
/**
* polyline: (250, 100) (300, 0) (350, 100) (320, 130) (300, 150)
*/
let state = getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[0]).toMatchObject({ x: 250, y: 100, pointType: "line" })
expect(points[1]).toMatchObject({ x: 300, y: 0, pointType: "line" })
expect(points[2]).toMatchObject({ x: 350, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 320, y: 130, pointType: "line" })
expect(points[4]).toMatchObject({ x: 300, y: 150, pointType: "line" })
// Delete vertex when closed
keyDown(label2dHandler, "d")
mouseMoveClick(label2dHandler, 325, 50, canvasSize, 0, 4)
mouseMoveClick(label2dHandler, 300, 150, canvasSize, 0, 9)
keyUp(label2dHandler, "d")
/**
* polyline: (250, 100) (300, 0) (350, 100) (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(4)
expect(points[0]).toMatchObject({ x: 250, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 320, y: 130, pointType: "line" })
// Draw bezier curve
keyDown(label2dHandler, "c")
mouseMoveClick(label2dHandler, 335, 115, canvasSize, 0, 6)
keyUp(label2dHandler, "c")
/**
* polyline: (250, 100) (300, 0) (350, 100)
* [ (340, 110) (330, 120) <bezier curve control points>]
* (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(6)
expect(points[3]).toMatchObject({ x: 340, y: 110, pointType: "bezier" })
expect(points[4]).toMatchObject({ x: 330, y: 120, pointType: "bezier" })
// Drag bezier curve control points
mouseMove(label2dHandler, 340, 110, canvasSize, 0, 6)
mouseDown(label2dHandler, 340, 110, 0, 6)
mouseMove(label2dHandler, 340, 90, canvasSize, 0, 6)
mouseUp(label2dHandler, 340, 90, 0, 6)
/**
* polyline: (250, 100) (300, 0) (350, 100)
* [ (340, 90) (330, 120) <bezier curve control points>]
* (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(6)
expect(points[2]).toMatchObject({ x: 350, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 340, y: 90, pointType: "bezier" })
expect(points[4]).toMatchObject({ x: 330, y: 120, pointType: "bezier" })
expect(points[5]).toMatchObject({ x: 320, y: 130, pointType: "line" })
// Delete vertex on bezier curve
keyDown(label2dHandler, "d")
mouseMove(label2dHandler, 350, 100, canvasSize, 0, 5)
mouseDown(label2dHandler, 350, 100, 0, 5)
mouseUp(label2dHandler, 350, 100, 0, 5)
keyUp(label2dHandler, "d")
/**
* polyline: (250, 100) (300, 0) (320, 130)
*/
state = getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(3)
expect(points[1]).toMatchObject({ x: 300, y: 0, pointType: "line" })
}) | the_stack |
import React from 'react'
import {
toHaveFocus,
toHaveClass,
toBeInTheDocument,
} from '@testing-library/jest-dom/matchers'
import {
screen,
render,
cleanup,
fireEvent,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
expect.extend({ toHaveFocus, toHaveClass, toBeInTheDocument })
import {
Form,
TextField,
NumberField,
CheckboxField,
TextAreaField,
DatetimeLocalField,
DateField,
SelectField,
Submit,
FieldError,
Label,
} from '../index'
describe('Form', () => {
const TestComponent = ({ onSubmit = () => {} }) => {
return (
<Form onSubmit={onSubmit}>
<TextField name="text" defaultValue="text" />
<NumberField name="number" defaultValue="42" />
<TextField
name="floatText"
defaultValue="3.14"
validation={{ valueAsNumber: true }}
/>
<CheckboxField name="checkbox" defaultChecked={true} />
<TextAreaField
name="json"
defaultValue={`
{
"key_one": "value1",
"key_two": 2,
"false": false
}
`}
validation={{ valueAsJSON: true }}
/>
<DatetimeLocalField
name="datetimeLocal"
defaultValue="2021-04-16T12:34"
/>
<DateField name="date" defaultValue="2021-04-16" />
<SelectField name="select1" data-testid="select1">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</SelectField>
<SelectField
name="select2"
data-testid="select2"
validation={{ valueAsNumber: true }}
>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<Submit>Save</Submit>
</Form>
)
}
const NumberFieldsWrapper = () => (
<div>
<h4>This is a wrapped form field header</h4>
<div>
<label htmlFor="wrapped-nf-1">Wrapped NumberField</label>
<NumberField name="wrapped-nf-1" defaultValue="0101" />
</div>
<div>
<label htmlFor="wrapped-nf-2">Wrapped NumberField</label>
<NumberField name="wrapped-nf-2" defaultValue="0102" />
</div>
</div>
)
const TestComponentWithWrappedFormElements = ({ onSubmit = () => {} }) => {
return (
<Form onSubmit={onSubmit}>
<p>Some text</p>
<div className="field">
<TextField
name="wrapped-ff"
defaultValue="3.14"
validation={{ valueAsNumber: true }}
/>
</div>
<NumberFieldsWrapper />
<Submit>Save</Submit>
</Form>
)
}
const TestComponentWithRef = () => {
const inputEl = React.useRef(null)
React.useEffect(() => {
inputEl.current.focus()
})
return (
<Form>
<TextField name="tf" defaultValue="text" ref={inputEl} />
</Form>
)
}
afterEach(() => {
cleanup()
})
it('does not crash', () => {
expect(() => render(<TestComponent />)).not.toThrow()
})
it('calls onSubmit', async () => {
const mockFn = jest.fn()
render(<TestComponent onSubmit={mockFn} />)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
})
it('renders and coerces user-supplied values', async () => {
const mockFn = jest.fn()
render(<TestComponent onSubmit={mockFn} />)
await userEvent.type(screen.getByDisplayValue('text'), 'text')
await userEvent.type(screen.getByDisplayValue('42'), '24')
await userEvent.type(screen.getByDisplayValue('3.14'), '1592')
fireEvent.change(screen.getByTestId('select1'), {
target: { value: 'Option 2' },
})
fireEvent.change(screen.getByTestId('select2'), {
target: { value: 3 },
})
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
text: 'texttext',
number: 4224, // i.e. NOT "4224"
floatText: 3.141592,
select1: 'Option 2',
select2: 3,
checkbox: true,
json: {
key_one: 'value1',
key_two: 2,
false: false,
},
datetimeLocal: new Date('2021-04-16T12:34'),
date: new Date('2021-04-16'),
},
expect.anything() // event that triggered the onSubmit call
)
})
it('finds nested form fields to coerce', async () => {
const mockFn = jest.fn()
render(<TestComponentWithWrappedFormElements onSubmit={mockFn} />)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{ 'wrapped-ff': 3.14, 'wrapped-nf-1': 101, 'wrapped-nf-2': 102 },
expect.anything() // event that triggered the onSubmit call
)
})
it('supports ref forwarding', async () => {
render(<TestComponentWithRef />)
const input = screen.getByDisplayValue('text')
await waitFor(() => {
expect(input).toHaveFocus()
})
})
it('lets users pass custom coercion functions', async () => {
const mockFn = jest.fn()
const coercionFunctionNumber = (value) =>
parseInt(value.replace('_', ''), 10)
const coercionFunctionText = (value) => value.replace('_', '-')
render(
<Form onSubmit={mockFn}>
<TextField
name="tf"
defaultValue="123_456"
validation={{ setValueAs: coercionFunctionNumber }}
/>
<SelectField
name="select"
defaultValue="Option_2"
validation={{ setValueAs: coercionFunctionText }}
>
<option>Option_1</option>
<option>Option_2</option>
</SelectField>
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{ tf: 123456, select: 'Option-2' },
expect.anything() // event that triggered the onSubmit call
)
})
it('sets the value to null for empty string on relational fields', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
{/* This is an optional relational field because the name ends with "Id"
and it doesn't have { required: true } */}
<TextField name="userId" defaultValue="" />
<SelectField name="groupId" defaultValue="">
<option value="">No group</option>
<option value={1}>Group 1</option>
<option value={2}>Group 2</option>
</SelectField>
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{ userId: null, groupId: null },
expect.anything() // event that triggered the onSubmit call
)
})
it('ensures required textField is enforced by validation', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField
name="userId2"
defaultValue=""
validation={{ required: true }}
/>
<FieldError name="userId2" data-testid="fieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.submit(screen.getByText('Save'))
await waitFor(() =>
expect(screen.getByTestId('fieldError')).toBeInTheDocument()
)
// The validation should catch and prevent the onSubmit from being called
expect(mockFn).not.toHaveBeenCalled()
})
it('ensures required selectField is enforced by validation', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<SelectField
name="groupId2"
defaultValue=""
validation={{ required: true }}
>
<option value="">No group</option>
<option value={1}>Group 1</option>
<option value={2}>Group 2</option>
</SelectField>
<FieldError name="groupId2" data-testid="fieldError" />{' '}
<Submit>Save</Submit>
</Form>
)
fireEvent.submit(screen.getByText('Save'))
await waitFor(() =>
expect(screen.getByTestId('fieldError')).toBeInTheDocument()
)
// The validation should catch and prevent the onSubmit from being called
expect(mockFn).not.toHaveBeenCalled()
})
it('handles int and float blank values gracefully', async () => {
const mockFn = jest.fn()
console.log('handles int and float blank values gracefully')
render(
<Form onSubmit={mockFn}>
<NumberField name="int" defaultValue="" />
<TextField
name="float"
defaultValue=""
validation={{ valueAsNumber: true }}
/>
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
int: NaN,
float: NaN,
},
expect.anything() // event that triggered the onSubmit call
)
})
// Note the good JSON case is tested in an earlier test
it('does not call the onSubmit function for a bad entry into a TextAreaField with valueAsJSON', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextAreaField
name="jsonField"
defaultValue="{bad-json}"
validation={{ valueAsJSON: true }}
/>
<FieldError name="jsonField" data-testid="fieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.submit(screen.getByText('Save'))
await waitFor(() =>
expect(screen.getByTestId('fieldError')).toBeInTheDocument()
)
// The validation should catch and prevent the onSubmit from being called
expect(mockFn).not.toHaveBeenCalled()
})
it('displays a FieldError for a bad entry into a TextAreaField with valueAsJSON', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextAreaField
name="jsonField"
defaultValue="{bad-json}"
validation={{ valueAsJSON: true }}
/>
<FieldError name="jsonField" data-testid="fieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.submit(screen.getByText('Save'))
await waitFor(() =>
expect(screen.getByTestId('fieldError')).toBeInTheDocument()
)
// The validation should catch and prevent the onSubmit from being called
expect(mockFn).not.toHaveBeenCalled()
})
it('for a FieldError with name set to path', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField
name="phone"
defaultValue="abcde"
validation={{ pattern: /^[0-9]+$/i }}
/>
<FieldError name="phone" data-testid="phoneFieldError" />
<TextField
name="address.street"
data-testid="streetField"
defaultValue="George123"
validation={{ pattern: /^[a-zA-z]+$/i }}
errorClassName="border-red"
/>
<FieldError name="address.street" data-testid="streetFieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.submit(screen.getByText('Save'))
await waitFor(() =>
expect(screen.getByTestId('phoneFieldError')).toBeInTheDocument()
)
// The validation should catch and prevent the onSubmit from being called
expect(mockFn).not.toHaveBeenCalled()
const phoneError = screen.getByTestId('phoneFieldError').textContent
const streetError = screen.getByTestId('streetFieldError').textContent
const streetField = screen.getByTestId('streetField')
expect(phoneError).toEqual('phone is not formatted correctly')
expect(streetError).toEqual('address.street is not formatted correctly')
expect(streetField).toHaveClass('border-red', { exact: true })
})
it("doesn't crash on Labels without name", async () => {
render(
<Form>
{/* @ts-expect-error - pretend this is a .js file */}
<Label htmlFor="phone">Input your phone number</Label>
<TextField
id="phone"
name="phone"
defaultValue="abcde"
validation={{ pattern: /^[0-9]+$/i }}
/>
<FieldError name="phone" data-testid="phoneFieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
const phoneError = await waitFor(
() => screen.getByTestId('phoneFieldError').textContent
)
expect(phoneError).toEqual('phone is not formatted correctly')
})
it('can handle falsy names ("false")', async () => {
render(
<Form>
<TextField
name="false"
defaultValue="abcde"
data-testid="phoneField"
validation={{ pattern: /^[0-9]+$/i }}
/>
<FieldError name="false" data-testid="phoneFieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
const phoneError = await waitFor(
() => screen.getByTestId('phoneFieldError').textContent
)
expect(phoneError).toEqual('false is not formatted correctly')
})
it('can handle falsy names ("0")', async () => {
render(
<Form>
<TextField
name="0"
defaultValue="abcde"
validation={{ pattern: /^[0-9]+$/i }}
/>
<FieldError name="0" data-testid="phoneFieldError" />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
const phoneError = await waitFor(
() => screen.getByTestId('phoneFieldError').textContent
)
expect(phoneError).toEqual('0 is not formatted correctly')
})
it('returns appropriate values for fields with emptyAs not defined ', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField name="textField" />
<TextField name="textAreaField" />
<NumberField name="numberField" />
<DateField name="dateField" />
<SelectField name="selectField" defaultValue="">
<option value="">No option selected</option>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<CheckboxField name="checkboxField0" defaultChecked={false} />
<CheckboxField name="checkboxField1" defaultChecked={true} />
<TextAreaField
name="jsonField"
defaultValue=""
validation={{ valueAsJSON: true }}
/>
<TextField name="fieldId" defaultValue="" />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
textField: '',
textAreaField: '',
numberField: NaN,
dateField: null,
selectField: '',
checkboxField0: false,
checkboxField1: true,
jsonField: null,
fieldId: null,
},
expect.anything() // event that triggered the onSubmit call
)
})
it(`returns appropriate values for non-empty fields with emptyAs={'undefined'}`, async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField name="textField" emptyAs={'undefined'} />
<TextAreaField name="textAreaField" emptyAs={'undefined'} />
<NumberField name="numberField" emptyAs={'undefined'} />
<DateField name="dateField" emptyAs={'undefined'} />
<SelectField name="selectField" defaultValue="" emptyAs={'undefined'}>
<option value="">No option selected</option>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<TextAreaField
name="jsonField"
defaultValue=""
validation={{ valueAsJSON: true }}
emptyAs={'undefined'}
/>
<TextField name="fieldId" defaultValue="" emptyAs={'undefined'} />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
textField: undefined,
textAreaField: undefined,
numberField: undefined,
dateField: undefined,
selectField: undefined,
jsonField: undefined,
fieldId: undefined,
},
expect.anything() // event that triggered the onSubmit call
)
})
it('returns null for empty fields with emptyAs={null}', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField name="textField" emptyAs={null} />
<TextAreaField name="textAreaField" emptyAs={null} />
<NumberField name="numberField" emptyAs={null} />
<DateField name="dateField" emptyAs={null} />
<SelectField name="selectField" defaultValue="" emptyAs={null}>
<option value="">No option selected</option>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<TextAreaField
name="jsonField"
defaultValue=""
validation={{ valueAsJSON: true }}
emptyAs={null}
/>
<TextField name="fieldId" defaultValue="" emptyAs={null} />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
textField: null,
textAreaField: null,
numberField: null,
dateField: null,
selectField: null,
jsonField: null,
fieldId: null,
},
expect.anything() // event that triggered the onSubmit call
)
})
it('returns appropriate value empty fields with emptyAs={0}', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField name="textField" emptyAs={0} />
<TextAreaField name="textAreaField" emptyAs={0} />
<NumberField name="numberField" emptyAs={0} />
<DateField name="dateField" emptyAs={0} />
<SelectField name="selectField" defaultValue="" emptyAs={0}>
<option value="">No option selected</option>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<TextAreaField
name="jsonField"
defaultValue=""
validation={{ valueAsJSON: true }}
emptyAs={0}
/>
<TextField name="fieldId" defaultValue="" emptyAs={0} />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
textField: 0,
textAreaField: 0,
numberField: 0,
dateField: 0,
selectField: 0,
jsonField: 0,
fieldId: 0,
},
expect.anything() // event that triggered the onSubmit call
)
})
it(`returns an empty string empty fields with emptyAs={''}`, async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField name="textField" emptyAs={''} />
<TextAreaField name="textAreaField" emptyAs={''} />
<NumberField name="numberField" emptyAs={''} />
<DateField name="dateField" emptyAs={''} />
<SelectField name="selectField" defaultValue="" emptyAs={''}>
<option value="">No option selected</option>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<TextAreaField
name="jsonField"
defaultValue=""
validation={{ valueAsJSON: true }}
emptyAs={''}
/>
<TextField name="fieldId" defaultValue="" emptyAs={''} />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
textField: '',
textAreaField: '',
numberField: '',
dateField: '',
selectField: '',
jsonField: '',
fieldId: '',
},
expect.anything() // event that triggered the onSubmit call
)
})
it('should have appropriate validation for NumberFields and DateFields with emptyAs={null}', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<NumberField
name="numberField"
data-testid="numberField"
emptyAs={null}
validation={{ min: 10 }}
/>
<FieldError name="numberField" data-testid="numberFieldError" />
<DateField name="dateField" emptyAs={null} />
<Submit>Save</Submit>
</Form>
)
fireEvent.change(screen.getByTestId('numberField'), {
target: { value: 2 },
})
fireEvent.submit(screen.getByText('Save'))
await waitFor(() =>
expect(screen.getByTestId('numberFieldError')).toBeInTheDocument()
)
// The validation should catch and prevent the onSubmit from being called
expect(mockFn).not.toHaveBeenCalled()
})
it(`handles invalid emptyAs values with default values`, async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
{/* @ts-expect-error - pretend this is a .js file */}
<TextField name="textField" emptyAs={'badEmptyAsValue'} />
{/* @ts-expect-error - pretend this is a .js file */}
<TextAreaField name="textAreaField" emptyAs={'badEmptyAsValue'} />
{/* @ts-expect-error - pretend this is a .js file */}
<NumberField name="numberField" emptyAs={'badEmptyAsValue'} />
{/* @ts-expect-error - pretend this is a .js file */}
<DateField name="dateField" emptyAs={'badEmptyAsValue'} />
<SelectField
name="selectField"
defaultValue=""
/* @ts-expect-error - pretend this is a .js file */
emptyAs={'badEmptyAsValue'}
>
<option value="">No option selected</option>
<option value={1}>Option 1</option>
<option value={2}>Option 2</option>
<option value={3}>Option 3</option>
</SelectField>
<TextAreaField
name="jsonField"
defaultValue=""
validation={{ valueAsJSON: true }}
/* @ts-expect-error - pretend this is a .js file */
emptyAs={'badEmptyAsValue'}
/>
{/* @ts-expect-error - pretend this is a .js file */}
<TextField name="fieldId" defaultValue="" emptyAs={'badEmptyAsValue'} />
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
textField: '',
textAreaField: '',
numberField: NaN,
dateField: null,
selectField: '',
jsonField: null,
fieldId: null,
},
expect.anything() // event that triggered the onSubmit call
)
})
it('should return a number for a textfield with valueAsNumber, regardless of emptyAs', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField
name="tf1"
validation={{ valueAsNumber: true }}
defaultValue="42"
/>
<TextField
name="tf2"
validation={{ valueAsNumber: true }}
defaultValue="42"
emptyAs={'undefined'}
/>
<TextField
name="tf3"
validation={{ valueAsNumber: true }}
defaultValue="42"
emptyAs={null}
/>
<TextField
name="tf4"
validation={{ valueAsNumber: true }}
defaultValue="42"
emptyAs={0}
/>
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
tf1: 42,
tf2: 42,
tf3: 42,
tf4: 42,
},
expect.anything() // event that triggered the onSubmit call
)
})
it('should return a date for a textfield with valueAsDate, regardless of emptyAs', async () => {
const mockFn = jest.fn()
render(
<Form onSubmit={mockFn}>
<TextField
name="tf1"
validation={{ valueAsDate: true }}
defaultValue="2022-02-01"
/>
<TextField
name="tf2"
validation={{ valueAsDate: true }}
defaultValue="2022-02-01"
emptyAs={'undefined'}
/>
<TextField
name="tf3"
validation={{ valueAsDate: true }}
defaultValue="2022-02-01"
emptyAs={null}
/>
<TextField
name="tf4"
validation={{ valueAsDate: true }}
defaultValue="2022-02-01"
emptyAs={0}
/>
<Submit>Save</Submit>
</Form>
)
fireEvent.click(screen.getByText('Save'))
await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1))
expect(mockFn).toBeCalledWith(
{
tf1: new Date('2022-02-01'),
tf2: new Date('2022-02-01'),
tf3: new Date('2022-02-01'),
tf4: new Date('2022-02-01'),
},
expect.anything() // event that triggered the onSubmit call
)
})
}) | the_stack |
import { expect } from "chai";
import { DOM } from "@microsoft/fast-element";
import { fixture } from "../test-utilities/fixture";
import { tooltipTemplate as template, Tooltip } from "./index";
import { TooltipPosition } from "./tooltip";
import { AnchoredRegion, anchoredRegionTemplate } from '../anchored-region';
const FASTTooltip = Tooltip.compose({
baseName: "tooltip",
template
})
const FASTAnchoredRegion = AnchoredRegion.compose({
baseName: "anchored-region",
template: anchoredRegionTemplate
})
async function setup() {
const { element, connect, disconnect, parent } = await fixture([FASTTooltip(), FASTAnchoredRegion()]);
const button = document.createElement("button");
button.id = "anchor";
parent.insertBefore(button, element);
element.setAttribute("anchor", "anchor");
element.id = "tooltip";
return { element, connect, disconnect };
}
describe("Tooltip", () => {
it("should not render the tooltip by default", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.delay = 0;
await connect();
await DOM.nextUpdate();
expect(tooltip.tooltipVisible).to.equal(false);
expect(tooltip.shadowRoot?.querySelector("fast-anchored-region")).to.equal(null);
await disconnect();
});
it("should render the tooltip when visible is true", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.visible = true;
tooltip.delay = 0;
await connect();
await DOM.nextUpdate();
expect(tooltip.tooltipVisible).to.equal(true);
expect(tooltip.shadowRoot?.querySelector("fast-anchored-region")).not.to.equal(
null
);
await disconnect();
});
it("should not render the tooltip when visible is false", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.visible = false;
tooltip.delay = 0;
await connect();
await DOM.nextUpdate();
expect(tooltip.tooltipVisible).to.equal(false);
expect(tooltip.shadowRoot?.querySelector("fast-anchored-region")).to.equal(null);
await disconnect();
});
it("should set positioning mode to dynamic by default", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
await connect();
expect(tooltip.verticalPositioningMode).to.equal("dynamic");
expect(tooltip.horizontalPositioningMode).to.equal("dynamic");
await disconnect();
});
it("should set update mode to 'anchor' by default", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
await connect();
expect(tooltip.autoUpdateMode).to.equal("anchor");
await disconnect();
});
it("should not set a default position by default", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
await connect();
expect(tooltip.verticalDefaultPosition).to.equal(undefined);
expect(tooltip.horizontalDefaultPosition).to.equal(undefined);
await disconnect();
});
it("should set horizontal scaling to match anchor and vertical scaling to match content by default", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
await connect();
expect(tooltip.verticalScaling).to.equal("content");
expect(tooltip.horizontalScaling).to.equal("anchor");
await disconnect();
});
// top position settings
it("should set vertical positioning mode to locked and horizontal to dynamic when position is set to top", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.top;
await connect();
expect(tooltip.verticalPositioningMode).to.equal("locktodefault");
expect(tooltip.horizontalPositioningMode).to.equal("dynamic");
await disconnect();
});
it("should set default vertical position to top when position is set to top", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.top;
await connect();
expect(tooltip.verticalDefaultPosition).to.equal("top");
expect(tooltip.horizontalDefaultPosition).to.equal(undefined);
await disconnect();
});
it("should set horizontal scaling to match anchor and vertical scaling to match content when position is set to top", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.top;
await connect();
expect(tooltip.verticalScaling).to.equal("content");
expect(tooltip.horizontalScaling).to.equal("anchor");
await disconnect();
});
// bottom position settings
it("should set vertical positioning mode to locked and horizontal to dynamic when position is set to bottom", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.bottom;
await connect();
expect(tooltip.verticalPositioningMode).to.equal("locktodefault");
expect(tooltip.horizontalPositioningMode).to.equal("dynamic");
await disconnect();
});
it("should set default vertical position to top when position is set to top", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.bottom;
await connect();
expect(tooltip.verticalDefaultPosition).to.equal("bottom");
expect(tooltip.horizontalDefaultPosition).to.equal(undefined);
await disconnect();
});
it("should set horizontal scaling to match anchor and vertical scaling to match content when position is set to bottom", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.bottom;
await connect();
expect(tooltip.verticalScaling).to.equal("content");
expect(tooltip.horizontalScaling).to.equal("anchor");
await disconnect();
});
// left position settings
it("should set horizontal positioning mode to locked and vertical to dynamic when position is set to left", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.left;
await connect();
expect(tooltip.verticalPositioningMode).to.equal("dynamic");
expect(tooltip.horizontalPositioningMode).to.equal("locktodefault");
await disconnect();
});
it("should set default horizontal position to left when position is set to left", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.left;
await connect();
expect(tooltip.verticalDefaultPosition).to.equal(undefined);
expect(tooltip.horizontalDefaultPosition).to.equal("left");
await disconnect();
});
it("should set vertical scaling to match anchor and horizontal scaling to match content when position is set to bottom", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.left;
await connect();
expect(tooltip.verticalScaling).to.equal("anchor");
expect(tooltip.horizontalScaling).to.equal("content");
await disconnect();
});
// right position settings
it("should set horizontal positioning mode to locked and vertical to dynamic when position is set to right", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.right;
await connect();
expect(tooltip.verticalPositioningMode).to.equal("dynamic");
expect(tooltip.horizontalPositioningMode).to.equal("locktodefault");
await disconnect();
});
it("should set default horizontal position to right when position is set to right", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.right;
await connect();
expect(tooltip.verticalDefaultPosition).to.equal(undefined);
expect(tooltip.horizontalDefaultPosition).to.equal("right");
await disconnect();
});
it("should set vertical scaling to match anchor and horizontal scaling to match content when position is set to rig", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
tooltip.position = TooltipPosition.right;
await connect();
expect(tooltip.verticalScaling).to.equal("anchor");
expect(tooltip.horizontalScaling).to.equal("content");
await disconnect();
});
it("should set viewport lock attributes to undefined(false) by default", async () => {
const { element, connect, disconnect } = await setup();
const tooltip: Tooltip = element;
await connect();
expect(tooltip.verticalViewportLock).to.equal(undefined);
expect(tooltip.horizontalViewportLock).to.equal(undefined);
await disconnect();
});
}); | the_stack |
import { Injectable, Injector } from '@angular/core';
import { createSelector, MemoizedSelector, select, Store } from '@ngrx/store';
import { CoreState } from '../../core.reducers';
import { coreSelector } from '../../core.selectors';
import {
FieldState,
FieldUpdates,
Identifiable,
OBJECT_UPDATES_TRASH_PATH,
ObjectUpdatesEntry,
ObjectUpdatesState,
VirtualMetadataSource
} from './object-updates.reducer';
import { Observable } from 'rxjs';
import {
AddFieldUpdateAction,
DiscardObjectUpdatesAction,
FieldChangeType,
InitializeFieldsAction,
ReinstateObjectUpdatesAction,
RemoveFieldUpdateAction,
SelectVirtualMetadataAction,
SetEditableFieldUpdateAction,
SetValidFieldUpdateAction
} from './object-updates.actions';
import { distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
import {
hasNoValue,
hasValue,
isEmpty,
isNotEmpty,
hasValueOperator
} from '../../../shared/empty.util';
import { INotification } from '../../../shared/notifications/models/notification.model';
import { Operation } from 'fast-json-patch';
import { PatchOperationService } from './patch-operation-service/patch-operation.service';
import { GenericConstructor } from '../../shared/generic-constructor';
function objectUpdatesStateSelector(): MemoizedSelector<CoreState, ObjectUpdatesState> {
return createSelector(coreSelector, (state: CoreState) => state['cache/object-updates']);
}
function filterByUrlObjectUpdatesStateSelector(url: string): MemoizedSelector<CoreState, ObjectUpdatesEntry> {
return createSelector(objectUpdatesStateSelector(), (state: ObjectUpdatesState) => state[url]);
}
function filterByUrlAndUUIDFieldStateSelector(url: string, uuid: string): MemoizedSelector<CoreState, FieldState> {
return createSelector(filterByUrlObjectUpdatesStateSelector(url), (state: ObjectUpdatesEntry) => state.fieldStates[uuid]);
}
function virtualMetadataSourceSelector(url: string, source: string): MemoizedSelector<CoreState, VirtualMetadataSource> {
return createSelector(filterByUrlObjectUpdatesStateSelector(url), (state: ObjectUpdatesEntry) => state.virtualMetadataSources[source]);
}
/**
* Service that dispatches and reads from the ObjectUpdates' state in the store
*/
@Injectable()
export class ObjectUpdatesService {
constructor(private store: Store<CoreState>,
private injector: Injector) {
}
/**
* Method to dispatch an InitializeFieldsAction to the store
* @param url The page's URL for which the changes are being mapped
* @param fields The initial fields for the page's object
* @param lastModified The date the object was last modified
* @param patchOperationService A {@link PatchOperationService} used for creating a patch
*/
initialize(url, fields: Identifiable[], lastModified: Date, patchOperationService?: GenericConstructor<PatchOperationService>): void {
this.store.dispatch(new InitializeFieldsAction(url, fields, lastModified, patchOperationService));
}
/**
* Method to dispatch an AddFieldUpdateAction to the store
* @param url The page's URL for which the changes are saved
* @param field An updated field for the page's object
* @param changeType The last type of change applied to this field
*/
private saveFieldUpdate(url: string, field: Identifiable, changeType: FieldChangeType) {
this.store.dispatch(new AddFieldUpdateAction(url, field, changeType));
}
/**
* Request the ObjectUpdatesEntry state for a specific URL
* @param url The URL to filter by
*/
private getObjectEntry(url: string): Observable<ObjectUpdatesEntry> {
return this.store.pipe(select(filterByUrlObjectUpdatesStateSelector(url)));
}
/**
* Request the getFieldState state for a specific URL and UUID
* @param url The URL to filter by
* @param uuid The field's UUID to filter by
*/
private getFieldState(url: string, uuid: string): Observable<FieldState> {
return this.store.pipe(select(filterByUrlAndUUIDFieldStateSelector(url, uuid)));
}
/**
* Method that combines the state's updates with the initial values (when there's no update) to create
* a FieldUpdates object
* @param url The URL of the page for which the FieldUpdates should be requested
* @param initialFields The initial values of the fields
* @param ignoreStates Ignore the fieldStates to loop over the fieldUpdates instead
*/
getFieldUpdates(url: string, initialFields: Identifiable[], ignoreStates?: boolean): Observable<FieldUpdates> {
const objectUpdates = this.getObjectEntry(url);
return objectUpdates.pipe(
switchMap((objectEntry) => {
const fieldUpdates: FieldUpdates = {};
if (hasValue(objectEntry)) {
Object.keys(ignoreStates ? objectEntry.fieldUpdates : objectEntry.fieldStates).forEach((uuid) => {
fieldUpdates[uuid] = objectEntry.fieldUpdates[uuid];
});
}
return this.getFieldUpdatesExclusive(url, initialFields).pipe(
map((fieldUpdatesExclusive) => {
Object.keys(fieldUpdatesExclusive).forEach((uuid) => {
fieldUpdates[uuid] = fieldUpdatesExclusive[uuid];
});
return fieldUpdates;
})
);
}),
);
}
/**
* Method that combines the state's updates (excluding updates that aren't part of the initialFields) with
* the initial values (when there's no update) to create a FieldUpdates object
* @param url The URL of the page for which the FieldUpdates should be requested
* @param initialFields The initial values of the fields
*/
getFieldUpdatesExclusive(url: string, initialFields: Identifiable[]): Observable<FieldUpdates> {
const objectUpdates = this.getObjectEntry(url);
return objectUpdates.pipe(
hasValueOperator(),
map((objectEntry) => {
const fieldUpdates: FieldUpdates = {};
for (const object of initialFields) {
let fieldUpdate = objectEntry.fieldUpdates[object.uuid];
if (isEmpty(fieldUpdate)) {
fieldUpdate = { field: object, changeType: undefined };
}
fieldUpdates[object.uuid] = fieldUpdate;
}
return fieldUpdates;
}));
}
/**
* Method to check if a specific field is currently editable in the store
* @param url The URL of the page on which the field resides
* @param uuid The UUID of the field
*/
isEditable(url: string, uuid: string): Observable<boolean> {
const fieldState$ = this.getFieldState(url, uuid);
return fieldState$.pipe(
filter((fieldState) => hasValue(fieldState)),
map((fieldState) => fieldState.editable),
distinctUntilChanged()
);
}
/**
* Method to check if a specific field is currently valid in the store
* @param url The URL of the page on which the field resides
* @param uuid The UUID of the field
*/
isValid(url: string, uuid: string): Observable<boolean> {
const fieldState$ = this.getFieldState(url, uuid);
return fieldState$.pipe(
filter((fieldState) => hasValue(fieldState)),
map((fieldState) => fieldState.isValid),
distinctUntilChanged()
);
}
/**
* Method to check if a specific page is currently valid in the store
* @param url The URL of the page
*/
isValidPage(url: string): Observable<boolean> {
const objectUpdates = this.getObjectEntry(url);
return objectUpdates.pipe(
map((entry: ObjectUpdatesEntry) => {
return Object.values(entry.fieldStates).findIndex((state: FieldState) => !state.isValid) < 0;
}),
distinctUntilChanged()
);
}
/**
* Calls the saveFieldUpdate method with FieldChangeType.ADD
* @param url The page's URL for which the changes are saved
* @param field An updated field for the page's object
*/
saveAddFieldUpdate(url: string, field: Identifiable) {
this.saveFieldUpdate(url, field, FieldChangeType.ADD);
}
/**
* Calls the saveFieldUpdate method with FieldChangeType.REMOVE
* @param url The page's URL for which the changes are saved
* @param field An updated field for the page's object
*/
saveRemoveFieldUpdate(url: string, field: Identifiable) {
this.saveFieldUpdate(url, field, FieldChangeType.REMOVE);
}
/**
* Calls the saveFieldUpdate method with FieldChangeType.UPDATE
* @param url The page's URL for which the changes are saved
* @param field An updated field for the page's object
*/
saveChangeFieldUpdate(url: string, field: Identifiable) {
this.saveFieldUpdate(url, field, FieldChangeType.UPDATE);
}
/**
* Check whether the virtual metadata of a given item is selected to be saved as real metadata
* @param url The URL of the page on which the field resides
* @param relationship The id of the relationship for which to check whether the virtual metadata is selected to be
* saved as real metadata
* @param item The id of the item for which to check whether the virtual metadata is selected to be
* saved as real metadata
*/
isSelectedVirtualMetadata(url: string, relationship: string, item: string): Observable<boolean> {
return this.store
.pipe(
select(virtualMetadataSourceSelector(url, relationship)),
map((virtualMetadataSource) => virtualMetadataSource && virtualMetadataSource[item]),
);
}
/**
* Method to dispatch a SelectVirtualMetadataAction to the store
* @param url The page's URL for which the changes are saved
* @param relationship the relationship for which virtual metadata is selected
* @param uuid the selection identifier, can either be the item uuid or the relationship type uuid
* @param selected whether or not to select the virtual metadata to be saved
*/
setSelectedVirtualMetadata(url: string, relationship: string, uuid: string, selected: boolean) {
this.store.dispatch(new SelectVirtualMetadataAction(url, relationship, uuid, selected));
}
/**
* Dispatches a SetEditableFieldUpdateAction to the store to set a field's editable state
* @param url The URL of the page on which the field resides
* @param uuid The UUID of the field that should be set
* @param editable The new value of editable in the store for this field
*/
setEditableFieldUpdate(url: string, uuid: string, editable: boolean) {
this.store.dispatch(new SetEditableFieldUpdateAction(url, uuid, editable));
}
/**
* Dispatches a SetValidFieldUpdateAction to the store to set a field's isValid state
* @param url The URL of the page on which the field resides
* @param uuid The UUID of the field that should be set
* @param valid The new value of isValid in the store for this field
*/
setValidFieldUpdate(url: string, uuid: string, valid: boolean) {
this.store.dispatch(new SetValidFieldUpdateAction(url, uuid, valid));
}
/**
* Method to dispatch an DiscardObjectUpdatesAction to the store
* @param url The page's URL for which the changes should be discarded
* @param undoNotification The notification which is should possibly be canceled
*/
discardFieldUpdates(url: string, undoNotification: INotification) {
this.store.dispatch(new DiscardObjectUpdatesAction(url, undoNotification));
}
/**
* Method to dispatch a DiscardObjectUpdatesAction to the store with discardAll set to true
* @param url The page's URL for which the changes should be discarded
* @param undoNotification The notification which is should possibly be canceled
*/
discardAllFieldUpdates(url: string, undoNotification: INotification) {
this.store.dispatch(new DiscardObjectUpdatesAction(url, undoNotification, true));
}
/**
* Method to dispatch an ReinstateObjectUpdatesAction to the store
* @param url The page's URL for which the changes should be reinstated
*/
reinstateFieldUpdates(url: string) {
this.store.dispatch(new ReinstateObjectUpdatesAction(url));
}
/**
* Method to dispatch an RemoveFieldUpdateAction to the store
* @param url The page's URL for which the changes should be removed
* @param uuid The UUID of the field that should be set
*/
removeSingleFieldUpdate(url: string, uuid) {
this.store.dispatch(new RemoveFieldUpdateAction(url, uuid));
}
/**
* Method that combines the state's updates with the initial values (when there's no update) to create
* a list of updates fields
* @param url The URL of the page for which the updated fields should be requested
* @param initialFields The initial values of the fields
*/
getUpdatedFields(url: string, initialFields: Identifiable[]): Observable<Identifiable[]> {
const objectUpdates = this.getObjectEntry(url);
return objectUpdates.pipe(map((objectEntry) => {
const fields: Identifiable[] = [];
Object.keys(objectEntry.fieldStates).forEach((uuid) => {
const fieldUpdate = objectEntry.fieldUpdates[uuid];
if (hasNoValue(fieldUpdate) || fieldUpdate.changeType !== FieldChangeType.REMOVE) {
let field;
if (isNotEmpty(fieldUpdate)) {
field = fieldUpdate.field;
} else {
field = initialFields.find((object: Identifiable) => object.uuid === uuid);
}
fields.push(field);
}
});
return fields;
}));
}
/**
* Checks if the page currently has updates in the store or not
* @param url The page's url to check for in the store
*/
hasUpdates(url: string): Observable<boolean> {
return this.getObjectEntry(url).pipe(map((objectEntry) => hasValue(objectEntry) && isNotEmpty(objectEntry.fieldUpdates)));
}
/**
* Checks if the page currently is reinstatable in the store or not
* @param url The page's url to check for in the store
*/
isReinstatable(url: string): Observable<boolean> {
return this.hasUpdates(url + OBJECT_UPDATES_TRASH_PATH);
}
/**
* Request the current lastModified date stored for the updates in the store
* @param url The page's url to check for in the store
*/
getLastModified(url: string): Observable<Date> {
return this.getObjectEntry(url).pipe(map((entry: ObjectUpdatesEntry) => entry.lastModified));
}
/**
* Create a patch from the current object-updates state
* The {@link ObjectUpdatesEntry} should contain a patchOperationService, in order to define how a patch should
* be created. If it doesn't, an empty patch will be returned.
* @param url The URL of the page for which the patch should be created
*/
createPatch(url: string): Observable<Operation[]> {
return this.getObjectEntry(url).pipe(
map((entry) => {
let patch = [];
if (hasValue(entry.patchOperationService)) {
patch = this.injector.get(entry.patchOperationService).fieldUpdatesToPatchOperations(entry.fieldUpdates);
}
return patch;
})
);
}
} | the_stack |
import * as fse from 'fs-extra';
import chalk from 'chalk';
import * as Sequelize from 'sequelize';
import { join } from 'path';
import { IEndpoint, IApplyOptions, IField } from '@materia/interfaces';
import { App } from './app';
import { MateriaError } from './error';
import { Addon } from './addons/addon';
import { MigrationType } from './history';
import { CustomQuery } from './entities/queries/custom';
import { DBEntity } from './entities/db-entity';
import { Entity } from './entities/entity';
import { ConfigType } from './config';
import { VirtualEntity } from './entities/virtual-entity';
/**
* @class Entities
* @classdesc
* Entity manager. This class is relative to all the entities of an app.
*/
export class Entities {
entities: {[name: string]: Entity | VirtualEntity};
entitiesJson: {[path: string]: Array<any>};
constructor(public app: App) {
this.entities = {};
this.entitiesJson = {};
this.app.history.register(MigrationType.CREATE_ENTITY, (data, opts) => {
return this.add(data.value, opts);
});
this.app.history.register(MigrationType.RENAME_ENTITY, (data, opts): any => {
return this.rename(data.table, data.value, opts);
});
this.app.history.register(MigrationType.DELETE_ENTITY, (data, opts) => {
return this.remove(data.table, opts);
});
this.app.history.register(MigrationType.ADD_FIELD, (data, opts) => {
return this.get(data.table).addFieldAt(data.value as IField, data.position, opts);
});
this.app.history.register(MigrationType.CHANGE_FIELD, (data, opts) => {
return this.get(data.table).updateField(data.name, data.value, opts);
});
this.app.history.register(MigrationType.DELETE_FIELD, (data, opts) => {
return this.get(data.table).removeField(data.value, opts);
});
this.app.history.register(MigrationType.ADD_RELATION, (data, opts) => {
return this.get(data.table).addRelation(data.value, opts);
});
this.app.history.register(MigrationType.DELETE_RELATION, (data, opts) => {
return this.get(data.table).removeRelation(data.value, opts);
});
this.app.history.register(MigrationType.ADD_QUERY, (data, opts) => {
const query = Object.assign({}, data.values);
query.id = data.id;
this.get(data.table).addQuery(query, opts);
return Promise.resolve();
});
this.app.history.register(MigrationType.DELETE_QUERY, (data, opts) => {
this.get(data.table).removeQuery(data.id, opts);
return Promise.resolve();
});
}
clear(): void {
this.entities = {};
this.entitiesJson = {};
}
cleanFiles(): void {
delete this.entitiesJson;
this.entitiesJson = {};
}
loadFiles(addon?: Addon): Promise<any> {
const basePath = addon ? addon.path : this.app.path;
this.entitiesJson[basePath] = [];
let files;
let p = Promise.resolve();
try {
files = fse.readdirSync(join(basePath, 'server', 'models'));
p = p.then(() => Promise.resolve());
} catch (e) {
files = [];
fse.mkdirsSync(join(basePath, 'server', 'models'));
return Promise.resolve(false);
}
const entitiesPositions = this.app.config.get<{[name: string]: {x: number, y: number}}>(null, ConfigType.ENTITIES_POSITION) || {};
for (const file of files) {
try {
if (file.substr(file.length - 5, 5) == '.json') {
const content = fse.readFileSync(join(basePath, 'server', 'models', file));
const entity = JSON.parse(content.toString());
entity.name = file.substr(0, file.length - 5);
if (entitiesPositions[entity.name]) {
entity.x = entitiesPositions[entity.name].x;
entity.y = entitiesPositions[entity.name].y;
}
this.entitiesJson[basePath].push(entity);
p = p.then(() => Promise.resolve());
}
} catch (e) {
e += ' in ' + file;
this.app.logger.error(new Error(e));
p = p.then(() => Promise.resolve());
}
}
return p;
}
loadEntities(addon?: Addon): Promise<Entity[]> {
const basePath = addon ? addon.path : this.app.path;
const promises: Promise<Entity>[] = [];
const opts: IApplyOptions = {
history: false,
db: false,
save: false,
wait_relations: true
};
if (addon) {
opts.fromAddon = addon;
if (this.entitiesJson[basePath].length > 0) {
this.app.logger.log(` │ └─┬ ${addon.package}`);
}
} else if (this.entitiesJson[basePath].length > 0) {
this.app.logger.log(` │ └─┬ Application`);
}
for (const file of this.entitiesJson[basePath]) {
this.app.logger.log(` │ │ └── ${chalk.bold(file.name)}`);
if (file.virtual) {
promises.push(this.addVirtual(file, opts));
} else {
if ( ! this.app.database.disabled ) {
promises.push(this.add(file, opts));
}
}
}
return Promise.all(promises);
}
loadQueries(addon?: Addon): Promise<void> {
const basePath = addon ? addon.path : this.app.path;
if (this.entitiesJson[basePath].length > 0) {
if (addon) {
this.app.logger.log(` │ └─┬ ${addon.package}`);
} else {
this.app.logger.log(` │ └─┬ Application`);
}
}
try {
for (const entityJson of this.entitiesJson[basePath]) {
const entity = this.get(entityJson.name);
if (entity) {
entity.loadQueries(entityJson.queries);
}
}
} catch (e) {
return Promise.reject(e);
}
return Promise.resolve();
}
loadRelations(): Promise<any> {
if ( this.app.database.disabled ) {
return Promise.resolve();
}
const promises = [];
for (const name in this.entities) {
if (this.entities[name]) {
const entity = this.entities[name];
promises.push(entity.applyRelations());
}
}
return Promise.all(promises);
}
start(): Promise<any> {
if ( this.app.database.disabled ) {
return Promise.resolve();
}
// detect rename then sync database
// return this.detect_rename().then(() => {
// return this._save_id_map()
return Promise.resolve()
.then(() => {
// Convert orphan n-n through tables
const promises = [];
for (const name in this.entities) {
if (this.entities[name]) {
promises.push(this.entities[name].fixIsRelation({save: false, db: false, history: false}));
}
}
return Promise.all(promises);
}).then(() => {
return this.sync();
}).then(() => {
return this.detect_rename();
}).then(() => {
return this.app.database.sequelize.sync();
});
}
/**
Add a new virtual entity
@param {object} - Entity description
@param {object} - Action's options
@returns {Promise<Entity>}
*/
addVirtual(entityobj, options?) {
options = options || {};
let entity: VirtualEntity | Entity, createPromise: Promise<any>;
if (entityobj instanceof Entity) {
entity = entityobj;
createPromise = Promise.resolve();
} else {
if (! entityobj.name) {
return Promise.reject(new MateriaError('missing entity name'));
}
entity = new VirtualEntity(this.app);
if (entityobj.overwritable && this.entities[entity.name] && options.apply) {
return Promise.resolve(entity);
}
createPromise = entity.create(entityobj, {wait_relations: options.wait_relations, fromAddon: options.fromAddon});
}
return createPromise.then(() => {
if (options.apply != false) {
this.entities[entity.name] = entity;
this.app.emit('entity:added', entity);
}
if (options.save != false) {
return entity.save().then(() => this._save_id_map(options));
}
}).then(() => {
if (options.overwritable) {
return entity;
}
if (options.history != false) {
this.app.history.push({
type: MigrationType.CREATE_ENTITY,
table: entity.name,
value: entity.toJson()
}, {
type: MigrationType.DELETE_ENTITY,
table: entity.name
});
}
let p;
if (options.apply != false) {
entity.generateDefaultQueries();
p = this.sync().then(() => {
entity.refreshQueries();
});
} else {
p = entity.loadModel();
}
return p.then(() => {
return entity;
});
});
}
/**
Add a new entity
@param {object} - Entity description
@param {object} - Action's options
@returns {Promise<Entity>}
*/
add(entityobj, options?): Promise<Entity> {
if (this.app.database.disabled) {
return Promise.reject({error: true, message: 'The database is disabled'});
}
options = options || {};
let entity: Entity, createPromise;
if (entityobj instanceof Entity) {
entity = entityobj;
createPromise = Promise.resolve();
} else {
if (! entityobj.name) {
return Promise.reject(new MateriaError('missing entity name'));
}
entity = new DBEntity(this.app);
if ( ! entityobj.isRelation && (! entityobj.fields || ! entityobj.fields.length)) {
entityobj.fields = [
{
'name': 'id_' + entityobj.name,
'type': 'number',
'required': true,
'primary': true,
'unique': true,
'default': false,
'autoIncrement': true,
'read': true,
'write': false
}
];
}
if (entityobj.overwritable && this.entities[entity.name] && options.apply) {
return Promise.resolve(entity);
}
if (entityobj.isRelation && entityobj.relations) {
delete entityobj.relations; // NEED TO CHECK THIS / NOT SURE ITS GOOD AS A RELATION TABLE CAN ALSO HAVE RELATIONS
}
createPromise = entity.create(entityobj, {wait_relations: options.wait_relations, fromAddon: options.fromAddon});
}
return createPromise.then(() => {
if (options.apply != false) {
this.entities[entity.name] = entity;
this.app.emit('entity:added', entity);
}
if (options.save != false) {
return entity.save().then(() => this._save_id_map(options));
} else {
return Promise.resolve();
}
}).then(() => {
if (options.overwritable) {
return entity;
}
if (options.history != false) {
this.app.history.push({
type: MigrationType.CREATE_ENTITY,
table: entity.name,
value: entity.toJson()
}, {
type: MigrationType.DELETE_ENTITY,
table: entity.name
});
}
if (options.db == false) {
return entity;
}
let p = Promise.resolve();
if (options.apply != false) {
entity.generateDefaultQueries();
p = this.sync().then(() => {
return entity.refreshQueries();
});
} else {
p = entity.loadModel();
}
return p.then(() => {
return entity.model.sync();
}).then(() => {
return entity;
});
});
}
detect_rename(): Promise<any> {
let name_map;
try {
const content = fse.readFileSync(join(this.app.path, '.materia', 'ids.json')).toString();
name_map = JSON.parse(content);
} catch (e) {
if (e.code == 'ENOENT') {
return Promise.resolve();
}
console.error(e);
return Promise.reject(e);
}
const diffs = [];
for (const entity_name in this.entities) {
if (this.entities[entity_name]) {
const entity = this.entities[entity_name];
if (name_map[entity.id] && name_map[entity.id] != entity_name) {
diffs.push({
redo: {
type: MigrationType.RENAME_ENTITY,
table: name_map[entity.id],
value: entity_name
},
undo: {
type: MigrationType.RENAME_ENTITY,
table: entity_name,
value: name_map[entity.id]
}
});
}
}
}
if (diffs.length == 0) {
return Promise.resolve();
}
for (const diff of diffs) {
this.app.logger.log(chalk.bold(`Detected entity rename: ${chalk.yellow(diff.redo.table)} -> ${chalk.yellow(diff.redo.value)}`));
}
return this.app.history.apply(diffs, {
full_rename: false
});
}
/**
Delete an entity.
@param {string} - Entity's name
@param {object} - Action's options
@returns {Promise}
*/
remove(name: string, options?: IApplyOptions): Promise<any> {
options = options || {};
if ( ! name) {
return Promise.reject(new MateriaError('You must specify an entity name to delete.'));
}
const entity = this.entities[name];
const endpoints: IEndpoint[] = this.app.api.findAll().map(e => e.toJson());
const relatedEndpoints: IEndpoint[] = endpoints.filter((e: IEndpoint) => e.query && e.query.entity === name);
for (const endpoint of relatedEndpoints) {
this.app.api.remove(endpoint.method, endpoint.url);
}
let p = Promise.resolve();
for (const entity_name in this.entities) {
if (this.entities[entity_name]) {
for (const relation of this.entities[entity_name].relations) {
if (relation.reference.entity == name) {
p = p.then(() => {
return this.entities[entity_name].removeRelation(relation, options);
});
}
}
}
}
return p.then(() => {
if (options.history != false) {
this.app.history.push({
type: MigrationType.DELETE_ENTITY,
table: name
}, {
type: MigrationType.CREATE_ENTITY,
table: name,
value: entity.toJson()
});
}
if (options.apply != false) {
delete this.entities[name];
}
const relativePath = join('server', 'models', name + '.json');
if (options.save != false && entity && fse.existsSync(join(this.app.path, relativePath))) {
// TODO: this.app.path replaced by basepath computed with fromAddon
fse.unlinkSync(join(this.app.path, relativePath));
}
if (entity instanceof VirtualEntity) {
return Promise.resolve();
}
if (options.db == false) {
return Promise.reject(new MateriaError('Cannot delete entity (database is disabled)'));
}
// TODO: remove constraint to avoid force:true ? more tests needed
return this.app.database.sequelize.getQueryInterface().dropTable(name, {force: true} as Sequelize.QueryOptions);
});
}
/**
Rename an entity
@param {string} - Entity's name (old name)
@param {string} - Entity's new name
@param {object} - Action's options
@returns {Promise}
*/
rename(name: string, new_name: string, options?): Promise<any> {
options = options || {};
const entity = this.get(name);
if ( ! entity && options.full_rename != false) {
return Promise.reject(new MateriaError(`Entity "${name}" does not exist.`));
}
if ( entity && this.get(new_name)) {
return Promise.reject(new MateriaError(`Entity "${new_name}" already exists.`));
}
let p = Promise.resolve();
if (options.history != false) {
this.app.history.push({
type: MigrationType.RENAME_ENTITY,
table: name,
value: new_name
}, {
type: MigrationType.RENAME_ENTITY,
table: new_name,
value: name
});
}
const entitiesChanged = entity ? [entity] : [];
if (options.apply != false) {
for (const entity_name in this.entities) {
if (this.entities[entity_name]) {
const ent = this.entities[entity_name];
let need_save = false;
for (const relation of ent.relations) {
if (relation.reference && relation.reference.entity == name) {
need_save = true;
relation.reference.entity = new_name;
}
if (relation.through == name) {
need_save = true;
relation.through = new_name;
}
}
if (need_save && options.save != false) {
entitiesChanged.push(entity);
p = p.then(() => entity.save());
}
}
}
/*if (entity.fields[0].name == 'id_' + name) {
entity.fields[0].name = 'id_' + new_name
// TODO: rename field (with options db:options.db save:false history:false)
}*/
if (entity) {
entity.name = new_name;
this.entities[new_name] = entity;
delete this.entities[name];
}
}
if (options.save != false) {
const relativePath = join('server', 'models', name + '.json');
if (fse.existsSync(join(this.app.path, relativePath))) {
fse.unlinkSync(join(this.app.path, relativePath));
p = p.then(() => this._save_id_map(options));
}
p = p.then(() => this.save());
}
if (entity instanceof VirtualEntity || options.db == false) {
return Promise.resolve();
}
return p.then(() =>
this.app.database.sequelize.getQueryInterface().renameTable(name, new_name)
).then(() => {
let promise = Promise.resolve();
for (const ent of entitiesChanged) {
promise = promise.then(() => {
return ent.loadModel().then(() => {
ent.loadRelationsInModel();
});
});
}
return promise;
});
}
/**
Returns a list of the entities
@returns {Array<Entity>}
*/
findAll() {
const entities = [];
for (const entity in this.entities) {
if (this.entities[entity]) {
entities.push(this.entities[entity]);
}
}
return entities;
}
/**
Returns an entity be specifying its name
@param {string} - Entity's name
@returns {Entity}
*/
get(name): Entity { return this.entities[name]; }
/**
Returns an entity be specifying its name, or create it with its description
@param {string} - Entity's name
@param {string} - Entity's description
@param {string} - Action's options
@returns {Entity}
*/
getOrAdd(name, entityobj, options) {
if (this.entities[name]) {
return Promise.resolve(this.entities[name]);
}
entityobj.name = name;
return this.add(entityobj, options);
}
save(): Promise<void> {
let p = Promise.resolve();
for (const entity in this.entities) {
if (this.entities[entity]) {
p = p .then(() => this.entities[entity].save());
}
}
return p;
}
sync() {
const promises = [];
for (const ent in this.entities) {
if (this.entities[ent]) {
promises.push(this.entities[ent].loadModel().catch((err) => {
err.message = 'Could not load entity ' + ent + ': ' + err.message;
throw err;
}));
}
}
return Promise.all(promises).then(() => {
// Need a second loop to executes relations when all models are created
for (const ent in this.entities) {
if (this.entities[ent]) {
this.entities[ent].loadRelationsInModel();
}
}
});
}
findAllRelations(opts) {
opts = opts || {};
const res = [];
for (const ent in this.entities) {
if (this.entities[ent]) {
const entity = this.entities[ent];
for (const r of entity.relations) {
if ( ! r.implicit || opts.implicit) {
r.entity = ent;
res.push(r);
}
}
if (entity.isRelation && opts.implicit) {
for (const f of entity.getFields()) {
const r = f.isRelation;
if (r) {
r.entity = ent;
r.implicit = true;
r.field = f.name;
res.push(r);
}
}
}
}
}
return res;
}
getModels(addon?: Addon) {
return Object.keys(CustomQuery.models).filter((value) => {
return (addon && value.substr(0, addon.name.length + 1) == addon.name + '/')
|| ( ! addon && value.indexOf('/') == -1);
});
}
resetModels(): void {
if ( ! this.app.database.disabled ) {
CustomQuery.resetModels();
}
}
private _save_id_map(opts?): Promise<any> {
opts = opts || {};
const name_map = {};
for (const entity_name in this.entities) {
if (this.entities[entity_name]) {
const entity = this.entities[entity_name];
name_map[entity.id] = entity_name;
}
}
const actions = Object.assign({}, opts);
actions.mkdir = true;
return this.app.saveFile(join(this.app.path, '.materia', 'ids.json'), JSON.stringify(name_map, null, '\t'), actions);
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
class BulkDeleteFailureApi {
/**
* DynamicsCrm.DevKit BulkDeleteFailureApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the system job that created this record. */
AsyncOperationId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the bulk deletion failure record. */
BulkDeleteFailureId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the bulk operation job which created this record */
BulkDeleteOperationId: DevKit.WebApi.LookupValueReadonly;
/** Description of the error. */
ErrorDescription: DevKit.WebApi.StringValueReadonly;
/** Error code for the failed bulk deletion. */
ErrorNumber: DevKit.WebApi.IntegerValueReadonly;
/** Index of the ordered query expression that retrieved this record. */
OrderedQueryIndex: DevKit.WebApi.IntegerValueReadonly;
/** 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.LookupValueReadonly;
/** 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.LookupValueReadonly;
/** Unique identifier of the business unit that owns the bulk deletion failure. */
OwningBusinessUnit: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the user who owns the bulk deletion failure record.
*/
OwningUser: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_account: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activitymimeattachment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activitypointer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_annotation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_annualfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appelement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_applicationuser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appnotification: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appointment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appusersetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_attributeimageconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_attributemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bot: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_botcomponent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_businessunit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_businessunitnewsarticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_calendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_catalog: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_catalogassignment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
channelaccessprofile_bulkdeletefailures: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
channelaccessprofileruleid: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_connectionreference: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_connector: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contact: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customapi: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customeraddress: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customerrelationship: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakefolder: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_devkit_bpfaccount: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_displaystring: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_email: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_emailserverprofile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entityanalyticsconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entityimageconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitymap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
externalparty_bulkdeletefailures: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
externalpartyitem_bulkdeletefailures: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_fax: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_featurecontrolsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_fixedmonthlyfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_flowmachine: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_flowsession: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_import: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importlog: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importmap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_isvconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_kbarticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_kbarticlecomment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_kbarticletemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_knowledgearticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_knowledgebaserecord: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_letter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_managedidentity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_monthlyfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organization: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organizationsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_package: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_pdfsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_phonecall: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_pluginpackage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_post: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_privilege: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_processstageparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_quarterlyfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_queue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_queueitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_recurringappointmentmaster: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_relationshipattribute: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_relationshiprole: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_relationshiprolemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_role: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_routingrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_routingruleitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_savedquery: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_semiannualfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_serviceplan: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_serviceplanmapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_settingdefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_sla: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_socialactivity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_subject: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_systemform: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_task: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_template: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_territory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_theme: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_userform: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_usermapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_userquery: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_workflowbinary: DevKit.WebApi.LookupValueReadonly;
RegardingObjectIdYomiName: DevKit.WebApi.StringValue;
}
}
declare namespace OptionSet {
namespace BulkDeleteFailure {
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':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import * as puppeteer from 'puppeteer';
import { relative, join, isAbsolute, dirname } from 'path';
import type { BoundQueries, WaitForOptions } from './pptr-testing-library';
import {
getQueriesForElement,
waitFor as innerWaitFor,
} from './pptr-testing-library';
import { connectToBrowser } from './connect-to-browser';
import { parseStackTrace } from 'errorstacks';
import './extend-expect';
import { bgRed, white, options as koloristOpts, bold, red } from 'kolorist';
import { ansiColorsLog } from './ansi-colors-browser';
import _ansiRegex from 'ansi-regex';
import { fileURLToPath } from 'url';
import type { PleasantestUser } from './user';
import { pleasantestUser } from './user';
import { assertElementHandle } from './utils';
import type { ModuleServerOpts } from './module-server';
import { createModuleServer } from './module-server';
import { cleanupClientRuntimeServer } from './module-server/client-runtime-server';
import { Console } from 'console';
import { createBuildStatusTracker } from './module-server/build-status-tracker';
import { sourceMapErrorFromBrowser } from './source-map-error-from-browser';
import type { AsyncHookTracker } from './async-hooks';
import { createAsyncHookTracker } from './async-hooks';
export { JSHandle, ElementHandle } from 'puppeteer';
koloristOpts.enabled = true;
const ansiRegex = _ansiRegex({ onlyFirst: true });
export type { PleasantestUser };
export interface PleasantestUtils {
/**
* Execute a JS code string in the browser.
* The code string inherits the syntax abilities of the file it is in,
* i.e. if your test file is a .tsx file, then the code string can include JSX and TS.
* The code string can use (static or dynamic) ES6 imports to import other modules,
* including TS/JSX modules, and it supports resolving from node_modules,
* and relative paths from the test file.
* The code string supports top-level await to wait for a Promise to resolve.
* You can pass an array of variables to be passed into the browser as the 2nd parameter.
*/
runJS(code: string, args?: unknown[]): Promise<void>;
/** Set the contents of a new style tag */
injectCSS(css: string): Promise<void>;
/** Set the contents of document.body */
injectHTML(html: string): Promise<void>;
/** Load a CSS (or Sass, Less, etc.) file into the browser. Pass a path that will be resolved from your test file. */
loadCSS(cssPath: string): Promise<void>;
/** Load a JS (or TS, JSX) file into the browser. Pass a path that will be resolved from your test file. */
loadJS(jsPath: string): Promise<void>;
}
export interface PleasantestContext {
/** DOM Testing Library queries that are bound to the document */
screen: BoundQueries;
utils: PleasantestUtils;
/** Returns DOM Testing Library queries that only search within a single element */
within(element: puppeteer.ElementHandle | null): BoundQueries;
page: puppeteer.Page;
user: PleasantestUser;
waitFor: <T>(cb: () => T | Promise<T>, opts?: WaitForOptions) => Promise<T>;
}
export interface WithBrowserOpts {
headless?: boolean;
device?: puppeteer.devices.Device;
moduleServer?: ModuleServerOpts;
}
interface TestFn {
(ctx: PleasantestContext): boolean | void | Promise<boolean | void>;
}
interface WithBrowserFn {
(testFn: TestFn): () => Promise<void>;
(options: WithBrowserOpts, testFn: TestFn): () => Promise<void>;
}
interface WithBrowser extends WithBrowserFn {
headed: WithBrowserFn;
}
// Call signatures of withBrowser:
// withBrowser(() => {})
// withBrowser({ ... }, () => {})
// withBrowser.headed(() => {})
// withBrowser.headed({ ... }, () => {})
export const withBrowser: WithBrowser = (...args: any[]) => {
const testFn: TestFn = args.length === 1 ? args[0] : args[1];
const options: WithBrowserOpts = args.length === 1 ? {} : args[0];
const thisFile = fileURLToPath(import.meta.url);
// Figure out the file that called withBrowser so that we can resolve paths correctly from there
// eslint-disable-next-line @cloudfour/unicorn/error-message
const stack = parseStackTrace(new Error().stack as string).map(
(stackFrame) => {
if (stackFrame.fileName) return stackFrame.fileName;
return /\s*at\s+([\w./-]*)/.exec(stackFrame.raw)?.[1];
},
);
const testFile = stack.find((stackItem) => {
if (!stackItem) return false;
// ignore if it is the current file
if (stackItem === thisFile) return false;
// ignore if it is an internal-to-node thing
if (!stackItem.startsWith('/')) return false;
// Find the first item that is not the current file
return true;
});
const testPath = testFile ? relative(process.cwd(), testFile) : thisFile;
return async () => {
const { cleanupServer, asyncHookTracker, ...ctx } = await createTab({
testPath,
options,
});
const cleanup = async (leaveOpen: boolean) => {
if (!leaveOpen || options.headless) {
await ctx.page.close();
}
ctx.page.browser().disconnect();
await cleanupServer();
};
try {
await testFn(ctx);
const forgotAwaitError = asyncHookTracker.close();
if (forgotAwaitError) throw forgotAwaitError;
} catch (error) {
const forgotAwaitError = asyncHookTracker.close();
if (forgotAwaitError) {
await cleanup(false);
throw forgotAwaitError;
}
const messageForBrowser: undefined | unknown[] =
// This is how we attach the elements to the error from testing-library
error?.messageForBrowser ||
// This is how we attach the elements to the error from jest-dom
error?.matcherResult?.messageForBrowser;
// Jest hangs when sending the error
// from the worker process up to the main process
// if the error has circular references in it
// (which it does if there are elementHandles)
if (error.matcherResult) delete error.matcherResult.messageForBrowser;
delete error.messageForBrowser;
if (!options.headless) {
const failureMessage: unknown[] = [
`${bold(white(bgRed(' FAIL ')))}\n\n`,
];
const testName = getTestName();
if (testName) {
failureMessage.push(`${bold(red(`● ${testName}`))}\n\n`);
}
if (messageForBrowser) {
failureMessage.push(
...messageForBrowser.map((segment: unknown, i) => {
if (typeof segment !== 'string') return segment;
if (i !== 0 && typeof messageForBrowser[i - 1] !== 'string') {
return indent(segment, false);
}
return indent(segment);
}),
);
} else {
failureMessage.push(
indent(error instanceof Error ? error.message : String(error)),
);
}
await ctx.page.evaluate((...colorErr) => {
console.log(...colorErr);
}, ...(ansiColorsLog(...failureMessage) as any));
}
await cleanup(true);
throw error;
}
await cleanup(false);
};
};
withBrowser.headed = (...args: any[]) => {
const testFn: TestFn = args.length === 1 ? args[0] : args[1];
const options: WithBrowserOpts = args.length === 1 ? {} : args[0];
return withBrowser({ ...options, headless: false }, testFn);
};
const getTestName = () => {
try {
return expect.getState().currentTestName;
} catch {
return null;
}
};
const indent = (input: string, indentFirstLine = true) =>
input
.split('\n')
.map((line, i) => {
if (!indentFirstLine && i === 0) return line;
// If there is an escape code at the beginning of the line
// put the tab after the escape code
// the reason for this is to prevent the indentation from getting messed up from wrapping
// you can see this if you squish the devtools window
const match = ansiRegex.exec(line);
if (!match || match.index !== 0) return ` ${line}`;
const insertPoint = match[0].length;
return `${line.slice(0, insertPoint)} ${line.slice(insertPoint)}`;
})
.join('\n');
const createTab = async ({
testPath,
options: {
headless = defaultOptions.headless ?? true,
device = defaultOptions.device,
moduleServer: moduleServerOpts = {},
},
}: {
testPath: string;
options: WithBrowserOpts;
}): Promise<
PleasantestContext & {
cleanupServer: () => Promise<void>;
asyncHookTracker: AsyncHookTracker;
}
> => {
const asyncHookTracker = createAsyncHookTracker();
const browser = await connectToBrowser('chromium', headless);
const browserContext = await browser.createIncognitoBrowserContext();
const page = await browserContext.newPage();
const {
requestCache,
port,
close: closeServer,
} = await createModuleServer({
...defaultOptions.moduleServer,
...moduleServerOpts,
});
if (device) {
if (!headless) {
const session = await page.target().createCDPSession();
const { windowId } = (await session.send(
'Browser.getWindowForTarget',
)) as any;
await session.send('Browser.setWindowBounds', {
windowId,
bounds: {
// Allow space for devtools
// start-disowned-browser.ts sets the devtools preferences with default width
width: device.viewport.width + 450,
height: device.viewport.height + 79, // Allow space for toolbar
},
});
await session.detach();
}
await page.emulate(device);
}
page.on('console', (message) => {
const text = message.text();
// This is naive, there is probably something better to check
// If the text includes %c, then it probably came from the jest output being forwarded into the browser
// So we don't need to print it _again_ in node, since it already came from node
if (text.includes('%c')) return;
// This is intended so that transpilation errors from the module server,
// which will get a nice code frame in node,
// do not also log "Failed to load resource: the server responded with a status of 500"
if (
/Failed to load resource: the server responded with a status of 500/.test(
text,
) &&
message.location().url?.includes(`http://localhost:${port}`)
)
return;
const type = message.type();
// Create a new console instance instead of using the global one
// Because the global one is overridden by Jest, and it adds a misleading second stack trace and code frame below it
const console = new Console(process.stdout, process.stderr);
if (type === 'error') {
const error = new Error(text);
const location = message.location();
error.stack = `Error: ${text}
at ${location.url}`;
console.error('[browser]', error);
} else {
console.log('[browser]', text);
}
});
await page.goto(`http://localhost:${port}`);
// eslint-disable-next-line @cloudfour/typescript-eslint/ban-types
const functionArgs: Function[] = [];
const runJS: PleasantestUtils['runJS'] = (code, args) =>
asyncHookTracker.addHook(async () => {
await page
.exposeFunction('pleasantest_callFunction', (id, args) =>
functionArgs[id](...args),
)
.catch((error) => {
if (!error.message.includes('already exists')) throw error;
});
// For some reason encodeURIComponent doesn't encode '
const encodedCode = encodeURIComponent(code).replace(/'/g, '%27');
const buildStatus = createBuildStatusTracker();
const argsWithFuncsAsObjs = args?.map((arg) => {
if (typeof arg === 'function') {
const id = functionArgs.push(arg) - 1;
return { isFunction: true, id };
}
return arg;
});
// This uses the testPath as the url so that if there are relative imports
// in the inline code, the relative imports are resolved relative to the test file
const url = `http://localhost:${port}/${testPath}?inline-code=${encodedCode}&build-id=${buildStatus.buildId}`;
const res = await page.evaluate(
new Function(
'...args',
`return import(${JSON.stringify(url)})
.then(async m => {
const argsWithFuncs = args.map(arg => {
if (typeof arg === 'object' && arg && arg.isFunction) {
return async (...args) => {
return await window.pleasantest_callFunction(arg.id, args);
}
}
return arg
})
if (m.default) await m.default(...argsWithFuncs)
})
.catch(e =>
e instanceof Error
? { message: e.message, stack: e.stack }
: e)`,
) as () => any,
...(Array.isArray(argsWithFuncsAsObjs)
? (argsWithFuncsAsObjs as any)
: []),
);
const errorsFromBuild = buildStatus.complete();
// It only throws the first one but that is probably OK
if (errorsFromBuild) throw errorsFromBuild[0];
await sourceMapErrorFromBrowser(res, requestCache, port, runJS);
}, runJS);
const injectHTML: PleasantestUtils['injectHTML'] = (html) =>
asyncHookTracker.addHook(
() =>
page.evaluate((html) => {
document.body.innerHTML = html;
}, html),
injectHTML,
);
const injectCSS: PleasantestUtils['injectCSS'] = (css) =>
asyncHookTracker.addHook(
() =>
page.evaluate((css) => {
const styleTag = document.createElement('style');
styleTag.innerHTML = css;
document.head.append(styleTag);
}, css),
injectCSS,
);
const loadCSS: PleasantestUtils['loadCSS'] = (cssPath) =>
asyncHookTracker.addHook(async () => {
const fullPath = isAbsolute(cssPath)
? relative(process.cwd(), cssPath)
: join(dirname(testPath), cssPath);
await page.evaluate(
`import(${JSON.stringify(
`http://localhost:${port}/${fullPath}?import`,
)})`,
);
}, loadCSS);
const loadJS: PleasantestUtils['loadJS'] = (jsPath) =>
asyncHookTracker.addHook(async () => {
const fullPath = jsPath.startsWith('.')
? join(dirname(testPath), jsPath)
: jsPath;
const buildStatus = createBuildStatusTracker();
const url = `http://localhost:${port}/${fullPath}?build-id=${buildStatus.buildId}`;
const res = await page.evaluate(
`import(${JSON.stringify(url)})
.then(mod => {})
.catch(e => e instanceof Error
? { message: e.message, stack: e.stack }
: e)`,
);
const errorsFromBuild = buildStatus.complete();
// It only throws the first one but that is probably OK
if (errorsFromBuild) throw errorsFromBuild[0];
await sourceMapErrorFromBrowser(res, requestCache, port, loadJS);
}, loadJS);
const utils: PleasantestUtils = {
runJS,
injectCSS,
injectHTML,
loadCSS,
loadJS,
};
const screen = getQueriesForElement(page, asyncHookTracker);
// The | null is so you can pass directly the result of page.$() which returns null if not found
const within: PleasantestContext['within'] = (
element: puppeteer.ElementHandle | null,
) => {
assertElementHandle(element, within);
return getQueriesForElement(page, asyncHookTracker, element);
};
const waitFor: PleasantestContext['waitFor'] = (
cb,
opts: WaitForOptions = {},
) => innerWaitFor(page, asyncHookTracker, cb, opts, waitFor);
return {
screen,
utils,
page,
within,
waitFor,
user: await pleasantestUser(page, asyncHookTracker),
asyncHookTracker,
cleanupServer: () => closeServer(),
};
};
let defaultOptions: WithBrowserOpts = {};
export const configureDefaults = (options: WithBrowserOpts) => {
defaultOptions = options;
};
export const devices = puppeteer.devices;
afterAll(async () => {
await cleanupClientRuntimeServer();
});
export type { WaitForOptions };
export { getAccessibilityTree } from './accessibility'; | the_stack |
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {
HttpClientTestingModule,
HttpTestingController,
} from '@angular/common/http/testing';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { CardType, Cart, PaymentDetails } from '@spartacus/cart/base/root';
import {
PAYMENT_CARD_TYPE_NORMALIZER,
PAYMENT_DETAILS_SERIALIZER,
} from '@spartacus/checkout/base/core';
import {
ConverterService,
HttpErrorModel,
normalizeHttpError,
Occ,
OccConfig,
OccEndpoints,
PAYMENT_DETAILS_NORMALIZER,
} from '@spartacus/core';
import { defer, of, throwError } from 'rxjs';
import { take } from 'rxjs/operators';
import { OccCheckoutPaymentAdapter } from './occ-checkout-payment.adapter';
const userId = '123';
const cartId = '456';
const cartData: Partial<Cart> = {
store: 'electronics',
guid: '1212121',
};
const mockPaymentDetails: PaymentDetails = {
accountHolderName: 'mockPaymentDetails',
cardType: {
code: 'aaa',
},
billingAddress: {
country: {},
region: {},
},
};
const MockOccModuleConfig: OccConfig = {
backend: {
occ: {
baseUrl: '',
prefix: '',
endpoints: {
setCartPaymentDetails: 'users/${userId}/carts/${cartId}/paymentdetails',
paymentProviderSubInfo:
'users/${userId}/carts/${cartId}/payment/sop/request?responseUrl=sampleUrl',
createPaymentDetails:
'users/${userId}/carts/${cartId}/payment/sop/response',
cardTypes: 'cardtypes',
} as OccEndpoints,
},
},
context: {
baseSite: [''],
},
};
const paymentProviderInfo = {
mappingLabels: {
entry: [
{
key: 'hybris_sop_amount',
value: 'amount',
},
{
key: 'hybris_sop_currency',
value: '',
},
{
key: 'hybris_billTo_country',
value: 'billTo_country',
},
{
key: 'hybris_card_type',
value: 'card_type',
},
{
key: 'hybris_card_expiration_year',
value: 'card_expirationYear',
},
{
key: 'hybris_sop_reason_code',
value: 'reason_code',
},
{
key: 'hybris_combined_expiry_date',
value: 'false',
},
{
key: 'hybris_sop_decision',
value: 'decision',
},
{
key: 'hybris_card_expiry_date',
value: 'card_expirationDate',
},
{
key: 'hybris_card_expiration_month',
value: 'card_expirationMonth',
},
{
key: 'hybris_billTo_street1',
value: 'billTo_street1',
},
{
key: 'hybris_sop_card_number',
value: 'card_accountNumber',
},
{
key: 'hybris_separator_expiry_date',
value: '',
},
{
key: 'hybris_account_holder_name',
value: 'mockup_account_holder',
},
{
key: 'hybris_sop_uses_public_signature',
value: 'false',
},
{
key: 'hybris_card_number',
value: 'card_accountNumber',
},
{
key: 'hybris_card_cvn',
value: 'card_cvNumber',
},
{
key: 'hybris_billTo_lastname',
value: 'billTo_lastName',
},
{
key: 'hybris_billTo_city',
value: 'billTo_city',
},
{
key: 'hybris_billTo_firstname',
value: 'billTo_firstName',
},
{
key: 'hybris_billTo_region',
value: 'billTo_state',
},
{
key: 'hybris_billTo_postalcode',
value: 'billTo_postalCode',
},
],
},
parameters: {
entry: [],
},
postUrl: 'https://testurl',
};
const html =
'<form id="silentOrderPostForm" name="silentOrderPostForm" action="javascript:false;" method="post">' +
'<div id="postFormItems">' +
'<dl>' +
'<input type="hidden" id="billTo_city" name="billTo_city" value="MainCity" />' +
'<input type="hidden" id="amount" name="amount" value="0" />' +
'<input type="hidden" id="decision_publicSignature" name="decision_publicSignature" value="mEhlMRLCsuPimhp50ElrY94zFyc=" />' +
'<input type="hidden" id="decision" name="decision" value="ACCEPT" />' +
'<input type="hidden" id="billTo_country" name="billTo_country" value="US" />' +
'<input type="hidden" id="billTo_state" name="billTo_state" value="CA" />' +
'<input type="hidden" id="billTo_lastName" name="billTo_lastName" value="test" />' +
'<input type="hidden" id="ccAuthReply_cvCode" name="ccAuthReply_cvCode" value="M" />' +
'<input type="hidden" id="billTo_postalCode" name="billTo_postalCode" value="12345" />' +
'<input type="hidden" id="billTo_street1" name="billTo_street1" value="999 de Maisonneuve" />' +
'<input type="hidden" id="billTo_firstName" name="billTo_firstName" value="test" />' +
'<input type="hidden" id="card_cardType" name="card_cardType" value="visa" />' +
'<input type="hidden" id="card_expirationMonth" name="card_expirationMonth" value="12" />' +
'<input type="hidden" id="card_expirationYear" name="card_expirationYear" value="2020" />' +
'<input type="hidden" id="reasonCode" name="reasonCode" value="100" />' +
'<input type="hidden" id="card_accountNumber" name="card_accountNumber" value="************1111" />' +
'</dl>' +
'</div>' +
'</form>';
const mockJaloError = new HttpErrorResponse({
error: {
errors: [
{
message: 'The application has encountered an error',
type: 'JaloObjectNoLongerValidError',
},
],
},
});
const mockNormalizedJaloError = normalizeHttpError(mockJaloError);
describe('OccCheckoutPaymentAdapter', () => {
let service: OccCheckoutPaymentAdapter;
let httpClient: HttpClient;
let httpMock: HttpTestingController;
let converter: ConverterService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
OccCheckoutPaymentAdapter,
{ provide: OccConfig, useValue: MockOccModuleConfig },
],
});
service = TestBed.inject(OccCheckoutPaymentAdapter);
httpClient = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
converter = TestBed.inject(ConverterService);
spyOn(converter, 'pipeable').and.callThrough();
spyOn(converter, 'pipeableMany').and.callThrough();
spyOn(converter, 'convert').and.callThrough();
});
afterEach(() => {
httpMock.verify();
});
describe(`setPaymentDetails`, () => {
const paymentDetailsId = '999';
it(`should set payment details for given user id, cart id and payment details id`, (done) => {
service
.setPaymentDetails(userId, cartId, paymentDetailsId)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(cartData);
done();
});
const mockReq = httpMock.expectOne((req) => {
return (
req.method === 'PUT' &&
req.url ===
`users/${userId}/carts/${cartId}/paymentdetails?paymentDetailsId=${paymentDetailsId}`
);
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(cartData);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'put').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service
.setPaymentDetails(userId, cartId, paymentDetailsId)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'put').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(cartData);
}
return throwError(mockJaloError);
})
);
let result: unknown;
const subscription = service
.setPaymentDetails(userId, cartId, paymentDetailsId)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(cartData);
subscription.unsubscribe();
}));
});
});
describe(`createPaymentDetails`, () => {
it(`should create payment`, (done) => {
service
.createPaymentDetails(userId, cartId, mockPaymentDetails)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(mockPaymentDetails);
done();
});
httpMock
.expectOne((req) => {
return (
req.method === 'GET' &&
req.url ===
`users/${userId}/carts/${cartId}/payment/sop/request?responseUrl=sampleUrl`
);
})
.flush(paymentProviderInfo);
httpMock
.expectOne((req) => {
return (
req.method === 'POST' && req.url === paymentProviderInfo.postUrl
);
})
.flush(html);
httpMock
.expectOne((req) => {
return (
req.method === 'POST' &&
req.url === `users/${userId}/carts/${cartId}/payment/sop/response`
);
})
.flush(mockPaymentDetails);
expect(converter.pipeable).toHaveBeenCalledWith(
PAYMENT_DETAILS_NORMALIZER
);
expect(converter.convert).toHaveBeenCalledWith(
mockPaymentDetails,
PAYMENT_DETAILS_SERIALIZER
);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'get').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service
.createPaymentDetails(userId, cartId, mockPaymentDetails)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'get').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(paymentProviderInfo);
}
return throwError(mockJaloError);
})
);
spyOn(httpClient, 'post').and.returnValues(
of(html),
of(mockPaymentDetails)
);
let result: PaymentDetails | undefined;
const subscription = service
.createPaymentDetails(userId, cartId, mockPaymentDetails)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(mockPaymentDetails);
subscription.unsubscribe();
}));
});
});
describe(`getProviderSubInfo`, () => {
it(`should get payment provider subscription info for given user id and cart id`, (done) => {
// testing protected method
service['getProviderSubInfo'](userId, cartId)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(cartData);
done();
});
const mockReq = httpMock.expectOne((req) => {
return (
req.method === 'GET' &&
req.url ===
`users/${userId}/carts/${cartId}/payment/sop/request?responseUrl=sampleUrl`
);
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(cartData);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'get').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service['getProviderSubInfo'](userId, cartId)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'get').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(cartData);
}
return throwError(mockJaloError);
})
);
let result: unknown;
const subscription = service['getProviderSubInfo'](userId, cartId)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(cartData);
subscription.unsubscribe();
}));
});
});
describe(`createSubWithProvider with single param`, () => {
const params = {
param: 'mockParam',
};
const mockUrl = 'mockUrl';
const mockPaymentProvider = 'mockPaymentProvider';
it(`should create subscription with payment provider for given url and parameters`, (done) => {
// testing protected method
service['createSubWithProvider'](mockUrl, params)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(mockPaymentProvider);
done();
});
const mockReq = httpMock.expectOne((req) => {
return req.method === 'POST' && req.url === mockUrl;
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.headers.get('Content-Type')).toEqual(
'application/x-www-form-urlencoded'
);
expect(mockReq.request.headers.get('Accept')).toEqual('text/html');
expect(mockReq.request.responseType).toEqual('text');
expect(mockReq.request.body.get('param')).toEqual('mockParam');
mockReq.flush(mockPaymentProvider);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'post').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service['createSubWithProvider'](mockUrl, params)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'post').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(mockPaymentProvider);
}
return throwError(mockJaloError);
})
);
let result: unknown;
const subscription = service['createSubWithProvider'](mockUrl, params)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(mockPaymentProvider);
subscription.unsubscribe();
}));
});
});
describe(`createSubWithProvider with multiple param`, () => {
const params = {
param1: 'mockParam1',
param2: 'mockParam2',
};
const mockUrl = 'mockUrl';
const mockPaymentProvider = 'mockPaymentProvider';
it(`should create subscription with payment provider for given url and parameters`, (done) => {
// testing protected method
service['createSubWithProvider'](mockUrl, params)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(mockPaymentProvider);
done();
});
const mockReq = httpMock.expectOne((req) => {
return req.method === 'POST' && req.url === mockUrl;
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.headers.get('Content-Type')).toEqual(
'application/x-www-form-urlencoded'
);
expect(mockReq.request.headers.get('Accept')).toEqual('text/html');
expect(mockReq.request.body.get('param1')).toEqual('mockParam1');
expect(mockReq.request.body.get('param2')).toEqual('mockParam2');
expect(mockReq.request.responseType).toEqual('text');
mockReq.flush(mockPaymentProvider);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'post').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service['createSubWithProvider'](mockUrl, params)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'post').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(mockPaymentProvider);
}
return throwError(mockJaloError);
})
);
let result: unknown;
const subscription = service['createSubWithProvider'](mockUrl, params)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(mockPaymentProvider);
subscription.unsubscribe();
}));
});
});
describe(`createDetailsWithParameter with single param`, () => {
const params = {
param: 'mockParam',
};
it(`should create payment details for given user id, cart id and parameters`, (done) => {
// testing protected method
service['createDetailsWithParameters'](userId, cartId, params)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(mockPaymentDetails);
done();
});
const mockReq = httpMock.expectOne((req) => {
return (
req.method === 'POST' &&
req.url === `users/${userId}/carts/${cartId}/payment/sop/response`
);
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.headers.get('Content-Type')).toEqual(
'application/x-www-form-urlencoded'
);
expect(mockReq.request.body.get('param')).toEqual('mockParam');
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(mockPaymentDetails);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'post').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service['createDetailsWithParameters'](
userId,
cartId,
params
)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'post').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(mockPaymentDetails);
}
return throwError(mockJaloError);
})
);
let result: unknown;
const subscription = service['createDetailsWithParameters'](
userId,
cartId,
params
)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(mockPaymentDetails);
subscription.unsubscribe();
}));
});
});
describe(`createDetailsWithParameter with multiple param`, () => {
const params = {
param1: 'mockParam1',
param2: 'mockParam2',
};
it(`should create payment details for given user id, cart id and parameters`, (done) => {
// testing protected method
service['createDetailsWithParameters'](userId, cartId, params)
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(mockPaymentDetails);
done();
});
const mockReq = httpMock.expectOne((req) => {
return (
req.method === 'POST' &&
req.url === `users/${userId}/carts/${cartId}/payment/sop/response`
);
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.headers.get('Content-Type')).toEqual(
'application/x-www-form-urlencoded'
);
expect(mockReq.request.responseType).toEqual('json');
expect(mockReq.request.body.get('param1')).toEqual('mockParam1');
expect(mockReq.request.body.get('param2')).toEqual('mockParam2');
mockReq.flush(mockPaymentDetails);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'post').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service['createDetailsWithParameters'](
userId,
cartId,
params
)
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'post').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(mockPaymentDetails);
}
return throwError(mockJaloError);
})
);
let result: unknown;
const subscription = service['createDetailsWithParameters'](
userId,
cartId,
params
)
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(mockPaymentDetails);
subscription.unsubscribe();
}));
});
});
describe(`getPaymentCardTypes`, () => {
const cardTypesList: Occ.CardTypeList = {
cardTypes: [
{
code: 'amex',
name: 'American Express',
},
{
code: 'maestro',
name: 'Maestro',
},
],
};
it(`should return cardTypes`, (done) => {
service
.getPaymentCardTypes()
.pipe(take(1))
.subscribe((result) => {
expect(result).toEqual(cardTypesList.cardTypes);
done();
});
const mockReq = httpMock.expectOne((req) => {
return req.method === 'GET' && req.url === 'cardtypes';
});
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(cardTypesList);
});
it(`should use converter`, (done) => {
service
.getPaymentCardTypes()
.pipe(take(1))
.subscribe(() => {
done();
});
httpMock.expectOne('cardtypes').flush({});
expect(converter.pipeableMany).toHaveBeenCalledWith(
PAYMENT_CARD_TYPE_NORMALIZER
);
});
describe(`back-off`, () => {
it(`should unsuccessfully backOff on Jalo error`, fakeAsync(() => {
spyOn(httpClient, 'get').and.returnValue(throwError(mockJaloError));
let result: HttpErrorModel | undefined;
const subscription = service
.getPaymentCardTypes()
.pipe(take(1))
.subscribe({ error: (err) => (result = err) });
tick(4200);
expect(result).toEqual(mockNormalizedJaloError);
subscription.unsubscribe();
}));
it(`should successfully backOff on Jalo error and recover after the 2nd retry`, fakeAsync(() => {
let calledTimes = -1;
spyOn(httpClient, 'get').and.returnValue(
defer(() => {
calledTimes++;
if (calledTimes === 3) {
return of(cardTypesList);
}
return throwError(mockJaloError);
})
);
let result: CardType[] | undefined;
const subscription = service
.getPaymentCardTypes()
.pipe(take(1))
.subscribe((res) => {
result = res;
});
// 1*1*300 = 300
tick(300);
expect(result).toEqual(undefined);
// 2*2*300 = 1200
tick(1200);
expect(result).toEqual(undefined);
// 3*3*300 = 2700
tick(2700);
expect(result).toEqual(cardTypesList.cardTypes);
subscription.unsubscribe();
}));
});
});
describe(`getParamsForPaymentProvider `, () => {
const parametersSentByBackend = [
{ key: 'billTo_country', value: 'CA' },
{ key: 'billTo_state', value: 'QC' },
];
const labelsMap = {
hybris_billTo_country: 'billTo_country',
hybris_billTo_region: 'billTo_state',
};
it(`should support billing address in a different country than the default/shipping address.`, () => {
const paymentDetails: PaymentDetails = {
cardType: { code: 'visa' },
billingAddress: {
country: { isocode: 'US' },
region: { isocodeShort: 'RG' },
},
};
const params = service['getParamsForPaymentProvider'](
paymentDetails,
parametersSentByBackend,
labelsMap
);
expect(params['billTo_country']).toEqual(
paymentDetails.billingAddress?.country?.isocode
);
expect(params['billTo_state']).toEqual(
paymentDetails.billingAddress?.region?.isocodeShort
);
});
it(`should support billing address different than shipping when billing country has no region.`, () => {
const paymentDetails: PaymentDetails = {
cardType: { code: 'visa' },
billingAddress: {
country: { isocode: 'PL' },
},
};
const params = service['getParamsForPaymentProvider'](
paymentDetails,
parametersSentByBackend,
labelsMap
);
expect(params['billTo_country']).toEqual(
paymentDetails.billingAddress?.country?.isocode
);
expect(params['billTo_state']).toEqual('');
});
});
}); | the_stack |
import * as vscode from './mocks/vscode';
jest.mock('vscode', () => vscode, { virtual: true });
import { getConfig } from '../src/config';
import { CommitDetailsViewLocation, CommitOrdering, DateFormatType, DateType, FileViewType, GitResetMode, GraphStyle, GraphUncommittedChangesStyle, RepoDropdownOrder, SquashMessageFormat, TabIconColourTheme, TagType } from '../src/types';
import { expectRenamedExtensionSettingToHaveBeenCalled } from './helpers/expectations';
const workspaceConfiguration = vscode.mocks.workspaceConfiguration;
type Config = ReturnType<typeof getConfig>;
describe('Config', () => {
let config: Config;
beforeEach(() => {
config = getConfig();
});
it('Should construct a Config instance', () => {
// Run
getConfig();
// Assert
expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith('git-graph', undefined);
});
it('Should construct a Config instance (for a specific repository)', () => {
// Run
getConfig('/path/to/repo');
// Assert
expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith('git-graph', {
scheme: 'file',
authority: '',
path: '/path/to/repo',
query: '',
fragment: ''
});
});
describe('commitDetailsView', () => {
describe('autoCenter', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.autoCenter', true);
// Run
const value = config.commitDetailsView.autoCenter;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.autoCenter', 'autoCenterCommitDetailsView');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.autoCenter', false);
// Run
const value = config.commitDetailsView.autoCenter;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.autoCenter', 'autoCenterCommitDetailsView');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.autoCenter', 5);
// Run
const value = config.commitDetailsView.autoCenter;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.autoCenter', 'autoCenterCommitDetailsView');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.autoCenter', 0);
// Run
const value = config.commitDetailsView.autoCenter;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.autoCenter', 'autoCenterCommitDetailsView');
expect(value).toBe(false);
});
it('Should return the default value (TRUE) when the configuration value is unknown', () => {
// Run
const value = config.commitDetailsView.autoCenter;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.autoCenter', 'autoCenterCommitDetailsView');
expect(value).toBe(true);
});
});
describe('fileTreeCompactFolders', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.fileTree.compactFolders', true);
// Run
const value = config.commitDetailsView.fileTreeCompactFolders;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.fileTree.compactFolders', 'commitDetailsViewFileTreeCompactFolders');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.fileTree.compactFolders', false);
// Run
const value = config.commitDetailsView.fileTreeCompactFolders;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.fileTree.compactFolders', 'commitDetailsViewFileTreeCompactFolders');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.fileTree.compactFolders', 5);
// Run
const value = config.commitDetailsView.fileTreeCompactFolders;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.fileTree.compactFolders', 'commitDetailsViewFileTreeCompactFolders');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.fileTree.compactFolders', 0);
// Run
const value = config.commitDetailsView.fileTreeCompactFolders;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.fileTree.compactFolders', 'commitDetailsViewFileTreeCompactFolders');
expect(value).toBe(false);
});
it('Should return the default value (TRUE) when the configuration value is unknown', () => {
// Run
const value = config.commitDetailsView.fileTreeCompactFolders;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.fileTree.compactFolders', 'commitDetailsViewFileTreeCompactFolders');
expect(value).toBe(true);
});
});
describe('fileViewType', () => {
it('Should return FileViewType.Tree when the configuration value is "File Tree"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.type', 'File Tree');
// Run
const value = config.commitDetailsView.fileViewType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.type', 'defaultFileViewType');
expect(value).toBe(FileViewType.Tree);
});
it('Should return FileViewType.List when the configuration value is "File List"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.type', 'File List');
// Run
const value = config.commitDetailsView.fileViewType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.type', 'defaultFileViewType');
expect(value).toBe(FileViewType.List);
});
it('Should return the default value (FileViewType.Tree) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.fileView.type', 'invalid');
// Run
const value = config.commitDetailsView.fileViewType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.type', 'defaultFileViewType');
expect(value).toBe(FileViewType.Tree);
});
it('Should return the default value (FileViewType.Tree) when the configuration value is unknown', () => {
// Run
const value = config.commitDetailsView.fileViewType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.fileView.type', 'defaultFileViewType');
expect(value).toBe(FileViewType.Tree);
});
});
describe('location', () => {
it('Should return CommitDetailsViewLocation.Inline when the configuration value is "Inline"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.location', 'Inline');
// Run
const value = config.commitDetailsView.location;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.location', 'commitDetailsViewLocation');
expect(value).toBe(CommitDetailsViewLocation.Inline);
});
it('Should return CommitDetailsViewLocation.DockedToBottom when the configuration value is "Docked to Bottom"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.location', 'Docked to Bottom');
// Run
const value = config.commitDetailsView.location;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.location', 'commitDetailsViewLocation');
expect(value).toBe(CommitDetailsViewLocation.DockedToBottom);
});
it('Should return the default value (CommitDetailsViewLocation.Inline) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('commitDetailsView.location', 'invalid');
// Run
const value = config.commitDetailsView.location;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.location', 'commitDetailsViewLocation');
expect(value).toBe(CommitDetailsViewLocation.Inline);
});
it('Should return the default value (CommitDetailsViewLocation.Inline) when the configuration value is unknown', () => {
// Run
const value = config.commitDetailsView.location;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('commitDetailsView.location', 'commitDetailsViewLocation');
expect(value).toBe(CommitDetailsViewLocation.Inline);
});
});
});
describe('contextMenuActionsVisibility', () => {
it('Should return the default value (all items enabled) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('contextMenuActionsVisibility', 1);
// Run
const value = config.contextMenuActionsVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('contextMenuActionsVisibility', {});
expect(value).toStrictEqual({
branch: {
checkout: true,
rename: true,
delete: true,
merge: true,
rebase: true,
push: true,
viewIssue: true,
createPullRequest: true,
createArchive: true,
selectInBranchesDropdown: true,
unselectInBranchesDropdown: true,
copyName: true
},
commit: {
addTag: true,
createBranch: true,
checkout: true,
cherrypick: true,
revert: true,
drop: true,
merge: true,
rebase: true,
reset: true,
copyHash: true,
copySubject: true
},
commitDetailsViewFile: {
viewDiff: true,
viewFileAtThisRevision: true,
viewDiffWithWorkingFile: true,
openFile: true,
markAsReviewed: true,
markAsNotReviewed: true,
resetFileToThisRevision: true,
copyAbsoluteFilePath: true,
copyRelativeFilePath: true
},
remoteBranch: {
checkout: true,
delete: true,
fetch: true,
merge: true,
pull: true,
viewIssue: true,
createPullRequest: true,
createArchive: true,
selectInBranchesDropdown: true,
unselectInBranchesDropdown: true,
copyName: true
},
stash: {
apply: true,
createBranch: true,
pop: true,
drop: true,
copyName: true,
copyHash: true
},
tag: {
viewDetails: true,
delete: true,
push: true,
createArchive: true,
copyName: true
},
uncommittedChanges: {
stash: true,
reset: true,
clean: true,
openSourceControlView: true
}
});
});
it('Should return the default value (all items enabled) when the configuration value is not set', () => {
// Run
const value = config.contextMenuActionsVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('contextMenuActionsVisibility', {});
expect(value).toStrictEqual({
branch: {
checkout: true,
rename: true,
delete: true,
merge: true,
rebase: true,
push: true,
viewIssue: true,
createPullRequest: true,
createArchive: true,
selectInBranchesDropdown: true,
unselectInBranchesDropdown: true,
copyName: true
},
commit: {
addTag: true,
createBranch: true,
checkout: true,
cherrypick: true,
revert: true,
drop: true,
merge: true,
rebase: true,
reset: true,
copyHash: true,
copySubject: true
},
commitDetailsViewFile: {
viewDiff: true,
viewFileAtThisRevision: true,
viewDiffWithWorkingFile: true,
openFile: true,
markAsReviewed: true,
markAsNotReviewed: true,
resetFileToThisRevision: true,
copyAbsoluteFilePath: true,
copyRelativeFilePath: true
},
remoteBranch: {
checkout: true,
delete: true,
fetch: true,
merge: true,
pull: true,
viewIssue: true,
createPullRequest: true,
createArchive: true,
selectInBranchesDropdown: true,
unselectInBranchesDropdown: true,
copyName: true
},
stash: {
apply: true,
createBranch: true,
pop: true,
drop: true,
copyName: true,
copyHash: true
},
tag: {
viewDetails: true,
delete: true,
push: true,
createArchive: true,
copyName: true
},
uncommittedChanges: {
stash: true,
reset: true,
clean: true,
openSourceControlView: true
}
});
});
it('Should only affect the provided configuration overrides', () => {
// Setup
vscode.mockExtensionSettingReturnValue('contextMenuActionsVisibility', {
branch: {
rename: false
},
commit: {
checkout: false
},
commitDetailsViewFile: {
resetFileToThisRevision: false
},
remoteBranch: {
delete: true,
fetch: false,
pull: true
}
});
// Run
const value = config.contextMenuActionsVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('contextMenuActionsVisibility', {});
expect(value).toStrictEqual({
branch: {
checkout: true,
rename: false,
delete: true,
merge: true,
rebase: true,
push: true,
viewIssue: true,
createPullRequest: true,
createArchive: true,
selectInBranchesDropdown: true,
unselectInBranchesDropdown: true,
copyName: true
},
commit: {
addTag: true,
createBranch: true,
checkout: false,
cherrypick: true,
revert: true,
drop: true,
merge: true,
rebase: true,
reset: true,
copyHash: true,
copySubject: true
},
commitDetailsViewFile: {
viewDiff: true,
viewFileAtThisRevision: true,
viewDiffWithWorkingFile: true,
openFile: true,
markAsReviewed: true,
markAsNotReviewed: true,
resetFileToThisRevision: false,
copyAbsoluteFilePath: true,
copyRelativeFilePath: true
},
remoteBranch: {
checkout: true,
delete: true,
fetch: false,
merge: true,
pull: true,
viewIssue: true,
createPullRequest: true,
createArchive: true,
selectInBranchesDropdown: true,
unselectInBranchesDropdown: true,
copyName: true
},
stash: {
apply: true,
createBranch: true,
pop: true,
drop: true,
copyName: true,
copyHash: true
},
tag: {
viewDetails: true,
delete: true,
push: true,
createArchive: true,
copyName: true
},
uncommittedChanges: {
stash: true,
reset: true,
clean: true,
openSourceControlView: true
}
});
});
});
describe('customBranchGlobPatterns', () => {
it('Should return a filtered array of glob patterns based on the configuration value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('customBranchGlobPatterns', [
{ name: 'Name 1', glob: 'glob1' },
{ name: 'Name 2', glob: 'glob2' },
{ name: 'Name 3' },
{ name: 'Name 4', glob: 'glob4' }
]);
// Run
const value = config.customBranchGlobPatterns;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customBranchGlobPatterns', []);
expect(value).toHaveLength(3);
expect(value[0]).toStrictEqual({ name: 'Name 1', glob: '--glob=glob1' });
expect(value[1]).toStrictEqual({ name: 'Name 2', glob: '--glob=glob2' });
expect(value[2]).toStrictEqual({ name: 'Name 4', glob: '--glob=glob4' });
});
it('Should return the default value ([]) when the configuration value is not set', () => {
// Run
const value = config.customBranchGlobPatterns;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customBranchGlobPatterns', []);
expect(value).toHaveLength(0);
});
});
describe('customEmojiShortcodeMappings', () => {
it('Should return a filtered array of emoji shortcode mappings based on the configuration value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('customEmojiShortcodeMappings', [
{ shortcode: 'dog', emoji: '🍎' },
{ shortcode: 'cat', emoji: '🎨' },
{ shortcode: 'bird' },
{ shortcode: 'fish', emoji: '🐛' }
]);
// Run
const value = config.customEmojiShortcodeMappings;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customEmojiShortcodeMappings', []);
expect(value).toStrictEqual([
{ shortcode: 'dog', emoji: '🍎' },
{ shortcode: 'cat', emoji: '🎨' },
{ shortcode: 'fish', emoji: '🐛' }
]);
});
it('Should return the default value ([]) when the configuration value is not set', () => {
// Run
const value = config.customEmojiShortcodeMappings;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customEmojiShortcodeMappings', []);
expect(value).toHaveLength(0);
});
});
describe('customPullRequestProviders', () => {
it('Should return a filtered array of pull request providers based on the configuration value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('customPullRequestProviders', [
{ name: 'dog', templateUrl: '$1/$2' },
{ name: 'cat', templateUrl: '$1/$3' },
{ name: 'bird' },
{ name: 'fish', templateUrl: '$1/$4' },
{ templateUrl: '$1/$5' }
]);
// Run
const value = config.customPullRequestProviders;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customPullRequestProviders', []);
expect(value).toStrictEqual([
{ name: 'dog', templateUrl: '$1/$2' },
{ name: 'cat', templateUrl: '$1/$3' },
{ name: 'fish', templateUrl: '$1/$4' }
]);
});
it('Should return the default value ([]) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('customPullRequestProviders', 5);
// Run
const value = config.customPullRequestProviders;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customPullRequestProviders', []);
expect(value).toHaveLength(0);
});
it('Should return the default value ([]) when the configuration value is not set', () => {
// Run
const value = config.customPullRequestProviders;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('customPullRequestProviders', []);
expect(value).toHaveLength(0);
});
});
describe('dateFormat', () => {
it('Should successfully parse the configuration value "Date & Time"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.format', 'Date & Time');
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.DateAndTime, iso: false });
});
it('Should successfully parse the configuration value "Date Only"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.format', 'Date Only');
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.DateOnly, iso: false });
});
it('Should successfully parse the configuration value "ISO Date & Time"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.format', 'ISO Date & Time');
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.DateAndTime, iso: true });
});
it('Should successfully parse the configuration value "ISO Date Only"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.format', 'ISO Date Only');
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.DateOnly, iso: true });
});
it('Should successfully parse the configuration value "Relative"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.format', 'Relative');
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.Relative, iso: false });
});
it('Should return the default value when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.format', 'invalid');
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.DateAndTime, iso: false });
});
it('Should return the default value when the configuration value is unknown', () => {
// Run
const value = config.dateFormat;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.format', 'dateFormat');
expect(value).toStrictEqual({ type: DateFormatType.DateAndTime, iso: false });
});
});
describe('dateType', () => {
it('Should return DateType.Author when the configuration value is "Author Date"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.type', 'Author Date');
// Run
const value = config.dateType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.type', 'dateType');
expect(value).toBe(DateType.Author);
});
it('Should return DateType.Commit when the configuration value is "Commit Date"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.type', 'Commit Date');
// Run
const value = config.dateType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.type', 'dateType');
expect(value).toBe(DateType.Commit);
});
it('Should return the default value (DateType.Author) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('date.type', 'invalid');
// Run
const value = config.dateType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.type', 'dateType');
expect(value).toBe(DateType.Author);
});
it('Should return the default value (DateType.Author) when the configuration value is unknown', () => {
// Run
const value = config.dateType;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('date.type', 'dateType');
expect(value).toBe(DateType.Author);
});
});
describe('defaultColumnVisibility', () => {
it('Should successfully parse the configuration value (Date column disabled)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('defaultColumnVisibility', { Date: false, Author: true, Commit: true });
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: false, author: true, commit: true });
});
it('Should successfully parse the configuration value (Author column disabled)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('defaultColumnVisibility', { Date: true, Author: false, Commit: true });
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: true, author: false, commit: true });
});
it('Should successfully parse the configuration value (Commit column disabled)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('defaultColumnVisibility', { Date: true, Author: true, Commit: false });
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: true, author: true, commit: false });
});
it('Should return the default value when the configuration value is invalid (not an object)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('defaultColumnVisibility', 'invalid');
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: true, author: true, commit: true });
});
it('Should return the default value when the configuration value is invalid (NULL)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('defaultColumnVisibility', null);
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: true, author: true, commit: true });
});
it('Should return the default value when the configuration value is invalid (column value is not a boolean)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('defaultColumnVisibility', { Date: true, Author: true, Commit: 5 });
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: true, author: true, commit: true });
});
it('Should return the default value when the configuration value is not set', () => {
// Run
const value = config.defaultColumnVisibility;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('defaultColumnVisibility', {});
expect(value).toStrictEqual({ date: true, author: true, commit: true });
});
});
describe('dialogDefaults', () => {
it('Should return TRUE values for boolean-based configuration values when they are TRUE', () => {
// Setup
[
'dialog.addTag.pushToRemote',
'dialog.applyStash.reinstateIndex',
'dialog.cherryPick.noCommit',
'dialog.cherryPick.recordOrigin',
'dialog.createBranch.checkOut',
'dialog.deleteBranch.forceDelete',
'dialog.fetchIntoLocalBranch.forceFetch',
'dialog.fetchRemote.prune',
'dialog.fetchRemote.pruneTags',
'dialog.merge.noCommit',
'dialog.merge.noFastForward',
'dialog.merge.squashCommits',
'dialog.popStash.reinstateIndex',
'dialog.pullBranch.noFastForward',
'dialog.pullBranch.squashCommits',
'dialog.rebase.ignoreDate',
'dialog.rebase.launchInteractiveRebase',
'dialog.stashUncommittedChanges.includeUntracked'
].forEach((section) => vscode.mockExtensionSettingReturnValue(section, true));
// Run
const value = config.dialogDefaults;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.pushToRemote', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.type', 'Annotated');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.applyStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.recordOrigin', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.createBranch.checkOut', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.deleteBranch.forceDelete', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchIntoLocalBranch.forceFetch', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.prune', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.pruneTags', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.general.referenceInputSpaceSubstitution', 'None');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noFastForward', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.popStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.noFastForward', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.ignoreDate', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.launchInteractiveRebase', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetUncommittedChanges.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.stashUncommittedChanges.includeUntracked', true);
expect(value).toStrictEqual({
addTag: {
pushToRemote: true,
type: TagType.Annotated
},
applyStash: {
reinstateIndex: true
},
cherryPick: {
noCommit: true,
recordOrigin: true
},
createBranch: {
checkout: true
},
deleteBranch: {
forceDelete: true
},
fetchIntoLocalBranch: {
forceFetch: true
},
fetchRemote: {
prune: true,
pruneTags: true
},
general: {
referenceInputSpaceSubstitution: null
},
merge: {
noCommit: true,
noFastForward: true,
squash: true
},
popStash: {
reinstateIndex: true
},
pullBranch: {
noFastForward: true,
squash: true
},
rebase: {
ignoreDate: true,
interactive: true
},
resetCommit: {
mode: GitResetMode.Mixed
},
resetUncommitted: {
mode: GitResetMode.Mixed
},
stashUncommittedChanges: {
includeUntracked: true
}
});
});
it('Should return FALSE values for boolean-based configuration values when they are FALSE', () => {
// Setup
[
'dialog.addTag.pushToRemote',
'dialog.applyStash.reinstateIndex',
'dialog.cherryPick.noCommit',
'dialog.cherryPick.recordOrigin',
'dialog.createBranch.checkOut',
'dialog.deleteBranch.forceDelete',
'dialog.fetchIntoLocalBranch.forceFetch',
'dialog.fetchRemote.prune',
'dialog.fetchRemote.pruneTags',
'dialog.merge.noCommit',
'dialog.merge.noFastForward',
'dialog.merge.squashCommits',
'dialog.popStash.reinstateIndex',
'dialog.pullBranch.noFastForward',
'dialog.pullBranch.squashCommits',
'dialog.rebase.ignoreDate',
'dialog.rebase.launchInteractiveRebase',
'dialog.stashUncommittedChanges.includeUntracked'
].forEach((section) => vscode.mockExtensionSettingReturnValue(section, false));
// Run
const value = config.dialogDefaults;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.pushToRemote', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.type', 'Annotated');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.applyStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.recordOrigin', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.createBranch.checkOut', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.deleteBranch.forceDelete', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchIntoLocalBranch.forceFetch', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.prune', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.pruneTags', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.general.referenceInputSpaceSubstitution', 'None');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noFastForward', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.popStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.noFastForward', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.ignoreDate', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.launchInteractiveRebase', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetUncommittedChanges.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.stashUncommittedChanges.includeUntracked', true);
expect(value).toStrictEqual({
addTag: {
pushToRemote: false,
type: TagType.Annotated
},
applyStash: {
reinstateIndex: false
},
cherryPick: {
noCommit: false,
recordOrigin: false
},
createBranch: {
checkout: false
},
deleteBranch: {
forceDelete: false
},
fetchIntoLocalBranch: {
forceFetch: false
},
fetchRemote: {
prune: false,
pruneTags: false
},
general: {
referenceInputSpaceSubstitution: null
},
merge: {
noCommit: false,
noFastForward: false,
squash: false
},
popStash: {
reinstateIndex: false
},
pullBranch: {
noFastForward: false,
squash: false
},
rebase: {
ignoreDate: false,
interactive: false
},
resetCommit: {
mode: GitResetMode.Mixed
},
resetUncommitted: {
mode: GitResetMode.Mixed
},
stashUncommittedChanges: {
includeUntracked: false
}
});
});
it('Should return TRUE values for boolean-based configuration values when they are truthy', () => {
// Setup
[
'dialog.addTag.pushToRemote',
'dialog.applyStash.reinstateIndex',
'dialog.cherryPick.noCommit',
'dialog.cherryPick.recordOrigin',
'dialog.createBranch.checkOut',
'dialog.deleteBranch.forceDelete',
'dialog.fetchIntoLocalBranch.forceFetch',
'dialog.fetchRemote.prune',
'dialog.fetchRemote.pruneTags',
'dialog.merge.noCommit',
'dialog.merge.noFastForward',
'dialog.merge.squashCommits',
'dialog.popStash.reinstateIndex',
'dialog.pullBranch.noFastForward',
'dialog.pullBranch.squashCommits',
'dialog.rebase.ignoreDate',
'dialog.rebase.launchInteractiveRebase',
'dialog.stashUncommittedChanges.includeUntracked'
].forEach((section) => vscode.mockExtensionSettingReturnValue(section, 1));
// Run
const value = config.dialogDefaults;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.pushToRemote', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.type', 'Annotated');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.applyStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.recordOrigin', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.createBranch.checkOut', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.deleteBranch.forceDelete', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchIntoLocalBranch.forceFetch', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.prune', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.pruneTags', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.general.referenceInputSpaceSubstitution', 'None');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noFastForward', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.popStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.noFastForward', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.ignoreDate', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.launchInteractiveRebase', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetUncommittedChanges.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.stashUncommittedChanges.includeUntracked', true);
expect(value).toStrictEqual({
addTag: {
pushToRemote: true,
type: TagType.Annotated
},
applyStash: {
reinstateIndex: true
},
cherryPick: {
noCommit: true,
recordOrigin: true
},
createBranch: {
checkout: true
},
deleteBranch: {
forceDelete: true
},
fetchIntoLocalBranch: {
forceFetch: true
},
fetchRemote: {
prune: true,
pruneTags: true
},
general: {
referenceInputSpaceSubstitution: null
},
merge: {
noCommit: true,
noFastForward: true,
squash: true
},
popStash: {
reinstateIndex: true
},
pullBranch: {
noFastForward: true,
squash: true
},
rebase: {
ignoreDate: true,
interactive: true
},
resetCommit: {
mode: GitResetMode.Mixed
},
resetUncommitted: {
mode: GitResetMode.Mixed
},
stashUncommittedChanges: {
includeUntracked: true
}
});
});
it('Should return FALSE values for boolean-based configuration values when they are falsy', () => {
// Setup
[
'dialog.addTag.pushToRemote',
'dialog.applyStash.reinstateIndex',
'dialog.cherryPick.noCommit',
'dialog.cherryPick.recordOrigin',
'dialog.createBranch.checkOut',
'dialog.deleteBranch.forceDelete',
'dialog.fetchIntoLocalBranch.forceFetch',
'dialog.fetchRemote.prune',
'dialog.fetchRemote.pruneTags',
'dialog.merge.noCommit',
'dialog.merge.noFastForward',
'dialog.merge.squashCommits',
'dialog.popStash.reinstateIndex',
'dialog.pullBranch.noFastForward',
'dialog.pullBranch.squashCommits',
'dialog.rebase.ignoreDate',
'dialog.rebase.launchInteractiveRebase',
'dialog.stashUncommittedChanges.includeUntracked'
].forEach((section) => vscode.mockExtensionSettingReturnValue(section, 0));
// Run
const value = config.dialogDefaults;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.pushToRemote', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.type', 'Annotated');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.applyStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.recordOrigin', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.createBranch.checkOut', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.deleteBranch.forceDelete', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchIntoLocalBranch.forceFetch', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.prune', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.pruneTags', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.general.referenceInputSpaceSubstitution', 'None');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noFastForward', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.popStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.noFastForward', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.ignoreDate', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.launchInteractiveRebase', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetUncommittedChanges.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.stashUncommittedChanges.includeUntracked', true);
expect(value).toStrictEqual({
addTag: {
pushToRemote: false,
type: TagType.Annotated
},
applyStash: {
reinstateIndex: false
},
cherryPick: {
noCommit: false,
recordOrigin: false
},
createBranch: {
checkout: false
},
deleteBranch: {
forceDelete: false
},
fetchIntoLocalBranch: {
forceFetch: false
},
fetchRemote: {
prune: false,
pruneTags: false
},
general: {
referenceInputSpaceSubstitution: null
},
merge: {
noCommit: false,
noFastForward: false,
squash: false
},
popStash: {
reinstateIndex: false
},
pullBranch: {
noFastForward: false,
squash: false
},
rebase: {
ignoreDate: false,
interactive: false
},
resetCommit: {
mode: GitResetMode.Mixed
},
resetUncommitted: {
mode: GitResetMode.Mixed
},
stashUncommittedChanges: {
includeUntracked: false
}
});
});
it('Should return the default values for text-based configuration values when they are invalid', () => {
// Setup
[
'dialog.addTag.type',
'dialog.resetCurrentBranchToCommit.mode',
'dialog.resetUncommittedChanges.mode'
].forEach((section) => vscode.mockExtensionSettingReturnValue(section, 'invalid'));
// Run
const value = config.dialogDefaults;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.pushToRemote', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.type', 'Annotated');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.applyStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.recordOrigin', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.createBranch.checkOut', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.deleteBranch.forceDelete', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchIntoLocalBranch.forceFetch', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.prune', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.pruneTags', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.general.referenceInputSpaceSubstitution', 'None');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noFastForward', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.popStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.noFastForward', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.ignoreDate', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.launchInteractiveRebase', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetUncommittedChanges.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.stashUncommittedChanges.includeUntracked', true);
expect(value).toStrictEqual({
addTag: {
pushToRemote: false,
type: TagType.Annotated
},
applyStash: {
reinstateIndex: false
},
cherryPick: {
noCommit: false,
recordOrigin: false
},
createBranch: {
checkout: false
},
deleteBranch: {
forceDelete: false
},
fetchIntoLocalBranch: {
forceFetch: false
},
fetchRemote: {
prune: false,
pruneTags: false
},
general: {
referenceInputSpaceSubstitution: null
},
merge: {
noCommit: false,
noFastForward: true,
squash: false
},
popStash: {
reinstateIndex: false
},
pullBranch: {
noFastForward: false,
squash: false
},
rebase: {
ignoreDate: true,
interactive: false
},
resetCommit: {
mode: GitResetMode.Mixed
},
resetUncommitted: {
mode: GitResetMode.Mixed
},
stashUncommittedChanges: {
includeUntracked: true
}
});
});
it('Should return the default values when the configuration values are not set', () => {
// Run
const value = config.dialogDefaults;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.pushToRemote', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.addTag.type', 'Annotated');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.applyStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.cherryPick.recordOrigin', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.createBranch.checkOut', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.deleteBranch.forceDelete', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchIntoLocalBranch.forceFetch', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.prune', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.fetchRemote.pruneTags', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.general.referenceInputSpaceSubstitution', 'None');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noCommit', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.noFastForward', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.popStash.reinstateIndex', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.noFastForward', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashCommits', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.ignoreDate', true);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.rebase.launchInteractiveRebase', false);
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.resetUncommittedChanges.mode', 'Mixed');
expect(workspaceConfiguration.get).toBeCalledWith('dialog.stashUncommittedChanges.includeUntracked', true);
expect(value).toStrictEqual({
addTag: {
pushToRemote: false,
type: TagType.Annotated
},
applyStash: {
reinstateIndex: false
},
cherryPick: {
noCommit: false,
recordOrigin: false
},
createBranch: {
checkout: false
},
deleteBranch: {
forceDelete: false
},
fetchIntoLocalBranch: {
forceFetch: false
},
fetchRemote: {
prune: false,
pruneTags: false
},
general: {
referenceInputSpaceSubstitution: null
},
merge: {
noCommit: false,
noFastForward: true,
squash: false
},
popStash: {
reinstateIndex: false
},
pullBranch: {
noFastForward: false,
squash: false
},
rebase: {
ignoreDate: true,
interactive: false
},
resetCommit: {
mode: GitResetMode.Mixed
},
resetUncommitted: {
mode: GitResetMode.Mixed
},
stashUncommittedChanges: {
includeUntracked: true
}
});
});
describe('dialogDefaults.addTag.type', () => {
it('Should return TagType.Annotated when the configuration value is "Annotated"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.addTag.type', 'Annotated');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.addTag.type).toBe(TagType.Annotated);
});
it('Should return TagType.Lightweight when the configuration value is "Lightweight"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.addTag.type', 'Lightweight');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.addTag.type).toBe(TagType.Lightweight);
});
});
describe('dialogDefaults.general.referenceInputSpaceSubstitution', () => {
it('Should return NULL when the configuration value is "None"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.general.referenceInputSpaceSubstitution', 'None');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.general.referenceInputSpaceSubstitution).toBe(null);
});
it('Should return "-" when the configuration value is "Hyphen"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.general.referenceInputSpaceSubstitution', 'Hyphen');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.general.referenceInputSpaceSubstitution).toBe('-');
});
it('Should return "_" when the configuration value is "Underscore"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.general.referenceInputSpaceSubstitution', 'Underscore');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.general.referenceInputSpaceSubstitution).toBe('_');
});
it('Should return the default value (NULL) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.general.referenceInputSpaceSubstitution', 'invalid');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.general.referenceInputSpaceSubstitution).toBe(null);
});
});
describe('dialogDefaults.resetCommit.mode', () => {
it('Should return GitResetMode.Hard when the configuration value is "Hard"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.resetCurrentBranchToCommit.mode', 'Hard');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.resetCommit.mode).toBe(GitResetMode.Hard);
});
it('Should return GitResetMode.Mixed when the configuration value is "Mixed"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.resetCurrentBranchToCommit.mode', 'Mixed');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.resetCommit.mode).toBe(GitResetMode.Mixed);
});
it('Should return GitResetMode.Soft when the configuration value is "Soft"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.resetCurrentBranchToCommit.mode', 'Soft');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.resetCommit.mode).toBe(GitResetMode.Soft);
});
});
describe('dialogDefaults.resetUncommitted.mode', () => {
it('Should return GitResetMode.Hard when the configuration value is "Hard"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.resetUncommittedChanges.mode', 'Hard');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.resetUncommitted.mode).toBe(GitResetMode.Hard);
});
it('Should return GitResetMode.Mixed when the configuration value is "Mixed"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.resetUncommittedChanges.mode', 'Mixed');
// Run
const value = config.dialogDefaults;
// Assert
expect(value.resetUncommitted.mode).toBe(GitResetMode.Mixed);
});
});
});
describe('squashMergeMessageFormat', () => {
it('Should return SquashMessageFormat.Default when the configuration value is "Default"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.merge.squashMessageFormat', 'Default');
// Run
const value = config.squashMergeMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.Default);
});
it('Should return SquashMessageFormat.GitSquashMsg when the configuration value is "Git SQUASH_MSG"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.merge.squashMessageFormat', 'Git SQUASH_MSG');
// Run
const value = config.squashMergeMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.GitSquashMsg);
});
it('Should return the default value (SquashMessageFormat.Default) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.merge.squashMessageFormat', 'invalid');
// Run
const value = config.squashMergeMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.Default);
});
it('Should return the default value (SquashMessageFormat.Default) when the configuration value is not set', () => {
// Run
const value = config.squashMergeMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.merge.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.Default);
});
});
describe('squashPullMessageFormat', () => {
it('Should return SquashMessageFormat.Default when the configuration value is "Default"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.pullBranch.squashMessageFormat', 'Default');
// Run
const value = config.squashPullMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.Default);
});
it('Should return SquashMessageFormat.GitSquashMsg when the configuration value is "Git SQUASH_MSG"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.pullBranch.squashMessageFormat', 'Git SQUASH_MSG');
// Run
const value = config.squashPullMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.GitSquashMsg);
});
it('Should return the default value (SquashMessageFormat.Default) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('dialog.pullBranch.squashMessageFormat', 'invalid');
// Run
const value = config.squashPullMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.Default);
});
it('Should return the default value (SquashMessageFormat.Default) when the configuration value is not set', () => {
// Run
const value = config.squashPullMessageFormat;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('dialog.pullBranch.squashMessageFormat', 'Default');
expect(value).toBe(SquashMessageFormat.Default);
});
});
describe('enhancedAccessibility', testBooleanExtensionSetting('enhancedAccessibility', 'enhancedAccessibility', false));
describe('fileEncoding', () => {
it('Should return the configured value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('fileEncoding', 'file-encoding');
// Run
const value = config.fileEncoding;
expect(workspaceConfiguration.get).toBeCalledWith('fileEncoding', 'utf8');
expect(value).toBe('file-encoding');
});
it('Should return the default configuration value ("utf8")', () => {
// Run
const value = config.fileEncoding;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('fileEncoding', 'utf8');
expect(value).toBe('utf8');
});
});
describe('graph', () => {
describe('colours', () => {
it('Should return a filtered array of colours based on the configuration value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.colours', ['#ff0000', '#0000000', '#00ff0088', 'rgb(1,2,3)', 'rgb(1,2,x)']);
// Run
const value = config.graph.colours;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.colours', 'graphColours');
expect(value).toHaveLength(3);
expect(value[0]).toBe('#ff0000');
expect(value[1]).toBe('#00ff0088');
expect(value[2]).toBe('rgb(1,2,3)');
});
it('Should return the default value when the configuration value is invalid (not an array)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.colours', 5);
// Run
const value = config.graph.colours;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.colours', 'graphColours');
expect(value).toStrictEqual(['#0085d9', '#d9008f', '#00d90a', '#d98500', '#a300d9', '#ff0000', '#00d9cc', '#e138e8', '#85d900', '#dc5b23', '#6f24d6', '#ffcc00']);
});
it('Should return the default value when the configuration value is invalid (an empty array)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.colours', []);
// Run
const value = config.graph.colours;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.colours', 'graphColours');
expect(value).toStrictEqual(['#0085d9', '#d9008f', '#00d90a', '#d98500', '#a300d9', '#ff0000', '#00d9cc', '#e138e8', '#85d900', '#dc5b23', '#6f24d6', '#ffcc00']);
});
it('Should return the default value when the configuration value is unknown', () => {
// Run
const value = config.graph.colours;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.colours', 'graphColours');
expect(value).toStrictEqual(['#0085d9', '#d9008f', '#00d90a', '#d98500', '#a300d9', '#ff0000', '#00d9cc', '#e138e8', '#85d900', '#dc5b23', '#6f24d6', '#ffcc00']);
});
});
describe('style', () => {
it('Should return GraphStyle.Rounded when the configuration value is "rounded"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.style', 'rounded');
// Run
const value = config.graph.style;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.style', 'graphStyle');
expect(value).toBe(GraphStyle.Rounded);
});
it('Should return GraphStyle.Angular when the configuration value is "angular"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.style', 'angular');
// Run
const value = config.graph.style;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.style', 'graphStyle');
expect(value).toBe(GraphStyle.Angular);
});
it('Should return the default value (GraphStyle.Rounded) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.style', 'invalid');
// Run
const value = config.graph.style;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.style', 'graphStyle');
expect(value).toBe(GraphStyle.Rounded);
});
it('Should return the default value (GraphStyle.Rounded) when the configuration value is unknown', () => {
// Run
const value = config.graph.style;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('graph.style', 'graphStyle');
expect(value).toBe(GraphStyle.Rounded);
});
});
describe('uncommittedChanges', () => {
it('Should return GraphUncommittedChangesStyle.OpenCircleAtTheUncommittedChanges when the configuration value is "Open Circle at the Uncommitted Changes"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.uncommittedChanges', 'Open Circle at the Uncommitted Changes');
// Run
const value = config.graph.uncommittedChanges;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('graph.uncommittedChanges', 'Open Circle at the Uncommitted Changes');
expect(value).toBe(GraphUncommittedChangesStyle.OpenCircleAtTheUncommittedChanges);
});
it('Should return GraphUncommittedChangesStyle.OpenCircleAtTheCheckedOutCommit when the configuration value is "Open Circle at the Checked Out Commit"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.uncommittedChanges', 'Open Circle at the Checked Out Commit');
// Run
const value = config.graph.uncommittedChanges;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('graph.uncommittedChanges', 'Open Circle at the Uncommitted Changes');
expect(value).toBe(GraphUncommittedChangesStyle.OpenCircleAtTheCheckedOutCommit);
});
it('Should return the default value (GraphUncommittedChangesStyle.OpenCircleAtTheUncommittedChanges) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('graph.uncommittedChanges', 'invalid');
// Run
const value = config.graph.uncommittedChanges;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('graph.uncommittedChanges', 'Open Circle at the Uncommitted Changes');
expect(value).toBe(GraphUncommittedChangesStyle.OpenCircleAtTheUncommittedChanges);
});
it('Should return the default value (GraphUncommittedChangesStyle.OpenCircleAtTheUncommittedChanges) when the configuration value is unknown', () => {
// Run
const value = config.graph.uncommittedChanges;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('graph.uncommittedChanges', 'Open Circle at the Uncommitted Changes');
expect(value).toBe(GraphUncommittedChangesStyle.OpenCircleAtTheUncommittedChanges);
});
});
});
describe('integratedTerminalShell', () => {
it('Should return the configured value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('integratedTerminalShell', '/path/to/shell');
// Run
const value = config.integratedTerminalShell;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('integratedTerminalShell', '');
expect(value).toBe('/path/to/shell');
});
it('Should return the default configuration value ("")', () => {
// Run
const value = config.integratedTerminalShell;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('integratedTerminalShell', '');
expect(value).toBe('');
});
});
describe('keybindings', () => {
describe('find', () => {
it('Should return the configured keybinding', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.find', 'CTRL/CMD + A');
// Run
const value = config.keybindings.find;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.find');
expect(value).toBe('a');
});
it('Should return the configured keybinding (unassigned)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.find', 'UNASSIGNED');
// Run
const value = config.keybindings.find;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.find');
expect(value).toBeNull();
});
it('Should return the default keybinding when the value is not one of the available keybindings', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.find', 'CTRL/CMD + Shift + A');
// Run
const value = config.keybindings.find;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.find');
expect(value).toBe('f');
});
it('Should return the default keybinding when the value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.find', 5);
// Run
const value = config.keybindings.find;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.find');
expect(value).toBe('f');
});
it('Should return the default keybinding', () => {
// Run
const value = config.keybindings.find;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.find');
expect(value).toBe('f');
});
});
describe('refresh', () => {
it('Should return the configured keybinding', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.refresh', 'CTRL/CMD + A');
// Run
const value = config.keybindings.refresh;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.refresh');
expect(value).toBe('a');
});
it('Should return the configured keybinding (unassigned)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.refresh', 'UNASSIGNED');
// Run
const value = config.keybindings.refresh;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.refresh');
expect(value).toBeNull();
});
it('Should return the default keybinding when the value is not one of the available keybindings', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.refresh', 'CTRL/CMD + Shift + A');
// Run
const value = config.keybindings.refresh;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.refresh');
expect(value).toBe('r');
});
it('Should return the default keybinding when the value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.refresh', 5);
// Run
const value = config.keybindings.refresh;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.refresh');
expect(value).toBe('r');
});
it('Should return the default keybinding', () => {
// Run
const value = config.keybindings.refresh;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.refresh');
expect(value).toBe('r');
});
});
describe('scrollToHead', () => {
it('Should return the configured keybinding', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToHead', 'CTRL/CMD + A');
// Run
const value = config.keybindings.scrollToHead;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToHead');
expect(value).toBe('a');
});
it('Should return the configured keybinding (unassigned)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToHead', 'UNASSIGNED');
// Run
const value = config.keybindings.scrollToHead;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToHead');
expect(value).toBeNull();
});
it('Should return the default keybinding when the value is not one of the available keybindings', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToHead', 'CTRL/CMD + Shift + A');
// Run
const value = config.keybindings.scrollToHead;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToHead');
expect(value).toBe('h');
});
it('Should return the default keybinding when the value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToHead', 5);
// Run
const value = config.keybindings.scrollToHead;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToHead');
expect(value).toBe('h');
});
it('Should return the default keybinding', () => {
// Run
const value = config.keybindings.scrollToHead;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToHead');
expect(value).toBe('h');
});
});
describe('scrollToStash', () => {
it('Should return the configured keybinding', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToStash', 'CTRL/CMD + A');
// Run
const value = config.keybindings.scrollToStash;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToStash');
expect(value).toBe('a');
});
it('Should return the configured keybinding (unassigned)', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToStash', 'UNASSIGNED');
// Run
const value = config.keybindings.scrollToStash;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToStash');
expect(value).toBeNull();
});
it('Should return the default keybinding when the value is not one of the available keybindings', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToStash', 'CTRL/CMD + Shift + A');
// Run
const value = config.keybindings.scrollToStash;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToStash');
expect(value).toBe('s');
});
it('Should return the default keybinding when the value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('keyboardShortcut.scrollToStash', 5);
// Run
const value = config.keybindings.scrollToStash;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToStash');
expect(value).toBe('s');
});
it('Should return the default keybinding', () => {
// Run
const value = config.keybindings.scrollToStash;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('keyboardShortcut.scrollToStash');
expect(value).toBe('s');
});
});
});
describe('markdown', testBooleanExtensionSetting('markdown', 'markdown', true));
describe('maxDepthOfRepoSearch', () => {
it('Should return the configured value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('maxDepthOfRepoSearch', 5);
// Run
const value = config.maxDepthOfRepoSearch;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('maxDepthOfRepoSearch', 0);
expect(value).toBe(5);
});
it('Should return the default configuration value (0)', () => {
// Run
const value = config.maxDepthOfRepoSearch;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('maxDepthOfRepoSearch', 0);
expect(value).toBe(0);
});
});
describe('openNewTabEditorGroup', () => {
it('Should return vscode.ViewColumn.Active when the configuration value is "Active"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Active');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Active);
});
it('Should return vscode.ViewColumn.Beside when the configuration value is "Beside"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Beside');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Beside);
});
it('Should return vscode.ViewColumn.One when the configuration value is "One"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'One');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.One);
});
it('Should return vscode.ViewColumn.Two when the configuration value is "Two"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Two');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Two);
});
it('Should return vscode.ViewColumn.Three when the configuration value is "Three"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Three');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Three);
});
it('Should return vscode.ViewColumn.Four when the configuration value is "Four"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Four');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Four);
});
it('Should return vscode.ViewColumn.Five when the configuration value is "Five"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Five');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Five);
});
it('Should return vscode.ViewColumn.Six when the configuration value is "Six"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Six');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Six);
});
it('Should return vscode.ViewColumn.Seven when the configuration value is "Seven"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Seven');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Seven);
});
it('Should return vscode.ViewColumn.Eight when the configuration value is "Eight"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Eight');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Eight);
});
it('Should return vscode.ViewColumn.Nine when the configuration value is "Nine"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'Nine');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Nine);
});
it('Should return the default value (vscode.ViewColumn.Active) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('openNewTabEditorGroup', 'invalid');
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Active);
});
it('Should return the default value (vscode.ViewColumn.Active) when the configuration value is unknown', () => {
// Run
const value = config.openNewTabEditorGroup;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('openNewTabEditorGroup', 'openDiffTabLocation');
expect(value).toBe(vscode.ViewColumn.Active);
});
});
describe('openToTheRepoOfTheActiveTextEditorDocument', testBooleanExtensionSetting('openToTheRepoOfTheActiveTextEditorDocument', 'openToTheRepoOfTheActiveTextEditorDocument', false));
describe('referenceLabels', () => {
describe('combineLocalAndRemoteBranchLabels', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.combineLocalAndRemoteBranchLabels', true);
// Run
const value = config.referenceLabels.combineLocalAndRemoteBranchLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.combineLocalAndRemoteBranchLabels', 'combineLocalAndRemoteBranchLabels');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.combineLocalAndRemoteBranchLabels', false);
// Run
const value = config.referenceLabels.combineLocalAndRemoteBranchLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.combineLocalAndRemoteBranchLabels', 'combineLocalAndRemoteBranchLabels');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.combineLocalAndRemoteBranchLabels', 5);
// Run
const value = config.referenceLabels.combineLocalAndRemoteBranchLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.combineLocalAndRemoteBranchLabels', 'combineLocalAndRemoteBranchLabels');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.combineLocalAndRemoteBranchLabels', 0);
// Run
const value = config.referenceLabels.combineLocalAndRemoteBranchLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.combineLocalAndRemoteBranchLabels', 'combineLocalAndRemoteBranchLabels');
expect(value).toBe(false);
});
it('Should return the default value (TRUE) when the configuration value is unknown', () => {
// Run
const value = config.referenceLabels.combineLocalAndRemoteBranchLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.combineLocalAndRemoteBranchLabels', 'combineLocalAndRemoteBranchLabels');
expect(value).toBe(true);
});
});
describe('branchLabelsAlignedToGraph & tagLabelsOnRight', () => {
it('Should return correct alignment values when the configuration value is "Normal"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.alignment', 'Normal');
// Run
const value = config.referenceLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.alignment', 'referenceLabelAlignment');
expect(value.branchLabelsAlignedToGraph).toBe(false);
expect(value.tagLabelsOnRight).toBe(false);
});
it('Should return correct alignment values when the configuration value is "Branches (on the left) & Tags (on the right)"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.alignment', 'Branches (on the left) & Tags (on the right)');
// Run
const value = config.referenceLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.alignment', 'referenceLabelAlignment');
expect(value.branchLabelsAlignedToGraph).toBe(false);
expect(value.tagLabelsOnRight).toBe(true);
});
it('Should return correct alignment values when the configuration value is "Branches (aligned to the graph) & Tags (on the right)"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.alignment', 'Branches (aligned to the graph) & Tags (on the right)');
// Run
const value = config.referenceLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.alignment', 'referenceLabelAlignment');
expect(value.branchLabelsAlignedToGraph).toBe(true);
expect(value.tagLabelsOnRight).toBe(true);
});
it('Should return the default values when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('referenceLabels.alignment', 'invalid');
// Run
const value = config.referenceLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.alignment', 'referenceLabelAlignment');
expect(value.branchLabelsAlignedToGraph).toBe(false);
expect(value.tagLabelsOnRight).toBe(false);
});
it('Should return the default values when the configuration value is unknown', () => {
// Run
const value = config.referenceLabels;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('referenceLabels.alignment', 'referenceLabelAlignment');
expect(value.branchLabelsAlignedToGraph).toBe(false);
expect(value.tagLabelsOnRight).toBe(false);
});
});
});
describe('fetchAvatars', testRenamedBooleanExtensionSetting('fetchAvatars', 'repository.commits.fetchAvatars', 'fetchAvatars', false));
describe('initialLoadCommits', () => {
it('Should return the configured value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.initialLoad', 600);
// Run
const value = config.initialLoadCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.initialLoad', 'initialLoadCommits');
expect(value).toBe(600);
});
it('Should return the default configuration value (300)', () => {
// Run
const value = config.initialLoadCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.initialLoad', 'initialLoadCommits');
expect(value).toBe(300);
});
});
describe('loadMoreCommits', () => {
it('Should return the configured value', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.loadMore', 200);
// Run
const value = config.loadMoreCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.loadMore', 'loadMoreCommits');
expect(value).toBe(200);
});
it('Should return the default configuration value (100)', () => {
// Run
const value = config.loadMoreCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.loadMore', 'loadMoreCommits');
expect(value).toBe(100);
});
});
describe('loadMoreCommitsAutomatically', testRenamedBooleanExtensionSetting('loadMoreCommitsAutomatically', 'repository.commits.loadMoreAutomatically', 'loadMoreCommitsAutomatically', true));
describe('muteCommits', () => {
describe('commitsNotAncestorsOfHead', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.commitsThatAreNotAncestorsOfHead', true);
// Run
const value = config.muteCommits.commitsNotAncestorsOfHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 'muteCommitsThatAreNotAncestorsOfHead');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.commitsThatAreNotAncestorsOfHead', false);
// Run
const value = config.muteCommits.commitsNotAncestorsOfHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 'muteCommitsThatAreNotAncestorsOfHead');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 5);
// Run
const value = config.muteCommits.commitsNotAncestorsOfHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 'muteCommitsThatAreNotAncestorsOfHead');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 0);
// Run
const value = config.muteCommits.commitsNotAncestorsOfHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 'muteCommitsThatAreNotAncestorsOfHead');
expect(value).toBe(false);
});
it('Should return the default value (FALSE) when the configuration value is unknown', () => {
// Run
const value = config.muteCommits.commitsNotAncestorsOfHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.commitsThatAreNotAncestorsOfHead', 'muteCommitsThatAreNotAncestorsOfHead');
expect(value).toBe(false);
});
});
describe('mergeCommits', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.mergeCommits', true);
// Run
const value = config.muteCommits.mergeCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.mergeCommits', 'muteMergeCommits');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.mergeCommits', false);
// Run
const value = config.muteCommits.mergeCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.mergeCommits', 'muteMergeCommits');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.mergeCommits', 5);
// Run
const value = config.muteCommits.mergeCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.mergeCommits', 'muteMergeCommits');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.mute.mergeCommits', 0);
// Run
const value = config.muteCommits.mergeCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.mergeCommits', 'muteMergeCommits');
expect(value).toBe(false);
});
it('Should return the default value (TRUE) when the configuration value is unknown', () => {
// Run
const value = config.muteCommits.mergeCommits;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.mute.mergeCommits', 'muteMergeCommits');
expect(value).toBe(true);
});
});
});
describe('commitOrder', () => {
it('Should return CommitOrdering.Date when the configuration value is "date"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.order', 'date');
// Run
const value = config.commitOrder;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.order', 'commitOrdering');
expect(value).toBe(CommitOrdering.Date);
});
it('Should return CommitOrdering.AuthorDate when the configuration value is "author-date"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.order', 'author-date');
// Run
const value = config.commitOrder;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.order', 'commitOrdering');
expect(value).toBe(CommitOrdering.AuthorDate);
});
it('Should return CommitOrdering.Topological when the configuration value is "topo"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.order', 'topo');
// Run
const value = config.commitOrder;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.order', 'commitOrdering');
expect(value).toBe(CommitOrdering.Topological);
});
it('Should return the default value (CommitOrdering.Date) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.commits.order', 'invalid');
// Run
const value = config.commitOrder;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.order', 'commitOrdering');
expect(value).toBe(CommitOrdering.Date);
});
it('Should return the default value (CommitOrdering.Date) when the configuration value is unknown', () => {
// Run
const value = config.commitOrder;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.commits.order', 'commitOrdering');
expect(value).toBe(CommitOrdering.Date);
});
});
describe('fetchAndPrune', testRenamedBooleanExtensionSetting('fetchAndPrune', 'repository.fetchAndPrune', 'fetchAndPrune', false));
describe('fetchAndPruneTags', testBooleanExtensionSetting('fetchAndPruneTags', 'repository.fetchAndPruneTags', false));
describe('includeCommitsMentionedByReflogs', testRenamedBooleanExtensionSetting('includeCommitsMentionedByReflogs', 'repository.includeCommitsMentionedByReflogs', 'includeCommitsMentionedByReflogs', false));
describe('onRepoLoad', () => {
describe('scrollToHead', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.scrollToHead', true);
// Run
const value = config.onRepoLoad.scrollToHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.scrollToHead', 'openRepoToHead');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.scrollToHead', false);
// Run
const value = config.onRepoLoad.scrollToHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.scrollToHead', 'openRepoToHead');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.scrollToHead', 5);
// Run
const value = config.onRepoLoad.scrollToHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.scrollToHead', 'openRepoToHead');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.scrollToHead', 0);
// Run
const value = config.onRepoLoad.scrollToHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.scrollToHead', 'openRepoToHead');
expect(value).toBe(false);
});
it('Should return the default value (FALSE) when the configuration value is unknown', () => {
// Run
const value = config.onRepoLoad.scrollToHead;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.scrollToHead', 'openRepoToHead');
expect(value).toBe(false);
});
});
describe('showCheckedOutBranch', () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showCheckedOutBranch', true);
// Run
const value = config.onRepoLoad.showCheckedOutBranch;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.showCheckedOutBranch', 'showCurrentBranchByDefault');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showCheckedOutBranch', false);
// Run
const value = config.onRepoLoad.showCheckedOutBranch;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.showCheckedOutBranch', 'showCurrentBranchByDefault');
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showCheckedOutBranch', 5);
// Run
const value = config.onRepoLoad.showCheckedOutBranch;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.showCheckedOutBranch', 'showCurrentBranchByDefault');
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showCheckedOutBranch', 0);
// Run
const value = config.onRepoLoad.showCheckedOutBranch;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.showCheckedOutBranch', 'showCurrentBranchByDefault');
expect(value).toBe(false);
});
it('Should return the default value (FALSE) when the configuration value is unknown', () => {
// Run
const value = config.onRepoLoad.showCheckedOutBranch;
// Assert
expectRenamedExtensionSettingToHaveBeenCalled('repository.onLoad.showCheckedOutBranch', 'showCurrentBranchByDefault');
expect(value).toBe(false);
});
});
describe('showSpecificBranches', () => {
it('Should return all branches when correctly configured', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showSpecificBranches', ['master', 'develop']);
// Run
const value = config.onRepoLoad.showSpecificBranches;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repository.onLoad.showSpecificBranches', expect.anything());
expect(value).toStrictEqual(['master', 'develop']);
});
it('Should filter out all non-string branches', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showSpecificBranches', ['master', 5, 'develop']);
// Run
const value = config.onRepoLoad.showSpecificBranches;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repository.onLoad.showSpecificBranches', expect.anything());
expect(value).toStrictEqual(['master', 'develop']);
});
it('Should return the default value ([]) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repository.onLoad.showSpecificBranches', 'master');
// Run
const value = config.onRepoLoad.showSpecificBranches;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repository.onLoad.showSpecificBranches', expect.anything());
expect(value).toStrictEqual([]);
});
it('Should return the default value ([]) when the configuration value is unknown', () => {
// Run
const value = config.onRepoLoad.showSpecificBranches;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repository.onLoad.showSpecificBranches', expect.anything());
expect(value).toStrictEqual([]);
});
});
});
describe('onlyFollowFirstParent', testRenamedBooleanExtensionSetting('onlyFollowFirstParent', 'repository.onlyFollowFirstParent', 'onlyFollowFirstParent', false));
describe('showCommitsOnlyReferencedByTags', testRenamedBooleanExtensionSetting('showCommitsOnlyReferencedByTags', 'repository.showCommitsOnlyReferencedByTags', 'showCommitsOnlyReferencedByTags', true));
describe('showSignatureStatus', testRenamedBooleanExtensionSetting('showSignatureStatus', 'repository.commits.showSignatureStatus', 'showSignatureStatus', false));
describe('showRemoteBranches', testBooleanExtensionSetting('showRemoteBranches', 'repository.showRemoteBranches', true));
describe('showRemoteHeads', testBooleanExtensionSetting('showRemoteHeads', 'repository.showRemoteHeads', true));
describe('showStashes', testBooleanExtensionSetting('showStashes', 'repository.showStashes', true));
describe('showTags', testRenamedBooleanExtensionSetting('showTags', 'repository.showTags', 'showTags', true));
describe('showUncommittedChanges', testRenamedBooleanExtensionSetting('showUncommittedChanges', 'repository.showUncommittedChanges', 'showUncommittedChanges', true));
describe('showUntrackedFiles', testRenamedBooleanExtensionSetting('showUntrackedFiles', 'repository.showUntrackedFiles', 'showUntrackedFiles', true));
describe('signCommits', testBooleanExtensionSetting('signCommits', 'repository.sign.commits', false));
describe('signTags', testBooleanExtensionSetting('signTags', 'repository.sign.tags', false));
describe('useMailmap', testRenamedBooleanExtensionSetting('useMailmap', 'repository.useMailmap', 'useMailmap', false));
describe('repoDropdownOrder', () => {
it('Should return RepoDropdownOrder.Name when the configuration value is "Name"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repositoryDropdownOrder', 'Name');
// Run
const value = config.repoDropdownOrder;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repositoryDropdownOrder', 'Workspace Full Path');
expect(value).toBe(RepoDropdownOrder.Name);
});
it('Should return RepoDropdownOrder.FullPath when the configuration value is "Full Path"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repositoryDropdownOrder', 'Full Path');
// Run
const value = config.repoDropdownOrder;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repositoryDropdownOrder', 'Workspace Full Path');
expect(value).toBe(RepoDropdownOrder.FullPath);
});
it('Should return RepoDropdownOrder.WorkspaceFullPath when the configuration value is "Workspace Full Path"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repositoryDropdownOrder', 'Workspace Full Path');
// Run
const value = config.repoDropdownOrder;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repositoryDropdownOrder', 'Workspace Full Path');
expect(value).toBe(RepoDropdownOrder.WorkspaceFullPath);
});
it('Should return the default value (RepoDropdownOrder.WorkspaceFullPath) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('repositoryDropdownOrder', 'invalid');
// Run
const value = config.repoDropdownOrder;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repositoryDropdownOrder', 'Workspace Full Path');
expect(value).toBe(RepoDropdownOrder.WorkspaceFullPath);
});
it('Should return the default value (RepoDropdownOrder.WorkspaceFullPath) when the configuration value is not set', () => {
// Run
const value = config.repoDropdownOrder;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('repositoryDropdownOrder', 'Workspace Full Path');
expect(value).toBe(RepoDropdownOrder.WorkspaceFullPath);
});
});
describe('retainContextWhenHidden', testBooleanExtensionSetting('retainContextWhenHidden', 'retainContextWhenHidden', true));
describe('showStatusBarItem', testBooleanExtensionSetting('showStatusBarItem', 'showStatusBarItem', true));
describe('tabIconColourTheme', () => {
it('Should return TabIconColourTheme.Colour when the configuration value is "colour"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('tabIconColourTheme', 'colour');
// Run
const value = config.tabIconColourTheme;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('tabIconColourTheme', 'colour');
expect(value).toBe(TabIconColourTheme.Colour);
});
it('Should return TabIconColourTheme.Grey when the configuration value is "grey"', () => {
// Setup
vscode.mockExtensionSettingReturnValue('tabIconColourTheme', 'grey');
// Run
const value = config.tabIconColourTheme;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('tabIconColourTheme', 'colour');
expect(value).toBe(TabIconColourTheme.Grey);
});
it('Should return the default value (TabIconColourTheme.Colour) when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('tabIconColourTheme', 'invalid');
// Run
const value = config.tabIconColourTheme;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('tabIconColourTheme', 'colour');
expect(value).toBe(TabIconColourTheme.Colour);
});
it('Should return the default value (TabIconColourTheme.Colour) when the configuration value is not set', () => {
// Run
const value = config.tabIconColourTheme;
// Assert
expect(workspaceConfiguration.get).toBeCalledWith('tabIconColourTheme', 'colour');
expect(value).toBe(TabIconColourTheme.Colour);
});
});
describe('gitPaths', () => {
it('Should return the configured path', () => {
// Setup
vscode.mockExtensionSettingReturnValue('path', '/path/to/git');
// Run
const value = config.gitPaths;
// Assert
expect(vscode.workspace.getConfiguration).toBeCalledWith('git');
expect(workspaceConfiguration.get).toBeCalledWith('path', null);
expect(value).toStrictEqual(['/path/to/git']);
});
it('Should return the valid configured paths', () => {
// Setup
vscode.mockExtensionSettingReturnValue('path', ['/path/to/first/git', '/path/to/second/git', 4, {}, null, '/path/to/third/git']);
// Run
const value = config.gitPaths;
// Assert
expect(vscode.workspace.getConfiguration).toBeCalledWith('git');
expect(workspaceConfiguration.get).toBeCalledWith('path', null);
expect(value).toStrictEqual(['/path/to/first/git', '/path/to/second/git', '/path/to/third/git']);
});
it('Should return an empty array when the configuration value is NULL', () => {
// Setup
vscode.mockExtensionSettingReturnValue('path', null);
// Run
const value = config.gitPaths;
// Assert
expect(vscode.workspace.getConfiguration).toBeCalledWith('git');
expect(workspaceConfiguration.get).toBeCalledWith('path', null);
expect(value).toStrictEqual([]);
});
it('Should return an empty array when the configuration value is invalid', () => {
// Setup
vscode.mockExtensionSettingReturnValue('path', 4);
// Run
const value = config.gitPaths;
// Assert
expect(vscode.workspace.getConfiguration).toBeCalledWith('git');
expect(workspaceConfiguration.get).toBeCalledWith('path', null);
expect(value).toStrictEqual([]);
});
it('Should return an empty array when the default configuration value (NULL) is received', () => {
// Run
const value = config.gitPaths;
// Assert
expect(vscode.workspace.getConfiguration).toBeCalledWith('git');
expect(workspaceConfiguration.get).toBeCalledWith('path', null);
expect(value).toStrictEqual([]);
});
});
describe('getRenamedExtensionSetting', () => {
it('Should return new workspace value', () => {
// Setup
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: true,
globalValue: false
});
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: false,
globalValue: false
});
// Run
const value = config.fetchAndPrune;
// Assert
expect(value).toBe(true);
});
it('Should return old workspace value', () => {
// Setup
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: false
});
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: true,
globalValue: false
});
// Run
const value = config.fetchAndPrune;
// Assert
expect(value).toBe(true);
});
it('Should return new global value', () => {
// Setup
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: true
});
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: false
});
// Run
const value = config.fetchAndPrune;
// Assert
expect(value).toBe(true);
});
it('Should return old global value', () => {
// Setup
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: undefined
});
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: true
});
// Run
const value = config.fetchAndPrune;
// Assert
expect(value).toBe(true);
});
it('Should return the default value', () => {
// Setup
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: undefined
});
workspaceConfiguration.inspect.mockReturnValueOnce({
workspaceValue: undefined,
globalValue: undefined
});
// Run
const value = config.fetchAndPrune;
// Assert
expect(value).toBe(false);
});
});
function testBooleanExtensionSetting(configKey: keyof Config, section: string, defaultValue: boolean) {
return () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, true);
// Run
const value = config[configKey];
// Assert
expect(workspaceConfiguration.get).toBeCalledWith(section, defaultValue);
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, false);
// Run
const value = config[configKey];
// Assert
expect(workspaceConfiguration.get).toBeCalledWith(section, defaultValue);
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, 5);
// Run
const value = config[configKey];
// Assert
expect(workspaceConfiguration.get).toBeCalledWith(section, defaultValue);
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, 0);
// Run
const value = config[configKey];
// Assert
expect(workspaceConfiguration.get).toBeCalledWith(section, defaultValue);
expect(value).toBe(false);
});
it('Should return the default value (' + (defaultValue ? 'TRUE' : 'FALSE') + ') when the configuration value is not set', () => {
// Run
const value = config[configKey];
// Assert
expect(workspaceConfiguration.get).toBeCalledWith(section, defaultValue);
expect(value).toBe(defaultValue);
});
};
}
function testRenamedBooleanExtensionSetting(configKey: keyof Config, section: string, oldSection: string, defaultValue: boolean) {
return () => {
it('Should return TRUE when the configuration value is TRUE', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, true);
// Run
const value = config[configKey];
// Assert
expectRenamedExtensionSettingToHaveBeenCalled(section, oldSection);
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is FALSE', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, false);
// Run
const value = config[configKey];
// Assert
expectRenamedExtensionSettingToHaveBeenCalled(section, oldSection);
expect(value).toBe(false);
});
it('Should return TRUE when the configuration value is truthy', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, 5);
// Run
const value = config[configKey];
// Assert
expectRenamedExtensionSettingToHaveBeenCalled(section, oldSection);
expect(value).toBe(true);
});
it('Should return FALSE when the configuration value is falsy', () => {
// Setup
vscode.mockExtensionSettingReturnValue(section, 0);
// Run
const value = config[configKey];
// Assert
expectRenamedExtensionSettingToHaveBeenCalled(section, oldSection);
expect(value).toBe(false);
});
it('Should return the default value (' + (defaultValue ? 'TRUE' : 'FALSE') + ') when the configuration value is not set', () => {
// Run
const value = config[configKey];
// Assert
expectRenamedExtensionSettingToHaveBeenCalled(section, oldSection);
expect(value).toBe(defaultValue);
});
};
}
}); | the_stack |
import { Assert, AITestClass } from "@microsoft/ai-test-framework";
import { addEventHandler, addEventListeners, createUniqueNamespace, removeEventHandler } from "../../../src/applicationinsights-core-js";
import { _InternalMessageId, LoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums";
import { _InternalLogMessage, DiagnosticLogger } from "../../../src/JavaScriptSDK/DiagnosticLogger";
import { mergeEvtNamespace, __getRegisteredEvents } from "../../../src/JavaScriptSDK/EventHelpers";
export class EventHelperTests extends AITestClass {
public testInitialize() {
super.testInitialize();
}
public testCleanup() {
super.testCleanup();
}
public registerTests() {
this.testCase({
name: "addEventHandler: add and remove test",
test: () => {
function _handler() {
// Do nothing
}
Assert.ok(addEventHandler("test", _handler, null), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, "fred");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, "fred");
_checkRegisteredAddEventHandler("test", 1);
removeEventHandler("test", _handler, null);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "addEventHandler: add and remove test with single namespace",
test: () => {
function _handler() {
// Do nothing
}
let testNamespace = createUniqueNamespace("evtHelperTests");
let test2Namespace = createUniqueNamespace("evtHelperTests");
Assert.ok(addEventHandler("test", _handler, testNamespace), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
removeEventHandler("test", _handler, testNamespace);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "addEventHandler: add with single namespace and remove only using namespace",
test: () => {
function _handler() {
// Do nothing
}
function _handler2() {
}
let testNamespace = createUniqueNamespace("evtHelperTests");
Assert.ok(addEventHandler("test", _handler, testNamespace), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// This remove should fail with invalid event and wrong handler
removeEventHandler("", _handler2, testNamespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, testNamespace + ".x");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, testNamespace + ".x");
_checkRegisteredAddEventHandler("test", 1);
// This remove should work
removeEventHandler("", null, testNamespace);
_checkRegisteredAddEventHandler("test", 0);
Assert.ok(addEventHandler("test", _handler, testNamespace), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// This remove should work
removeEventHandler(null, null, testNamespace);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "addEventHandler: add and remove test with multiple namespaces in order",
test: () => {
function _handler() {
// Do nothing
}
let testNamespace = createUniqueNamespace("AA");
let test2Namespace = createUniqueNamespace("BB");
// Add in reverse order
Assert.ok(addEventHandler("test", _handler, [test2Namespace, testNamespace]), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, testNamespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using reverse order should work
removeEventHandler("test", _handler, [ test2Namespace, testNamespace ]);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "addEventHandler: add and remove test with multiple merged namespaces",
test: () => {
function _handler() {
// Do nothing
}
let testNamespace = createUniqueNamespace("AA");
let test2Namespace = createUniqueNamespace("BB");
let evtNamespace = mergeEvtNamespace("MultipleNamespaceTest", [testNamespace, test2Namespace]);
// Add in reverse order
Assert.ok(addEventHandler("test", _handler, evtNamespace), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, testNamespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, [testNamespace, test2Namespace]);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, [test2Namespace, testNamespace]);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using reverse order should work
removeEventHandler("test", _handler, evtNamespace);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "addEventHandler: add and remove test with multiple merged namespaces and removed with a different reversed merged namespace",
test: () => {
function _handler() {
// Do nothing
}
let testNamespace = createUniqueNamespace("AA");
let test2Namespace = createUniqueNamespace("BB");
let evtNamespace = mergeEvtNamespace("MultipleNamespaceTest", [testNamespace, test2Namespace]);
let evt2Namespace = mergeEvtNamespace("MultipleNamespaceTest", [test2Namespace, testNamespace]);
// Add in reverse order
Assert.ok(addEventHandler("test", _handler, evtNamespace), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, testNamespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, [testNamespace, test2Namespace]);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, [test2Namespace, testNamespace]);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using reverse order should work
removeEventHandler("test", _handler, evt2Namespace);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "addEventHandler: add and remove test with multiple namespaces in reverse order",
test: () => {
function _handler() {
// Do nothing
}
let testNamespace = createUniqueNamespace("AA");
let test2Namespace = createUniqueNamespace("BB");
// Add in reverse order
Assert.ok(addEventHandler("test", _handler, [test2Namespace, testNamespace]), "Events added");
_checkRegisteredAddEventHandler("test", 1);
// Try removing using a different namespace which should fail
removeEventHandler("test", _handler, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", null, test2Namespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using only a different namespace which should fail
removeEventHandler("test", _handler, testNamespace);
_checkRegisteredAddEventHandler("test", 1);
// Try removing using reverse order should work
removeEventHandler("test", _handler, [ testNamespace, test2Namespace ]);
_checkRegisteredAddEventHandler("test", 0);
}
});
this.testCase({
name: "mergeEventNamespaces: Initializing different values",
test: () => {
Assert.equal(null, mergeEvtNamespace(null, null), "All null");
Assert.equal(undefined, mergeEvtNamespace(undefined, undefined), "All undefined");
Assert.equal(null, mergeEvtNamespace(null, undefined), "Null and undefined");
Assert.equal(undefined, mergeEvtNamespace(undefined, null), "Undefined and null");
Assert.equal("", mergeEvtNamespace("", undefined), "Empty and undefined");
Assert.equal("", mergeEvtNamespace("", null), "Empty and null");
Assert.equal("", mergeEvtNamespace(null, []), "null and empty array");
Assert.equal("", mergeEvtNamespace(undefined, []), "undefined and empty");
Assert.equal("", mergeEvtNamespace("", []), "undefined and empty");
Assert.equal("a", mergeEvtNamespace("a", []));
Assert.equal("b", mergeEvtNamespace(null, ["b"]));
Assert.equal("z", mergeEvtNamespace(null, ["z"]));
Assert.equal(JSON.stringify(["a", "z"]), JSON.stringify(mergeEvtNamespace("a", ["z"])));
Assert.equal(JSON.stringify(["a", "z"]), JSON.stringify(mergeEvtNamespace("z", ["a"])));
Assert.equal(JSON.stringify(["a", "b", "c", "d", "z"]), JSON.stringify(mergeEvtNamespace("z", ["d", "b", "c", "a"])));
Assert.equal(JSON.stringify(["a", "b", "c", "d", "z"]), JSON.stringify(mergeEvtNamespace("z", ["d", "b", "c", "a"])));
Assert.equal(JSON.stringify(["a", "b", "c", "d", "z"]), JSON.stringify(mergeEvtNamespace("z", "d.b.c.a")));
Assert.equal(JSON.stringify(["a", "aa", "f", "g", "x", "z"]), JSON.stringify(mergeEvtNamespace("z.a", "x.f.g.aa")));
Assert.equal(JSON.stringify(["a", "b", "c", "d", "e"]), JSON.stringify(mergeEvtNamespace("e", ["d", "b", "", "c", null, "a"])));
Assert.equal(JSON.stringify(["a", "ab", "f", "g", "x", "z"]), JSON.stringify(mergeEvtNamespace("z.a", "x.f..g.ab")));
Assert.equal(JSON.stringify(["ab", "b", "f", "g", "x", "z"]), JSON.stringify(mergeEvtNamespace("z.b.", "x.f..g.ab")));
}
});
function _checkRegisteredAddEventHandler(name: string, expected: number) {
let registered = __getRegisteredEvents(window, name);
Assert.equal(expected, registered.length, "Check that window event was registered");
if (window["body"]) {
registered = __getRegisteredEvents(window["body"], name);
Assert.equal(expected, registered.length, "Check that window.body event was registered");
}
registered = __getRegisteredEvents(document, name);
Assert.equal(expected, registered.length, "Check that document event was registered");
}
}
} | the_stack |
import {getJSON} from '../util/ajax';
import {RequestPerformance} from '../util/performance';
import rewind from '@mapbox/geojson-rewind';
import GeoJSONWrapper from './geojson_wrapper';
import vtpbf from 'vt-pbf';
import Supercluster from 'supercluster';
import geojsonvt from 'geojson-vt';
import assert from 'assert';
import VectorTileWorkerSource from './vector_tile_worker_source';
import {createExpression} from '../style-spec/expression';
import type {
WorkerTileParameters,
WorkerTileCallback,
} from '../source/worker_source';
import type Actor from '../util/actor';
import type StyleLayerIndex from '../style/style_layer_index';
import type {LoadVectorDataCallback} from './vector_tile_worker_source';
import type {RequestParameters, ResponseCallback} from '../util/ajax';
import type {Callback} from '../types/callback';
export type LoadGeoJSONParameters = {
request?: RequestParameters;
data?: string;
source: string;
cluster: boolean;
superclusterOptions?: any;
geojsonVtOptions?: any;
clusterProperties?: any;
filter?: Array<unknown>;
};
export type LoadGeoJSON = (params: LoadGeoJSONParameters, callback: ResponseCallback<any>) => void;
export interface GeoJSONIndex {
getTile(z: number, x: number, y: number): any;
// supercluster methods
getClusterExpansionZoom(clusterId: number): number;
getChildren(clusterId: number): Array<GeoJSON.Feature>;
getLeaves(clusterId: number, limit: number, offset: number): Array<GeoJSON.Feature>;
}
function loadGeoJSONTile(params: WorkerTileParameters, callback: LoadVectorDataCallback): (() => void) | void {
const canonical = params.tileID.canonical;
if (!this._geoJSONIndex) {
return callback(null, null); // we couldn't load the file
}
const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);
if (!geoJSONTile) {
return callback(null, null); // nothing in the given tile
}
const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features);
// Encode the geojson-vt tile into binary vector tile form. This
// is a convenience that allows `FeatureIndex` to operate the same way
// across `VectorTileSource` and `GeoJSONSource` data.
let pbf = vtpbf(geojsonWrapper);
if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {
// Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35)
pbf = new Uint8Array(pbf);
}
callback(null, {
vectorTile: geojsonWrapper,
rawData: pbf.buffer
});
}
export type SourceState = // Source empty or data loaded
'Idle' | // Data finished loading, but discard 'loadData' messages until receiving 'coalesced'
'Coalescing' | 'NeedsLoadData'; // 'loadData' received while coalescing, trigger one more 'loadData' on receiving 'coalesced'
/**
* The {@link WorkerSource} implementation that supports {@link GeoJSONSource}.
* This class is designed to be easily reused to support custom source types
* for data formats that can be parsed/converted into an in-memory GeoJSON
* representation. To do so, create it with
* `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`.
* For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson).
*
* @private
*/
class GeoJSONWorkerSource extends VectorTileWorkerSource {
_state: SourceState;
_pendingCallback: Callback<{
resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>};
abandoned?: boolean;
}>;
_pendingLoadDataParams: LoadGeoJSONParameters;
_geoJSONIndex: GeoJSONIndex;
/**
* @param [loadGeoJSON] Optional method for custom loading/parsing of
* GeoJSON based on parameters passed from the main-thread Source.
* See {@link GeoJSONWorkerSource#loadGeoJSON}.
* @private
*/
constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, loadGeoJSON?: LoadGeoJSON | null) {
super(actor, layerIndex, availableImages, loadGeoJSONTile);
if (loadGeoJSON) {
this.loadGeoJSON = loadGeoJSON;
}
}
/**
* Fetches (if appropriate), parses, and index geojson data into tiles. This
* preparatory method must be called before {@link GeoJSONWorkerSource#loadTile}
* can correctly serve up tiles.
*
* Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching/parsing,
* expecting `callback(error, data)` to be called with either an error or a
* parsed GeoJSON object.
*
* When `loadData` requests come in faster than they can be processed,
* they are coalesced into a single request using the latest data.
* See {@link GeoJSONWorkerSource#coalesce}
*
* @param params
* @param callback
* @private
*/
loadData(params: LoadGeoJSONParameters, callback: Callback<{
resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>};
abandoned?: boolean;
}>) {
if (this._pendingCallback) {
// Tell the foreground the previous call has been abandoned
this._pendingCallback(null, {abandoned: true});
}
this._pendingCallback = callback;
this._pendingLoadDataParams = params;
if (this._state &&
this._state !== 'Idle') {
this._state = 'NeedsLoadData';
} else {
this._state = 'Coalescing';
this._loadData();
}
}
/**
* Internal implementation: called directly by `loadData`
* or by `coalesce` using stored parameters.
*/
_loadData() {
if (!this._pendingCallback || !this._pendingLoadDataParams) {
assert(false);
return;
}
const callback = this._pendingCallback;
const params = this._pendingLoadDataParams;
delete this._pendingCallback;
delete this._pendingLoadDataParams;
const perf = (params && params.request && params.request.collectResourceTiming) ?
new RequestPerformance(params.request) : false;
this.loadGeoJSON(params, (err?: Error | null, data?: any | null) => {
if (err || !data) {
return callback(err);
} else if (typeof data !== 'object') {
return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));
} else {
rewind(data, true);
try {
if (params.filter) {
const compiled = createExpression(params.filter, {type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false} as any);
if (compiled.result === 'error')
throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));
const features = data.features.filter(feature => compiled.value.evaluate({zoom: 0}, feature));
data = {type: 'FeatureCollection', features};
}
this._geoJSONIndex = params.cluster ?
new Supercluster(getSuperclusterOptions(params)).load(data.features) :
geojsonvt(data, params.geojsonVtOptions);
} catch (err) {
return callback(err);
}
this.loaded = {};
const result = {} as { resourceTiming: any };
if (perf) {
const resourceTimingData = perf.finish();
// it's necessary to eval the result of getEntriesByName() here via parse/stringify
// late evaluation in the main thread causes TypeError: illegal invocation
if (resourceTimingData) {
result.resourceTiming = {};
result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData));
}
}
callback(null, result);
}
});
}
/**
* While processing `loadData`, we coalesce all further
* `loadData` messages into a single call to _loadData
* that will happen once we've finished processing the
* first message. {@link GeoJSONSource#_updateWorkerData}
* is responsible for sending us the `coalesce` message
* at the time it receives a response from `loadData`
*
* State: Idle
* ↑ |
* 'coalesce' 'loadData'
* | (triggers load)
* | ↓
* State: Coalescing
* ↑ |
* (triggers load) |
* 'coalesce' 'loadData'
* | ↓
* State: NeedsLoadData
*/
coalesce() {
if (this._state === 'Coalescing') {
this._state = 'Idle';
} else if (this._state === 'NeedsLoadData') {
this._state = 'Coalescing';
this._loadData();
}
}
/**
* Implements {@link WorkerSource#reloadTile}.
*
* If the tile is loaded, uses the implementation in VectorTileWorkerSource.
* Otherwise, such as after a setData() call, we load the tile fresh.
*
* @param params
* @param params.uid The UID for this tile.
* @private
*/
reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {
const loaded = this.loaded,
uid = params.uid;
if (loaded && loaded[uid]) {
return super.reloadTile(params, callback);
} else {
return this.loadTile(params, callback);
}
}
/**
* Fetch and parse GeoJSON according to the given params. Calls `callback`
* with `(err, data)`, where `data` is a parsed GeoJSON object.
*
* GeoJSON is loaded and parsed from `params.url` if it exists, or else
* expected as a literal (string or object) `params.data`.
*
* @param params
* @param [params.url] A URL to the remote GeoJSON data.
* @param [params.data] Literal GeoJSON data. Must be provided if `params.url` is not.
* @private
*/
loadGeoJSON(params: LoadGeoJSONParameters, callback: ResponseCallback<any>) {
// Because of same origin issues, urls must either include an explicit
// origin or absolute path.
// ie: /foo/bar.json or http://example.com/bar.json
// but not ../foo/bar.json
if (params.request) {
getJSON(params.request, callback);
} else if (typeof params.data === 'string') {
try {
return callback(null, JSON.parse(params.data));
} catch (e) {
return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));
}
} else {
return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));
}
}
removeSource(params: {
source: string;
}, callback: WorkerTileCallback) {
if (this._pendingCallback) {
// Don't leak callbacks
this._pendingCallback(null, {abandoned: true});
}
callback();
}
getClusterExpansionZoom(params: {
clusterId: number;
}, callback: Callback<number>) {
try {
callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId));
} catch (e) {
callback(e);
}
}
getClusterChildren(params: {
clusterId: number;
}, callback: Callback<Array<GeoJSON.Feature>>) {
try {
callback(null, this._geoJSONIndex.getChildren(params.clusterId));
} catch (e) {
callback(e);
}
}
getClusterLeaves(params: {
clusterId: number;
limit: number;
offset: number;
}, callback: Callback<Array<GeoJSON.Feature>>) {
try {
callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset));
} catch (e) {
callback(e);
}
}
}
function getSuperclusterOptions({superclusterOptions, clusterProperties}: { superclusterOptions?: any; clusterProperties?: any}) {
if (!clusterProperties || !superclusterOptions) return superclusterOptions;
const mapExpressions = {};
const reduceExpressions = {};
const globals = {accumulated: null, zoom: 0};
const feature = {properties: null};
const propertyNames = Object.keys(clusterProperties);
for (const key of propertyNames) {
const [operator, mapExpression] = clusterProperties[key];
const mapExpressionParsed = createExpression(mapExpression);
const reduceExpressionParsed = createExpression(
typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator);
assert(mapExpressionParsed.result === 'success');
assert(reduceExpressionParsed.result === 'success');
mapExpressions[key] = mapExpressionParsed.value;
reduceExpressions[key] = reduceExpressionParsed.value;
}
superclusterOptions.map = (pointProperties) => {
feature.properties = pointProperties;
const properties = {};
for (const key of propertyNames) {
properties[key] = mapExpressions[key].evaluate(globals, feature);
}
return properties;
};
superclusterOptions.reduce = (accumulated, clusterProperties) => {
feature.properties = clusterProperties;
for (const key of propertyNames) {
globals.accumulated = accumulated[key];
accumulated[key] = reduceExpressions[key].evaluate(globals, feature);
}
};
return superclusterOptions;
}
export default GeoJSONWorkerSource; | the_stack |
import { Directionality } from '@angular/cdk/bidi';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { ESCAPE, UP_ARROW } from '@angular/cdk/keycodes';
import { Overlay, OverlayConfig, OverlayRef, PositionStrategy, ScrollStrategy } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { DOCUMENT } from '@angular/common';
import { ChangeDetectionStrategy, Component, ComponentRef, ElementRef, EventEmitter, Inject, InjectionToken, Input, NgZone, OnDestroy, OnInit, Optional, Output, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { CanColor, CanColorCtor, mixinColor, ThemePalette } from '@angular/material/core';
import { matDatepickerAnimations } from '@angular/material/datepicker';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { merge, Subject, Subscription } from 'rxjs';
import { filter, take } from 'rxjs/operators';
import { Color } from '../../models';
import { ColorAdapter } from '../../services';
import { NgxMatColorPaletteComponent } from '../color-palette/color-palette.component';
import { NgxMatColorPickerInput } from './color-input.component';
/** Injection token that determines the scroll handling while the calendar is open. */
export const NGX_MAT_COLOR_PICKER_SCROLL_STRATEGY =
new InjectionToken<() => ScrollStrategy>('ngx-mat-colorpicker-scroll-strategy');
export function NGX_MAT_COLOR_PICKER_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
export const NGX_MAT_COLOR_PICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: NGX_MAT_COLOR_PICKER_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: NGX_MAT_COLOR_PICKER_SCROLL_STRATEGY_FACTORY,
};
class NgxMatColorPickerContentBase {
constructor(public _elementRef: ElementRef) { }
}
const _MatDatepickerContentMixinBase: CanColorCtor & typeof NgxMatColorPickerContentBase =
mixinColor(NgxMatColorPickerContentBase);
@Component({
selector: 'ngx-mat-color-picker-content',
templateUrl: './color-picker-content.component.html',
styleUrls: ['color-picker-content.component.scss'],
host: {
'class': 'ngx-mat-colorpicker-content',
'[@transformPanel]': '"enter"',
'[class.ngx-mat-colorpicker-content-touch]': 'picker.touchUi',
},
animations: [
matDatepickerAnimations.transformPanel,
matDatepickerAnimations.fadeInCalendar,
],
exportAs: 'ngxMatColorPickerContent',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
inputs: ['color']
})
export class NgxMatColorPickerContentComponent extends _MatDatepickerContentMixinBase
implements CanColor {
/** Reference to the internal calendar component. */
@ViewChild(NgxMatColorPaletteComponent) _palette: NgxMatColorPaletteComponent;
picker: NgxMatColorPickerComponent;
_isAbove: boolean;
constructor(elementRef: ElementRef) {
super(elementRef);
}
}
@Component({
selector: 'ngx-mat-color-picker',
template: '',
exportAs: 'ngxMatColorPicker',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class NgxMatColorPickerComponent implements OnInit, OnDestroy, CanColor {
private _scrollStrategy: () => ScrollStrategy;
/** Emits when the datepicker has been opened. */
@Output('opened') openedStream: EventEmitter<void> = new EventEmitter<void>();
/** Emits when the datepicker has been closed. */
@Output('closed') closedStream: EventEmitter<void> = new EventEmitter<void>();
@Input() get disabled() {
return this._disabled === undefined && this._pickerInput ?
this._pickerInput.disabled : !!this._disabled;
}
set disabled(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._disabled) {
this._disabled = newValue;
this._disabledChange.next(newValue);
}
}
private _disabled: boolean;
@Input()
get touchUi(): boolean { return this._touchUi; }
set touchUi(value: boolean) {
this._touchUi = coerceBooleanProperty(value);
}
private _touchUi = false;
/** Whether the calendar is open. */
@Input()
get opened(): boolean { return this._opened; }
set opened(value: boolean) { value ? this.open() : this.close(); }
private _opened = false;
/** Color palette to use on the datepicker's calendar. */
@Input()
get color(): ThemePalette {
return this._color ||
(this._pickerInput ? this._pickerInput.getThemePalette() : undefined);
}
set color(value: ThemePalette) {
this._color = value;
}
_color: ThemePalette;
/** The currently selected date. */
get _selected(): Color { return this._validSelected; }
set _selected(value: Color) { this._validSelected = value; }
private _validSelected: Color = null;
_pickerInput: NgxMatColorPickerInput;
/** A reference to the overlay when the picker is opened as a popup. */
_popupRef: OverlayRef;
/** A reference to the dialog when the picker is opened as a dialog. */
private _dialogRef: MatDialogRef<NgxMatColorPickerContentComponent> | null;
/** Reference to the component instantiated in popup mode. */
private _popupComponentRef: ComponentRef<NgxMatColorPickerContentComponent> | null;
/** A portal containing the content for this picker. */
private _portal: ComponentPortal<NgxMatColorPickerContentComponent>;
/** Emits when the datepicker is disabled. */
readonly _disabledChange = new Subject<boolean>();
/** The element that was focused before the datepicker was opened. */
private _focusedElementBeforeOpen: HTMLElement | null = null;
/** Subscription to value changes in the associated input element. */
private _inputSubscription = Subscription.EMPTY;
/** Emits new selected date when selected date changes. */
readonly _selectedChanged = new Subject<Color>();
constructor(private _dialog: MatDialog,
private _overlay: Overlay,
private _zone: NgZone,
private _adapter: ColorAdapter,
@Optional() private _dir: Directionality,
@Inject(NGX_MAT_COLOR_PICKER_SCROLL_STRATEGY) scrollStrategy: any,
@Optional() @Inject(DOCUMENT) private _document: any,
private _viewContainerRef: ViewContainerRef) {
this._scrollStrategy = scrollStrategy;
}
ngOnInit() {
}
ngOnDestroy() {
this.close();
this._inputSubscription.unsubscribe();
this._disabledChange.complete();
if (this._popupRef) {
this._popupRef.dispose();
this._popupComponentRef = null;
}
}
/** Selects the given date */
select(nextVal: Color): void {
let oldValue = this._selected;
this._selected = nextVal;
if (!this._adapter.sameColor(oldValue, this._selected)) {
this._selectedChanged.next(nextVal);
}
}
/**
* Register an input with this datepicker.
* @param input The datepicker input to register with this datepicker.
*/
registerInput(input: NgxMatColorPickerInput): void {
if (this._pickerInput) {
throw Error('A ColorPicker can only be associated with a single input.');
}
this._pickerInput = input;
this._inputSubscription =
this._pickerInput._valueChange.subscribe((value: Color) => this._selected = value);
}
public open(): void {
if (this._opened || this.disabled) {
return;
}
if (!this._pickerInput) {
throw Error('Attempted to open an ColorPicker with no associated input.');
}
if (this._document) {
this._focusedElementBeforeOpen = this._document.activeElement;
}
this.touchUi ? this._openAsDialog() : this._openAsPopup();
this._opened = true;
this.openedStream.emit();
}
/** Open the calendar as a dialog. */
private _openAsDialog(): void {
if (this._dialogRef) {
this._dialogRef.close();
}
this._dialogRef = this._dialog.open<NgxMatColorPickerContentComponent>(NgxMatColorPickerContentComponent, {
direction: this._dir ? this._dir.value : 'ltr',
viewContainerRef: this._viewContainerRef,
panelClass: 'ngx-mat-colorpicker-dialog',
});
this._dialogRef.afterClosed().subscribe(() => this.close());
this._dialogRef.componentInstance.picker = this;
this._setColor();
}
/** Open the calendar as a popup. */
private _openAsPopup(): void {
if (!this._portal) {
this._portal = new ComponentPortal<NgxMatColorPickerContentComponent>(NgxMatColorPickerContentComponent,
this._viewContainerRef);
}
if (!this._popupRef) {
this._createPopup();
}
if (!this._popupRef.hasAttached()) {
this._popupComponentRef = this._popupRef.attach(this._portal);
this._popupComponentRef.instance.picker = this;
this._setColor();
// Update the position once the calendar has rendered.
this._zone.onStable.asObservable().pipe(take(1)).subscribe(() => {
this._popupRef.updatePosition();
});
}
}
/** Create the popup. */
private _createPopup(): void {
const overlayConfig = new OverlayConfig({
positionStrategy: this._createPopupPositionStrategy(),
hasBackdrop: true,
backdropClass: 'mat-overlay-transparent-backdrop',
direction: this._dir,
scrollStrategy: this._scrollStrategy(),
panelClass: 'mat-colorpicker-popup',
});
this._popupRef = this._overlay.create(overlayConfig);
this._popupRef.overlayElement.setAttribute('role', 'dialog');
merge(
this._popupRef.backdropClick(),
this._popupRef.detachments(),
this._popupRef.keydownEvents().pipe(filter(event => {
// Closing on alt + up is only valid when there's an input associated with the datepicker.
return event.keyCode === ESCAPE ||
(this._pickerInput && event.altKey && event.keyCode === UP_ARROW);
}))
).subscribe(event => {
if (event) {
event.preventDefault();
}
this.close();
});
}
close(): void {
if (!this._opened) {
return;
}
if (this._popupRef && this._popupRef.hasAttached()) {
this._popupRef.detach();
}
if (this._dialogRef) {
this._dialogRef.close();
this._dialogRef = null;
}
if (this._portal && this._portal.isAttached) {
this._portal.detach();
}
const completeClose = () => {
// The `_opened` could've been reset already if
// we got two events in quick succession.
if (this._opened) {
this._opened = false;
this.closedStream.emit();
this._focusedElementBeforeOpen = null;
}
};
if (this._focusedElementBeforeOpen &&
typeof this._focusedElementBeforeOpen.focus === 'function') {
// Because IE moves focus asynchronously, we can't count on it being restored before we've
// marked the datepicker as closed. If the event fires out of sequence and the element that
// we're refocusing opens the datepicker on focus, the user could be stuck with not being
// able to close the calendar at all. We work around it by making the logic, that marks
// the datepicker as closed, async as well.
this._focusedElementBeforeOpen.focus();
setTimeout(completeClose);
} else {
completeClose();
}
}
/** Passes the current theme color along to the calendar overlay. */
private _setColor(): void {
const color = this.color;
if (this._popupComponentRef) {
this._popupComponentRef.instance.color = color;
}
if (this._dialogRef) {
this._dialogRef.componentInstance.color = color;
}
}
/** Create the popup PositionStrategy. */
private _createPopupPositionStrategy(): PositionStrategy {
return this._overlay.position()
.flexibleConnectedTo(this._pickerInput.getConnectedOverlayOrigin())
.withTransformOriginOn('.ngx-mat-colorpicker-content')
.withFlexibleDimensions(false)
.withViewportMargin(8)
.withLockedPosition()
.withPositions([
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
}
]);
}
} | the_stack |
import { BoardType, CostumeType, View } from "../types";
import { getCurrentBoard, IBoard, boardIsROM, currentBoardIsROM, BoardAudioType, IBoardAudioData, setBoardName, setBoardDescription, setBoardDifficulty, setBoardOtherBackground, setBoardAudio, IBoardAudioChanges, setBoardCostumeTypeIndex } from "../boards";
import * as React from "react";
import { make8Bit } from "../utils/img/RGBA32";
import { MPEditor, MPEditorDisplayMode } from "../texteditor";
import { openFile } from "../utils/input";
import { arrayBufferToDataURL } from "../utils/arrays";
import { getAdapter } from "../adapter/adapters";
import { changeView, promptUser, refresh, showMessage } from "../app/appControl";
import { getImageData } from "../utils/img/getImageData";
import { audio } from "../fs/audio";
import { assert } from "../utils/debug";
import { romhandler } from "../romhandler";
import { $setting, get } from "./settings";
import { DetailsBoardStats } from "./details/stats";
import "../css/details.scss";
import editImage from "../img/audio/edit.png";
import audioImage from "../img/details/audio.png";
import deleteImage from "../img/details/delete.png";
import audioConfigImage from "../img/details/audioconfig.png";
import { IToggleItem, ToggleGroup } from "../controls";
type DetailsType = "image" | "richtext" | "audio" | "difficulty" | "header" | "audioheader" | "stats" | "costume" | "br";
interface IDetailsItemBase {
type: DetailsType;
id?: string;
desc?: string;
maxlines?: number;
width?: number;
height?: number;
}
const _details_mp1: IDetailsItemBase[] = [
{ type: "header", desc: "Basic Info" },
{ type: "richtext", id: "detailBoardName", desc: "Board name", maxlines: 1 },
{ type: "richtext", id: "detailBoardDesc", desc: "Board description", maxlines: 2 },
{ type: "difficulty", id: "detailBoardDifficulty", desc: "Difficulty" },
{ type: "audioheader", desc: "Background Music" },
{ type: "audio", id: "detailBoardAudio", desc: "Background music" },
{ type: "header", desc: "Images" },
{ type: "image", id: "detailBoardSelectImg", desc: "Board select image", width: 128, height: 64 },
{ type: "image", id: "detailBoardLogoImg", desc: "Board logo", width: 250, height: 100 },
{ type: "br" },
{ type: "image", id: "detailBoardLargeSceneBg", desc: "Large scene background", width: 320, height: 240 },
{ type: "image", id: "detailBoardConversationBg", desc: "Conversation background", width: 320, height: 240 },
{ type: "image", id: "detailBoardSplashscreenBg", desc: "Splashscreen background", width: 320, height: 240 },
{ type: "header", desc: "Stats" },
{ type: "stats" },
];
const _details_mp2: IDetailsItemBase[] = [
{ type: "header", desc: "Basic Info" },
{ type: "richtext", id: "detailBoardName", desc: "Board name", maxlines: 1 },
{ type: "richtext", id: "detailBoardDesc", desc: "Board description", maxlines: 2 },
{ type: "difficulty", id: "detailBoardDifficulty", desc: "Difficulty" },
{ type: "costume", id: "detailBoardCostume", desc: "Costume Theme" },
{ type: "audioheader", desc: "Background Music" },
{ type: "audio", id: "detailBoardAudio", desc: "Background music" },
{ type: "header", desc: "Images" },
{ type: "image", id: "detailBoardSelectImg", desc: "Board select image", width: 64, height: 48 },
{ type: "image", id: "detailBoardSelectIcon", desc: "Board select icon", width: 32, height: 32 },
{ type: "image", id: "detailBoardLogoImg", desc: "Board logo", width: 260, height: 120 },
{ type: "br" },
{ type: "image", id: "detailBoardLargeSceneBg", desc: "Large scene background", width: 320, height: 240 },
{ type: "header", desc: "Stats" },
{ type: "stats" },
];
const _details_mp3: IDetailsItemBase[] = [
{ type: "header", desc: "Basic Info" },
{ type: "richtext", id: "detailBoardName", desc: "Board name", maxlines: 1 },
{ type: "richtext", id: "detailBoardDesc", desc: "Board description", maxlines: 2 },
{ type: "difficulty", id: "detailBoardDifficulty", desc: "Difficulty" },
{ type: "audioheader", desc: "Background Music" },
{ type: "audio", id: "detailBoardAudio", desc: "Background music" },
{ type: "header", desc: "Images" },
{ type: "image", id: "detailBoardSelectImg", desc: "Board select image", width: 64, height: 64 },
{ type: "image", id: "detailBoardLogoImg", desc: "Board logo", width: 226, height: 120 },
{ type: "image", id: "detailBoardLogoTextImg", desc: "Board logo text", width: 226, height: 36 },
{ type: "br" },
{ type: "image", id: "detailBoardLargeSceneBg", desc: "Large scene background", width: 320, height: 240 },
{ type: "header", desc: "Stats" },
{ type: "stats" },
];
const _details_mp3_duel: IDetailsItemBase[] = [
{ type: "header", desc: "Basic Info" },
{ type: "richtext", id: "detailBoardName", desc: "Board name", maxlines: 1 },
{ type: "richtext", id: "detailBoardDesc", desc: "Board description", maxlines: 2 },
{ type: "difficulty", id: "detailBoardDifficulty", desc: "Difficulty" },
{ type: "header", desc: "Background Music" },
{ type: "audio", id: "detailBoardAudio", desc: "Background music" },
{ type: "header", desc: "Images" },
{ type: "image", id: "detailBoardSelectImg", desc: "Board select image", width: 64, height: 64 },
{ type: "image", id: "detailBoardLogoImg", desc: "Board logo", width: 226, height: 120 },
{ type: "image", id: "detailBoardLogoTextImg", desc: "Board logo text", width: 226, height: 36 },
];
function _getGameDetails(): IDetailsItemBase[] {
const board = getCurrentBoard();
const gameVersion = board.game;
const boardType = board.type;
switch (gameVersion) {
case 1:
return _details_mp1;
case 2:
return _details_mp2;
case 3:
switch (boardType) {
case BoardType.DUEL:
return _details_mp3_duel;
default:
return _details_mp3;
}
}
}
function _getValue(id: string | undefined, props: IDetailsProps) {
switch (id) {
case "detailBoardName":
return props.board.name;
case "detailBoardDesc":
return props.board.description;
case "detailBoardDifficulty":
return props.board.difficulty;
case "detailBoardCostume":
return props.board.costumeTypeIndex;
case "detailBoardSelectImg":
return props.board.otherbg.boardselect;
case "detailBoardSelectIcon":
return props.board.otherbg.boardselecticon;
case "detailBoardLogoImg":
return props.board.otherbg.boardlogo;
case "detailBoardLogoTextImg":
return props.board.otherbg.boardlogotext;
case "detailBoardAudio":
return props.board.audioIndex;
case "detailBoardLargeSceneBg":
return props.board.otherbg.largescene;
case "detailBoardConversationBg":
return props.board.otherbg.conversation;
case "detailBoardSplashscreenBg":
return props.board.otherbg.splashscreen;
}
return "";
}
function _setValue(id: string, value: any, board: IBoard) {
switch (id) {
case "detailBoardName":
setBoardName(value);
refresh();
break;
case "detailBoardDesc":
setBoardDescription(value);
break;
case "detailBoardDifficulty":
setBoardDifficulty(value);
break;
case "detailBoardCostume":
setBoardCostumeTypeIndex(value);
break;
case "detailBoardSelectImg":
setBoardOtherBackground("boardselect", value);
break;
case "detailBoardSelectIcon":
setBoardOtherBackground("boardselecticon", value);
break;
case "detailBoardLogoImg":
setBoardOtherBackground("boardlogo", value);
break;
case "detailBoardLogoTextImg":
setBoardOtherBackground("boardlogotext", value);
break;
case "detailBoardLargeSceneBg":
setBoardOtherBackground("largescene", value);
break;
case "detailBoardConversationBg":
setBoardOtherBackground("conversation", value);
break;
case "detailBoardSplashscreenBg":
setBoardOtherBackground("splashscreen", value);
break;
case "detailBoardAudio":
const audioChanges = value as IBoardAudioChanges;
setBoardAudio(audioChanges);
refresh();
break;
}
}
function _processImage(id: string, buffer: ArrayBuffer) {
if (id === "detailBoardSelectImg" && getCurrentBoard().game === 1) { // Apply masking
let rgba32 = new Uint32Array(buffer);
// Do the two full rows on each edge...
for (let y = 0; y < 128; y++) {
rgba32[y] = 0; // 1st row
rgba32[y + 128] = 0; // 2nd row
rgba32[y + (128 * 62)] = 0; // 2nd to last row
rgba32[y + (128 * 63)] = 0; // last row
}
// Then round the corners
for (let y = 0; y < 6; y++) {
rgba32[y + (128 * 2)] = 0; // Upper left corner
rgba32[y + (128 * 2) + 122] = 0; // Upper right corner
rgba32[y + (128 * 61)] = 0; // Lower left corner
rgba32[y + (128 * 61) + 122] = 0; // Lower right corner
}
for (let y = 0; y < 4; y++) {
rgba32[y + (128 * 3)] = 0; // Upper left corner
rgba32[y + (128 * 3) + 124] = 0; // Upper right corner
rgba32[y + (128 * 60)] = 0; // Lower left corner
rgba32[y + (128 * 60) + 124] = 0; // Lower right corner
}
for (let y = 0; y < 3; y++) {
rgba32[y + (128 * 4)] = 0; // Upper left corner
rgba32[y + (128 * 4) + 125] = 0; // Upper right corner
rgba32[y + (128 * 59)] = 0; // Lower left corner
rgba32[y + (128 * 59) + 125] = 0; // Lower right corner
}
for (let y = 0; y < 2; y++) {
rgba32[y + (128 * 5)] = 0; // Upper left corner
rgba32[y + (128 * 5) + 126] = 0; // Upper right corner
rgba32[y + (128 * 58)] = 0; // Lower left corner
rgba32[y + (128 * 58) + 126] = 0; // Lower right corner
rgba32[y + (128 * 6)] = 0; // Upper left corner
rgba32[y + (128 * 6) + 126] = 0; // Upper right corner
rgba32[y + (128 * 57)] = 0; // Lower left corner
rgba32[y + (128 * 57) + 126] = 0; // Lower right corner
}
rgba32[(128 * 7)] = 0; // Upper left corner
rgba32[(128 * 7) + 127] = 0; // Upper right corner
rgba32[(128 * 56)] = 0; // Lower left corner
rgba32[(128 * 56) + 127] = 0; // Lower right corner
rgba32[(128 * 8)] = 0; // Upper left corner
rgba32[(128 * 8) + 127] = 0; // Upper right corner
rgba32[(128 * 55)] = 0; // Lower left corner
rgba32[(128 * 55) + 127] = 0; // Lower right corner
// Validate that the image meets the color limits
// Technically this is 256 colors when split into 4 tiles
let colors: { [color: number]: boolean } = {};
for (let y = 0; y < 32; y++) {
for (let x = 0; x < 64; x++) {
colors[rgba32[(y * 128) + x]] = true;
}
}
let colors2: { [color: number]: boolean } = {};
for (let y = 0; y < 32; y++) {
for (let x = 64; x < 128; x++) {
colors2[rgba32[(y * 128) + 64 + x]] = true;
}
}
let colors3: { [color: number]: boolean } = {};
for (let y = 32; y < 64; y++) {
for (let x = 0; x < 64; x++) {
colors3[rgba32[(y * 128) + x]] = true;
}
}
let colors4: { [color: number]: boolean } = {};
for (let y = 32; y < 64; y++) {
for (let x = 64; x < 128; x++) {
colors4[rgba32[(y * 128) + 64 + x]] = true;
}
}
if (Object.keys(colors).length > 256 || Object.keys(colors2).length > 256 ||
Object.keys(colors3).length > 256 || Object.keys(colors4).length > 256) {
showMessage(`Sorry, but the palette limit for this image is 256 unique colors. For now, the image has been reduced to 8-bit, but most image editors should be able to reduce the palette for you with higher quality.`);
make8Bit(rgba32, 128, 64);
}
}
return buffer;
}
interface IDetailsProps {
board: IBoard;
}
export class Details extends React.Component<IDetailsProps> {
state = {}
onTextChange = (id: string, event: any) => {
_setValue(id, event.target.value, this.props.board);
this.forceUpdate();
}
onRichTextChange = (id: string, value: any) => {
_setValue(id, value, this.props.board);
this.forceUpdate();
}
onValueChange = (id: string, value: any) => {
_setValue(id, value, this.props.board);
this.forceUpdate();
}
render() {
if (!this.props.board)
return null;
let keyId = 0;
let readonly = boardIsROM(this.props.board);
let formEls = _getGameDetails().map(detail => {
let value = _getValue(detail.id, this.props);
switch (detail.type) {
case "richtext":
const displayMode = readonly
? MPEditorDisplayMode.Readonly
: MPEditorDisplayMode.Edit;
return (
<div className="detailRichTextContainer" key={detail.id}>
<label htmlFor={detail.id}>{detail.desc}</label>
<MPEditor id={detail.id}
value={value as string}
showToolbar={!readonly}
displayMode={displayMode}
maxlines={detail.maxlines || 0}
itemBlacklist={["COLOR", "ADVANCED", "DARKLIGHT"]}
onValueChange={this.onRichTextChange} />
</div>
);
case "image":
return (
<DetailsImage id={detail.id!} desc={detail.desc!} readonly={readonly}
value={value as string} key={detail.id} onImageSelected={this.onValueChange}
width={detail.width!} height={detail.height!} />
);
case "audio":
return (
<DetailsAudio id={detail.id!} desc={detail.desc!} readonly={readonly}
value={value as number} key={detail.id}
onAudioSelected={this.onValueChange}
onAudioDeleted={(id, index) => this.onValueChange(id, { customAudioIndex: index, delete: true })}/>
);
case "difficulty":
return (
<DetailsDifficulty id={detail.id!} desc={detail.desc!} readonly={readonly}
value={value} key={detail.id} onDifficultySelected={this.onValueChange} />
);
case "costume":
return (
<DetailsCostumeType id={detail.id!} desc={detail.desc!} readonly={readonly}
costumeType={value as CostumeType} key={detail.id} onCostumeTypeSelected={type => this.onValueChange(detail.id!, type)} />
);
case "stats":
return (
<DetailsBoardStats key={"stats" + keyId++} />
);
case "header":
return (
<h2 key={"header" + keyId++}>{detail.desc!}</h2>
);
case "audioheader":
return (
<div key={"header" + keyId++} className="detailsAudioHeaderDiv">
<h2 className="detailsAudioHeader">
{detail.desc!}
<AudioSelectionConfigButton board={this.props.board} />
</h2>
</div>
);
case "br":
return (
<br key={"br" + keyId++} />
);
}
return null;
});
return (
<div id="detailsForm">
{formEls}
</div>
);
}
};
interface IDetailsImageProps {
id: string;
desc: string;
readonly: boolean;
width: number;
height: number;
value: string;
onImageSelected(id: string, src: string): any;
}
class DetailsImage extends React.Component<IDetailsImageProps> {
handleClick = () => {
if (currentBoardIsROM())
return;
openFile("image/*", this.imageSelected.bind(this));
}
imageSelected(event: any) {
let file = event.target.files[0];
if (!file)
return;
const reader = new FileReader();
reader.onload = async e => {
const onImageSelected = this.props.onImageSelected;
const id = this.props.id;
const detailImg = document.getElementById(id) as HTMLImageElement;
const width = this.props.width;
const height = this.props.height;
const imgData = await getImageData(reader.result as string, width, height);
let rgba32 = imgData.data.buffer;
// Extra level of indirection so we can manipulate the image sometimes.
rgba32 = _processImage(id, rgba32);
const newSrc = arrayBufferToDataURL(rgba32, width, height);
detailImg.src = newSrc;
onImageSelected(id, newSrc);
};
reader.readAsDataURL(file);
}
render() {
let id = this.props.id;
let desc = this.props.desc;
let width = this.props.width;
let height = this.props.height;
let hoverCover = null;
if (!this.props.readonly) {
let hoverCoverSize = `${width} × ${height}`;
if (width > 100 && height > 50) {
let hoverCoverMsg = "Choose a new image";
hoverCover = (
<div className="detailImgHoverCover">
<span>{hoverCoverMsg}</span><br />
<span className="detailImgHoverCoverSize">{hoverCoverSize}</span>
</div>
);
}
else {
hoverCover = (
<div className="detailImgHoverCover" title={hoverCoverSize}></div>
);
}
}
let imgSelectStyle = { width, height, minWidth: width, minHeight: height };
return (
<div className="detailImgContainer">
<label>{desc}</label>
<div className="detailImgSelect" style={imgSelectStyle} onClick={this.handleClick}>
<img id={id} className="detailImg"
height={height} width={width} style={imgSelectStyle}
src={this.props.value} alt={desc} />
{hoverCover}
</div>
</div>
);
}
};
interface IDetailsAudioProps {
id: string;
desc: string;
readonly: boolean;
value: number;
onAudioSelected(id: string, changes: IBoardAudioChanges): any;
onAudioDeleted(id: string, customAudioIndex: number): void;
}
class DetailsAudio extends React.Component<IDetailsAudioProps> {
state = {}
onGameMusicIndexSelection = (e: any) => {
this.props.onAudioSelected(this.props.id, {
gameAudioIndex: parseInt(e.target.value)
});
}
onAudioTypeChanged = (audioType: BoardAudioType) => {
this.props.onAudioSelected(this.props.id, {
audioType
});
}
onMidiPrompt = async (customAudioIndex: number) => {
openFile("audio/midi", (event: any) => {
const file = event.target.files[0];
if (!file)
return;
const reader = new FileReader();
reader.onload = error => {
assert(typeof reader.result === "string");
this.props.onAudioSelected(this.props.id, {
customAudioIndex,
midiName: file.name,
midiData: reader.result,
});
};
reader.readAsDataURL(file);
});
}
onSoundbankIndexPrompt = async (customAudioIndex: number) => {
let upperBound = 0;
if (romhandler.romIsLoaded() && romhandler.getGameVersion() === getCurrentBoard().game) {
const seqTable = audio.getSequenceTable(0)!;
upperBound = seqTable.soundbanks.banks.length - 1;
}
return await promptUser(`Enter new soundbank index${upperBound ? ` (0 through ${upperBound})` : ""}:`).then(value => {
if (!value) {
return;
}
const newSoundbankIndex = parseInt(value);
if (isNaN(newSoundbankIndex) || (upperBound && newSoundbankIndex > upperBound)) {
showMessage("Invalid soundbank index.");
return;
}
this.props.onAudioSelected(this.props.id, {
customAudioIndex,
soundbankIndex: newSoundbankIndex
});
});
}
onDeleteAudioEntry = (customAudioIndex: number) => {
this.props.onAudioDeleted(this.props.id, customAudioIndex);
}
render() {
const currentBoard = getCurrentBoard();
let audioInputUI;
switch (currentBoard.audioType) {
case BoardAudioType.InGame:
let index = 0;
let audioNames = getAdapter(currentBoard.game)!.getAudioMap(0);
let audioOptions = audioNames.map((song: string) => {
let curIndex = index++;
if (!song)
return null;
return (
<option value={curIndex} key={curIndex}>{song}</option>
);
});
audioInputUI = (
<select className="audioSelect" value={this.props.value}
disabled={this.props.readonly} onChange={this.onGameMusicIndexSelection}>
{audioOptions}
</select>
);
break;
case BoardAudioType.Custom:
audioInputUI = currentBoard.audioData!.map((audioEntry, i) => (
<DetailsCustomAudioEntry
key={i + audioEntry.name}
audioEntry={audioEntry}
canDelete
onDeleteAudioEntry={() => this.onDeleteAudioEntry(i)}
onMidiPrompt={() => this.onMidiPrompt(i)}
onSoundbankIndexPrompt={() => this.onSoundbankIndexPrompt(i)} />
));
audioInputUI.push(
<DetailsCustomAudioEntry
key="newentry"
audioEntry={{
name: "",
data: "",
soundbankIndex: 0
}}
canDelete={false}
onMidiPrompt={() => this.onMidiPrompt(currentBoard.audioData!.length)}
onSoundbankIndexPrompt={() => this.onSoundbankIndexPrompt(currentBoard.audioData!.length)} />
)
break;
}
return (
<div className="audioDetailsContainer">
<div className="audioDetailsRadioGroup">
<input type="radio" id={this.props.id + "-romaudio"} value="romaudio"
checked={currentBoard.audioType === BoardAudioType.InGame}
onChange={() => this.onAudioTypeChanged(BoardAudioType.InGame)} />
<label htmlFor={this.props.id + "-romaudio"}>In-Game Music Track</label>
<input type="radio" id={this.props.id + "-custom"} value="custom"
checked={currentBoard.audioType === BoardAudioType.Custom}
onChange={() => this.onAudioTypeChanged(BoardAudioType.Custom)} />
<label htmlFor={this.props.id + "-custom"}>Custom Audio</label>
</div>
{audioInputUI}
</div>
);
}
};
interface IDetailsCustomAudioEntry {
audioEntry: IBoardAudioData;
canDelete: boolean;
onDeleteAudioEntry?(): void;
onMidiPrompt(): void;
onSoundbankIndexPrompt(): void;
}
function DetailsCustomAudioEntry(props: IDetailsCustomAudioEntry) {
const name = props.audioEntry.name || "(select a midi file)";
const hasData = !!props.audioEntry.data;
return (
<div className="audioCustomEntry">
<img src={audioImage}
className="audioCustomIcon audioCustomIconAudio"
title="Custom audio track"
alt="Custom audio track" />
<div className="audioCustomTextSections">
<div className="audioCustomSection">
<span className="detailsSpan">{name}</span>
<img src={editImage}
className="audioDetailsSmallEditIcon"
title="Upload midi file"
alt="Upload midi file"
onClick={props.onMidiPrompt}
tabIndex={0} />
</div>
{hasData && <div className="audioCustomSection">
<label>Soundbank index: </label>
<span className="detailsSpan">{props.audioEntry.soundbankIndex || 0}</span>
<img src={editImage}
className="audioDetailsSmallEditIcon"
title="Change soundbank index"
alt="Change soundbank index"
onClick={props.onSoundbankIndexPrompt}
tabIndex={0} />
</div>}
</div>
{props.canDelete && <img src={deleteImage}
onClick={props.onDeleteAudioEntry}
className="audioCustomIcon audioCustomIconDelete"
title="Remove audio track"
alt="Remove audio track"
tabIndex={0} />}
</div>
);
}
interface IAudioSelectionConfigButtonProps {
board: IBoard;
}
function AudioSelectionConfigButton(props: IAudioSelectionConfigButtonProps) {
if (boardIsROM(props.board)) {
return null;
}
if (!get($setting.uiAdvanced)) {
return null;
}
return (
<div className="audioSelectConfigButton"
title="Add custom code for choosing the music to play each turn"
tabIndex={0}
onClick={() => changeView(View.AUDIO_SELECTION_CODE)}>
<img src={audioConfigImage} alt="Configure audio selection" />
</div>
);
}
interface IDetailsDifficultyProps {
id: string;
desc: string;
readonly: boolean;
value: any;
onDifficultySelected(id: string, level: number): any;
}
interface IDetailsDifficultyState {
focusedLevel: number;
}
class DetailsDifficulty extends React.Component<IDetailsDifficultyProps, IDetailsDifficultyState> {
constructor(props: IDetailsDifficultyProps) {
super(props);
this.state = { focusedLevel: 0 };
}
onSelection = (level: number) => {
if (this.props.readonly)
return;
this.props.onDifficultySelected(this.props.id, level);
}
onDifficultyFocused = (level: number) => {
if (this.props.readonly)
return;
this.setState({ focusedLevel: level });
}
render() {
const levels = [];
for (let i = 1; i <= 5; i++) {
levels.push(<DetailsDifficultyLevel
level={i}
key={i.toString()}
readonly={this.props.readonly}
currentLevel={this.props.value}
focusedLevel={this.state.focusedLevel}
onDifficultyLevelSelected={this.onSelection}
onDifficultyFocused={this.onDifficultyFocused} />
);
}
return (
<div className="difficultyDetailsContainer">
<label>{this.props.desc}</label>
<div className="difficultyDetailsLevels">
{levels}
</div>
</div>
);
}
};
interface IDetailsDifficultyLevelProps {
level: number;
currentLevel: number;
focusedLevel: number;
readonly: boolean;
onDifficultyLevelSelected(level: number): any;
onDifficultyFocused(level: number): any;
}
class DetailsDifficultyLevel extends React.Component<IDetailsDifficultyLevelProps> {
state = {}
onClick = () => {
if (this.props.readonly)
return;
this.props.onDifficultyLevelSelected(this.props.level);
}
onMouseEnter = () => {
if (this.props.readonly)
return;
this.props.onDifficultyFocused(this.props.level);
}
onMouseLeave = () => {
if (this.props.readonly)
return;
this.props.onDifficultyFocused(0);
}
render() {
let className = "difficultyDetailsLevel";
if (!this.props.readonly) {
if (this.props.level <= this.props.currentLevel)
className += " difficultyLevelCurrent";
if (this.props.focusedLevel > 0 && this.props.level <= this.props.focusedLevel)
className += " difficultyLevelFocused";
}
return (
<div className={className} onClick={this.onClick}
onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}></div>
);
}
};
const CostumeTypesArr = [
CostumeType.NORMAL,
CostumeType.WESTERN,
CostumeType.PIRATE,
CostumeType.HORROR,
CostumeType.SPACE,
CostumeType.MYSTERY,
]
const CostumeTypeDescriptions = {
[CostumeType.NORMAL]: "Normal",
[CostumeType.WESTERN]: "Western",
[CostumeType.PIRATE]: "Pirate",
[CostumeType.HORROR]: "Horror",
[CostumeType.SPACE]: "Space",
[CostumeType.MYSTERY]: "Mystery",
};
interface IDetailsCostumeTypeProps {
costumeType: CostumeType;
id: string;
desc: string;
readonly: boolean;
onCostumeTypeSelected(costumeType: CostumeType): void;
}
function DetailsCostumeType(props: IDetailsCostumeTypeProps) {
const costumeOptions: IToggleItem<CostumeType>[] = [];
for (const costumeType of CostumeTypesArr) {
costumeOptions.push({
id: costumeType,
selected: props.costumeType === costumeType
|| (typeof props.costumeType === "undefined" && costumeType === CostumeType.NORMAL),
text: CostumeTypeDescriptions[costumeType],
});
}
return (
<div className="difficultyDetailsContainer">
<label>{props.desc}</label>
<ToggleGroup<CostumeType> items={costumeOptions}
allowDeselect={false}
readonly={props.readonly}
onToggleClick={(costumeType) => props.onCostumeTypeSelected(costumeType)} />
</div>
);
} | the_stack |
export const description = `
Validation tests for GPUBuffer.mapAsync, GPUBuffer.unmap and GPUBuffer.getMappedRange.
`;
import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { attemptGarbageCollection } from '../../../../common/util/collect_garbage.js';
import { assert, unreachable } from '../../../../common/util/util.js';
import { kBufferUsages } from '../../../capability_info.js';
import { GPUConst } from '../../../constants.js';
import { ValidationTest } from '../validation_test.js';
class F extends ValidationTest {
async testMapAsyncCall(
success: boolean,
rejectName: string | null,
buffer: GPUBuffer,
mode: GPUMapModeFlags,
offset?: number,
size?: number
) {
if (success) {
const p = buffer.mapAsync(mode, offset, size);
await p;
} else {
let p: Promise<void>;
this.expectValidationError(() => {
p = buffer.mapAsync(mode, offset, size);
});
try {
await p!;
assert(rejectName === null, 'mapAsync unexpectedly passed');
} catch (ex) {
assert(rejectName === ex.name, `mapAsync rejected unexpectedly with: ${ex}`);
}
}
}
testGetMappedRangeCall(success: boolean, buffer: GPUBuffer, offset?: number, size?: number) {
if (success) {
const data = buffer.getMappedRange(offset, size);
this.expect(data instanceof ArrayBuffer);
if (size !== undefined) {
this.expect(data.byteLength === size);
}
} else {
this.shouldThrow('OperationError', () => {
buffer.getMappedRange(offset, size);
});
}
}
createMappableBuffer(type: GPUMapModeFlags, size: number): GPUBuffer {
switch (type) {
case GPUMapMode.READ:
return this.device.createBuffer({
size,
usage: GPUBufferUsage.MAP_READ,
});
case GPUMapMode.WRITE:
return this.device.createBuffer({
size,
usage: GPUBufferUsage.MAP_WRITE,
});
default:
unreachable();
}
}
}
export const g = makeTestGroup(F);
const kMapModeOptions = [GPUConst.MapMode.READ, GPUConst.MapMode.WRITE];
const kOffsetAlignment = 8;
const kSizeAlignment = 4;
g.test('mapAsync,usage')
.desc(
`Test the usage validation for mapAsync.
For each buffer usage:
For GPUMapMode.READ, GPUMapMode.WRITE, and 0:
Test that the mapAsync call is valid iff the mapping usage is not 0 and the buffer usage
the mapMode flag.`
)
.paramsSubcasesOnly(u =>
u //
.combineWithParams([
{ mapMode: GPUConst.MapMode.READ, validUsage: GPUConst.BufferUsage.MAP_READ },
{ mapMode: GPUConst.MapMode.WRITE, validUsage: GPUConst.BufferUsage.MAP_WRITE },
// Using mapMode 0 is never valid, so there is no validUsage.
{ mapMode: 0, validUsage: null },
])
.combine('usage', kBufferUsages)
)
.fn(async t => {
const { mapMode, validUsage, usage } = t.params;
const buffer = t.device.createBuffer({
size: 16,
usage,
});
const success = usage === validUsage;
await t.testMapAsyncCall(success, 'OperationError', buffer, mapMode);
});
g.test('mapAsync,invalidBuffer')
.desc('Test that mapAsync is an error when called on an invalid buffer.')
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.getErrorBuffer();
await t.testMapAsyncCall(false, 'OperationError', buffer, mapMode);
});
g.test('mapAsync,state,destroyed')
.desc('Test that mapAsync is an error when called on a destroyed buffer.')
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
buffer.destroy();
await t.testMapAsyncCall(false, 'OperationError', buffer, mapMode);
});
g.test('mapAsync,state,mappedAtCreation')
.desc(
`Test that mapAsync is an error when called on a buffer mapped at creation,
but succeeds after unmapping it.`
)
.paramsSubcasesOnly([
{ mapMode: GPUConst.MapMode.READ, validUsage: GPUConst.BufferUsage.MAP_READ },
{ mapMode: GPUConst.MapMode.WRITE, validUsage: GPUConst.BufferUsage.MAP_WRITE },
])
.fn(async t => {
const { mapMode, validUsage } = t.params;
const buffer = t.device.createBuffer({
size: 16,
usage: validUsage,
mappedAtCreation: true,
});
await t.testMapAsyncCall(false, 'OperationError', buffer, mapMode);
buffer.unmap();
t.testMapAsyncCall(true, null, buffer, mapMode);
});
g.test('mapAsync,state,mapped')
.desc(
`Test that mapAsync is an error when called on a mapped buffer, but succeeds
after unmapping it.`
)
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
await t.testMapAsyncCall(true, null, buffer, mapMode);
await t.testMapAsyncCall(false, 'OperationError', buffer, mapMode);
buffer.unmap();
await t.testMapAsyncCall(true, null, buffer, mapMode);
});
g.test('mapAsync,state,mappingPending')
.desc(
`Test that mapAsync is an error when called on a buffer that is being mapped,
but succeeds after the previous mapping request is cancelled.`
)
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
// Start mapping the buffer, we are going to unmap it before it resolves so it will reject
// the mapping promise with an AbortError.
t.shouldReject('AbortError', buffer.mapAsync(mapMode));
// Do the test of mapAsync while [[state]] is mapping pending. It has to be synchronous so
// that we can unmap the previous mapping in the same stack frame and check this one doesn't
// get canceled, but instead is treated as a real error.
t.expectValidationError(() => {
t.shouldReject('OperationError', buffer.mapAsync(mapMode));
});
// Unmap the first mapping. It should now be possible to successfully call mapAsync
buffer.unmap();
await t.testMapAsyncCall(true, null, buffer, mapMode);
});
g.test('mapAsync,sizeUnspecifiedOOB')
.desc(
`Test that mapAsync with size unspecified rejects if offset > buffer.[[size]],
with various cases at the limits of the buffer size or with a misaligned offset.
Also test for an empty buffer.`
)
.paramsSubcasesOnly(u =>
u //
.combine('mapMode', kMapModeOptions)
.combineWithParams([
// 0 size buffer.
{ bufferSize: 0, offset: 0 },
{ bufferSize: 0, offset: 1 },
{ bufferSize: 0, offset: kOffsetAlignment },
// Test with a buffer that's not empty.
{ bufferSize: 16, offset: 0 },
{ bufferSize: 16, offset: kOffsetAlignment },
{ bufferSize: 16, offset: 16 },
{ bufferSize: 16, offset: 17 },
{ bufferSize: 16, offset: 16 + kOffsetAlignment },
])
)
.fn(async t => {
const { mapMode, bufferSize, offset } = t.params;
const buffer = t.createMappableBuffer(mapMode, bufferSize);
const success = offset <= bufferSize;
await t.testMapAsyncCall(success, 'OperationError', buffer, mapMode, offset);
});
g.test('mapAsync,offsetAndSizeAlignment')
.desc("Test that mapAsync fails if the alignment of offset and size isn't correct.")
.paramsSubcasesOnly(u =>
u
.combine('mapMode', kMapModeOptions)
.combine('offset', [0, kOffsetAlignment, kOffsetAlignment / 2])
.combine('size', [0, kSizeAlignment, kSizeAlignment / 2])
)
.fn(async t => {
const { mapMode, offset, size } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
const success = offset % kOffsetAlignment === 0 && size % kSizeAlignment === 0;
await t.testMapAsyncCall(success, 'OperationError', buffer, mapMode, offset, size);
});
g.test('mapAsync,offsetAndSizeOOB')
.desc('Test that mapAsync fails if offset + size is larger than the buffer size.')
.paramsSubcasesOnly(u =>
u //
.combine('mapMode', kMapModeOptions)
.combineWithParams([
// For a 0 size buffer
{ bufferSize: 0, offset: 0, size: 0 },
{ bufferSize: 0, offset: 0, size: 4 },
{ bufferSize: 0, offset: 8, size: 0 },
// For a small buffer
{ bufferSize: 16, offset: 0, size: 16 },
{ bufferSize: 16, offset: kOffsetAlignment, size: 16 },
{ bufferSize: 16, offset: 16, size: 0 },
{ bufferSize: 16, offset: 16, size: kSizeAlignment },
{ bufferSize: 16, offset: 8, size: 0 },
{ bufferSize: 16, offset: 8, size: 8 },
{ bufferSize: 16, offset: 8, size: 8 + kSizeAlignment },
// For a larger buffer
{ bufferSize: 1024, offset: 0, size: 1024 },
{ bufferSize: 1024, offset: kOffsetAlignment, size: 1024 },
{ bufferSize: 1024, offset: 1024, size: 0 },
{ bufferSize: 1024, offset: 1024, size: kSizeAlignment },
{ bufferSize: 1024, offset: 512, size: 0 },
{ bufferSize: 1024, offset: 512, size: 512 },
{ bufferSize: 1024, offset: 512, size: 512 + kSizeAlignment },
])
)
.fn(async t => {
const { mapMode, bufferSize, size, offset } = t.params;
const buffer = t.createMappableBuffer(mapMode, bufferSize);
const success = offset + size <= bufferSize;
await t.testMapAsyncCall(success, 'OperationError', buffer, mapMode, offset, size);
});
g.test('getMappedRange,state,mapped')
.desc('Test that it is valid to call getMappedRange in the mapped state')
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const bufferSize = 16;
const buffer = t.createMappableBuffer(mapMode, bufferSize);
await buffer.mapAsync(mapMode);
const data = buffer.getMappedRange();
t.expect(data instanceof ArrayBuffer);
t.expect(data.byteLength === bufferSize);
t.expectValidationError(() => {
// map on already mapped buffer should be rejected
const mapping = buffer.mapAsync(mapMode);
t.expect(data.byteLength === bufferSize);
t.shouldReject('OperationError', mapping);
});
t.expect(data.byteLength === bufferSize);
buffer.unmap();
t.expect(data.byteLength === 0);
});
g.test('getMappedRange,state,mappedAtCreation')
.desc(
`Test that, in the mapped-at-creation state, it is valid to call getMappedRange, for all buffer usages,
and invalid to call mapAsync, for all map modes.`
)
.paramsSubcasesOnly(u =>
u.combine('bufferUsage', kBufferUsages).combine('mapMode', kMapModeOptions)
)
.fn(async t => {
const { bufferUsage, mapMode } = t.params;
const bufferSize = 16;
const buffer = t.device.createBuffer({
usage: bufferUsage,
size: bufferSize,
mappedAtCreation: true,
});
const data = buffer.getMappedRange();
t.expect(data instanceof ArrayBuffer);
t.expect(data.byteLength === bufferSize);
t.expectValidationError(() => {
// map on already mapped buffer should be rejected
const mapping = buffer.mapAsync(mapMode);
t.expect(data.byteLength === bufferSize);
t.shouldReject('OperationError', mapping);
});
t.expect(data.byteLength === bufferSize);
buffer.unmap();
t.expect(data.byteLength === 0);
});
g.test('getMappedRange,state,invalid_mappedAtCreation')
.desc(
`mappedAtCreation should return a mapped buffer, even if the buffer is invalid.
Like VRAM allocation (see map_oom), validation can be performed asynchronously (in the GPU process)
so the Content process doesn't necessarily know the buffer is invalid.`
)
.fn(async t => {
const buffer = t.expectGPUError('validation', () =>
t.device.createBuffer({
mappedAtCreation: true,
size: 16,
usage: 0xffff_ffff, // Invalid usage
})
);
// Should still be valid.
buffer.getMappedRange();
});
g.test('getMappedRange,state,mappedAgain')
.desc(
'Test that it is valid to call getMappedRange in the mapped state, even if there is a duplicate mapAsync before'
)
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
await buffer.mapAsync(mapMode);
// call mapAsync again on already mapped buffer should fail
await t.testMapAsyncCall(false, 'OperationError', buffer, mapMode);
// getMapppedRange should still success
t.testGetMappedRangeCall(true, buffer);
});
g.test('getMappedRange,state,unmapped')
.desc(
`Test that it is invalid to call getMappedRange in the unmapped state.
Test for various cases of being unmapped: at creation, after a mapAsync call or after being created mapped.`
)
.fn(async t => {
// It is invalid to call getMappedRange when the buffer starts unmapped when created.
{
const buffer = t.createMappableBuffer(GPUMapMode.READ, 16);
t.testGetMappedRangeCall(false, buffer);
}
// It is invalid to call getMappedRange when the buffer is unmapped after mapAsync.
{
const buffer = t.createMappableBuffer(GPUMapMode.READ, 16);
await buffer.mapAsync(GPUMapMode.READ);
buffer.unmap();
t.testGetMappedRangeCall(false, buffer);
}
// It is invalid to call getMappedRange when the buffer is unmapped after mappedAtCreation.
{
const buffer = t.device.createBuffer({
usage: GPUBufferUsage.MAP_READ,
size: 16,
mappedAtCreation: true,
});
buffer.unmap();
t.testGetMappedRangeCall(false, buffer);
}
});
g.test('getMappedRange,subrange,mapped')
.desc(
`Test that old getMappedRange returned arraybuffer does not exist after unmap, and newly returned
arraybuffer after new map has correct subrange`
)
.params(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const bufferSize = 16;
const offset = 8;
const subrangeSize = bufferSize - offset;
const buffer = t.createMappableBuffer(mapMode, bufferSize);
await buffer.mapAsync(mapMode);
const data0 = buffer.getMappedRange();
t.expect(data0 instanceof ArrayBuffer);
t.expect(data0.byteLength === bufferSize);
buffer.unmap();
t.expect(data0.byteLength === 0);
await buffer.mapAsync(mapMode, offset);
const data1 = buffer.getMappedRange(8);
t.expect(data0.byteLength === 0);
t.expect(data1.byteLength === subrangeSize);
});
g.test('getMappedRange,subrange,mappedAtCreation')
.desc(
`Test that old getMappedRange returned arrybuffer does not exist after unmap and newly returned
arraybuffer after new map has correct subrange`
)
.fn(async t => {
const bufferSize = 16;
const offset = 8;
const subrangeSize = bufferSize - offset;
const buffer = t.device.createBuffer({
size: bufferSize,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
mappedAtCreation: true,
});
const data0 = buffer.getMappedRange();
t.expect(data0 instanceof ArrayBuffer);
t.expect(data0.byteLength === bufferSize);
buffer.unmap();
t.expect(data0.byteLength === 0);
await buffer.mapAsync(GPUMapMode.READ, offset);
const data1 = buffer.getMappedRange(8);
t.expect(data0.byteLength === 0);
t.expect(data1.byteLength === subrangeSize);
});
g.test('getMappedRange,state,destroyed')
.desc(
`Test that it is invalid to call getMappedRange in the destroyed state.
Test for various cases of being destroyed: at creation, after a mapAsync call or after being created mapped.`
)
.fn(async t => {
// It is invalid to call getMappedRange when the buffer is destroyed when unmapped.
{
const buffer = t.createMappableBuffer(GPUMapMode.READ, 16);
buffer.destroy();
t.testGetMappedRangeCall(false, buffer);
}
// It is invalid to call getMappedRange when the buffer is destroyed when mapped.
{
const buffer = t.createMappableBuffer(GPUMapMode.READ, 16);
await buffer.mapAsync(GPUMapMode.READ);
buffer.destroy();
t.testGetMappedRangeCall(false, buffer);
}
// It is invalid to call getMappedRange when the buffer is destroyed when mapped at creation.
{
const buffer = t.device.createBuffer({
usage: GPUBufferUsage.MAP_READ,
size: 16,
mappedAtCreation: true,
});
buffer.destroy();
t.testGetMappedRangeCall(false, buffer);
}
});
g.test('getMappedRange,state,mappingPending')
.desc('Test that it is invalid to call getMappedRange in the mappingPending state.')
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
/* noawait */ const mapping0 = buffer.mapAsync(mapMode);
t.expectValidationError(() => {
// seconding mapping should be rejected
t.shouldReject('OperationError', buffer.mapAsync(mapMode));
});
// invalid in mappingPending state
t.testGetMappedRangeCall(false, buffer);
await mapping0;
// valid after buffer is mapped
t.testGetMappedRangeCall(true, buffer);
});
g.test('getMappedRange,offsetAndSizeAlignment,mapped')
.desc(`Test that getMappedRange fails if the alignment of offset and size isn't correct.`)
.params(u =>
u
.combine('mapMode', kMapModeOptions)
.beginSubcases()
.combine('mapOffset', [0, kOffsetAlignment])
.combine('offset', [0, kOffsetAlignment, kOffsetAlignment / 2])
.combine('size', [0, kSizeAlignment, kSizeAlignment / 2])
)
.fn(async t => {
const { mapMode, mapOffset, offset, size } = t.params;
const buffer = t.createMappableBuffer(mapMode, 32);
await buffer.mapAsync(mapMode, mapOffset);
const success = offset % kOffsetAlignment === 0 && size % kSizeAlignment === 0;
t.testGetMappedRangeCall(success, buffer, offset + mapOffset, size);
});
g.test('getMappedRange,offsetAndSizeAlignment,mappedAtCreation')
.desc(`Test that getMappedRange fails if the alignment of offset and size isn't correct.`)
.paramsSubcasesOnly(u =>
u
.combine('offset', [0, kOffsetAlignment, kOffsetAlignment / 2])
.combine('size', [0, kSizeAlignment, kSizeAlignment / 2])
)
.fn(async t => {
const { offset, size } = t.params;
const buffer = t.device.createBuffer({
size: 16,
usage: GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
const success = offset % kOffsetAlignment === 0 && size % kSizeAlignment === 0;
t.testGetMappedRangeCall(success, buffer, offset, size);
});
g.test('getMappedRange,sizeAndOffsetOOB,mappedAtCreation')
.desc(
`Test that getMappedRange size + offset must be less than the buffer size for a
buffer mapped at creation. (and offset has not constraints on its own)`
)
.paramsSubcasesOnly([
// Tests for a zero-sized buffer, with and without a size defined.
{ bufferSize: 0, offset: undefined, size: undefined },
{ bufferSize: 0, offset: undefined, size: 0 },
{ bufferSize: 0, offset: undefined, size: kSizeAlignment },
{ bufferSize: 0, offset: 0, size: undefined },
{ bufferSize: 0, offset: 0, size: 0 },
{ bufferSize: 0, offset: kOffsetAlignment, size: undefined },
{ bufferSize: 0, offset: kOffsetAlignment, size: 0 },
// Tests for a non-empty buffer, with an undefined offset.
{ bufferSize: 80, offset: undefined, size: 80 },
{ bufferSize: 80, offset: undefined, size: 80 + kSizeAlignment },
// Tests for a non-empty buffer, with an undefined size.
{ bufferSize: 80, offset: undefined, size: undefined },
{ bufferSize: 80, offset: 0, size: undefined },
{ bufferSize: 80, offset: kOffsetAlignment, size: undefined },
{ bufferSize: 80, offset: 80, size: undefined },
{ bufferSize: 80, offset: 80 + kOffsetAlignment, size: undefined },
// Tests for a non-empty buffer with a size defined.
{ bufferSize: 80, offset: 0, size: 80 },
{ bufferSize: 80, offset: 0, size: 80 + kSizeAlignment },
{ bufferSize: 80, offset: kOffsetAlignment, size: 80 },
{ bufferSize: 80, offset: 40, size: 40 },
{ bufferSize: 80, offset: 40 + kOffsetAlignment, size: 40 },
{ bufferSize: 80, offset: 40, size: 40 + kSizeAlignment },
])
.fn(t => {
const { bufferSize, offset, size } = t.params;
const buffer = t.device.createBuffer({
size: bufferSize,
usage: GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
const actualOffset = offset ?? 0;
const actualSize = size ?? bufferSize - actualOffset;
const success = actualOffset <= bufferSize && actualOffset + actualSize <= bufferSize;
t.testGetMappedRangeCall(success, buffer, offset, size);
});
g.test('getMappedRange,sizeAndOffsetOOB,mapped')
.desc('Test that getMappedRange size + offset must be less than the mapAsync range.')
.paramsSubcasesOnly(u =>
u //
.combine('mapMode', kMapModeOptions)
.combineWithParams([
// Tests for an empty buffer, and implicit mapAsync size.
{ bufferSize: 0, mapOffset: 0, mapSize: undefined, offset: undefined, size: undefined },
{ bufferSize: 0, mapOffset: 0, mapSize: undefined, offset: undefined, size: 0 },
{
bufferSize: 0,
mapOffset: 0,
mapSize: undefined,
offset: undefined,
size: kSizeAlignment,
},
{ bufferSize: 0, mapOffset: 0, mapSize: undefined, offset: 0, size: undefined },
{ bufferSize: 0, mapOffset: 0, mapSize: undefined, offset: 0, size: 0 },
{
bufferSize: 0,
mapOffset: 0,
mapSize: undefined,
offset: kOffsetAlignment,
size: undefined,
},
{ bufferSize: 0, mapOffset: 0, mapSize: undefined, offset: kOffsetAlignment, size: 0 },
// Tests for an empty buffer, and explicit mapAsync size.
{ bufferSize: 0, mapOffset: 0, mapSize: 0, offset: undefined, size: undefined },
{ bufferSize: 0, mapOffset: 0, mapSize: 0, offset: 0, size: undefined },
{ bufferSize: 0, mapOffset: 0, mapSize: 0, offset: 0, size: 0 },
{ bufferSize: 0, mapOffset: 0, mapSize: 0, offset: kOffsetAlignment, size: undefined },
{ bufferSize: 0, mapOffset: 0, mapSize: 0, offset: kOffsetAlignment, size: 0 },
// Test for a fully implicit mapAsync call
{ bufferSize: 80, mapOffset: undefined, mapSize: undefined, offset: 0, size: 80 },
{
bufferSize: 80,
mapOffset: undefined,
mapSize: undefined,
offset: 0,
size: 80 + kSizeAlignment,
},
{
bufferSize: 80,
mapOffset: undefined,
mapSize: undefined,
offset: kOffsetAlignment,
size: 80,
},
// Test for a mapAsync call with an implicit size
{ bufferSize: 80, mapOffset: 24, mapSize: undefined, offset: 24, size: 80 - 24 },
{
bufferSize: 80,
mapOffset: 24,
mapSize: undefined,
offset: 0,
size: 80 - 24 + kSizeAlignment,
},
{
bufferSize: 80,
mapOffset: 24,
mapSize: undefined,
offset: kOffsetAlignment,
size: 80 - 24,
},
// Test for a non-empty buffer fully mapped.
{ bufferSize: 80, mapOffset: 0, mapSize: 80, offset: 0, size: 80 },
{ bufferSize: 80, mapOffset: 0, mapSize: 80, offset: kOffsetAlignment, size: 80 },
{ bufferSize: 80, mapOffset: 0, mapSize: 80, offset: 0, size: 80 + kSizeAlignment },
{ bufferSize: 80, mapOffset: 0, mapSize: 80, offset: 40, size: 40 },
{ bufferSize: 80, mapOffset: 0, mapSize: 80, offset: 40 + kOffsetAlignment, size: 40 },
{ bufferSize: 80, mapOffset: 0, mapSize: 80, offset: 40, size: 40 + kSizeAlignment },
// Test for a buffer partially mapped.
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: 24, size: 40 },
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: 24 - kOffsetAlignment, size: 40 },
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: 24 + kOffsetAlignment, size: 40 },
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: 24, size: 40 + kSizeAlignment },
// Test for a partially mapped buffer with implicit size and offset for getMappedRange.
// - Buffer partially mapped in the middle
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: undefined, size: undefined },
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: 0, size: undefined },
{ bufferSize: 80, mapOffset: 24, mapSize: 40, offset: 24, size: undefined },
// - Buffer partially mapped to the end
{ bufferSize: 80, mapOffset: 24, mapSize: undefined, offset: 24, size: undefined },
{ bufferSize: 80, mapOffset: 24, mapSize: undefined, offset: 80, size: undefined },
// - Buffer partially mapped from the start
{ bufferSize: 80, mapOffset: 0, mapSize: 64, offset: undefined, size: undefined },
{ bufferSize: 80, mapOffset: 0, mapSize: 64, offset: undefined, size: 64 },
])
)
.fn(async t => {
const { mapMode, bufferSize, mapOffset, mapSize, offset, size } = t.params;
const buffer = t.createMappableBuffer(mapMode, bufferSize);
await buffer.mapAsync(mapMode, mapOffset, mapSize);
const actualMapOffset = mapOffset ?? 0;
const actualMapSize = mapSize ?? bufferSize - actualMapOffset;
const actualOffset = offset ?? 0;
const actualSize = size ?? bufferSize - actualOffset;
const success =
actualOffset >= actualMapOffset &&
actualOffset <= bufferSize &&
actualOffset + actualSize <= actualMapOffset + actualMapSize;
t.testGetMappedRangeCall(success, buffer, offset, size);
});
g.test('getMappedRange,disjointRanges')
.desc('Test that the ranges asked through getMappedRange must be disjoint.')
.paramsSubcasesOnly(u =>
u //
.combine('remapBetweenCalls', [false, true])
.combineWithParams([
// Disjoint ranges with one that's empty.
{ offset1: 8, size1: 0, offset2: 8, size2: 8 },
{ offset1: 16, size1: 0, offset2: 8, size2: 8 },
{ offset1: 8, size1: 8, offset2: 8, size2: 0 },
{ offset1: 8, size1: 8, offset2: 16, size2: 0 },
// Disjoint ranges with both non-empty.
{ offset1: 0, size1: 8, offset2: 8, size2: 8 },
{ offset1: 16, size1: 8, offset2: 8, size2: 8 },
{ offset1: 8, size1: 8, offset2: 0, size2: 8 },
{ offset1: 8, size1: 8, offset2: 16, size2: 8 },
// Empty range contained inside another one.
{ offset1: 16, size1: 20, offset2: 24, size2: 0 },
{ offset1: 24, size1: 0, offset2: 16, size2: 20 },
// Ranges that overlap only partially.
{ offset1: 16, size1: 20, offset2: 8, size2: 20 },
{ offset1: 16, size1: 20, offset2: 32, size2: 20 },
// Ranges that include one another.
{ offset1: 0, size1: 80, offset2: 16, size2: 20 },
{ offset1: 16, size1: 20, offset2: 0, size2: 80 },
])
)
.fn(async t => {
const { offset1, size1, offset2, size2, remapBetweenCalls } = t.params;
const buffer = t.device.createBuffer({ size: 80, usage: GPUBufferUsage.MAP_READ });
await buffer.mapAsync(GPUMapMode.READ);
t.testGetMappedRangeCall(true, buffer, offset1, size1);
if (remapBetweenCalls) {
buffer.unmap();
await buffer.mapAsync(GPUMapMode.READ);
}
const range1StartsAfter2 = offset1 >= offset2 + size2;
const range2StartsAfter1 = offset2 >= offset1 + size1;
const disjoint = range1StartsAfter2 || range2StartsAfter1;
const success = disjoint || remapBetweenCalls;
t.testGetMappedRangeCall(success, buffer, offset2, size2);
});
g.test('getMappedRange,disjoinRanges_many')
.desc('Test getting a lot of small ranges, and that the disjoint check checks them all.')
.fn(async t => {
const kStride = 256;
const kNumStrides = 256;
const buffer = t.device.createBuffer({
size: kStride * kNumStrides,
usage: GPUBufferUsage.MAP_READ,
});
await buffer.mapAsync(GPUMapMode.READ);
// Get a lot of small mapped ranges.
for (let stride = 0; stride < kNumStrides; stride++) {
t.testGetMappedRangeCall(true, buffer, stride * kStride, 8);
}
// Check for each range it is invalid to get a range that overlaps it and check that it is valid
// to get ranges for the rest of the buffer.
for (let stride = 0; stride < kNumStrides; stride++) {
t.testGetMappedRangeCall(false, buffer, stride * kStride, kStride);
t.testGetMappedRangeCall(true, buffer, stride * kStride + 8, kStride - 8);
}
});
g.test('unmap,state,unmapped')
.desc(
`Test it is invalid to call unmap on a buffer that is unmapped (at creation, or after
mappedAtCreation or mapAsync)`
)
.fn(async t => {
// It is invalid to call unmap after creation of an unmapped buffer.
{
const buffer = t.device.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ });
t.expectValidationError(() => {
buffer.unmap();
});
}
// It is invalid to call unmap after unmapping a mapAsynced buffer.
{
const buffer = t.createMappableBuffer(GPUMapMode.READ, 16);
await buffer.mapAsync(GPUMapMode.READ);
buffer.unmap();
t.expectValidationError(() => {
buffer.unmap();
});
}
// It is invalid to call unmap after unmapping a mappedAtCreation buffer.
{
const buffer = t.device.createBuffer({
usage: GPUBufferUsage.MAP_READ,
size: 16,
mappedAtCreation: true,
});
buffer.unmap();
t.expectValidationError(() => {
buffer.unmap();
});
}
});
g.test('unmap,state,destroyed')
.desc(
`Test it is invalid to call unmap on a buffer that is destroyed (at creation, or after
mappedAtCreation or mapAsync)`
)
.fn(async t => {
// It is invalid to call unmap after destruction of an unmapped buffer.
{
const buffer = t.device.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ });
buffer.destroy();
t.expectValidationError(() => {
buffer.unmap();
});
}
// It is invalid to call unmap after destroying a mapAsynced buffer.
{
const buffer = t.createMappableBuffer(GPUMapMode.READ, 16);
await buffer.mapAsync(GPUMapMode.READ);
buffer.destroy();
t.expectValidationError(() => {
buffer.unmap();
});
}
// It is invalid to call unmap after destroying a mappedAtCreation buffer.
{
const buffer = t.device.createBuffer({
usage: GPUBufferUsage.MAP_READ,
size: 16,
mappedAtCreation: true,
});
buffer.destroy();
t.expectValidationError(() => {
buffer.unmap();
});
}
});
g.test('unmap,state,mappedAtCreation')
.desc('Test it is valid to call unmap on a buffer mapped at creation, for various usages')
.paramsSubcasesOnly(u =>
u //
.combine('bufferUsage', kBufferUsages)
)
.fn(t => {
const { bufferUsage } = t.params;
const buffer = t.device.createBuffer({ size: 16, usage: bufferUsage, mappedAtCreation: true });
buffer.unmap();
});
g.test('unmap,state,mapped')
.desc("Test it is valid to call unmap on a buffer that's mapped")
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
await buffer.mapAsync(mapMode);
buffer.unmap();
});
g.test('unmap,state,mappingPending')
.desc("Test it is valid to call unmap on a buffer that's being mapped")
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(t => {
const { mapMode } = t.params;
const buffer = t.createMappableBuffer(mapMode, 16);
const mapping = buffer.mapAsync(mapMode);
t.shouldReject('AbortError', mapping);
buffer.unmap();
});
g.test('gc_behavior,mappedAtCreation')
.desc(
"Test that GCing the buffer while mappings are handed out doesn't invalidate them - mappedAtCreation case"
)
.fn(async t => {
let buffer = null;
buffer = t.device.createBuffer({
size: 256,
usage: GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
// Write some non-zero data to the buffer.
const contents = new Uint32Array(buffer.getMappedRange());
for (let i = 0; i < contents.length; i++) {
contents[i] = i;
}
// Trigger garbage collection that should collect the buffer (or as if it collected it)
// NOTE: This won't fail unless the browser immediately starts reusing the memory, or gives it
// back to the OS. One good option for browsers to check their logic is good is to zero-out the
// memory on GPUBuffer (or internal gpu::Buffer-like object) destruction.
buffer = null;
await attemptGarbageCollection();
// Use the mapping again both for read and write, it should work.
for (let i = 0; i < contents.length; i++) {
t.expect(contents[i] === i);
contents[i] = i + 1;
}
});
g.test('gc_behavior,mapAsync')
.desc(
"Test that GCing the buffer while mappings are handed out doesn't invalidate them - mapAsync case"
)
.paramsSubcasesOnly(u => u.combine('mapMode', kMapModeOptions))
.fn(async t => {
const { mapMode } = t.params;
let buffer = null;
buffer = t.createMappableBuffer(mapMode, 256);
await buffer.mapAsync(mapMode);
// Write some non-zero data to the buffer.
const contents = new Uint32Array(buffer.getMappedRange());
for (let i = 0; i < contents.length; i++) {
contents[i] = i;
}
// Trigger garbage collection that should collect the buffer (or as if it collected it)
// NOTE: This won't fail unless the browser immediately starts reusing the memory, or gives it
// back to the OS. One good option for browsers to check their logic is good is to zero-out the
// memory on GPUBuffer (or internal gpu::Buffer-like object) destruction.
buffer = null;
await attemptGarbageCollection();
// Use the mapping again both for read and write, it should work.
for (let i = 0; i < contents.length; i++) {
t.expect(contents[i] === i);
contents[i] = i + 1;
}
}); | the_stack |
import { inspect } from 'util'
import { memoize } from './utils/memoize-utils'
import { enumerablizeWithPrototypeGetters } from './utils/object-utils'
import { createLayerEntitySelector } from './utils/selector-utils'
import type { CancelToken } from '@avocode/cancel-token'
import {
ILayerCollection,
DesignLayerSelector,
ILayer,
ArtboardId,
LayerId,
} from '@opendesign/octopus-reader'
import type { Bounds } from '@opendesign/rendering'
import type { LayerAttributesConfig } from './artboard-facade'
import type { DesignFacade } from './design-facade'
import type {
FontDescriptor,
LayerFacade,
LayerOctopusAttributesConfig,
} from './layer-facade'
import type { BitmapAssetDescriptor } from './local/local-design'
export class LayerCollectionFacade {
private _layerCollection: ILayerCollection
private _designFacade: DesignFacade;
[index: number]: LayerFacade
/** @internal */
constructor(
layerCollection: ILayerCollection,
params: {
designFacade: DesignFacade
}
) {
this._layerCollection = layerCollection
this._designFacade = params.designFacade
enumerablizeWithPrototypeGetters(this)
this._registerArrayIndexes()
}
private _registerArrayIndexes() {
for (let i = 0; i < this._layerCollection.length; i += 1) {
Object.defineProperty(this, i, {
get() {
const layers = this.getLayers()
return layers[i]
},
enumerable: true,
})
}
}
/** @internal */
toString(): string {
const layers = this.toJSON()
return `DesignLayerCollection ${inspect(layers)}`
}
/** @internal */
[inspect.custom](): string {
return this.toString()
}
/** @internal */
toJSON(): unknown {
return this.getLayers()
}
/**
* Returns an iterator which iterates over the collection layers.
*
* The layers explicitly included in the collection are iterated over, but layers nested in them are not.
*
* @category Iteration
* @returns A layer object iterator.
*/
[Symbol.iterator](): Iterator<LayerFacade> {
return this.getLayers().values()
}
/**
* Returns the number of layers explicitly included in the collection.
*
* This count reflects the number of items returned by {@link LayerCollectionFacade.getLayers} and the native iterator.
*
* @category Iteration
*/
get length(): number {
return this._layerCollection.length
}
/** @internal */
getFileLayerCollectionEntity(): ILayerCollection {
return this._layerCollection
}
/**
* Returns the collection layers as a native `Array`.
*
* The layers explicitly included in the collection are iterated over, but layers nested in them are not.
*
* @category Layer Lookup
* @returns An array of layer objects from the collection.
*/
getLayers(): Array<LayerFacade> {
return this._getLayersMemoized()
}
private _getLayersMemoized = memoize(
(): Array<LayerFacade> => {
return this._layerCollection
.map((layerEntity) => {
return this._resolveArtboardLayer(layerEntity)
})
.filter(Boolean) as Array<LayerFacade>
}
)
/**
* Returns the first layer object from the collection (optionally down to a specific nesting level) matching the specified criteria.
*
* Both layers explicitly included in the collection and layers nested within those layers are searched.
*
* Note that the layer subtrees within the individual layers explicitly included in the collection are walked in *document order*, not level by level, which means that nested layers of a layer are searched before searching sibling layers of the layer.
*
* @category Layer Lookup
* @param selector A layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within the layers explictly included in the collection to search. By default, all levels are searched. `0` also means "no limit"; `1` means only the layers explicitly included in the collection should be searched.
* @returns A matched layer object.
*
* @example Layer by name from any artboard
* ```typescript
* const layer = await collection.findLayer({ name: 'Share icon' })
* ```
*
* @example Layer by function selector from any artboard
* ```typescript
* const shareIconLayer = await collection.findLayer((layer) => {
* return layer.name === 'Share icon'
* })
* ```
*
* @example Layer by name from a certain artboad subset
* ```typescript
* const layer = await collection.findLayer({
* name: 'Share icon',
* artboardId: [ '<ID1>', '<ID2>' ],
* })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await collection.findLayer(
* { name: 'Share icon' },
* { cancelToken: token }
* )
* ```
*/
findLayer(
selector: DesignLayerSelector | ((layer: LayerFacade) => boolean),
options: { depth?: number } = {}
): LayerFacade | null {
const entitySelector = createLayerEntitySelector(
this._designFacade,
selector
)
const layerEntity = this._layerCollection.findLayer(entitySelector, options)
return layerEntity ? this._resolveArtboardLayer(layerEntity) : null
}
/**
* Returns a collection of all layer objects from the collection (optionally down to a specific nesting level) matching the specified criteria.
*
* Both layers explicitly included in the collection and layers nested within those layers are searched.
*
* Note that the results from layer subtrees within the individual layers explicitly included in the collection are sorted in *document order*, not level by level, which means that nested layers of a layer are included before matching sibling layers of the layer.
*
* @category Layer Lookup
* @param selector A layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within the layers explictly included in the collection to search. By default, all levels are searched. `0` also means "no limit"; `1` means only the layers explicitly included in the collection should be searched.
* @returns A layer collection of matched layers.
*
* @example Layers by name from all artboards
* ```typescript
* const layers = await collection.findLayers({ name: 'Share icon' })
* ```
*
* @example Layers by function selector from all artboards
* ```typescript
* const shareIconLayers = await collection.findLayers((layer) => {
* return layer.name === 'Share icon'
* })
* ```
*
* @example Invisible layers from all a certain artboard subset
* ```typescript
* const layers = await collection.findLayers({
* visible: false,
* artboardId: [ '<ID1>', '<ID2>' ],
* })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await collection.findLayers(
* { type: 'shapeLayer' },
* { cancelToken: token }
* )
* ```
*/
findLayers(
selector: DesignLayerSelector | ((layer: LayerFacade) => boolean),
options: { depth?: number } = {}
): LayerCollectionFacade {
const entitySelector = createLayerEntitySelector(
this._designFacade,
selector
)
const layerCollection = this._layerCollection.findLayers(
entitySelector,
options
)
return new LayerCollectionFacade(layerCollection, {
designFacade: this._designFacade,
})
}
/**
* Returns a new layer collection which only includes layers for which the filter returns `true`.
*
* The layers explicitly included in the collection are iterated over, but layers nested in them are not.
*
* @category Iteration
* @param filter The filter to apply to the layers in the collection.
* @returns A filtered layer collection.
*
* @example
* ```typescript
* const textLayers = collection.filter((layer) => {
* return layer.type === 'textLayer'
* })
* ```
*/
filter(
filter: (layer: LayerFacade, index: number) => boolean
): LayerCollectionFacade {
const layerCollection = this._layerCollection.filter(
(layerEntity, index) => {
const layerFacade = this._resolveArtboardLayer(layerEntity)
return Boolean(layerFacade && filter(layerFacade, index))
}
)
return new LayerCollectionFacade(layerCollection, {
designFacade: this._designFacade,
})
}
/**
* Iterates over the the layers in the collection and invokes the provided function with each one of them.
*
* The layers explicitly included in the collection are iterated over, but layers nested in them are not.
*
* @category Iteration
* @param fn The function to apply to the layers in the collection.
*
* @example
* ```typescript
* collection.forEach((layer) => {
* console.log(layer.name)
* })
* ```
*/
forEach(
fn: (
layer: LayerFacade,
index: number,
layers: Array<LayerFacade>
) => unknown
): void {
this.getLayers().forEach(fn)
}
/**
* Returns a native `Array` which returns mapper function results for each of the layers from the collection.
*
* The layers explicitly included in the collection are iterated ovser, but layers nested in them are not.
*
* @category Iteration
* @param mapper The mapper function to apply to the layers in the collection.
* @returns An array of mapper function results.
*
* @example
* ```typescript
* const textValues = collection.map((layer) => {
* const text = layer.getText()
* return text ? text.getTextContent() : null
* })
* ```
*/
map<T>(
mapper: (layer: LayerFacade, index: number, layers: Array<LayerFacade>) => T
): Array<T> {
return this.getLayers().map(mapper)
}
/**
* Returns a native `Array` which returns mapper function results for all of the layers from the collection. The arrays produced by the mapper function are concatenated (flattened).
*
* The layers explicitly included in the collection are iterated over, but layers nested in them are not.
*
* @category Iteration
* @param mapper The mapper function to apply to the layers in the collection.
* @returns An array of flattened mapper results.
*
* @example
* ```typescript
* const textValues = collection.flatMap((layer) => {
* const text = layer.getText()
* return text ? [ text.getTextContent() ] : []
* })
* ```
*/
flatMap<T>(
mapper: (
layer: LayerFacade,
index: number,
layers: Array<LayerFacade>
) => Array<T>
): Array<T> {
return this.getLayers().flatMap(mapper)
}
/**
* Returns a reduction of all layers from the collection.
*
* The layers explicitly included in the collection are iterated over, but layers nested in them are not.
*
* @category Iteration
* @param reducer The reducer function to apply to the layers in the collection.
* @param initialValue The value passed as the first argument to the reducer function applied to the first layer in the collection.
* @returns The reduction result.
*
* @example
* ```typescript
* const textValues = collection.reduce((values, layer) => {
* const text = layer.getText()
* return text ? values.concat([ text.getTextContent() ]) : values
* }, [])
* ```
*/
reduce<T>(
reducer: (state: T, layer: LayerFacade, index: number) => T,
initialValue: T
): T {
return this.getLayers().reduce(reducer, initialValue)
}
/**
* Returns a new layer collection which includes all layers explicitly included in the original collection and the provided collection.
*
* Layers nested in the layers explicitly included in the collections are not explictly included in the new collection either.
*
* @category Collection Manipulation
* @param addedLayers The layer collection to concatenate with the original collection. A native `Array` of layer objects can be provided instead of an actual collection object.
* @returns A merged layer collection.
*
* @example Merge two collections
* ```typescript
* const textLayersFromA = await artboardA.findLayers({ type: 'textLayers' })
* const textLayersFromB = await artboardB.findLayers({ type: 'textLayers' })
* const textLayersFromAB = textLayersFromA.concat(textLayersFromB)
* ```
*
* @example Append individual layers
* ```typescript
* const extraLayer = await artboard.getLayerById('<ID>')
* const extendedCollection = collection.concat([ extraLayer ])
* ```
*/
concat(
addedLayers: LayerCollectionFacade | Array<LayerFacade>
): LayerCollectionFacade {
const addedLayerList = Array.isArray(addedLayers)
? addedLayers.map((layerFacade) => {
return layerFacade.getLayerEntity()
})
: addedLayers.getFileLayerCollectionEntity()
const nextLayerCollection = this._layerCollection.concat(addedLayerList)
return new LayerCollectionFacade(nextLayerCollection, {
designFacade: this._designFacade,
})
}
/**
* Returns a new layer collection which includes all layers explicitly included in the original collection as well as layers nested within those layers (optionally down to a specific nesting level).
*
* @category Collection Manipulation
* @param options Options
* @param options.depth The maximum nesting level within the layers explicitly included in the original collection to explicitly include in the new collection. `0` also means "no limit"; `1` means only the layers nested immediately in the collection layers should be included in the new colleciton.
* @returns A flattened layer collection.
*
* @example
* ```typescript
* const groupLayers = await artboard.findLayers({ type: 'groupLayer' })
*
* const groupLayersWithImmediateChildren = groupLayers.flatten({ depth: 1 })
* const groupLayersWithAllChildren = groupLayers.flatten()
* ```
*/
flatten(options: { depth?: number } = {}): LayerCollectionFacade {
const flattenedLayerCollection = this._layerCollection.flatten(options)
return new LayerCollectionFacade(flattenedLayerCollection, {
designFacade: this._designFacade,
})
}
/**
* Returns a list of bitmap assets used by the layers in the collection within the layer (optionally down to a specific nesting level).
*
* Both layers explicitly included in the collection and layers nested within those layers are searched.
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within the layer to search for bitmap asset usage. By default, all levels are searched. Specifying the depth of `0` leads to bitmap assets of layers nested in the explicitly included layers being omitted altogether.
* @param options.includePrerendered Whether to also include "pre-rendered" bitmap assets. These assets can be produced by the rendering engine (if configured; future functionality) but are available as assets for either performance reasons or due to the some required data (such as font files) potentially not being available. By default, pre-rendered assets are included.
* @returns A list of bitmap assets.
*
* @example All bitmap assets from layers from any artboard
* ```typescript
* const bitmapAssetDescs = await collection.getBitmapAssets()
* ```
*
* @example Bitmap assets excluding pre-renredered bitmaps from layers from any artboards
* ```typescript
* const bitmapAssetDescs = await collection.getBitmapAssets({
* includePrerendered: false,
* })
* ```
*/
getBitmapAssets(
options: { depth?: number; includePrerendered?: boolean } = {}
): Array<
BitmapAssetDescriptor & {
artboardLayerIds: Record<ArtboardId, Array<LayerId>>
}
> {
return this._layerCollection.getBitmapAssets(options)
}
/**
* Returns a list of fonts used by the layers in the collection within the layer (optionally down to a specific nesting level).
*
* Both layers explicitly included in the collection and layers nested within those layers are searched.
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within the layer to search for font usage. By default, all levels are searched. Specifying the depth of `0` leads to bitmap assets of layers nested in the explicitly included layers being omitted altogether.
* @returns A list of bitmap assets.
*
* @example All fonts from layers from any artboard
* ```typescript
* const fontDescs = await design.getFonts()
* ```
*/
getFonts(
options: { depth?: number } = {}
): Array<
FontDescriptor & { artboardLayerIds: Record<ArtboardId, Array<LayerId>> }
> {
return this._layerCollection.getFonts(options)
}
private _resolveArtboardLayer(layerEntity: ILayer): LayerFacade | null {
const artboardId = layerEntity.artboardId
if (!artboardId) {
return null
}
return this._designFacade.getArtboardLayerFacade(artboardId, layerEntity.id)
}
/**
* Renders all layers in the collection as a single PNG image file.
*
* In case of group layers, all visible nested layers are also included.
*
* This can only be done for collections containing layers from a single artboards. When there are layers from multiple artboards, the operation is rejected.
*
* Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param filePath The target location of the produced PNG image file.
* @param options Render options.
* @param options.bounds The area to include. This can be used to either crop or expand (add empty space to) the default layer area.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.layerAttributes Layer-specific options to use for the rendering instead of the default values.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
* @returns A list of fonts.
*
* @example With default options (1x, whole combined layer area)
* ```typescript
* await collection.renderToFile(
* './rendered/collection.png'
* )
* ```
*
* @example With custom scale and crop and using the custom layer configuration
* ```typescript
* await collection.renderToFile(
* './rendered/collection.png',
* {
* scale: 2,
* // The result is going to have the dimensions of 400x200 due to the 2x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* layerAttributes: {
* '<LAYER1>': { blendingMode: 'SOFT_LIGHT', includeComponentBackground: true },
* '<LAYER2>': { opacity: 0.6 },
* }
* }
* )
* ```
*/
async renderToFile(
filePath: string,
options: {
layerAttributes?: Record<string, LayerAttributesConfig>
scale?: number
bounds?: Bounds
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const layerIds = this.getLayers().map((layer) => {
return layer.id
})
const artboardIds = [...new Set(this.getLayers().map((layer) => layer.artboardId))]
const artboardId = artboardIds.length === 1 ? artboardIds[0] : null
if (!artboardId) {
throw new Error(
'The number of artboards from which to render layers must be exactly 1'
)
}
return this._designFacade.renderArtboardLayersToFile(
artboardId,
layerIds,
filePath,
options
)
}
/**
* Return an SVG document string of all layers in the collection.
*
* In case of group layers, all visible nested layers are also included.
*
* This can only be done for collections containing layers from a single artboards. When there are layers from multiple artboards, the operation is rejected.
*
* Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category SVG Export
* @param options Options
* @param options.layerAttributes Layer-specific options to use for instead of the default values.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
* @returns An SVG document string.
*
* @example With default options (1x)
* ```typescript
* const svg = await collection.exportToSvgCode()
* ```
*
* @example With a custom scale
* ```typescript
* const svg = await collection.exportToSvgCode({ scale: 2 })
* ```
*/
async exportToSvgCode(
options: {
layerAttributes?: Record<LayerId, LayerOctopusAttributesConfig>
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<string> {
const layerIds = this.getLayers().map((layer) => {
return layer.id
})
const artboardIds = [...new Set(this.getLayers().map((layer) => layer.artboardId))]
const artboardId = artboardIds.length === 1 ? artboardIds[0] : null
if (!artboardId) {
throw new Error(
'The number of artboards from which to export layers must be exactly 1'
)
}
return this._designFacade.exportArtboardLayersToSvgCode(
artboardId,
layerIds,
options
)
}
/**
* Export all layers in the collection as an SVG file.
*
* In case of group layers, all visible nested layers are also included.
*
* This can only be done for collections containing layers from a single artboards. When there are layers from multiple artboards, the operation is rejected.
*
* Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category SVG Export
* @param filePath The target location of the produced SVG file.
* @param options Options
* @param options.layerAttributes Layer-specific options to use for instead of the default values.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x)
* ```typescript
* const svg = await collection.exportToSvgFile('./collection.svg')
* ```
*
* @example With a custom scale
* ```typescript
* const svg = await collection.exportToSvgFile('./collection.svg', { scale: 2 })
* ```
*/
async exportToSvgFile(
filePath: string,
options: {
layerAttributes?: Record<LayerId, LayerOctopusAttributesConfig>
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const layerIds = this.getLayers().map((layer) => {
return layer.id
})
const artboardIds = [...new Set(this.getLayers().map((layer) => layer.artboardId))]
const artboardId = artboardIds.length === 1 ? artboardIds[0] : null
if (!artboardId) {
throw new Error(
'The number of artboards from which to export layers must be exactly 1'
)
}
await this._designFacade.exportArtboardLayersToSvgFile(
artboardId,
layerIds,
filePath,
options
)
}
} | the_stack |
* Contains config details and operations meant for package subscriber orgs.
* This could potentially include test orgs used by CI process for testing packages,
* and target subscriber orgs.
**/
import * as util from 'util';
import * as BBPromise from 'bluebird';
import * as _ from 'lodash';
// New messages (move to this)
import { Messages } from '@salesforce/core';
Messages.importMessagesDirectory(__dirname);
const packagingMessages = Messages.loadMessages('salesforce-alm', 'packaging');
// Old style messages
import MessagesLocal = require('../messages');
const messages = MessagesLocal();
import logger = require('../core/logApi');
import pkgUtils = require('../package/packageUtils');
const DEFAULT_POLL_INTERVAL_MILLIS = 5000;
const REPLICATION_POLLING_INTERVAL_MILLIS = 10000;
const DEFAULT_MAX_RETRIES = 0;
const RETRY_MINUTES_IN_MILLIS = 60000;
const DEFAULT_PUBLISH_WAIT_MIN = 0;
const SECURITY_TYPE_KEY_ALLUSERS = 'AllUsers';
const SECURITY_TYPE_KEY_ADMINSONLY = 'AdminsOnly';
const SECURITY_TYPE_VALUE_ALLUSERS = 'full';
const SECURITY_TYPE_VALUE_ADMINSONLY = 'none';
const SECURITY_TYPE_MAP = new Map();
SECURITY_TYPE_MAP.set(SECURITY_TYPE_KEY_ALLUSERS, SECURITY_TYPE_VALUE_ALLUSERS);
SECURITY_TYPE_MAP.set(SECURITY_TYPE_KEY_ADMINSONLY, SECURITY_TYPE_VALUE_ADMINSONLY);
const UPGRADE_TYPE_KEY_DELETE = 'Delete';
const UPGRADE_TYPE_KEY_DEPRECATE_ONLY = 'DeprecateOnly';
const UPGRADE_TYPE_KEY_MIXED = 'Mixed';
const UPGRADE_TYPE_VALUE_DELETE = 'delete-only';
const UPGRADE_TYPE_VALUE_DEPRECATE_ONLY = 'deprecate-only';
const UPGRADE_TYPE_VALUE_MIXED = 'mixed-mode';
const UPGRADE_TYPE_MAP = new Map();
UPGRADE_TYPE_MAP.set(UPGRADE_TYPE_KEY_DELETE, UPGRADE_TYPE_VALUE_DELETE);
UPGRADE_TYPE_MAP.set(UPGRADE_TYPE_KEY_DEPRECATE_ONLY, UPGRADE_TYPE_VALUE_DEPRECATE_ONLY);
UPGRADE_TYPE_MAP.set(UPGRADE_TYPE_KEY_MIXED, UPGRADE_TYPE_VALUE_MIXED);
const APEX_COMPILE_KEY_ALL = 'all';
const APEX_COMPILE_KEY_PACKAGE = 'package';
const APEX_COMPILE_VALUE_ALL = 'all';
const APEX_COMPILE_VALUE_PACKAGE = 'package';
const APEX_COMPILE_MAP = new Map();
APEX_COMPILE_MAP.set(APEX_COMPILE_KEY_ALL, APEX_COMPILE_VALUE_ALL);
APEX_COMPILE_MAP.set(APEX_COMPILE_KEY_PACKAGE, APEX_COMPILE_VALUE_PACKAGE);
/**
* Private utility to parse out errors from PackageInstallRequest as a user-readable string.
*/
const readInstallErrorsAsString = function (request) {
if (request.Errors && request.Errors.errors) {
const errorsArray = request.Errors.errors;
const len = errorsArray.length;
if (len > 0) {
let errorMessage = 'Installation errors: ';
for (let i = 0; i < len; i++) {
errorMessage += `\n${i + 1}) ${errorsArray[i].message}`;
}
return errorMessage;
}
}
return '<empty>';
};
class PackageInstallCommand {
// TODO: proper property typing
// eslint-disable-next-line no-undef
[property: string]: any;
constructor(stdinPrompt?) {
this.pollIntervalMillis = DEFAULT_POLL_INTERVAL_MILLIS;
this.replicationPollIntervalMillis = REPLICATION_POLLING_INTERVAL_MILLIS;
this.maxRetries = DEFAULT_MAX_RETRIES;
this.allPackageVersionId = null;
this.installationKey = null;
this.publishwait = DEFAULT_PUBLISH_WAIT_MIN;
this.logger = logger.child('PackageInstallCommand');
this.stdinPrompt = stdinPrompt;
this.packageInstallRequest = {};
}
poll(context, id, retries) {
this.org = context.org;
this.configApi = this.org.config;
this.force = this.org.force;
return this.force.toolingRetrieve(this.org, 'PackageInstallRequest', id).then((request) => {
switch (request.Status) {
case 'SUCCESS':
return request;
case 'ERROR': {
const err = readInstallErrorsAsString(request);
this.logger.error('Encountered errors installing the package!', err);
throw new Error(err);
}
default:
if (retries > 0) {
// Request still in progress. Just log a message and move on. Server will be polled again.
this.logger.log(messages.getMessage('installStatus', request.Status, 'packaging'));
return BBPromise.delay(this.pollIntervalMillis).then(() => this.poll(context, id, retries - 1));
} else {
// timed out
}
}
return request;
});
}
async _waitForApvReplication(remainingRetries) {
const QUERY_NO_KEY =
'SELECT Id, SubscriberPackageId, InstallValidationStatus FROM SubscriberPackageVersion' +
` WHERE Id ='${this.allPackageVersionId}'`;
const escapedInstallationKey =
this.installationKey != null ? this.installationKey.replace(/\\/g, '\\\\').replace(/\'/g, "\\'") : null;
const QUERY_W_KEY =
'SELECT Id, SubscriberPackageId, InstallValidationStatus FROM SubscriberPackageVersion' +
` WHERE Id ='${this.allPackageVersionId}' AND InstallationKey ='${escapedInstallationKey}'`;
let queryResult = null;
try {
queryResult = await this.force.toolingQuery(this.org, util.format(QUERY_W_KEY));
} catch (e) {
// Check first for Implementation Restriction error that is enforced in 214, before it was possible to query
// against InstallationKey, otherwise surface the error.
if (pkgUtils.isErrorFromSPVQueryRestriction(e)) {
queryResult = await this.force.toolingQuery(this.org, util.format(QUERY_NO_KEY));
} else {
if (!pkgUtils.isErrorPackageNotAvailable(e)) {
throw e;
}
}
}
// Continue retrying if there is no record
// or for an InstallValidationStatus of PACKAGE_UNAVAILABLE (replication to the subscriber's instance has not completed)
// or for an InstallValidationStatus of UNINSTALL_IN_PROGRESS
let installValidationStatus = null;
if (queryResult && queryResult.records && queryResult.records.length > 0) {
installValidationStatus = queryResult.records[0].InstallValidationStatus;
if (installValidationStatus != 'PACKAGE_UNAVAILABLE' && installValidationStatus != 'UNINSTALL_IN_PROGRESS') {
return queryResult.records[0];
}
}
if (remainingRetries <= 0) {
// There are no more reties. Throw an error indicating the package is unavailable.
// For UNINSTALL_IN_PROGRESS, though, allow install to proceed which will result in an appropriate UninstallInProgressProblem
// error message being displayed.
if (installValidationStatus == 'UNINSTALL_IN_PROGRESS') {
return null;
} else {
throw new Error(messages.getMessage('errorApvIdNotPublished', [], 'package_install'));
}
}
return BBPromise.delay(this.replicationPollIntervalMillis).then(() => {
this.logger.log(messages.getMessage('publishWaitProgress', [], 'package_install'));
return this._waitForApvReplication(remainingRetries - 1);
});
}
/**
* This installs a package version into a target org.
*
* @param context: heroku context
* @returns {*|promise}
*/
async execute(context) {
this.org = context.org;
this.configApi = this.org.config;
this.force = this.org.force;
// either of the id or package flag is required, not both at the same time
if ((!context.flags.id && !context.flags.package) || (context.flags.id && context.flags.package)) {
const idFlag = context.command.flags.find((x) => x.name === 'id');
const packageFlag = context.command.flags.find((x) => x.name === 'package');
throw new Error(
messages.getMessage(
'errorRequiredFlags',
[`--${idFlag.name} (-${idFlag.char})`, `--${packageFlag.name}`],
'package_install'
)
);
}
let apvId;
if (context.flags.id) {
apvId = context.flags.id;
} else if (context.flags.package) {
// look up the alias only when it's not a 04t
apvId = context.flags.package.startsWith(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID.prefix)
? context.flags.package
: pkgUtils.getPackageIdFromAlias(context.flags.package, this.force);
}
// validate whatever is set as the apvId, even if that might be a bunk alias
try {
pkgUtils.validateId(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, apvId);
} catch (err) {
throw new Error(messages.getMessage('invalidIdOrPackage', apvId, 'package_install'));
}
this.allPackageVersionId = apvId;
this.maxRetries = _.isNil(context.flags.wait)
? this.maxRetries
: (RETRY_MINUTES_IN_MILLIS / this.pollIntervalMillis) * context.flags.wait;
// Be careful with the fact that cmd line flags are NOT camel cased: flags.installationkey
this.installationKey = _.isNil(context.flags.installationkey)
? this.installationKey
: context.flags.installationkey;
this.publishwait = _.isNil(context.flags.publishwait) ? this.publishwait : context.flags.publishwait;
const apiVersion = this.configApi.getApiVersion();
if (apiVersion < 36) {
throw new Error('This command is supported only on API versions 36.0 and higher');
}
const publishWaitRetries = Math.ceil(
(parseInt(this.publishwait) * 60 * 1000) / parseInt(this.replicationPollIntervalMillis)
);
await this._waitForApvReplication(publishWaitRetries);
const pkgType = await pkgUtils.getPackage2TypeBy04t(apvId, this.force, this.org, this.installationKey);
// If the user has specified --upgradetype Delete, then prompt for confirmation
// unless the noprompt option has been included
if (context.flags.upgradetype == UPGRADE_TYPE_KEY_DELETE && pkgType === 'Unlocked') {
// don't prompt if we're going to ignore anyway
const accepted = await this._prompt(
context.flags.noprompt,
messages.getMessage('promptUpgradeType', [], 'package_install')
);
if (!accepted) {
throw new Error(messages.getMessage('promptUpgradeTypeDeny', [], 'package_install'));
}
}
// If the user is installing an unlocked package with external sites (RSS/CSP) then
// inform and prompt the user of these sites for acknowledgement.
const externalSiteData = await this._getExternalSites(this.allPackageVersionId);
let enableExternalSites = false;
if (externalSiteData.trustedSites && externalSiteData.trustedSites.length > 0) {
const accepted = await this._prompt(
context.flags.noprompt,
messages.getMessage('promptRss', externalSiteData.trustedSites.join('\n'), 'package_install')
);
if (accepted) {
enableExternalSites = true;
}
}
// Construct PackageInstallRequest sobject used to trigger package version install.
this.packageInstallRequest.subscriberPackageVersionKey = this.allPackageVersionId;
this.packageInstallRequest.password = this.installationKey; // W-3980736 in the future we hope to change "Password" to "InstallationKey" on the server
if (context.flags.upgradetype !== UPGRADE_TYPE_KEY_MIXED) {
if (pkgType === 'Unlocked') {
// include upgradetype if it's not the default value 'mixed'
this.packageInstallRequest.upgradeType = UPGRADE_TYPE_MAP.get(context.flags.upgradetype);
} else {
this.logger.log(packagingMessages.getMessage('install.warningUpgradeTypeOnlyForUnlocked'));
}
}
if (context.flags.apexcompile !== APEX_COMPILE_KEY_ALL) {
if (pkgType === 'Unlocked') {
// include apexcompile if it's not the default value 'all'
this.packageInstallRequest.apexCompileType = APEX_COMPILE_MAP.get(context.flags.apexcompile);
} else {
this.logger.log(packagingMessages.getMessage('install.warningApexCompileOnlyForUnlocked'));
}
}
// Add default parameters to input object.
this.packageInstallRequest.securityType = SECURITY_TYPE_MAP.get(context.flags.securitytype);
this.packageInstallRequest.nameConflictResolution = 'Block';
this.packageInstallRequest.packageInstallSource = 'U';
this.packageInstallRequest.enableRss = enableExternalSites;
const result = await this.force.toolingCreate(this.org, 'PackageInstallRequest', this.packageInstallRequest);
const packageInstallRequestId = result.id;
if (_.isNil(packageInstallRequestId)) {
throw new Error(`Failed to create PackageInstallRequest for: ${this.allPackageVersionId}`);
}
return this.poll(context, packageInstallRequestId, this.maxRetries);
}
async _prompt(noninteractive, message) {
const answer = noninteractive ? 'YES' : await this.stdinPrompt(message);
// print a line of white space after the prompt is entered for separation
this.logger.log('');
return answer.toUpperCase() === 'YES' || answer.toUpperCase() === 'Y';
}
/**
* Returns all RSS/CSP external third party websites
*
* @param allPackageVersionId
* @returns {object}
*
* {
* unlocked: boolean,
* trustedSites: [string]
* }
*/
async _getExternalSites(allPackageVersionId) {
const subscriberPackageValues: any = {};
const query_no_key =
'SELECT RemoteSiteSettings, CspTrustedSites ' +
'FROM SubscriberPackageVersion ' +
`WHERE Id ='${allPackageVersionId}'`;
const escapedInstallationKey =
this.installationKey != null ? this.installationKey.replace(/\\/g, '\\\\').replace(/\'/g, "\\'") : null;
const query_w_key =
'SELECT RemoteSiteSettings, CspTrustedSites ' +
'FROM SubscriberPackageVersion ' +
`WHERE Id ='${allPackageVersionId}' AND InstallationKey ='${escapedInstallationKey}'`;
let queryResult = null;
try {
queryResult = await this.force.toolingQuery(this.org, query_w_key);
} catch (e) {
// Check first for Implementation Restriction error that is enforced in 214, before it was possible to query
// against InstallationKey, otherwise surface the error.
if (pkgUtils.isErrorFromSPVQueryRestriction(e)) {
queryResult = await this.force.toolingQuery(this.org, query_no_key);
} else {
throw e;
}
}
if (queryResult.records && queryResult.records.length > 0) {
const record = queryResult.records[0];
const rssUrls = record.RemoteSiteSettings.settings.map((rss) => rss.url);
const cspUrls = record.CspTrustedSites.settings.map((csp) => csp.endpointUrl);
subscriberPackageValues.trustedSites = rssUrls.concat(cspUrls);
}
return subscriberPackageValues;
}
/**
* returns a human readable message for a cli output
*
* @returns {string}
*/
getHumanSuccessMessage(result) {
switch (result.Status) {
case 'SUCCESS':
return messages.getMessage(result.Status, [result.SubscriberPackageVersionKey], 'package_install_report');
case 'TERMINATED':
return '';
default:
return messages.getMessage(result.Status, [result.Id, this.org.name], 'package_install_report');
}
}
}
export = PackageInstallCommand; | the_stack |
import {
timelineFrameBeforeActiveItem,
timelineFrameAfterActiveItem,
} from '../timelineFrames'
import {
START_TERMINAL_ITEM_ID,
END_TERMINAL_ITEM_ID,
PRESAVED_STEP_ID,
} from '../../steplist/types'
import {
SINGLE_STEP_SELECTION_TYPE,
TERMINAL_ITEM_SELECTION_TYPE,
HoverableItem,
} from '../../ui/steps/reducers'
import { CommandsAndRobotState } from '@opentrons/step-generation'
import { StepIdType } from '../../form-types'
const initialRobotState: any = 'fake initial robot state'
const initialFrame: any = {
robotState: initialRobotState,
commands: [],
}
const lastValidRobotState: any = 'fake last valid robot state'
const lastValidFrame: any = {
robotState: lastValidRobotState,
commands: [],
}
const orderedStepIds: StepIdType[] = [
'step1',
'step2',
'step3',
'step4',
'step5',
]
describe('timelineFrameBeforeActiveItem', () => {
describe('full timeline (no errors)', () => {
// this should represent the full timeline, no errors in any steps
const fullRobotStateTimeline: any = {
timeline: ['frameA', 'frameB', 'frameC', 'frameD', 'frameE'],
}
const noErrorTestCases: Array<{
title: string
activeItem: HoverableItem | null
expected: CommandsAndRobotState | null | string
}> = [
{
title: 'should return null when there is no activeItem',
activeItem: null,
expected: null,
},
{
title:
'should return the correct timeline frame when the initial deck setup is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: START_TERMINAL_ITEM_ID,
},
expected: initialFrame,
},
{
title:
'should return the last timeline frame when final deck state is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: END_TERMINAL_ITEM_ID,
},
expected: lastValidFrame,
},
{
title:
'should return the last timeline frame when presaved form item is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: PRESAVED_STEP_ID,
},
expected: lastValidFrame,
},
{
title:
'should return the timeline frame before step 5 when step 5 is selected',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step5',
},
expected: 'frameD',
},
]
noErrorTestCases.forEach(({ title, activeItem, expected }) => {
it(title, () => {
const result = (timelineFrameBeforeActiveItem as any).resultFunc(
activeItem,
initialRobotState,
fullRobotStateTimeline,
lastValidRobotState,
orderedStepIds
)
expect(result).toEqual(expected)
})
})
})
describe('error case (timeline trunacted due to error at step 3)', () => {
// this should represent a timeline truncated due to error in step 3
const truncatedRobotStateTimeline: any = {
timeline: ['frameA', 'frameB'],
errors: ['fake error (truncating timeline at step 3)'],
}
const errorTestCases: Array<{
title: string
activeItem: HoverableItem | null
expected: CommandsAndRobotState | null | string
}> = [
{
title:
'should return the correct timeline frame when final deck state is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: END_TERMINAL_ITEM_ID,
},
expected: lastValidFrame,
},
{
title:
'should return the correct timeline frame when presaved form item is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: PRESAVED_STEP_ID,
},
expected: lastValidFrame,
},
{
title: 'should return the timeline frame before step 1',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step1',
},
expected: initialFrame,
},
{
title: 'should return the timeline frame before step 2',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step2',
},
expected: 'frameA',
},
{
title: 'should return the timeline frame before step 3',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step3',
},
expected: 'frameB',
},
{
title:
'should return the last valid timeline frame before step 4 (timeline error case)',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step4',
},
expected: lastValidFrame,
},
{
title:
'should return the last valid timeline frame before step 5 (timeline error case)',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step4',
},
expected: lastValidFrame,
},
]
errorTestCases.forEach(({ title, activeItem, expected }) => {
it(title, () => {
const result = (timelineFrameBeforeActiveItem as any).resultFunc(
activeItem,
initialRobotState,
truncatedRobotStateTimeline,
lastValidRobotState,
orderedStepIds
)
expect(result).toEqual(expected)
})
})
})
})
describe('timelineFrameAfterActiveItem', () => {
describe('full timeline (no errors)', () => {
// this should represent the full timeline, no errors in any steps
const fullRobotStateTimeline: any = {
timeline: ['frameA', 'frameB', 'frameC', 'frameD', 'frameE'],
}
const noErrorTestCases: Array<{
title: string
activeItem: HoverableItem | null
expected: CommandsAndRobotState | null | string
}> = [
{
title: 'should return null when there is no activeItem',
activeItem: null,
expected: null,
},
{
title:
'should return the correct timeline frame when the initial deck setup is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: START_TERMINAL_ITEM_ID,
},
expected: initialFrame,
},
{
title:
'should return the last timeline frame when final deck state is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: END_TERMINAL_ITEM_ID,
},
expected: lastValidFrame,
},
{
title:
'should return the last timeline frame when presaved form item is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: PRESAVED_STEP_ID,
},
expected: lastValidFrame,
},
{
title:
'should return the timeline frame after step 1 when step 1 is selected',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step1',
},
expected: 'frameA',
},
{
title:
'should return the timeline frame after step 5 when step 5 is selected',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step5',
},
expected: 'frameE',
},
]
noErrorTestCases.forEach(({ title, activeItem, expected }) => {
it(title, () => {
const result = (timelineFrameAfterActiveItem as any).resultFunc(
activeItem,
initialRobotState,
fullRobotStateTimeline,
lastValidRobotState,
orderedStepIds
)
expect(result).toEqual(expected)
})
})
})
describe('error case (timeline trunacted due to error at step 3)', () => {
// this should represent a timeline truncated due to error in step 3
const truncatedRobotStateTimeline: any = {
timeline: ['frameA', 'frameB'],
errors: ['fake error (truncating timeline at step 3)'],
}
const errorTestCases: Array<{
title: string
activeItem: HoverableItem | null
expected: CommandsAndRobotState | null | string
}> = [
{
title:
'should return the correct timeline frame when final deck state is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: END_TERMINAL_ITEM_ID,
},
expected: lastValidFrame,
},
{
title:
'should return the correct timeline frame when presaved form item is active',
activeItem: {
selectionType: TERMINAL_ITEM_SELECTION_TYPE,
id: PRESAVED_STEP_ID,
},
expected: lastValidFrame,
},
{
title: 'should return the timeline frame after step 1',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step1',
},
expected: 'frameA',
},
{
title: 'should return the timeline frame after step 2',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step2',
},
expected: 'frameB',
},
{
title:
'should return the timeline frame after step 3 (timeline error case)',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step3',
},
expected: lastValidFrame,
},
{
title:
'should return the last valid timeline frame after step 4 (timeline error case)',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step4',
},
expected: lastValidFrame,
},
{
title:
'should return the last valid timeline frame after step 5 (timeline error case)',
activeItem: {
selectionType: SINGLE_STEP_SELECTION_TYPE,
id: 'step4',
},
expected: lastValidFrame,
},
]
errorTestCases.forEach(({ title, activeItem, expected }) => {
it(title, () => {
const result = (timelineFrameAfterActiveItem as any).resultFunc(
activeItem,
initialRobotState,
truncatedRobotStateTimeline,
lastValidRobotState,
orderedStepIds
)
expect(result).toEqual(expected)
})
})
})
}) | the_stack |
import ms from 'ms';
import fs from 'fs-extra';
import { join } from 'path';
import build from '../../../src/commands/build';
import { client } from '../../mocks/client';
import { defaultProject, useProject } from '../../mocks/project';
import { useTeams } from '../../mocks/team';
import { useUser } from '../../mocks/user';
jest.setTimeout(ms('1 minute'));
const fixture = (name: string) =>
join(__dirname, '../../fixtures/unit/commands/build', name);
describe('build', () => {
const originalCwd = process.cwd();
it('should build with `@vercel/static`', async () => {
const cwd = fixture('static');
const output = join(cwd, '.vercel/output');
try {
process.chdir(cwd);
const exitCode = await build(client);
expect(exitCode).toEqual(0);
// `builds.json` says that "@vercel/static" was run
const builds = await fs.readJSON(join(output, 'builds.json'));
expect(builds).toMatchObject({
target: 'preview',
builds: [
{
require: '@vercel/static',
apiVersion: 2,
src: '**',
use: '@vercel/static',
},
],
});
// "static" directory contains static files
const files = await fs.readdir(join(output, 'static'));
expect(files.sort()).toEqual(['index.html']);
} finally {
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should build with `@vercel/node`', async () => {
const cwd = fixture('node');
const output = join(cwd, '.vercel/output');
try {
process.chdir(cwd);
const exitCode = await build(client);
expect(exitCode).toEqual(0);
// `builds.json` says that "@vercel/node" was run
const builds = await fs.readJSON(join(output, 'builds.json'));
expect(builds).toMatchObject({
target: 'preview',
builds: [
{
require: '@vercel/node',
apiVersion: 3,
use: '@vercel/node',
src: 'api/es6.js',
config: { zeroConfig: true },
},
{
require: '@vercel/node',
apiVersion: 3,
use: '@vercel/node',
src: 'api/index.js',
config: { zeroConfig: true },
},
{
require: '@vercel/node',
apiVersion: 3,
use: '@vercel/node',
src: 'api/mjs.mjs',
config: { zeroConfig: true },
},
{
require: '@vercel/node',
apiVersion: 3,
use: '@vercel/node',
src: 'api/typescript.ts',
config: { zeroConfig: true },
},
],
});
// "static" directory is empty
const hasStaticFiles = await fs.pathExists(join(output, 'static'));
expect(
hasStaticFiles,
'Expected ".vercel/output/static" to not exist'
).toEqual(false);
// "functions/api" directory has output Functions
const functions = await fs.readdir(join(output, 'functions/api'));
expect(functions.sort()).toEqual([
'es6.func',
'index.func',
'mjs.func',
'typescript.func',
]);
} finally {
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should normalize "src" path in `vercel.json`', async () => {
const cwd = fixture('normalize-src');
const output = join(cwd, '.vercel/output');
try {
process.chdir(cwd);
const exitCode = await build(client);
expect(exitCode).toEqual(0);
// `builds.json` says that "@vercel/node" was run
const builds = await fs.readJSON(join(output, 'builds.json'));
expect(builds).toMatchObject({
target: 'preview',
builds: [
{
require: '@vercel/node',
apiVersion: 3,
use: '@vercel/node',
src: 'server.js',
},
],
});
// `config.json` includes "route" from `vercel.json`
const config = await fs.readJSON(join(output, 'config.json'));
expect(config).toMatchObject({
version: 3,
routes: [
{
src: '^/(.*)$',
dest: '/server.js',
},
],
});
// "static" directory is empty
const hasStaticFiles = await fs.pathExists(join(output, 'static'));
expect(
hasStaticFiles,
'Expected ".vercel/output/static" to not exist'
).toEqual(false);
// "functions" directory has output Function
const functions = await fs.readdir(join(output, 'functions'));
expect(functions.sort()).toEqual(['server.js.func']);
} finally {
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should build with 3rd party Builder', async () => {
const cwd = fixture('third-party-builder');
const output = join(cwd, '.vercel/output');
try {
process.chdir(cwd);
const exitCode = await build(client);
expect(exitCode).toEqual(0);
// `builds.json` says that "@vercel/node" was run
const builds = await fs.readJSON(join(output, 'builds.json'));
expect(builds).toMatchObject({
target: 'preview',
builds: [
{
require: 'txt-builder',
apiVersion: 3,
use: 'txt-builder@0.0.0',
src: 'api/foo.txt',
config: {
zeroConfig: true,
functions: {
'api/*.txt': {
runtime: 'txt-builder@0.0.0',
},
},
},
},
{
require: '@vercel/static',
apiVersion: 2,
use: '@vercel/static',
src: '!{api/**,package.json,middleware.[jt]s}',
config: {
zeroConfig: true,
},
},
],
});
// "static" directory is empty
const hasStaticFiles = await fs.pathExists(join(output, 'static'));
expect(
hasStaticFiles,
'Expected ".vercel/output/static" to not exist'
).toEqual(false);
// "functions/api" directory has output Functions
const functions = await fs.readdir(join(output, 'functions/api'));
expect(functions.sort()).toEqual(['foo.func']);
const vcConfig = await fs.readJSON(
join(output, 'functions/api/foo.func/.vc-config.json')
);
expect(vcConfig).toMatchObject({
handler: 'api/foo.txt',
runtime: 'provided',
environment: {},
});
} finally {
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should serialize `EdgeFunction` output in version 3 Builder', async () => {
const cwd = fixture('edge-function');
const output = join(cwd, '.vercel/output');
try {
process.chdir(cwd);
client.setArgv('build', '--prod');
const exitCode = await build(client);
expect(exitCode).toEqual(0);
// `builds.json` says that "@vercel/node" was run
const builds = await fs.readJSON(join(output, 'builds.json'));
expect(builds).toMatchObject({
target: 'production',
builds: [
{
require: 'edge-function',
apiVersion: 3,
use: 'edge-function@0.0.0',
src: 'api/edge.js',
config: {
zeroConfig: true,
functions: {
'api/*.js': {
runtime: 'edge-function@0.0.0',
},
},
},
},
{
require: '@vercel/static',
apiVersion: 2,
use: '@vercel/static',
src: '!{api/**,package.json,middleware.[jt]s}',
config: {
zeroConfig: true,
},
},
],
});
// "static" directory is empty
const hasStaticFiles = await fs.pathExists(join(output, 'static'));
expect(
hasStaticFiles,
'Expected ".vercel/output/static" to not exist'
).toEqual(false);
// "functions/api" directory has output Functions
const functions = await fs.readdir(join(output, 'functions/api'));
expect(functions.sort()).toEqual(['edge.func']);
const vcConfig = await fs.readJSON(
join(output, 'functions/api/edge.func/.vc-config.json')
);
expect(vcConfig).toMatchObject({
runtime: 'edge',
name: 'api/edge.js',
deploymentTarget: 'v8-worker',
entrypoint: 'api/edge.js',
});
} finally {
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should pull "preview" env vars by default', async () => {
const cwd = fixture('static-pull');
useUser();
useTeams('team_dummy');
useProject({
...defaultProject,
id: 'vercel-pull-next',
name: 'vercel-pull-next',
});
const envFilePath = join(cwd, '.vercel', '.env.preview.local');
const projectJsonPath = join(cwd, '.vercel', 'project.json');
const originalProjectJson = await fs.readJSON(
join(cwd, '.vercel/project.json')
);
try {
process.chdir(cwd);
client.setArgv('build', '--yes');
const exitCode = await build(client);
expect(exitCode).toEqual(0);
const previewEnv = await fs.readFile(envFilePath, 'utf8');
const envFileHasPreviewEnv = previewEnv.includes(
'REDIS_CONNECTION_STRING'
);
expect(envFileHasPreviewEnv).toBeTruthy();
} finally {
await fs.remove(envFilePath);
await fs.writeJSON(projectJsonPath, originalProjectJson, { spaces: 2 });
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should pull "production" env vars with `--prod`', async () => {
const cwd = fixture('static-pull');
useUser();
useTeams('team_dummy');
useProject({
...defaultProject,
id: 'vercel-pull-next',
name: 'vercel-pull-next',
});
const envFilePath = join(cwd, '.vercel', '.env.production.local');
const projectJsonPath = join(cwd, '.vercel', 'project.json');
const originalProjectJson = await fs.readJSON(
join(cwd, '.vercel/project.json')
);
try {
process.chdir(cwd);
client.setArgv('build', '--yes', '--prod');
const exitCode = await build(client);
expect(exitCode).toEqual(0);
const prodEnv = await fs.readFile(envFilePath, 'utf8');
const envFileHasProductionEnv1 = prodEnv.includes(
'REDIS_CONNECTION_STRING'
);
expect(envFileHasProductionEnv1).toBeTruthy();
const envFileHasProductionEnv2 = prodEnv.includes(
'SQL_CONNECTION_STRING'
);
expect(envFileHasProductionEnv2).toBeTruthy();
} finally {
await fs.remove(envFilePath);
await fs.writeJSON(projectJsonPath, originalProjectJson, { spaces: 2 });
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
it('should build root-level `middleware.js` and exclude from static files', async () => {
const cwd = fixture('middleware');
const output = join(cwd, '.vercel/output');
try {
process.chdir(cwd);
const exitCode = await build(client);
expect(exitCode).toEqual(0);
// `builds.json` says that "@vercel/static" was run
const builds = await fs.readJSON(join(output, 'builds.json'));
expect(builds).toMatchObject({
target: 'preview',
builds: [
{
require: '@vercel/node',
apiVersion: 3,
use: '@vercel/node',
src: 'middleware.js',
config: {
zeroConfig: true,
middleware: true,
},
},
{
require: '@vercel/static',
apiVersion: 2,
use: '@vercel/static',
src: '!{api/**,package.json,middleware.[jt]s}',
config: {
zeroConfig: true,
},
},
],
});
// `config.json` includes the "middlewarePath" route
const config = await fs.readJSON(join(output, 'config.json'));
expect(config).toMatchObject({
version: 3,
routes: [
{ src: '/.*', middlewarePath: 'middleware', continue: true },
{ handle: 'filesystem' },
{ src: '^/api(/.*)?$', status: 404 },
{ handle: 'error' },
{ status: 404, src: '^(?!/api).*$', dest: '/404.html' },
],
});
// "static" directory contains `index.html`, but *not* `middleware.js`
const staticFiles = await fs.readdir(join(output, 'static'));
expect(staticFiles.sort()).toEqual(['index.html']);
// "functions" directory contains `middleware.func`
const functions = await fs.readdir(join(output, 'functions'));
expect(functions.sort()).toEqual(['middleware.func']);
} finally {
process.chdir(originalCwd);
delete process.env.__VERCEL_BUILD_RUNNING;
}
});
}); | the_stack |
import '@loaders.gl/polyfills';
import {join} from 'path';
import {I3SConverter, Tiles3DConverter} from '@loaders.gl/tile-converter';
import {DepsInstaller} from './deps-installer/deps-installer';
type TileConversionOptions = {
/** "I3S" - for I3S to 3DTiles conversion, "3DTILES" for 3DTiles to I3S conversion */
inputType?: string;
/** "tileset.json" file (3DTiles) / "http://..../SceneServer/layers/0" resource (I3S) */
tileset?: string;
/** Tileset name. This option is used for naming in resulting json resouces and for resulting path/*.slpk file naming */
name?: string;
/** Output folder. This folder will be created by converter if doesn't exist. It is relative to the converter path.
* Default: "data" folder */
output: string;
/** 3DTiles->I3S only. location of 7z.exe archiver to create slpk on Windows OS, default: "C:\Program Files\7-Zip\7z.exe" */
sevenZipExe: string;
/** location of the Earth Gravity Model (*.pgm) file to convert heights from ellipsoidal to gravity-related format,
* default: "./deps/egm2008-5.pgm". A model file can be loaded from GeographicLib
* https://geographiclib.sourceforge.io/html/geoid.html */
egm: string;
/** 3DTile->I3S only. Token for Cesium ION tileset authentication. */
token?: string;
/** 3DTiles->I3S only. Enable draco compression for geometry. Default: true */
draco: boolean;
/** Run the script for installing dependencies. Run this options separate from others. Now "*.pgm" file installation is
* implemented */
installDependencies: boolean;
/** 3DTile->I3S only. Enable KTX2 textures generation if only one of (JPG, PNG) texture is provided or generate JPG texture
* if only KTX2 is provided */
generateTextures: boolean;
/** 3DTile->I3S only. Will generate obb and mbs bounding volumes from geometry */
generateBoundingVolumes: boolean;
/** Validate the dataset during conversion. Validation messages will be posted in the console output */
validate: boolean;
/** Maximal depth of the hierarchical tiles tree traversal, default: infinite */
maxDepth?: number;
/** 3DTiles->I3S only. Whether the converter generates *.slpk (Scene Layer Package) I3S output file */
slpk: boolean;
};
/* During validation we check that particular options are defined so they can't be undefined */
type ValidatedTileConversionOptions = TileConversionOptions & {
/** "I3S" - for I3S to 3DTiles conversion, "3DTILES" for 3DTiles to I3S conversion */
inputType: string;
/** "tileset.json" file (3DTiles) / "http://..../SceneServer/layers/0" resource (I3S) */
tileset: string;
/** Tileset name. This option is used for naming in resulting json resouces and for resulting path/*.slpk file naming */
name: string;
};
const TILESET_TYPE = {
I3S: 'I3S',
_3DTILES: '3DTILES'
};
/**
* CLI entry
* @returns
*/
async function main() {
const [, , ...args] = process.argv;
if (args.length === 0) {
printHelp();
}
const validatedOptionsArr = validateOptionsWithEqual(args);
const options: TileConversionOptions = parseOptions(validatedOptionsArr);
if (options.installDependencies) {
const depthInstaller = new DepsInstaller();
depthInstaller.install('deps');
return;
}
const validatedOptions: ValidatedTileConversionOptions = validateOptions(options);
await convert(validatedOptions);
}
main().catch((error) => {
console.log(error);
process.exit(1); // eslint-disable-line
});
/**
* Output for `npx tile-converter --help`
*/
function printHelp(): void {
console.log('cli: converter 3dTiles to I3S or I3S to 3dTiles...');
console.log(
'--install-dependencies [Run the script for installing dependencies. Run this options separate from others. Now "*.pgm" file installation is implemented]'
);
console.log(
'--max-depth [Maximal depth of hierarchical tiles tree traversal, default: infinite]'
);
console.log('--name [Tileset name]');
console.log('--output [Output folder, default: "data" folder]');
console.log('--slpk [Generate slpk (Scene Layer Packages) I3S output file]');
console.log(
'--tileset [tileset.json file (3DTiles) / http://..../SceneServer/layers/0 resource (I3S)]'
);
console.log('--input-type [tileset input type: I3S or 3DTILES]');
console.log(
'--7zExe [location of 7z.exe archiver to create slpk on Windows, default: "C:\\Program Files\\7-Zip\\7z.exe"]'
);
console.log(
'--egm [location of Earth Gravity Model *.pgm file to convert heights from ellipsoidal to gravity-related format. A model file can be loaded from GeographicLib https://geographiclib.sourceforge.io/html/geoid.html], default: "./deps/egm2008-5.zip"'
);
console.log('--token [Token for Cesium ION tilesets authentication]');
console.log('--no-draco [Disable draco compression for geometry]');
console.log(
'--generate-textures [Enable KTX2 textures generation if only one of (JPG, PNG) texture is provided or generate JPG texture if only KTX2 is provided]'
);
console.log(
'--generate-bounding-volumes [Will generate obb and mbs bounding volumes from geometry]'
);
console.log('--validate [Enable validation]');
process.exit(0); // eslint-disable-line
}
/**
* Run conversion process
* @param options validated tile-converter options
*/
async function convert(options: ValidatedTileConversionOptions) {
console.log(`------------------------------------------------`); // eslint-disable-line
console.log(`Starting conversion of ${options.inputType}`); // eslint-disable-line
console.log(`------------------------------------------------`); // eslint-disable-line
const inputType = options.inputType.toUpperCase();
switch (inputType) {
case TILESET_TYPE.I3S:
const tiles3DConverter = new Tiles3DConverter();
tiles3DConverter.convert({
inputUrl: options.tileset,
outputPath: options.output,
tilesetName: options.name,
maxDepth: options.maxDepth,
egmFilePath: options.egm
});
break;
case TILESET_TYPE._3DTILES:
const converter = new I3SConverter();
await converter.convert({
inputUrl: options.tileset,
outputPath: options.output,
tilesetName: options.name,
maxDepth: options.maxDepth,
slpk: options.slpk,
sevenZipExe: options.sevenZipExe,
egmFilePath: options.egm,
token: options.token,
draco: options.draco,
generateTextures: options.generateTextures,
generateBoundingVolumes: options.generateBoundingVolumes,
validate: options.validate
});
break;
default:
printHelp();
}
}
// OPTIONS
/**
* Validate input options of the CLI command
* @param options - input options of the CLI command
* @returns validated options
*/
function validateOptions(options: TileConversionOptions): ValidatedTileConversionOptions {
const mandatoryOptionsWithExceptions: {
[key: string]: () => void;
} = {
name: () => console.log('Missed: --name [Tileset name]'),
output: () => console.log('Missed: --output [Output path name]'),
sevenZipExe: () => console.log('Missed: --7zExe [7z archiver executable path]'),
egm: () => console.log('Missed: --egm [*.pgm earth gravity model file path]'),
tileset: () => console.log('Missed: --tileset [tileset.json file]'),
inputType: () =>
console.log('Missed/Incorrect: --input-type [tileset input type: I3S or 3DTILES]')
};
const exceptions: (() => void)[] = [];
for (const mandatoryOption in mandatoryOptionsWithExceptions) {
const optionValue = options[mandatoryOption];
const isWrongInputType =
Boolean(optionValue) &&
mandatoryOption === 'inputType' &&
!Object.values(TILESET_TYPE).includes(optionValue.toUpperCase());
if (!optionValue || isWrongInputType) {
exceptions.push(mandatoryOptionsWithExceptions[mandatoryOption]);
}
}
if (exceptions.length) {
exceptions.forEach((exeption) => exeption());
process.exit(0); // eslint-disable-line
}
return <ValidatedTileConversionOptions>options;
}
function validateOptionsWithEqual(args: string[]): string[] {
return args.reduce((acc: string[], curr) => {
const equalSignIndex = curr.indexOf('=');
const beforeEqual = curr.slice(0, equalSignIndex);
const afterEqual = curr.slice(equalSignIndex + 1, curr.length);
const condition = curr.includes('=') && curr.startsWith('--') && afterEqual;
if (condition) {
return acc.concat(beforeEqual, afterEqual);
}
return acc.concat(curr);
}, []);
}
/**
* Parse option from the cli arguments array
* @param args
* @returns
*/
function parseOptions(args: string[]): TileConversionOptions {
const opts: TileConversionOptions = {
output: 'data',
sevenZipExe: 'C:\\Program Files\\7-Zip\\7z.exe',
egm: join(process.cwd(), 'deps', 'egm2008-5.pgm'),
draco: true,
installDependencies: false,
generateTextures: false,
generateBoundingVolumes: false,
validate: false,
slpk: false
};
// eslint-disable-next-line complexity
args.forEach((arg, index) => {
if (arg.indexOf('--') === 0) {
switch (arg) {
case '--input-type':
opts.inputType = getStringValue(index, args);
break;
case '--tileset':
opts.tileset = getStringValue(index, args);
break;
case '--name':
opts.name = getStringValue(index, args);
break;
case '--output':
opts.output = getStringValue(index, args);
break;
case '--max-depth':
opts.maxDepth = getIntegerValue(index, args);
break;
case '--slpk':
opts.slpk = getBooleanValue(index, args);
break;
case '--7zExe':
opts.sevenZipExe = getStringValue(index, args);
break;
case '--egm':
opts.egm = getStringValue(index, args);
break;
case '--token':
opts.token = getStringValue(index, args);
break;
case '--no-draco':
opts.draco = getBooleanValue(index, args);
break;
case '--validate':
opts.validate = getBooleanValue(index, args);
break;
case '--install-dependencies':
opts.installDependencies = getBooleanValue(index, args);
break;
case '--generate-textures':
opts.generateTextures = getBooleanValue(index, args);
break;
case '--generate-bounding-volumes':
opts.generateBoundingVolumes = getBooleanValue(index, args);
break;
case '--help':
printHelp();
break;
default:
console.warn(`Unknown option ${arg}`);
process.exit(0); // eslint-disable-line
}
}
});
return opts;
}
/**
* Get string option value from cli arguments
* @param index - option's name index in the argument's array.
* The value of the option should be next to name of the option.
* @param args - cli arguments array
* @returns - string value of the option
*/
function getStringValue(index: number, args: string[]): string {
if (index + 1 >= args.length) {
return '';
}
const value = args[index + 1];
if (value.indexOf('--') === 0) {
return '';
}
return value;
}
/**
* Get integer option value from cli arguments
* @param index - option's name index in the argument's array
* The value of the option should be next to name of the option.
* @param args - cli arguments array
* @returns - number value of the option
*/
function getIntegerValue(index: number, args: string[]): number {
const stringValue: string = getStringValue(index, args);
const result: number = Number.parseInt(stringValue);
if (isFinite(result)) {
return result;
}
return NaN;
}
function getBooleanValue(index: number, args: string[]): boolean {
const stringValue: string = getStringValue(index, args).toLowerCase().trim();
if (args[index] === '--no-draco' && !stringValue) {
return false;
}
if (!stringValue || stringValue === 'true') {
return true;
}
return false;
} | the_stack |
import * as arraybuffers from '../arraybuffers/arraybuffers';
import * as logging from '../logging/logging';
var log :logging.Log = new logging.Log('arithmetic shaper');
// Here is some background reading on arithmetic coding and range coding.
// http://www.arturocampos.com/ac_arithmetic.html
// http://www.arturocampos.com/ac_range.html
// http://www.compressconsult.com/rangecoder/
// http://sachingarg.com/compression/entropy_coding/range_coder.pdf
// http://ezcodesample.com/reanatomy.html
// http://www.cc.gatech.edu/~jarek/courses/7491/Arithmetic2.pdf
// http://www.drdobbs.com/cpp/data-compression-with-arithmetic-encodin/240169251?pgno=2
// Summarized from "A Fast Renormalisation Method for Arithmetic Coding" by
// Michael Schindler:
//
// At any point during arithmetic coding the output consists of four parts:
// 1. The part already written into the output buffer and does not change.
// 2. One digit that may be changed by at most one carry when adding to the
// lower end of the interval. There will never be two carries. since the
// range when fixing that digit was <= 1 unit. Two carries would require
// range > 1 unit.
// 3. There is a (possibly empty) block of digits that pass on a carry. (255 for
// bytes) that are represented by a counter counting their number.
// 4. The last part is represented by the low end range variable of the encoder.
// Returns the sum of a list of numbers
function sum(items :number[]) :number {
return items.reduce((a :number, b :number ) => {
return a + b;
}, 0);
}
// Takes an input list of integer and returns a list of integers where all of
// the input integer have been divided by a constant.
function scale(items :number[], divisor :number) :number[] {
return items.map((item :number) => {
let scaled = Math.floor(item / divisor);
if (scaled === 0) {
return 1;
} else {
return scaled;
}
});
}
// Takes a list of numbers where the inputs should all be integers from 0 to
// 255 and converts them to bytes in an ArrayBuffer.
function saveProbs(items :number[]) :ArrayBuffer {
var bytes = new Uint8Array(items.length);
for(var index = 0; index < items.length; index++) {
if (items[index] >= 0 && items[index] <= 255) {
bytes[index] = items[index];
} else {
throw new Error('Probabilities must be between 0 and 255 inclusive.');
}
}
return bytes.buffer;
}
// Models a symbol as an interval in the arithmetic coding space
export interface Interval {
// The byte that corresponds to this interval in the coding
symbol :number;
// The lower range of the interval
low :number;
// The length of this interval
length :number;
// The upper range of this interval
// This should always be lower+length
// This is precomputed and stored separately in order to increase the clarity
// of the implementation of the coding algorithm.
high :number
}
// Creates a new interval
// This maintains the constraint that high = low + length.
function makeInterval(symbol :number, low :number, length :number) {
return {
symbol: symbol,
low: low,
length: length,
high: low + length
}
}
// The precision of the arithmetic coder
const CODE_BITS :number = 32;
// The maximum possible signed value given the precision of the coder.
const TOP_VALUE :number = Math.pow(2, CODE_BITS - 1);
// The maximum possible unsigned value given the precision of the coder.
const MAX_INT :number = Math.pow(2, CODE_BITS) - 1;
// The number of bits to shift over during renormalization.
const SHIFT_BITS :number = CODE_BITS - 9;
// Tne number of bits left over during renormalization.
const EXTRA_BITS = (CODE_BITS - 2) % 8 + 1;
// The lowest possible value.
// Anything lower than this will be shifted up during renormalization.
const BOTTOM_VALUE = TOP_VALUE >>> 8;
// The state and initialiation code for arithmetic coding.
// This class is never instantiated directly.
// The subclasses Encoder and Decoder are used instead.
export class Coder {
// The probability distribution of the input.
// This will be a list of 256 entries, each consisting of an integer from
// 0 to 255.
protected probabilities_ :number[];
// The low end of the encoded range. Starts at 0.
protected low_ :number = 0x00000000;
// The high end of the encoded range. Starts at the maximum 32-bit value.
protected high_ :number = 0xFFFFFFFF;
// The extra bits that need to be stored for later if underflow occurs.
protected underflow_ :number = 0;
// The current byte that's being constructed for eventual output.
protected working_ :number = 0;
// A coding table derived from the probability distribution.
protected intervals_ :{[index :number] :Interval} = {};
// The total of the lengths of all intervals in the coding table.
// This determines the maximum amount that the range can change by encoding
// one symbol.
protected total_ :number;
// The input buffer. This is a list of bytes represented as numbers.
protected input_ :number[] = [];
// The output buffer. This is a list of bytes represented as numbers.
protected output_ :number[] = [];
// The Coder constructor normalizes the symbol probabilities and build the
// coding table.
public constructor(probs :number[]) {
// Scale the symbol probabilities to fit constraints.
this.probabilities_ = Coder.adjustProbs_(probs);
// Build the symbol table.
var low = 0;
for(var index = 0; index < probs.length; index++) {
this.intervals_[index] = makeInterval(index, low, probs[index]);
low = low + probs[index];
}
// Calculate the sum of the lengths of all intervals.
this.total_ = sum(this.probabilities_);
}
// Scale the symbol probabilities to fit the following constraints:
// - No probability can be higher than 255.
// - The sum of all probabilities must be less than 2^14.
static adjustProbs_ = (probs :number[]) :number[] => {
// The maximum value for any single probability
const MAX_PROB :number = 255;
// The amount to scale probabilities if they are greater than the maximum.
const SCALER :number = 256;
// The maximum value for the sum of all probabilities. 2^14
const MAX_SUM :number = 16384;
// If any single probability is too high, rescale.
var highestProb = Math.max(...probs);
if (highestProb > MAX_PROB) {
var divisor = highestProb / SCALER;
probs = scale(probs, divisor);
}
// If the sum of probabilities is too high, rescale.
while(sum(probs) >= MAX_SUM) {
probs = scale(probs, 2);
}
return probs;
}
}
// Encodes a sequence of bytes using a probability distribution with the goal of
// yielding a higher entropy sequence of bytes.
export class Encoder extends Coder {
// Encode a sequence of bytes.
public encode = (input :ArrayBuffer) :ArrayBuffer => {
// Initialize state.
// The Coder superclass initializes state common to Encoder and Decoder.
// Encoder and Decoder do some additional initialization that must be
// reset when encoding each byte sequence.
this.init_();
// Encode all of the symbols in the input ArrayBuffer
// The primary effect is to fill up the output buffer with output bytes.
// Internal state variables also change after encoding each symbol.
var bytes = new Uint8Array(input);
for(var index = 0; index < bytes.length; index++) {
this.encodeSymbol_(bytes[index]);
}
// Flush any remaining state in the internal state variables into
// the output buffer.
this.flush_();
// Copy the output buffer into an ArrayBuffer that can be returned.
var output = new Uint8Array(this.output_.length);
for(index = 0; index < this.output_.length; index++) {
output[index] = this.output_[index];
}
// Return the ArrayBuffer copy of the internal output buffer.
return output.buffer;
}
// Initialize state.
// The Coder superclass initializes state common to Encoer and Decoder.
// Encoder and Decoder do some additional initialization that must be
// reset when encoding each byte sequence.
private init_ = () :void => {
this.low_ = 0;
this.high_ = TOP_VALUE;
this.working_ = 0xCA;
this.underflow_ = 0;
this.input_ = [];
this.output_ = [];
}
// Encode a symbol. The symbol is a byte represented as a number.
// The effect of this is to change internal state variables.
// As a consequence, bytes may of may not be written to the output buffer.
// When all symbols have been encoded, flush() must be called to recover any
// remaining state.
private encodeSymbol_ = (symbol :number) => {
// Look up the corresponding interval for the symbol in the coding table.
// This is what we actually use for encoding.
var interval = this.intervals_[symbol];
// Renormalize. This is the complicated but less interesting part of coding.
// This is also where bytes are actually written to the output buffer.
this.renormalize_();
// Now do the interesting part of arithmetic coding.
// Every sequence of symbols is mapped to a positive integer.
// As we encode each symbol we are calculating the digits of this integer
// using the interval information for the symbol.
// The result of encoding a symbol is a new range, as represented by are new
// values for low_ and high_.
// The new symbol subdivides the existing range.
// Take the existing range and subdivide it by the total length of the
// intervals in the coding table.
var newRange = this.high_ / this.total_;
// Find the place in the new subdivide range where the new symbol's interval
// begins.
var temp = newRange * interval.low;
// The case where the symbol being encoded has the highest range is a
// special case.
if (interval.high >= this.total_) {
// Special case where the symbol being encoded has the highest range
// Adjust the high part of the range
this.high_ = this.high_ - temp;
} else {
// General case
// Adjust the high part of the range
this.high_ = newRange * interval.length;
}
// Adjust the low part of the range
this.low_ = this.low_ + temp;
}
// Summarized from "A Fast Renormalisation Method for Arithmetic Coding" by
// Michael Schindler:
//
// When doing encoding renormalisation the following can happen:
// A No renormalisation is needed since the range is in the desired interval.
// B The low end plus the range (this is the upper end of the interval) will
// not produce any carry. In this case the second and third part can be
// output as they will never change. The digit produced will become part two
// and part three will be empty.
// C The low end has already produced a carry. Here the (changed) second and
// third part can be output. There will not be another carry. Set the second
// and third part as before.
// D The digit produced will pass on a possible future carry, so it is added
// to the third block.
private renormalize_ = () :void => {
// If renormalization is needed, we are in case B, C, or D.
// Otherwise, we are in case A.
while(this.high_ <= BOTTOM_VALUE) {
if (this.low_ < (0xFF << SHIFT_BITS)) {
// B The low end plus the range (this is the upper end of the interval) will
// not produce any carry. In this case the second and third part can be
// output as they will never change. The digit produced will become part two
// and part three will be empty.
this.write_(this.working_);
for(; this.underflow_ !== 0; this.underflow_ = this.underflow_ - 1) {
this.write_(0xFF);
}
this.working_ = (this.low_ >>> SHIFT_BITS) & 0xFF;
} else if ((this.low_ & TOP_VALUE) !== 0) {
// C The low end has already produced a carry. Here the (changed) second and
// third part can be output. There will not be another carry. Set the second
// and third part as before.
this.write_(this.working_ + 1);
for(; this.underflow_ !== 0; this.underflow_ = this.underflow_ - 1) {
this.write_(0x00);
}
this.working_ = (this.low_ >>> SHIFT_BITS) & 0xFF;
} else {
// D The digit produced will pass on a possible future carry, so it is added
// to the third block.
this.underflow_ = this.underflow_ + 1;
}
// This is the goal of renormalization, to move the whole range over 8
// bits in order to make room for more computation.
this.high_ = (this.high_ << 8) >>> 0;
this.low_ = ((this.low_ << 8) & (TOP_VALUE - 1)) >>> 0;
}
// A No renormalisation is needed since the range is in the desired interval.
}
private flush_ = () :void => {
// Output the internal state variables.
this.renormalize_();
var temp = this.low_ >>> SHIFT_BITS;
if (temp > 0xFF) {
this.write_(this.working_ + 1);
for(; this.underflow_ !== 0; this.underflow_ = this.underflow_ - 1) {
this.write_(0x00);
}
} else {
this.write_(this.working_);
for(; this.underflow_ !== 0; this.underflow_ = this.underflow_ - 1) {
this.write_(0xFF);
}
}
// Output the remaining internal state.
this.write_(temp & 0xFF);
this.write_((this.low_ >>> (23 - 8)) & 0xFF);
// Output the length
this.write_((this.output_.length >>> 8) & 0xFF);
this.write_((this.output_.length) & 0xFF);
}
private write_ = (byte:number) :void => {
this.output_.push(byte);
}
}
// Decodes a sequence of bytes using a probability distribution with the goal of
// yielding a lower entropy sequence of bytes.
export class Decoder extends Coder {
// Decode a sequence of bytes
public decode = (input :ArrayBuffer) :ArrayBuffer => {
// Create an empty input buffer.
this.input_ = [];
// Fetch the size of the target output.
// This is encoded as two bytes at the end of the encoded byte sequence.
var sizeBytes = input.slice(-2);
// Decode the two-byte size into a number.
var size = arraybuffers.decodeShort(sizeBytes) - 4;
// Copy the bytes from the given ArrayBuffer into the internal input buffer.
var bytes = new Uint8Array(input);
for(var index = 0; index < bytes.length; index++) {
this.input_.push(bytes[index]);
}
// Initialize state.
// The Coder superclass initializes state common to Encoder and Decoder.
// Encoder and Decoder do some additional initialization that must be
// reset when encoding each byte sequence.
this.init_();
// Decode all of the symbols in the input buffer
// The primary effect is to fill up the output buffer with output bytes.
// Internal state variables also change after decoding each symbol.
this.decodeSymbols_();
// Flush any remaining state in the internal state variables into
// the output buffer.
this.flush_();
// Copy the output buffer into an ArrayBuffer that can be returned.
var output=new Uint8Array(this.output_.length);
for(index = 0; index < this.output_.length; index++) {
output[index] = this.output_[index];
}
return output.buffer;
}
// Initialize state variables for decoding.
private init_ = () :void => {
// Discard first byte because the encoder is weird.
var discard = this.input_.shift();
this.working_ = this.input_.shift();
this.low_ = this.working_ >>> (8 - EXTRA_BITS);
this.high_ = 1 << EXTRA_BITS;
this.underflow_ = 0;
this.output_ = [];
}
// Decode symbols from the input buffer until it is empty.
private decodeSymbols_ = () :void => {
while(this.input_.length > 0) {
this.decodeSymbol_();
}
}
// Run the decoding algorithm. This uses internal state variables and
// may or may not consume bytes from the input buffer.
// The primary result of running this is changing internal state variables
// and one byte will always be written to the output buffer.
// After decoding symbols, flush_ must be called to get the remaining state
// out of the internal state variables.
private decodeSymbol_ = () :void => {
// Renormalize. This is the complicated but less interesting part of coding.
// This is also where bytes are actually read from the input buffer.
this.renormalize_();
//
this.underflow_ = this.high_ >>> 8;
var temp = (this.low_ / this.underflow_) >>> 0;
// Calculate the byte to output.
// There is a special case for 255.
var result :number = null;
if (temp >>> 8 !== 0) {
// Special case.
// Output 255.
result = 255;
} else {
// General case.
// Output the byte that has been calculated.
result = temp;
}
// Output the decoded byte into the output buffer.
this.output_.push(result);
// Update the internal state variables base on the byte that was decoded.
this.update_(result);
}
// Renormalizing is the tricky but boring part of coding.
// The purpose of renormalizing is to allow the computation of an arbitrary
// precision fraction using only 32 bits of space.
// In the range coding variant of arithmetic coding implemented here,
// renormalization happens at bytes instead of bits. This means that it
// happens less frequently and so is faster to compute.
private renormalize_ = () :void => {
// Renormalization clears bits out of the working area to make room for
// more bits for computation. Continue until the working area is clear.
while(this.high_ <= BOTTOM_VALUE) {
// More the high bits over to make room.
// This might have caused the sign bit to be set, so coerce from a float
// to a 32-bit unsigned int.
this.high_ = (this.high_ << 8) >>> 0;
// Shift the low end of the range over to make room.
// Shift the working byte and move it into the low end of the range.
this.low_ = (this.low_ << 8) | ((this.working_ << EXTRA_BITS) & 0xFF);
// Obtain new bits to decode if there are any in the input buffer.
// There is a special case when the input buffer is empty.
if (this.input_.length == 0) {
// Special case. The input buffer is empty.
// This will only be called while flushing the internal state variables.
this.working_ = 0;
} else {
// General case. There input buffer has bits that have not been decoded.
// Put them in the working byte.
this.working_ = this.input_.shift();
}
// Load the bits from the new working byte into the low end of the range.
// Be careful not to overwrite the bits we stored in there from the old
// working byte.
this.low_ = (this.low_ | (this.working_ >>> (8-EXTRA_BITS)));
// Coerce the low end of the range from a float to a 32-bit unsigned int.
this.low_ = this.low_ >>> 0;
}
}
// Update internal state variables based on the symbol that was last decoded.
private update_ = (symbol :number) :void => {
// Look up the corresponding interval for the symbol in the coding table.
// This is what we actually use for encoding.
var interval = this.intervals_[symbol];
// Recover the bits stored from the underflow
// This will be 0 if there are no underflow bits.
var temp = this.underflow_ * interval.low;
// Adjust the low value to account for underflow.
// There is no adjustment if there are no underflow bits.
this.low_ = this.low_ - temp;
// The case where the symbol being encoded has the highest range is a
// special case.
if (interval.high >= this.total_) {
// Special case where the symbol being encoded has the highest range
// Adjust the high part of the range
this.high_ = this.high_ - temp;
} else {
// General case
// Adjust the high part of the range
this.high_ = this.underflow_*interval.length;
}
}
// Get the remaining information from the internal state variables and
// write it to the output buffer.
// This should be called after the input buffer is empty.
private flush_ = () :void => {
// Attempt to decode a symbol even though the input buffer is empty.
// This should get the remaining state out of working_.
this.decodeSymbol_();
// Renormalize. This should get the remaining state out of the rest of the
// internal state variables.
this.renormalize_();
}
} | the_stack |
import { } from '@cypress/react';
import { Action, Actions, BorderNode, DockLocation, IJsonModel, Model, Node, Orientation, Rect, RowNode, SplitterNode, TabNode, TabSetNode } from "../src";
/*
* The textRendered tabs: a representation of the model 'rendered' to a list of tab paths
* where /ts0/t1[One]* is tab index 1 in tabset 0 of the root row with name=One and its selected (ie. path + tabname and selected indicator))
*/
let tabsArray = []; // the rendered tabs as an array
let tabs = ""; // the rendered tabs array as a comma separated string
let pathMap: Record<string, Node> = {}; // maps tab path (e.g /ts1/t0) to the actual Node
let model: Model;
describe("Tree", function () {
context("Actions", () => {
afterEach(() => {
checkLayout(model);
});
context("Add", () => {
it("empty tabset", function () {
model = Model.fromJson(
{
global: {},
layout: {
type: "row",
children: [
{
type: "tabset",
id: "1",
enableDeleteWhenEmpty: false,
children: []
}
]
}
}
);
doAction(Actions.addNode({ id: "2", name: "newtab1", component: "grid" }, "1", DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[newtab1]*");
expect(tab("/ts0/t0").getId()).equal("2");
expect(tab("/ts0/t0").getComponent()).equal("grid");
});
context("tabsets", () => {
beforeEach(() => {
model = Model.fromJson(twoTabs);
textRender(model);
// two tabsets in a row, each with a single tab will textRender as:
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*");
});
it("add to tabset center", () => {
const id0 = tabset("/ts0").getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[One],/ts0/t1[newtab1]*,/ts1/t0[Two]*");
const id1 = tabset("/ts1").getId();
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id1, DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[One],/ts0/t1[newtab1]*,/ts1/t0[Two],/ts1/t1[newtab2]*");
});
it("add to tabset at position", () => {
const id0 = tabset("/ts0").getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.CENTER, 0));
expect(tabs).equal("/ts0/t0[newtab1]*,/ts0/t1[One],/ts1/t0[Two]*");
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id0, DockLocation.CENTER, 1));
expect(tabs).equal("/ts0/t0[newtab1],/ts0/t1[newtab2]*,/ts0/t2[One],/ts1/t0[Two]*");
doAction(Actions.addNode({ name: "newtab3", component: "grid" }, id0, DockLocation.CENTER, 3));
expect(tabs).equal("/ts0/t0[newtab1],/ts0/t1[newtab2],/ts0/t2[One],/ts0/t3[newtab3]*,/ts1/t0[Two]*");
});
it("add to tabset top", () => {
const id0 = tabset("/ts0").getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.TOP, -1));
expect(tabs).equal("/c0/ts0/t0[newtab1]*,/c0/ts1/t0[One]*,/ts1/t0[Two]*");
const id1 = tabset("/ts1").getId();
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id1, DockLocation.TOP, -1));
expect(tabs).equal("/c0/ts0/t0[newtab1]*,/c0/ts1/t0[One]*,/c1/ts0/t0[newtab2]*,/c1/ts1/t0[Two]*");
});
it("add to tabset bottom", () => {
const id0 = tabset("/ts0").getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.BOTTOM, -1));
expect(tabs).equal("/c0/ts0/t0[One]*,/c0/ts1/t0[newtab1]*,/ts1/t0[Two]*");
const id1 = tabset("/ts1").getId();
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id1, DockLocation.BOTTOM, -1));
expect(tabs).equal("/c0/ts0/t0[One]*,/c0/ts1/t0[newtab1]*,/c1/ts0/t0[Two]*,/c1/ts1/t0[newtab2]*");
});
it("add to tabset left", () => {
const id0 = tabset("/ts0").getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.LEFT, -1));
expect(tabs).equal("/ts0/t0[newtab1]*,/ts1/t0[One]*,/ts2/t0[Two]*");
const id1 = tabset("/ts2").getId();
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id1, DockLocation.LEFT, -1));
expect(tabs).equal("/ts0/t0[newtab1]*,/ts1/t0[One]*,/ts2/t0[newtab2]*,/ts3/t0[Two]*");
});
it("add to tabset right", () => {
const id0 = tabset("/ts0").getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.RIGHT, -1));
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[newtab1]*,/ts2/t0[Two]*");
const id1 = tabset("/ts2").getId();
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id1, DockLocation.RIGHT, -1));
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[newtab1]*,/ts2/t0[Two]*,/ts3/t0[newtab2]*");
});
});
context("borders", () => {
beforeEach(() => {
model = Model.fromJson(withBorders);
textRender(model);
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One]*");
});
it("add to top border", () => {
const path = "/b/top";
const others = tabsDontMatch(path);
const id0 = border(path).getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.CENTER, -1));
expect(tabsMatch(path)).equal("/b/top/t0[top1],/b/top/t1[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 0
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id0, DockLocation.CENTER, 0));
expect(tabsMatch(path)).equal("/b/top/t0[newtab2],/b/top/t1[top1],/b/top/t2[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 1
doAction(Actions.addNode({ name: "newtab3", component: "grid" }, id0, DockLocation.CENTER, 1));
expect(tabsMatch(path)).equal("/b/top/t0[newtab2],/b/top/t1[newtab3],/b/top/t2[top1],/b/top/t3[newtab1]");
expect(tabsDontMatch(path)).equal(others);
});
it("add to bottom border", () => {
const path = "/b/bottom";
const others = tabsDontMatch(path);
const id0 = border(path).getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.CENTER, -1));
expect(tabsMatch(path)).equal("/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/bottom/t2[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 0
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id0, DockLocation.CENTER, 0));
expect(tabsMatch(path)).equal("/b/bottom/t0[newtab2],/b/bottom/t1[bottom1],/b/bottom/t2[bottom2],/b/bottom/t3[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 1
doAction(Actions.addNode({ name: "newtab3", component: "grid" }, id0, DockLocation.CENTER, 1));
expect(tabsMatch(path)).equal("/b/bottom/t0[newtab2],/b/bottom/t1[newtab3],/b/bottom/t2[bottom1],/b/bottom/t3[bottom2],/b/bottom/t4[newtab1]");
expect(tabsDontMatch(path)).equal(others);
});
it("add to left border", () => {
const path = "/b/left";
const others = tabsDontMatch(path);
const id0 = border(path).getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.CENTER, -1));
expect(tabsMatch(path)).equal("/b/left/t0[left1],/b/left/t1[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 0
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id0, DockLocation.CENTER, 0));
expect(tabsMatch(path)).equal("/b/left/t0[newtab2],/b/left/t1[left1],/b/left/t2[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 1
doAction(Actions.addNode({ name: "newtab3", component: "grid" }, id0, DockLocation.CENTER, 1));
expect(tabsMatch(path)).equal("/b/left/t0[newtab2],/b/left/t1[newtab3],/b/left/t2[left1],/b/left/t3[newtab1]");
expect(tabsDontMatch(path)).equal(others);
});
it("add to right border", () => {
const path = "/b/right";
const others = tabsDontMatch(path);
const id0 = border(path).getId();
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, id0, DockLocation.CENTER, -1));
expect(tabsMatch(path)).equal("/b/right/t0[right1],/b/right/t1[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 0
doAction(Actions.addNode({ name: "newtab2", component: "grid" }, id0, DockLocation.CENTER, 0));
expect(tabsMatch(path)).equal("/b/right/t0[newtab2],/b/right/t1[right1],/b/right/t2[newtab1]");
expect(tabsDontMatch(path)).equal(others);
// add tab at position 1
doAction(Actions.addNode({ name: "newtab3", component: "grid" }, id0, DockLocation.CENTER, 1));
expect(tabsMatch(path)).equal("/b/right/t0[newtab2],/b/right/t1[newtab3],/b/right/t2[right1],/b/right/t3[newtab1]");
expect(tabsDontMatch(path)).equal(others);
});
});
});
context("Move", () => {
beforeEach(() => {
model = Model.fromJson(threeTabs);
textRender(model);
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*,/ts2/t0[Three]*");
});
it("move to center", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[Two],/ts0/t1[One]*,/ts1/t0[Three]*");
});
it("move to center position", () => {
let fromId = tab("/ts0/t0").getId();
const toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, 0));
expect(tabs).equal("/ts0/t0[One]*,/ts0/t1[Two],/ts1/t0[Three]*");
fromId = tab("/ts1/t0").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, 1));
expect(tabs).equal("/ts0/t0[One],/ts0/t1[Three]*,/ts0/t2[Two]");
});
it("move to top", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.TOP, -1));
expect(tabs).equal("/c0/ts0/t0[One]*,/c0/ts1/t0[Two]*,/ts1/t0[Three]*");
});
it("move to bottom", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.BOTTOM, -1));
expect(tabs).equal("/c0/ts0/t0[Two]*,/c0/ts1/t0[One]*,/ts1/t0[Three]*");
});
it("move to left", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.LEFT, -1));
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*,/ts2/t0[Three]*");
});
it("move to right", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.RIGHT, -1));
expect(tabs).equal("/ts0/t0[Two]*,/ts1/t0[One]*,/ts2/t0[Three]*");
});
});
context("Move to/from borders", () => {
beforeEach(() => {
model = Model.fromJson(withBorders);
textRender(model);
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One]*");
});
it("move to border top", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/b/top").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/top/t1[One],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1]");
});
it("move to border bottom", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/b/bottom").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/bottom/t2[One],/b/left/t0[left1],/b/right/t0[right1]");
});
it("move to border left", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/b/left").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/left/t1[One],/b/right/t0[right1]");
});
it("move to border right", () => {
const fromId = tab("/ts0/t0").getId();
const toId = tab("/b/right").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1],/b/right/t1[One]");
});
it("move from border top", () => {
const fromId = tab("/b/top/t0").getId();
const toId = tab("/ts0").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One],/ts0/t1[top1]*");
});
it("move from border bottom", () => {
const fromId = tab("/b/bottom/t0").getId();
const toId = tab("/ts0").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One],/ts0/t1[bottom1]*");
});
it("move from border left", () => {
const fromId = tab("/b/left/t0").getId();
const toId = tab("/ts0").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/right/t0[right1],/ts0/t0[One],/ts0/t1[left1]*");
});
it("move from border right", () => {
const fromId = tab("/b/right/t0").getId();
const toId = tab("/ts0").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/ts0/t0[One],/ts0/t1[right1]*");
});
});
context("Delete", () => {
beforeEach(() => {
});
it("delete from tabset with 1 tab", () => {
model = Model.fromJson(threeTabs);
textRender(model);
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*,/ts2/t0[Three]*");
doAction(Actions.deleteTab(tab("/ts0/t0").getId()));
expect(tabs).equal("/ts0/t0[Two]*,/ts1/t0[Three]*");
});
it("delete tab from tabset with 3 tabs", () => {
model = Model.fromJson(threeTabs);
textRender(model);
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*,/ts2/t0[Three]*");
let fromId = tab("/ts0/t0").getId();
let toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
fromId = tab("/ts1/t0").getId();
toId = tab("/ts0").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[Two],/ts0/t1[One],/ts0/t2[Three]*");
// now had three tabs in /ts0
doAction(Actions.deleteTab(tab("/ts0/t1").getId()));
expect(tabs).equal("/ts0/t0[Two],/ts0/t1[Three]*");
doAction(Actions.deleteTab(tab("/ts0/t1").getId()));
expect(tabs).equal("/ts0/t0[Two]*");
});
it("delete tabset", () => {
model = Model.fromJson(threeTabs);
textRender(model);
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*,/ts2/t0[Three]*");
let fromId = tab("/ts0/t0").getId();
let toId = tab("/ts1").getId();
doAction(Actions.moveNode(fromId, toId, DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[Two],/ts0/t1[One]*,/ts1/t0[Three]*");
doAction(Actions.deleteTabset(tabset("/ts0").getId()));
expect(tabs).equal("/ts0/t0[Three]*");
});
it("delete tab from borders", () => {
model = Model.fromJson(withBorders);
textRender(model);
expect(tabs).equal("/b/top/t0[top1],/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One]*");
doAction(Actions.deleteTab(tab("/b/top/t0").getId()));
expect(tabs).equal("/b/bottom/t0[bottom1],/b/bottom/t1[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One]*");
doAction(Actions.deleteTab(tab("/b/bottom/t0").getId()));
expect(tabs).equal("/b/bottom/t0[bottom2],/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One]*");
doAction(Actions.deleteTab(tab("/b/bottom/t0").getId()));
expect(tabs).equal("/b/left/t0[left1],/b/right/t0[right1],/ts0/t0[One]*");
doAction(Actions.deleteTab(tab("/b/left/t0").getId()));
expect(tabs).equal("/b/right/t0[right1],/ts0/t0[One]*");
doAction(Actions.deleteTab(tab("/b/right/t0").getId()));
expect(tabs).equal("/ts0/t0[One]*");
});
});
context("Other Actions", () => {
beforeEach(() => {
model = Model.fromJson(twoTabs);
textRender(model);
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*");
});
it("rename tab", () => {
doAction(Actions.renameTab(tab("/ts0/t0").getId(), "renamed"));
expect(tabs).equal("/ts0/t0[renamed]*,/ts1/t0[Two]*");
});
it("select tab", () => {
doAction(Actions.addNode({ name: "newtab1", component: "grid" }, tabset("/ts0").getId(), DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[One],/ts0/t1[newtab1]*,/ts1/t0[Two]*");
doAction(Actions.selectTab(tab("/ts0/t0").getId()));
expect(tabs).equal("/ts0/t0[One]*,/ts0/t1[newtab1],/ts1/t0[Two]*");
});
it("set active tabset", () => {
const ts0 = tabset("/ts0");
const ts1 = tabset("/ts1");
expect(ts0.isActive()).equal(false);
expect(ts1.isActive()).equal(false);
doAction(Actions.selectTab(tab("/ts0/t0").getId()));
expect(ts0.isActive()).equal(true);
expect(ts1.isActive()).equal(false);
doAction(Actions.selectTab(tab("/ts1/t0").getId()));
expect(ts0.isActive()).equal(false);
expect(ts1.isActive()).equal(true);
doAction(Actions.setActiveTabset(tabset("/ts0").getId()));
expect(ts0.isActive()).equal(true);
expect(ts1.isActive()).equal(false);
});
it("maximize tabset", () => {
expect(tabset("/ts0").isMaximized()).equals(false);
expect(tabset("/ts1").isMaximized()).equals(false);
doAction(Actions.maximizeToggle(tabset("/ts0").getId()));
expect(tabset("/ts0").isMaximized()).equals(true);
expect(tabset("/ts1").isMaximized()).equals(false);
doAction(Actions.maximizeToggle(tabset("/ts1").getId()));
expect(tabset("/ts0").isMaximized()).equals(false);
expect(tabset("/ts1").isMaximized()).equals(true);
expect(model.getMaximizedTabset()).equals(tabset("/ts1"));
doAction(Actions.maximizeToggle(tabset("/ts1").getId()));
expect(tabset("/ts0").isMaximized()).equals(false);
expect(tabset("/ts1").isMaximized()).equals(false);
expect(model.getMaximizedTabset()).equals(undefined);
});
it("float/unfloat tab", () => {
expect(tab("/ts1/t0").isFloating()).equals(false);
doAction(Actions.floatTab(tab("/ts1/t0").getId()));
expect(tab("/ts1/t0").isFloating()).equals(true);
doAction(Actions.unFloatTab(tab("/ts1/t0").getId()));
expect(tab("/ts1/t0").isFloating()).equals(false);
});
it("set tab attributes", () => {
expect(tab("/ts1/t0").getConfig()).equals(undefined);
doAction(Actions.updateNodeAttributes(tab("/ts1/t0").getId(), { config: "newConfig" }));
expect(tab("/ts1/t0").getConfig()).equals("newConfig");
});
it("set model attributes", () => {
expect(model.getSplitterSize()).equals(8);
doAction(Actions.updateModelAttributes({ splitterSize: 10 }));
expect(model.getSplitterSize()).equals(10);
});
});
});
context("Node events", () => {
beforeEach(() => {
model = Model.fromJson(twoTabs);
textRender(model);
expect(tabs).equal("/ts0/t0[One]*,/ts1/t0[Two]*");
});
it("close tab", () => {
let closed = false;
tab("/ts0/t0").setEventListener("close", () => { closed = true; })
doAction(Actions.deleteTab(tab("/ts0/t0").getId()));
expect(closed).equals(true);
});
it("save tab", () => {
let saved = false;
tab("/ts0/t0").setEventListener("save", () => { saved = true; })
model.toJson();
expect(saved).equals(true);
});
it("visibility tab", () => {
const layoutRect = new Rect(0, 0, 1000, 800);
model._layout(layoutRect, {
headerBarSize: 30,
tabBarSize: 30,
borderBarSize: 30
})
let visibility = true;
tab("/ts0/t0").setEventListener("visibility", (data) => {
visibility = data.visible;
console.log(data);
})
doAction(Actions.moveNode(tab("/ts1/t0").getId(), tabset("/ts0").getId(), DockLocation.CENTER, -1));
expect(tabs).equal("/ts0/t0[One],/ts0/t1[Two]*");
// need to layout for visibility to change!
model._layout(layoutRect, {
headerBarSize: 30,
tabBarSize: 30,
borderBarSize: 30
})
expect(visibility).equals(false);
});
it("resize tab", () => {
const layoutRect = new Rect(0, 0, 1000, 800);
model._layout(layoutRect, {
headerBarSize: 30,
tabBarSize: 30,
borderBarSize: 30
})
let resized = false;
tab("/ts0/t0").setEventListener("resize", () => { resized = true; })
expect(resized).equals(false);
model._layout(layoutRect, {
headerBarSize: 30,
tabBarSize: 130, // changed size
borderBarSize: 30
})
expect(resized).equals(true);
});
});
});
// ---------------------------- helpers ------------------------
function doAction(action: Action) {
model.doAction(action);
textRender(model);
}
// functions to save some inline casting
function tab(path: string) {
return pathMap[path] as TabNode;
}
function tabset(path: string) {
return pathMap[path] as TabSetNode;
}
function row(path: string) {
return pathMap[path] as RowNode;
}
function border(path: string) {
return pathMap[path] as BorderNode;
}
function tabsMatch(regExStr: string) {
const regex = new RegExp(regExStr);
return tabsArray.filter(t => regex.test(t)).join(",");
}
function tabsDontMatch(regExStr: string) {
const regex = new RegExp(regExStr);
return tabsArray.filter(t => !regex.test(t)).join(",");
}
function textRender(model: Model) {
pathMap = {};
tabsArray = [];
textRenderInner(pathMap, "", model.getBorderSet().getBorders());
textRenderInner(pathMap, "", model.getRoot().getChildren());
tabs = tabsArray.join(",");
}
function textRenderInner(pathMap: Record<string, Node>, path: string, children: Node[]) {
let index = 0;
let splitterIndex = 0;
children.forEach((c) => {
if (c instanceof BorderNode) {
const newpath = path + "/b/" + c.getLocation().getName();
pathMap[newpath] = c;
textRenderInner(pathMap, newpath, c.getChildren());
} else if (c instanceof TabSetNode) {
const newpath = path + "/ts" + index++;
pathMap[newpath] = c;
textRenderInner(pathMap, newpath, c.getChildren());
} else if (c instanceof TabNode) {
const newpath = path + "/t" + index++;
pathMap[newpath] = c;
const parent = c.getParent() as (BorderNode | TabSetNode);
const selected = parent.getSelectedNode() === c;
tabsArray.push(newpath + "[" + c.getName() + "]" + (selected ? "*" : ""));
textRenderInner(pathMap, newpath, c.getChildren());
} else if (c instanceof RowNode) {
const newpath = path + ((c.getOrientation() === Orientation.HORZ) ? "/r" : "/c") + index++;
pathMap[newpath] = c;
textRenderInner(pathMap, newpath, c.getChildren());
} else if (c instanceof SplitterNode) {
const newpath = path + "/s" + splitterIndex++;
pathMap[newpath] = c;
textRenderInner(pathMap, newpath, c.getChildren());
}
});
}
// check layout covers area
function checkLayout(model: Model) {
const layoutRect = new Rect(0, 0, 1000, 800);
model._layout(layoutRect, {
headerBarSize: 30,
tabBarSize: 30,
borderBarSize: 30
})
if (model.getMaximizedTabset() === undefined) {
// should also check borders
checkRowLayout(model.getRoot());
}
}
// check row children take up all space in row
function checkRowLayout(row: RowNode) {
const r = row.getRect();
if (row.getOrientation() === Orientation.HORZ) {
let x = r.x;
row._getDrawChildren().forEach(c => {
const cr = c.getRect();
expect(cr.height).equal(r.height);
x += cr.width;
if (c instanceof RowNode) {
checkRowLayout(c);
}
});
expect(x).equal(r.getRight());
} else {
let y = r.y;
row._getDrawChildren().forEach(c => {
const cr = c.getRect();
expect(cr.width).equal(r.width);
y += cr.height;
if (c instanceof RowNode) {
checkRowLayout(c);
}
});
expect(y).equal(r.getBottom());
}
}
// -------------------- layouts --------------------
const twoTabs: IJsonModel = {
global: {},
borders: [],
layout: {
type: "row",
weight: 100,
children: [
{
type: "tabset",
weight: 50,
children: [
{
type: "tab",
name: "One",
component: "text",
}
]
},
{
type: "tabset",
id: "#1",
weight: 50,
children: [
{
type: "tab",
name: "Two",
component: "text",
}
]
}
]
}
};
const withBorders: IJsonModel = {
global: {},
borders: [
{
"type": "border",
"location": "top",
"children": [
{
"type": "tab",
"name": "top1",
"component": "text"
}
]
},
{
"type": "border",
"location": "bottom",
"children": [
{
"type": "tab",
"name": "bottom1",
"component": "text"
},
{
"type": "tab",
"name": "bottom2",
"component": "text"
}
]
},
{
"type": "border",
"location": "left",
"children": [
{
"type": "tab",
"name": "left1",
"component": "text"
}
]
},
{
"type": "border",
"location": "right",
"children": [
{
"type": "tab",
"name": "right1",
"component": "text"
}
]
}
],
layout: {
type: "row",
weight: 100,
children: [
{
type: "tabset",
weight: 50,
children: [
{
type: "tab",
name: "One",
component: "text",
}
]
}
]
}
};
const threeTabs: IJsonModel = {
global: {},
borders: [],
layout: {
type: "row",
weight: 100,
children: [
{
type: "tabset",
weight: 50,
children: [
{
type: "tab",
name: "One",
component: "text",
}
]
},
{
type: "tabset",
weight: 50,
name: "TheHeader",
children: [
{
type: "tab",
name: "Two",
icon: "/test/images/settings.svg",
component: "text",
}
]
},
{
type: "tabset",
weight: 50,
children: [
{
type: "tab",
name: "Three",
component: "text",
}
]
}
]
}
}; | the_stack |
import 'neuroglancer/render_layer_backend';
import {Chunk, ChunkConstructor, ChunkRenderLayerBackend, ChunkSource, getNextMarkGeneration, withChunkManager} from 'neuroglancer/chunk_manager/backend';
import {ChunkPriorityTier, ChunkState} from 'neuroglancer/chunk_manager/base';
import {SharedWatchableValue} from 'neuroglancer/shared_watchable_value';
import { filterVisibleSources, forEachPlaneIntersectingVolumetricChunk, MultiscaleVolumetricDataRenderLayer, SLICEVIEW_ADD_VISIBLE_LAYER_RPC_ID, SLICEVIEW_REMOVE_VISIBLE_LAYER_RPC_ID, SLICEVIEW_RENDERLAYER_RPC_ID, SLICEVIEW_RPC_ID, SliceViewBase, SliceViewChunkSource as SliceViewChunkSourceInterface, SliceViewChunkSpecification, SliceViewRenderLayer as SliceViewRenderLayerInterface, TransformedSource, getNormalizedChunkLayout} from 'neuroglancer/sliceview/base';
import {ChunkLayout} from 'neuroglancer/sliceview/chunk_layout';
import {WatchableValueInterface} from 'neuroglancer/trackable_value';
import {erf} from 'neuroglancer/util/erf';
import {vec3, vec3Key} from 'neuroglancer/util/geom';
import {VelocityEstimator} from 'neuroglancer/util/velocity_estimation';
import {getBasePriority, getPriorityTier, withSharedVisibility} from 'neuroglancer/visibility_priority/backend';
import {registerRPC, registerSharedObject, RPC, SharedObjectCounterpart} from 'neuroglancer/worker_rpc';
export const BASE_PRIORITY = -1e12;
export const SCALE_PRIORITY_MULTIPLIER = 1e9;
// Temporary values used by SliceView.updateVisibleChunk
const tempChunkPosition = vec3.create();
const tempCenter = vec3.create();
const tempChunkSize = vec3.create();
class SliceViewCounterpartBase extends
SliceViewBase<SliceViewChunkSourceBackend, SliceViewRenderLayerBackend> {
constructor(rpc: RPC, options: any) {
super(rpc.get(options.projectionParameters));
this.initializeSharedObject(rpc, options['id']);
}
}
function disposeTransformedSources(
allSources: TransformedSource<SliceViewRenderLayerBackend, SliceViewChunkSourceBackend>[][]) {
for (const scales of allSources) {
for (const tsource of scales) {
tsource.source.dispose();
}
}
}
const SliceViewIntermediateBase = withSharedVisibility(withChunkManager(SliceViewCounterpartBase));
@registerSharedObject(SLICEVIEW_RPC_ID)
export class SliceViewBackend extends SliceViewIntermediateBase {
velocityEstimator = new VelocityEstimator();
constructor(rpc: RPC, options: any) {
super(rpc, options);
this.registerDisposer(this.chunkManager.recomputeChunkPriorities.add(() => {
this.updateVisibleChunks();
}));
this.registerDisposer(this.projectionParameters.changed.add(() => {
this.velocityEstimator.addSample(this.projectionParameters.value.globalPosition);
}));
}
invalidateVisibleChunks() {
super.invalidateVisibleChunks();
this.chunkManager.scheduleUpdateChunkPriorities();
}
handleLayerChanged = (() => {
this.chunkManager.scheduleUpdateChunkPriorities();
});
updateVisibleChunks() {
const projectionParameters = this.projectionParameters.value;
let chunkManager = this.chunkManager;
const visibility = this.visibility.value;
if (visibility === Number.NEGATIVE_INFINITY) {
return;
}
this.updateVisibleSources();
const {centerDataPosition} = projectionParameters;
const priorityTier = getPriorityTier(visibility);
let basePriority = getBasePriority(visibility);
basePriority += BASE_PRIORITY;
const localCenter = tempCenter;
const chunkSize = tempChunkSize;
const curVisibleChunks: SliceViewChunk[] = [];
this.velocityEstimator.addSample(this.projectionParameters.value.globalPosition);
for (const [layer, visibleLayerSources] of this.visibleLayers) {
chunkManager.registerLayer(layer);
const {visibleSources} = visibleLayerSources;
for (let i = 0, numVisibleSources = visibleSources.length; i < numVisibleSources; ++i) {
const tsource = visibleSources[i];
const prefetchOffsets = chunkManager.queueManager.enablePrefetch.value ?
getPrefetchChunkOffsets(this.velocityEstimator, tsource) :
[];
const {chunkLayout} = tsource;
chunkLayout.globalToLocalSpatial(localCenter, centerDataPosition);
const {size, finiteRank} = chunkLayout;
vec3.copy(chunkSize, size);
for (let i = finiteRank; i < 3; ++i) {
chunkSize[i] = 0;
localCenter[i] = 0;
}
const priorityIndex = i;
const sourceBasePriority = basePriority + SCALE_PRIORITY_MULTIPLIER * priorityIndex;
curVisibleChunks.length = 0;
const curMarkGeneration = getNextMarkGeneration();
forEachPlaneIntersectingVolumetricChunk(
projectionParameters, tsource.renderLayer.localPosition.value, tsource,
getNormalizedChunkLayout(projectionParameters, tsource.chunkLayout),
positionInChunks => {
vec3.multiply(tempChunkPosition, positionInChunks, chunkSize);
let priority = -vec3.distance(localCenter, tempChunkPosition);
const {curPositionInChunks} = tsource;
let chunk = tsource.source.getChunk(curPositionInChunks);
chunkManager.requestChunk(chunk, priorityTier, sourceBasePriority + priority);
++layer.numVisibleChunksNeeded;
if (chunk.state === ChunkState.GPU_MEMORY) {
++layer.numVisibleChunksAvailable;
}
curVisibleChunks.push(chunk);
// Mark visible chunks to avoid duplicate work when prefetching. Once we hit a
// visible chunk, we don't continue prefetching in the same direction.
chunk.markGeneration = curMarkGeneration;
});
if (prefetchOffsets.length !== 0) {
const {curPositionInChunks} = tsource;
for (const visibleChunk of curVisibleChunks) {
curPositionInChunks.set(visibleChunk.chunkGridPosition);
for (let j = 0, length = prefetchOffsets.length; j < length;) {
const chunkDim = prefetchOffsets[j];
const minChunk = prefetchOffsets[j + 2];
const maxChunk = prefetchOffsets[j + 3];
const newPriority = prefetchOffsets[j + 4];
const jumpOffset = prefetchOffsets[j + 5];
const oldIndex = curPositionInChunks[chunkDim];
const newIndex = oldIndex + prefetchOffsets[j + 1];
if (newIndex < minChunk || newIndex > maxChunk) {
j = jumpOffset;
continue;
}
curPositionInChunks[chunkDim] = newIndex;
const chunk = tsource.source.getChunk(curPositionInChunks);
curPositionInChunks[chunkDim] = oldIndex;
if (chunk.markGeneration === curMarkGeneration) {
j = jumpOffset;
continue;
}
if (!Number.isFinite(newPriority)) {
debugger;
}
chunkManager.requestChunk(
chunk, ChunkPriorityTier.PREFETCH, sourceBasePriority + newPriority);
++layer.numPrefetchChunksNeeded;
if (chunk.state === ChunkState.GPU_MEMORY) {
++layer.numPrefetchChunksAvailable;
}
j += PREFETCH_ENTRY_SIZE;
}
}
}
}
}
}
removeVisibleLayer(layer: SliceViewRenderLayerBackend) {
const {visibleLayers} = this;
const layerInfo = visibleLayers.get(layer)!;
visibleLayers.delete(layer);
disposeTransformedSources(layerInfo.allSources);
layer.renderScaleTarget.changed.remove(this.invalidateVisibleSources);
layer.localPosition.changed.remove(this.handleLayerChanged);
this.invalidateVisibleSources();
}
addVisibleLayer(
layer: SliceViewRenderLayerBackend,
allSources: TransformedSource<SliceViewRenderLayerBackend, SliceViewChunkSourceBackend>[][]) {
const {displayDimensionRenderInfo} = this.projectionParameters.value;
let layerInfo = this.visibleLayers.get(layer);
if (layerInfo === undefined) {
layerInfo = {
allSources,
visibleSources: [],
displayDimensionRenderInfo: displayDimensionRenderInfo,
};
this.visibleLayers.set(layer, layerInfo);
layer.renderScaleTarget.changed.add(() => this.invalidateVisibleSources());
layer.localPosition.changed.add(this.handleLayerChanged);
} else {
disposeTransformedSources(layerInfo.allSources);
layerInfo.allSources = allSources;
layerInfo.visibleSources.length = 0;
layerInfo.displayDimensionRenderInfo = displayDimensionRenderInfo;
}
this.invalidateVisibleSources();
}
disposed() {
for (let layer of this.visibleLayers.keys()) {
this.removeVisibleLayer(layer);
}
super.disposed();
}
invalidateVisibleSources() {
super.invalidateVisibleSources();
this.chunkManager.scheduleUpdateChunkPriorities();
}
}
export function deserializeTransformedSources<
Source extends SliceViewChunkSourceBackend, RLayer extends MultiscaleVolumetricDataRenderLayer>(
rpc: RPC, serializedSources: any[][], layer: any) {
const sources = serializedSources.map(
scales => scales.map((serializedSource): TransformedSource<RLayer, Source> => {
const source = rpc.getRef<Source>(serializedSource.source);
const chunkLayout = serializedSource.chunkLayout;
const {rank} = source.spec;
const tsource: TransformedSource<RLayer, Source> = {
renderLayer: layer,
source,
chunkLayout: ChunkLayout.fromObject(chunkLayout),
layerRank: serializedSource.layerRank,
nonDisplayLowerClipBound: serializedSource.nonDisplayLowerClipBound,
nonDisplayUpperClipBound: serializedSource.nonDisplayUpperClipBound,
lowerClipBound: serializedSource.lowerClipBound,
upperClipBound: serializedSource.upperClipBound,
lowerClipDisplayBound: serializedSource.lowerClipDisplayBound,
upperClipDisplayBound: serializedSource.upperClipDisplayBound,
lowerChunkDisplayBound: serializedSource.lowerChunkDisplayBound,
upperChunkDisplayBound: serializedSource.upperChunkDisplayBound,
effectiveVoxelSize: serializedSource.effectiveVoxelSize,
chunkDisplayDimensionIndices: serializedSource.chunkDisplayDimensionIndices,
fixedLayerToChunkTransform: serializedSource.fixedLayerToChunkTransform,
combinedGlobalLocalToChunkTransform: serializedSource.combinedGlobalLocalToChunkTransform,
curPositionInChunks: new Float32Array(rank),
fixedPositionWithinChunk: new Uint32Array(rank),
};
return tsource;
}));
return sources;
}
registerRPC(SLICEVIEW_ADD_VISIBLE_LAYER_RPC_ID, function(x) {
const obj = <SliceViewBackend>this.get(x['id']);
const layer = <SliceViewRenderLayerBackend>this.get(x['layerId']);
const sources =
deserializeTransformedSources<SliceViewChunkSourceBackend, SliceViewRenderLayerBackend>(
this, x.sources, layer);
obj.addVisibleLayer(layer, sources);
});
registerRPC(SLICEVIEW_REMOVE_VISIBLE_LAYER_RPC_ID, function(x) {
let obj = <SliceViewBackend>this.get(x['id']);
let layer = <SliceViewRenderLayerBackend>this.get(x['layerId']);
obj.removeVisibleLayer(layer);
});
export class SliceViewChunk extends Chunk {
chunkGridPosition: Float32Array;
source: SliceViewChunkSourceBackend|null = null;
constructor() {
super();
}
initializeVolumeChunk(key: string, chunkGridPosition: Float32Array) {
super.initialize(key);
this.chunkGridPosition = Float32Array.from(chunkGridPosition);
}
serialize(msg: any, transfers: any[]) {
super.serialize(msg, transfers);
msg['chunkGridPosition'] = this.chunkGridPosition;
}
downloadSucceeded() {
super.downloadSucceeded();
}
freeSystemMemory() {}
toString() {
return this.source!.toString() + ':' + vec3Key(this.chunkGridPosition);
}
}
export interface SliceViewChunkSourceBackend<
Spec extends SliceViewChunkSpecification = SliceViewChunkSpecification,
ChunkType extends SliceViewChunk = SliceViewChunk> {
// TODO(jbms): Move this declaration to the class definition below and declare abstract once
// TypeScript supports mixins with abstact classes.
getChunk(chunkGridPosition: vec3): ChunkType;
chunkConstructor: ChunkConstructor<SliceViewChunk>;
}
export class SliceViewChunkSourceBackend<
Spec extends SliceViewChunkSpecification = SliceViewChunkSpecification,
ChunkType extends SliceViewChunk = SliceViewChunk> extends ChunkSource implements
SliceViewChunkSourceInterface {
spec: Spec;
chunks: Map<string, ChunkType>;
constructor(rpc: RPC, options: any) {
super(rpc, options);
this.spec = options.spec;
}
getChunk(chunkGridPosition: Float32Array) {
const key = chunkGridPosition.join();
let chunk = this.chunks.get(key);
if (chunk === undefined) {
chunk = this.getNewChunk_(this.chunkConstructor) as ChunkType;
chunk.initializeVolumeChunk(key, chunkGridPosition);
this.addChunk(chunk);
}
return chunk;
}
}
@registerSharedObject(SLICEVIEW_RENDERLAYER_RPC_ID)
export class SliceViewRenderLayerBackend extends SharedObjectCounterpart implements
SliceViewRenderLayerInterface, ChunkRenderLayerBackend {
rpcId: number;
renderScaleTarget: SharedWatchableValue<number>;
localPosition: WatchableValueInterface<Float32Array>;
numVisibleChunksNeeded: number;
numVisibleChunksAvailable: number;
numPrefetchChunksNeeded: number;
numPrefetchChunksAvailable: number;
chunkManagerGeneration: number;
constructor(rpc: RPC, options: any) {
super(rpc, options);
this.renderScaleTarget = rpc.get(options.renderScaleTarget);
this.localPosition = rpc.get(options.localPosition);
this.numVisibleChunksNeeded = 0;
this.numVisibleChunksAvailable = 0;
this.numPrefetchChunksAvailable = 0;
this.numPrefetchChunksNeeded = 0;
this.chunkManagerGeneration = -1;
}
filterVisibleSources(sliceView: SliceViewBase, sources: readonly TransformedSource[]):
Iterable<TransformedSource> {
return filterVisibleSources(sliceView, this, sources);
}
}
const PREFETCH_MS = 2000;
const MAX_PREFETCH_VELOCITY = 0.1; // voxels per millisecond
const MAX_SINGLE_DIRECTION_PREFETCH_CHUNKS =
32; // Maximum number of chunks to prefetch in a single direction.
// If the probability under the model of needing a chunk within `PREFETCH_MS` is less than this
// probability, skip prefetching it.
const PREFETCH_PROBABILITY_CUTOFF = 0.05;
const PREFETCH_ENTRY_SIZE = 6;
function getPrefetchChunkOffsets(
velocityEstimator: VelocityEstimator, tsource: TransformedSource): number[] {
const offsets: number[] = [];
const globalRank = velocityEstimator.rank;
const {combinedGlobalLocalToChunkTransform, layerRank} = tsource;
const {rank: chunkRank, chunkDataSize} = tsource.source.spec;
const {mean: meanVec, variance: varianceVec} = velocityEstimator;
for (let chunkDim = 0; chunkDim < chunkRank; ++chunkDim) {
const isDisplayDimension = tsource.chunkDisplayDimensionIndices.includes(chunkDim);
let mean = 0;
let variance = 0;
for (let globalDim = 0; globalDim < globalRank; ++globalDim) {
const meanValue = meanVec[globalDim];
const varianceValue = varianceVec[globalDim];
const coeff = combinedGlobalLocalToChunkTransform[globalDim * layerRank + chunkDim];
mean += coeff * meanValue;
variance += coeff * coeff * varianceValue;
}
if (mean > MAX_PREFETCH_VELOCITY) {
continue;
}
const chunkSize = chunkDataSize[chunkDim];
const initialFraction =
isDisplayDimension ? 0 : tsource.fixedPositionWithinChunk[chunkDim] / chunkSize;
const adjustedMean = mean / chunkSize * PREFETCH_MS;
let adjustedStddevTimesSqrt2 = Math.sqrt(2 * variance) / chunkSize * PREFETCH_MS;
if (Math.abs(adjustedMean) < 1e-3 && adjustedStddevTimesSqrt2 < 1e-3) {
continue;
}
adjustedStddevTimesSqrt2 = Math.max(1e-6, adjustedStddevTimesSqrt2);
const cdf = (x: number) => 0.5 * (1 + erf((x - adjustedMean) / adjustedStddevTimesSqrt2));
const curChunk = tsource.curPositionInChunks[chunkDim];
const minChunk = Math.floor(tsource.lowerClipBound[chunkDim] / chunkSize);
const maxChunk = Math.ceil(tsource.upperClipBound[chunkDim] / chunkSize) - 1;
let groupStart = offsets.length;
for (let i = 1; i <= MAX_SINGLE_DIRECTION_PREFETCH_CHUNKS; ++i) {
if (!isDisplayDimension && curChunk + i > maxChunk) break;
const probability = 1 - cdf(i - initialFraction);
// Probability that chunk `curChunk + i` will be needed within `PREFETCH_MS`.
if (probability < PREFETCH_PROBABILITY_CUTOFF) break;
offsets.push(chunkDim, i, minChunk, maxChunk, probability, 0);
}
let newGroupStart = offsets.length;
for (let i = groupStart, end = offsets.length; i < end; i += PREFETCH_ENTRY_SIZE) {
offsets[i + PREFETCH_ENTRY_SIZE - 1] = newGroupStart;
}
groupStart = newGroupStart;
for (let i = 1; i <= MAX_SINGLE_DIRECTION_PREFETCH_CHUNKS; ++i) {
if (!isDisplayDimension && curChunk - i < minChunk) break;
const probability = cdf(-i + 1 - initialFraction);
// Probability that chunk `curChunk - i` will be needed within `PREFETCH_MS`.
if (probability < PREFETCH_PROBABILITY_CUTOFF) break;
offsets.push(chunkDim, -i, minChunk, maxChunk, probability, 0);
}
newGroupStart = offsets.length;
for (let i = groupStart, end = offsets.length; i < end; i += PREFETCH_ENTRY_SIZE) {
offsets[i + PREFETCH_ENTRY_SIZE - 1] = newGroupStart;
}
}
return offsets;
} | the_stack |
import './setup';
import { StageComponent } from './component-tester';
import { PLATFORM } from 'aurelia-pal';
import { createAssertionQueue, validateState, validateScrolledState, AsyncQueue, waitForTimeout } from './utilities';
import { VirtualRepeat } from '../src/virtual-repeat';
PLATFORM.moduleName('src/virtual-repeat');
PLATFORM.moduleName('test/noop-value-converter');
PLATFORM.moduleName('src/infinite-scroll-next');
describe('vr-integration.spec.ts', () => {
// async queue
let nq: AsyncQueue = createAssertionQueue();
let itemHeight = 100;
/**
* Manually dispatch a scroll event and validate scrolled state of virtual repeat
*
* Programatically set `scrollTop` of element specified with `elementSelector` query string
* (or `#scrollContainer` by default) to be equal with its `scrollHeight`
*/
function validateScroll(virtualRepeat: VirtualRepeat, viewModel: any, done: Function, elementSelector?: string): void {
let elem = document.getElementById(elementSelector || 'scrollContainer');
let event = new Event('scroll');
elem.scrollTop = elem.scrollHeight;
elem.dispatchEvent(event);
window.setTimeout(() => {
window.requestAnimationFrame(() => {
validateScrolledState(virtualRepeat, viewModel, itemHeight);
done();
});
});
}
function validatePush(virtualRepeat: VirtualRepeat, viewModel: any, done: Function) {
viewModel.items.push('Foo');
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
for (let i = 0; i < 5; ++i) {
viewModel.items.push(`Foo ${i}`);
}
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
function validatePop(virtualRepeat: VirtualRepeat, viewModel: any, done: Function) {
viewModel.items.pop();
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items.pop());
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items.pop());
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
function validateUnshift(virtualRepeat, viewModel, done) {
viewModel.items.unshift('z');
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items.unshift('y', 'x'));
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items.unshift());
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
function validateShift(virtualRepeat, viewModel, done) {
viewModel.items.shift();
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items.shift());
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items.shift());
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
function validateReverse(virtualRepeat, viewModel, done) {
viewModel.items.reverse();
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
function validateSplice(virtualRepeat: VirtualRepeat, viewModel: any, done: Function) {
viewModel.items.splice(2, 1, 'x', 'y');
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
function validateArrayChange(virtualRepeat, viewModel, done) {
const createItems = (name, amount) => new Array(amount).map((v, index) => name + index);
viewModel.items = createItems('A', 4);
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items = createItems('B', 0));
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items = createItems('C', 101));
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => viewModel.items = createItems('D', 0));
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
}
describe('iterating div', () => {
let component;
let virtualRepeat: VirtualRepeat;
let viewModel;
let create;
let items;
let hiddenComponent;
let hiddenCreate;
let hiddenVirtualRepeat: VirtualRepeat;
let hiddenViewModel;
let containerComponent;
let containerCreate;
let containerVirtualRepeat: VirtualRepeat;
let containerViewModel;
beforeEach(() => {
items = [];
for (let i = 0; i < 1000; ++i) {
items.push('item' + i);
}
component = StageComponent
.withResources('src/virtual-repeat')
.inView(`<div style="height: ${itemHeight}px;" virtual-repeat.for="item of items">\${item}</div>`)
.boundTo({ items: items });
create = component.create().then(() => {
virtualRepeat = component.sut;
viewModel = component.viewModel;
});
hiddenComponent = StageComponent
.withResources('src/virtual-repeat')
.inView(`<div id="scrollContainer" style="height: 500px; overflow-y: scroll; display: none">
<div style="height: ${itemHeight}px;" virtual-repeat.for="item of items">\${item}</div>
</div>`)
.boundTo({ items: items });
hiddenCreate = hiddenComponent.create().then(() => {
hiddenVirtualRepeat = hiddenComponent.sut;
hiddenViewModel = hiddenComponent.viewModel;
});
containerComponent = StageComponent
.withResources('src/virtual-repeat')
.inView(`<div id="scrollContainer2" style="height: 500px; overflow-y: scroll;">
<div style="height: ${itemHeight}px;" virtual-repeat.for="item of items">\${item}</div>
</div>`)
.boundTo({ items: items });
containerCreate = containerComponent.create().then(() => {
containerVirtualRepeat = containerComponent.sut;
containerViewModel = containerComponent.viewModel;
spyOn(containerVirtualRepeat, '_onScroll').and.callThrough();
});
create = Promise.all([
create,
hiddenCreate,
containerCreate,
]);
});
afterEach(() => {
component.cleanUp();
hiddenComponent.cleanUp();
containerComponent.cleanUp();
});
describe('handles delete', () => {
it('can delete one at start', async done => {
await create;
viewModel.items.splice(0, 1);
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
it('can delete one at end', done => {
create.then(() => {
viewModel.items.splice(viewModel.items.length - 1, 1);
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
it('can delete two at start', done => {
create.then(() => {
viewModel.items.splice(0, 1);
viewModel.items.splice(0, 1);
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
it('can delete two at end', done => {
create.then(() => {
viewModel.items.splice(viewModel.items.length - 1, 1);
viewModel.items.splice(viewModel.items.length - 1, 1);
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
it('can delete as many as in the DOM', done => {
create.then(() => {
let deleteCount = virtualRepeat.viewCount();
for (let i = 0; i < deleteCount; ++i) {
viewModel.items.splice(0, 1);
}
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
it('can delete more element than what is in the DOM', done => {
create.then(() => {
let deleteCount = virtualRepeat.viewCount() * 2;
for (let i = 0; i < deleteCount; ++i) {
viewModel.items.splice(0, 1);
}
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
it('can delete all', done => {
create.then(() => {
let deleteCount = viewModel.items.length;
for (let i = 0; i < deleteCount; ++i) {
viewModel.items.splice(0, 1);
}
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
});
it('handles push', done => {
create.then(() => validatePush(virtualRepeat, viewModel, done));
});
it('handles pop', done => {
create.then(() => validatePop(virtualRepeat, viewModel, done));
});
it('handles unshift', async () => {
await create;
viewModel.items.unshift('z');
expect(virtualRepeat.view(0).bindingContext.item).toBe('item0', 'unshifting z 1');
await Promise.resolve();
expect(virtualRepeat.view(0).bindingContext.item).toBe('z', 'unshifted z 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
viewModel.items.unshift('y', 'x');
expect(virtualRepeat.view(0).bindingContext.item).toBe('z', 'unshifting y,x 1');
await Promise.resolve();
expect(virtualRepeat.view(0).bindingContext.item).toBe('y', 'unshifted y,x 1');
expect(virtualRepeat.view(1).bindingContext.item).toBe('x', 'unshifted y,x 2');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
// verify that unshifting undefined won't disrupt anything
viewModel.items.unshift();
expect(virtualRepeat.view(0).bindingContext.item).toBe('y', 'unshifting undefined 1');
await Promise.resolve();
expect(virtualRepeat.view(0).bindingContext.item).toBe('y', 'unshifted undefined 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
});
it('handles shift', done => {
create.then(() => validateShift(virtualRepeat, viewModel, done));
});
it('handles reverse', done => {
create.then(() => validateReverse(virtualRepeat, viewModel, done));
});
it('handles splice', done => {
create.then(() => validateSplice(virtualRepeat, viewModel, done));
});
it('handles displaying when initially hidden', async done => {
await hiddenCreate;
hiddenVirtualRepeat.scrollerEl.style.display = 'block';
window.requestAnimationFrame(() => {
window.setTimeout(() => {
validateState(hiddenVirtualRepeat, hiddenViewModel, itemHeight);
done();
}, 750);
});
});
it('does not invoke _onScroll after attached()', async done => {
await containerCreate;
validateScroll(containerVirtualRepeat, containerViewModel, () => {
expect(containerVirtualRepeat._onScroll).not.toHaveBeenCalled();
done();
}, 'scrollContainer2');
});
it('handles array changes', done => {
create.then(() => validateArrayChange(virtualRepeat, viewModel, done));
});
it('handles array changes with null / undefined', async (done) => {
await create;
viewModel.items = null;
await waitForTimeout(50);
let topBufferHeight = virtualRepeat.topBufferEl.getBoundingClientRect().height;
let bottomBufferHeight = virtualRepeat.bottomBufferEl.getBoundingClientRect().height;
expect(topBufferHeight + bottomBufferHeight).toBe(0);
validateArrayChange(virtualRepeat, viewModel, done);
});
});
describe('value converters', () => {
let component;
let virtualRepeat: VirtualRepeat;
let viewModel;
let create;
let items;
beforeEach(() => {
items = [];
for (let i = 0; i < 1000; ++i) {
items.push('item' + i);
}
component = StageComponent
.withResources(['src/virtual-repeat', 'test/noop-value-converter'])
.inView(`<div style="height: ${itemHeight}px;" virtual-repeat.for="item of items | noop">\${item}</div>`)
.boundTo({ items: items });
create = component.create().then(() => {
virtualRepeat = component.sut;
viewModel = component.viewModel;
});
});
afterEach(() => {
component.cleanUp();
});
it('handles push', done => {
create.then(() => validatePush(virtualRepeat, viewModel, done));
});
it('handles pop', done => {
create.then(() => validatePop(virtualRepeat, viewModel, done));
});
it('handles unshift', done => {
create.then(() => {
viewModel.items.unshift('z');
nq(() => validateState(virtualRepeat, viewModel, itemHeight));
nq(() => done());
});
});
it('handles shift', done => {
create.then(() => validateShift(virtualRepeat, viewModel, done));
});
it('handles reverse', done => {
create.then(() => validateReverse(virtualRepeat, viewModel, done));
});
it('handles splice', done => {
create.then(() => validateSplice(virtualRepeat, viewModel, done));
});
});
}); | the_stack |
import { AttributeScores, AttributeScore, EnabledAttributes,
linscale, getCommentVisibility,
getHideReasonDescription, getFeedbackQuestion,
scaleEnabledAttributeScore } from './scores';
function zeroScores(): AttributeScores {
return {
'identityAttack': 0.0,
'insult': 0.0,
'profanity': 0.0,
'threat': 0.0,
'sexuallyExplicit': 0.0,
'toxicity': 0.0,
'severeToxicity': 0.0,
'likelyToReject': 0.0,
};
}
function allEnabled(): EnabledAttributes {
return {
'identityAttack': true,
'insult': true,
'profanity': true,
'threat': true,
'sexuallyExplicit': true,
};
}
function allDisabled(): EnabledAttributes {
return {
'identityAttack': false,
'insult': false,
'profanity': false,
'threat': false,
'sexuallyExplicit': false,
};
}
describe('linscale', () => {
it('should work', () => {
expect(linscale(0.0, [0, 1], [2, 4])).toBe(2);
expect(linscale(0.5, [0, 1], [2, 4])).toBe(3);
expect(linscale(0.75, [0, 1], [2, 4])).toBe(3.5);
expect(linscale(1.0, [0, 1], [2, 4])).toBe(4);
expect(linscale(5, [5, 18], [0, 1])).toBe(0);
expect(linscale(18, [5, 18], [0, 1])).toBe(1);
expect(linscale(0.2, [0.0, 1.0], [0, 100])).toBe(20);
expect(linscale(0.89, [0.0, 1.0], [0, 100])).toBe(89);
});
});
describe('getCommentVisibility', () => {
describe('check severe toxicity', () => {
it('should hide severe toxicity with subtypes enabled', () => {
const scores = zeroScores();
scores.severeToxicity = 0.9;
const decision = getCommentVisibility(
scores, 0.85, allEnabled(), true /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.9});
});
it('should hide severe toxicity with subtypes enabled and give highest subtype', () => {
const scores = zeroScores();
scores.severeToxicity = 0.9;
scores.insult = 0.95;
const decision = getCommentVisibility(
scores, 0.85, allEnabled(), true /* subtypesEnabled */);
// Returns 'insult' as the attribute because it has a high score value.
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.9});
});
it('should hide severe toxicity without subtypes enabled', () => {
const scores = zeroScores();
scores.severeToxicity = 0.9;
const decision = getCommentVisibility(
scores, 0.85, allEnabled(), false /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.9});
});
it('should show low severe toxicity with subtypes enabled', () => {
const scores = zeroScores();
scores.severeToxicity = 0.6;
const decision = getCommentVisibility(
scores, 0.9, allEnabled(), true /* subtypesEnabled */);
expect(decision).toEqual({kind: 'showComment'});
});
it('should show low severe toxicity without subtypes enabled', () => {
const scores = zeroScores();
scores.severeToxicity = 0.6;
const decision = getCommentVisibility(
scores, 0.9, allEnabled(), false /* subtypesEnabled */);
expect(decision).toEqual({kind: 'showComment'});
});
});
describe('check low quality', () => {
it('should hide low quality with subtypes enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.2;
// Note: we scale down the likelyToReject score because it's sensitive, so
// it needs to be significantly above the threshold to trigger the
// filtering logic.
scores.likelyToReject = 0.5;
scores.insult = 0.1;
const decision = getCommentVisibility(
scores, 0.15, allEnabled(), true /* subtypesEnabled */);
// We return the 'toxicity' attribute and score when hiding due to low
// quality.
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'toxicity', scaledScore: 0.2});
});
it('should hide low quality without subtypes enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.2;
// Note: we scale down the likelyToReject score because it's sensitive, so
// it needs to be significantly above the threshold to trigger the
// filtering logic.
scores.likelyToReject = 0.5;
scores.insult = 0.1;
const decision = getCommentVisibility(
scores, 0.15, allEnabled(), false /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'toxicity', scaledScore: 0.2});
});
it('should show high quality with subtypes enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.2;
scores.likelyToReject = 0.05;
scores.insult = 0.1;
const decision = getCommentVisibility(
scores, 0.15, allEnabled(), true /* subtypesEnabled */);
expect(decision).toEqual({kind: 'showComment'});
});
it('should show high quality without subtypes enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.2;
scores.likelyToReject = 0.05;
scores.insult = 0.1;
const decision = getCommentVisibility(
scores, 0.15, allEnabled(), false /* subtypesEnabled */);
expect(decision).toEqual({kind: 'showComment'});
});
it('should show low toxicity with subtypes enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.03;
scores.likelyToReject = 0.99;
const decision = getCommentVisibility(
scores, 0.15, allEnabled(), true /* subtypesEnabled */);
expect(decision).toEqual({kind: 'showComment'});
});
it('should show low toxicity without subtypes enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.03;
scores.likelyToReject = 0.99;
const decision = getCommentVisibility(
scores, 0.15, allEnabled(), false /* subtypesEnabled */);
expect(decision).toEqual({kind: 'showComment'});
});
});
describe('check enabled attributes', () => {
it('should hide due to one enabled attribute', () => {
const scores = zeroScores();
scores.profanity = 1.0;
const enabled = allDisabled();
enabled.profanity = true;
const decision = getCommentVisibility(
scores, 0.6, enabled, true /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'profanity',
scaledScore: scaleEnabledAttributeScore(1.0)});
});
it('should ignore higher score from disabled attribute', () => {
const scores = zeroScores();
scores.toxicity = 0.99;
scores.profanity = 0.95;
scores.insult = 0.90;
const enabled = allDisabled();
enabled.insult = true;
const decision = getCommentVisibility(
scores, 0.5, enabled, true /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'insult',
scaledScore: scaleEnabledAttributeScore(0.90)});
});
it('should give highest enabled score', () => {
const scores = zeroScores();
scores.profanity = 0.8;
scores.insult = 0.7;
const enabled = allDisabled();
enabled.profanity = true;
enabled.insult = true;
const decision = getCommentVisibility(
scores, 0.5, enabled, true /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'profanity',
scaledScore: scaleEnabledAttributeScore(0.8)});
});
it('should use toxicity score when subtypes are not enabled', () => {
const scores = zeroScores();
scores.toxicity = 0.80;
scores.profanity = 0.95;
scores.insult = 0.90;
const enabled = allDisabled();
enabled.insult = true;
const decision = getCommentVisibility(
scores, 0.5, enabled, false /* subtypesEnabled */);
expect(decision).toEqual(
{kind: 'hideCommentDueToScores', attribute: 'toxicity',
scaledScore: scaleEnabledAttributeScore(0.80)});
});
});
});
describe('getHideDescription', () => {
it('should say "Blaring" for high score values', () => {
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.9}))
.toBe('Blaring');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'profanity', scaledScore: 0.88}))
.toBe('Blaring');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'identityAttack', scaledScore: 0.87}))
.toBe('Blaring');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.90}))
.toBe('Blaring');
});
it('should say "Loud" with medium-high score values', () => {
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.80}))
.toBe('Loud');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.75}))
.toBe('Loud');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'sexuallyExplicit', scaledScore: 0.70}))
.toBe('Loud');
});
it('should say "Medium" with middle score values', () => {
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.60}))
.toBe('Medium');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.50}))
.toBe('Medium');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.45}))
.toBe('Medium');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'sexuallyExplicit', scaledScore: 0.40}))
.toBe('Medium');
});
it('should say "Low" for medium-low score values', () => {
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.35}))
.toBe('Low');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.20}))
.toBe('Low');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'identityAttack', scaledScore: 0.18}))
.toBe('Low');
});
it('should say "Quiet" for very low score values', () => {
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.10}))
.toBe('Quiet');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: 'identityAttack', scaledScore: 0.13}))
.toBe('Quiet');
expect(getHideReasonDescription(
{kind: 'hideCommentDueToScores', attribute: null, scaledScore: 0.0}))
.toBe('Quiet');
});
it('should be empty for showComment', () => {
expect(getHideReasonDescription({kind: 'showComment'})).toBe('');
});
it('should show unsupported-language message', () => {
expect(getHideReasonDescription({kind: 'hideCommentDueToUnsupportedLanguage'}))
.toBe('Tune doesn\'t currently support this language.');
});
});
describe('getFeedbackQuestion', () => {
it('should mention the subtype when we have higher scores with subtypes enabled', () => {
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.9}, true /* subtypesEnabled */))
.toBe('Is this an insult?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'profanity', scaledScore: 0.8}, true /* subtypesEnabled */))
.toBe('Is this profanity?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'identityAttack', scaledScore: 0.75}, true /* subtypesEnabled */))
.toBe('Is this an attack on identity?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.70}, true /* subtypesEnabled */))
.toBe('Is this toxic?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'toxicity', scaledScore: 0.70}, true /* subtypesEnabled */))
.toBe('Is this toxic?');
});
it('should just ask "should this be hidden" when we have higher scores without subtypes enabled', () => {
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.9}, false /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.8}, false /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.75}, false /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'toxicity', scaledScore: 0.7}, false /* subtypesEnabled */))
.toBe('Should this be hidden?');
});
it('should just ask "should this be hidden" for middle and low score values', () => {
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: 0.60}, true /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'insult', scaledScore: 0.50}, true /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'threat', scaledScore: 0.10}, true /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'sexuallyExplicit', scaledScore: 0.05}, true /* subtypesEnabled */))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion(
{kind: 'hideCommentDueToScores', attribute: 'toxicity', scaledScore: 0.05}, true /* subtypesEnabled */))
.toBe('Should this be hidden?');
});
it('should be empty for showComment', () => {
expect(getFeedbackQuestion({kind: 'showComment'}, true)).toBe('');
expect(getFeedbackQuestion({kind: 'showComment'}, false)).toBe('');
});
it('should show generic message for unsupported-language comments', () => {
expect(getFeedbackQuestion({kind: 'hideCommentDueToUnsupportedLanguage'}, true))
.toBe('Should this be hidden?');
expect(getFeedbackQuestion({kind: 'hideCommentDueToUnsupportedLanguage'}, false))
.toBe('Should this be hidden?');
});
}); | the_stack |
import { DirectiveHook, App, DirectiveBinding, ObjectDirective } from 'vue';
import { getComputedStyleList } from '../shared';
export interface ToDragOptions {
isAbsolute?: boolean,
adsorbOffset: number,
moveCursor?: boolean,
adsorb?: number,
transitionDuration?: number,
transitionTimingFunction?: string,
forbidBodyScroll?: boolean,
parentSelector?: string,
positionMode?: 1 | 2 | 3 | 4,
disabled?: () => boolean,
needComputeBorder?: boolean
}
export type ToDragEventString = 'todraginit' | 'todragstart' | 'todragmove' | 'todragend'
export interface ToDragEvent extends Event {
left?: number,
top?: number,
width?: number,
height?: number,
maxX?: number,
maxY?: number,
right?: number,
bottom?: number
}
class ToDrag {
el: HTMLElement
isTouch: boolean
isDrag: boolean
parent: HTMLElement
left = 0
top = 0
right = 0
bottom = 0
width = 0
height = 0
maxX = 0
maxY = 0
private options: ToDragOptions
private scrollbarWidth: number
private startX = 0
private startY = 0
private getScrollbarWidth = () => {
const el = document.createElement('div');
el.style.cssText = 'width:100px;height:100px;overflow-y:scroll';
document.body.appendChild(el);
const scrollbarWidth = el.offsetWidth - el.clientWidth;
document.body.removeChild(el);
return scrollbarWidth;
}
private setBetween = (num: number, min: number, max:number) => {
if (num < min) return min;
if (num > max) return max;
return num;
}
constructor({ el, options } : { el: string | HTMLElement, options?: ToDragOptions }) {
this.el = el instanceof HTMLElement ? el : document.querySelector(el) as HTMLElement;
this.scrollbarWidth = this.getScrollbarWidth();
this.isTouch = 'ontouchstart' in document.documentElement;
this.isDrag = false;
this.options = {
moveCursor: true,
adsorb: 0,
adsorbOffset: 0,
transitionDuration: 400,
transitionTimingFunction: 'ease-in-out',
forbidBodyScroll: true,
isAbsolute: false,
positionMode: 1,
needComputeBorder: true,
...options
};
this.parent = (this.options.parentSelector && document.querySelector(this.options.parentSelector)) || this.el.parentNode as HTMLElement;
if (this.options.transitionDuration) {
this.options.transitionDuration = this.options.transitionDuration / 1000;
}
// init
this.handleTouchStart = this.handleTouchStart.bind(this);
this.handleMousedown = this.handleMousedown.bind(this);
this.moveEvent = this.moveEvent.bind(this);
this.endEvent = this.endEvent.bind(this);
this.init();
}
init () {
if (this.isTouch) {
this.el.addEventListener('touchstart', this.handleTouchStart);
} else {
this.el.addEventListener('mousedown', this.handleMousedown);
}
if (this.options.moveCursor) {
this.el.style.cursor = 'move';
}
this.setPosition();
this.setLimit();
this.handleAdsorb();
this.handlePositionMode();
setTimeout(() => {
this.emitEvent('todraginit');
});
}
handleMousedown (e: MouseEvent) {
if (typeof this.options.disabled === 'function' && this.options.disabled()) {
return;
}
const { x, y } = e;
this.setStartInfo(x, y);
document.addEventListener('mousemove', this.moveEvent);
document.addEventListener('mouseup', this.endEvent);
}
handleTouchStart (e: TouchEvent | MouseEvent) {
if (typeof this.options.disabled === 'function' && this.options.disabled()) {
return;
}
const x = this.isTouch ? (e as TouchEvent).changedTouches[0].clientX : (e as MouseEvent).x;
const y = this.isTouch ? (e as TouchEvent).changedTouches[0].clientY : (e as MouseEvent).y;
this.setStartInfo(x, y);
document.addEventListener('touchmove', this.moveEvent, { passive: false });
document.addEventListener('touchend', this.endEvent);
}
setPosition() {
const { left, top, width, height } = this.el.getBoundingClientRect();
this.left = left;
this.top = top;
this.width = width;
this.height = height;
if (!this.options.isAbsolute) {
this.maxX = document.body.scrollWidth > window.innerWidth ? window.innerWidth - this.width - this.scrollbarWidth : window.innerWidth - this.width;
this.maxY = document.body.scrollHeight > window.innerHeight ? window.innerHeight - this.height - this.scrollbarWidth : window.innerHeight - this.height;
} else {
this.maxX = this.parent.offsetWidth - this.width;
this.maxY = this.parent.offsetHeight - this.height;
}
}
setStartInfo (x: number, y: number) {
this.setPosition();
this.setLimit();
this.startX = x - this.left;
this.startY = y - this.top;
this.isDrag = true;
this.el.style.transition = '';
document.body.style.userSelect = 'none';
if (this.options.forbidBodyScroll) {
document.body.style.overflow = 'hidden';
}
this.emitEvent('todragstart');
}
moveEvent (e: TouchEvent | MouseEvent) {
if (!this.isDrag) {
return;
}
e.preventDefault();
let dragX, dragY;
const x = this.isTouch ? (e as TouchEvent).changedTouches[0].clientX : (e as MouseEvent).x;
const y = this.isTouch ? (e as TouchEvent).changedTouches[0].clientY : (e as MouseEvent).y;
if (!this.options.isAbsolute) {
dragX = x - this.startX;
dragY = y - this.startY;
} else {
const parentDomRect = this.parent.getClientRects()[0];
dragX = x - parentDomRect.x - this.startX - this.borderInfo[1];
dragY = y - parentDomRect.y - this.startY - this.borderInfo[2];
}
this.left = this.setBetween(dragX, 0, this.maxX - this.borderInfo[1] - this.borderInfo[3]);
this.top = this.setBetween(dragY, 0, this.maxY - this.borderInfo[2] - this.borderInfo[0]);
this.el.style.left = this.left + 'px';
this.el.style.top = this.top + 'px';
this.emitEvent('todragmove');
}
endEvent () {
this.isDrag = false;
document.removeEventListener('mousemove', this.moveEvent);
document.removeEventListener('mouseup', this.endEvent);
document.removeEventListener('touchmove', this.moveEvent);
document.removeEventListener('touchend', this.endEvent);
document.body.style.userSelect = 'auto';
if (this.options.forbidBodyScroll) {
document.body.style.overflow = 'visible';
}
this.handleAdsorb();
this.handlePositionMode();
this.emitEvent('todragend');
}
handleAdsorb () {
if (this.options.isAbsolute) return;
const endPoint = [this.left + this.width / 2, this.top + this.height / 2];
const maxPoint = [window.innerWidth, window.innerHeight];
this.el.style.transition = `left ${this.options.transitionDuration}s ${this.options.transitionTimingFunction},
top ${this.options.transitionDuration}s ${this.options.transitionTimingFunction}`;
if (this.options.adsorb === 1) {
// 左右吸附
if (endPoint[0] <= window.innerWidth / 2) {
// left
this.left = this.options.adsorbOffset;
} else {
// right
this.left = this.maxX - this.options.adsorbOffset;
}
} else if (this.options.adsorb === 2) {
// 四方向吸附
const k1 = maxPoint[1] / maxPoint[0];
const k2 = maxPoint[1] / -maxPoint[0];
const k3 = endPoint[1] / endPoint[0];
const k4 = endPoint[1] / (endPoint[0] - maxPoint[0]);
if (k1 >= k3 && k2 < k4) {
// top
this.top = this.options.adsorbOffset;
} else if (k1 >= k3 && k2 >= k4) {
// right
this.left = this.maxX - this.options.adsorbOffset;
} else if (k1 < k3 && k2 >= k4) {
// bottom
this.top = this.maxY - this.options.adsorbOffset;
} else {
// left
this.left = this.options.adsorbOffset;
}
if (this.options.adsorbOffset) {
if (this.top === 0) {
this.top = this.options.adsorbOffset;
}
if (this.top === this.maxY) {
this.top = this.maxY - this.options.adsorbOffset;
}
if (this.left === 0) {
this.left = this.options.adsorbOffset;
}
if (this.left === this.maxX) {
this.left = this.maxX - this.options.adsorbOffset;
}
}
}
this.el.style.left = this.left + 'px';
this.el.style.top = this.top + 'px';
}
handlePositionMode() {
if (this.options.adsorb) return;
const left = this.options.isAbsolute ? this.el.offsetLeft : this.left;
const top = this.options.isAbsolute ? this.el.offsetTop : this.top;
this.right = this.maxX - left - this.borderInfo[1] - this.borderInfo[3];
this.bottom = this.maxY - top - this.borderInfo[2] - this.borderInfo[0];
if (this.options.positionMode === 2) {
this.el.style.left = 'auto';
this.el.style.right = this.right + 'px';
} else if (this.options.positionMode === 3) {
this.el.style.top = 'auto';
this.el.style.bottom = this.bottom + 'px';
} else if (this.options.positionMode === 4) {
this.el.style.left = 'auto';
this.el.style.top = 'auto';
this.el.style.right = this.right + 'px';
this.el.style.bottom = this.bottom + 'px';
}
}
emitEvent (type: ToDragEventString) {
const event = document.createEvent('HTMLEvents') as ToDragEvent;
event.initEvent(type, false, false);
const { left, top, right, bottom, width, height, maxX, maxY } = this;
event['left'] = left;
event['top'] = top;
event['width'] = width;
event['height'] = height;
event['maxX'] = maxX;
event['maxY'] = maxY;
event['right'] = right;
event['bottom'] = bottom;
this.el.dispatchEvent(event);
}
destroy () {
if (this.isTouch) {
this.el.removeEventListener('touchstart', this.handleTouchStart);
} else {
this.el.removeEventListener('mousedown', this.handleMousedown);
}
}
// absolute limit add border, padding size control
borderInfo = [0, 0, 0, 0] // [top, right, bottom, left]
private setLimit() {
if (!this.options.isAbsolute || !this.options.needComputeBorder) return;
const position = ['top', 'right', 'bottom', 'left'];
const borderInfo = getComputedStyleList(this.parent, [
...position.map(p => `border-${p}-width`),
], true) as Record<string, number>;
this.borderInfo = position.map(p => borderInfo[`border-${p}-width`]);
}
}
const mounted = (el: HTMLElement, binding: DirectiveBinding, userOptions?: ToDragOptions):void => {
const { value }:{ value: ToDragOptions } = binding;
const customGlobalOptions = userOptions || {};
const options = {
...customGlobalOptions,
...value
};
(el as any).$toDarg = new ToDrag({
el,
options
});
};
const unmounted: DirectiveHook = (el: any) => {
el.$toDarg && el.$toDarg.destroy();
};
export const ToDragDirective: ObjectDirective = {
mounted: (el: HTMLElement, binding: DirectiveBinding) => mounted(el, binding),
unmounted,
// @ts-ignore
inserted: (el, binding) => mounted(el, binding),
unbind: unmounted,
install: (Vue: App, userOptions: ToDragOptions):void => {
Vue.directive('to-drag', {
mounted: ((el, binding) => mounted(el, binding, userOptions)),
unmounted,
// @ts-ignore
inserted: ((el, binding) => mounted(el, binding, userOptions)),
unbind: unmounted
});
}
};
export default ToDrag; | the_stack |
import { platform } from "os";
import { EventEmitter } from "events";
import { getCanonicalUUID } from "./helpers";
import { BluetoothDevice } from "./device";
import { BluetoothRemoteGATTService } from "./service";
import { BluetoothRemoteGATTCharacteristic } from "./characteristic";
import * as noble from "@abandonware/noble";
/**
* @hidden
*/
export interface Adapter extends EventEmitter {
getEnabled: (completeFn: (enabled: boolean) => void) => void;
startScan: (serviceUUIDs: Array<string>, foundFn: (device: Partial<BluetoothDevice>) => void, completeFn?: () => void, errorFn?: (errorMsg: string) => void) => void;
stopScan: (errorFn?: (errorMsg: string) => void) => void;
connect: (handle: string, connectFn: () => void, disconnectFn: () => void, errorFn?: (errorMsg: string) => void) => void;
disconnect: (handle: string, errorFn?: (errorMsg: string) => void) => void;
discoverServices: (handle: string, serviceUUIDs: Array<string>, completeFn: (services: Array<Partial<BluetoothRemoteGATTService>>) => void, errorFn?: (errorMsg: string) => void) => void;
discoverIncludedServices: (handle: string, serviceUUIDs: Array<string>, completeFn: (services: Array<Partial<BluetoothRemoteGATTService>>) => void, errorFn?: (errorMsg: string) => void) => void;
discoverCharacteristics: (handle: string, characteristicUUIDs: Array<string>, completeFn: (characteristics: Array<Partial<BluetoothRemoteGATTCharacteristic>>) => void, errorFn?: (errorMsg: string) => void) => void;
discoverDescriptors: (handle: string, descriptorUUIDs: Array<string>, completeFn: (descriptors: Array<Partial<BluetoothRemoteGATTDescriptor>>) => void, errorFn?: (errorMsg: string) => void) => void;
readCharacteristic: (handle: string, completeFn: (value: DataView) => void, errorFn?: (errorMsg: string) => void) => void;
writeCharacteristic: (handle: string, value: DataView, completeFn?: () => void, errorFn?: (errorMsg: string) => void, withoutResponse?: boolean) => void;
enableNotify: (handle: string, notifyFn: () => void, completeFn?: () => void, errorFn?: (errorMsg: string) => void) => void;
disableNotify: (handle: string, completeFn?: () => void, errorFn?: (errorMsg: string) => void) => void;
readDescriptor: (handle: string, completeFn: (value: DataView) => void, errorFn?: (errorMsg: string) => void) => void;
writeDescriptor: (handle: string, value: DataView, completeFn?: () => void, errorFn?: (errorMsg: string) => void) => void;
}
/**
* @hidden
*/
export class NobleAdapter extends EventEmitter implements Adapter {
public static EVENT_ENABLED: string = "enabledchanged";
private deviceHandles: {} = {};
private serviceHandles: {} = {};
private characteristicHandles: {} = {};
private descriptorHandles: {} = {};
private charNotifies: {} = {};
private discoverFn: (device: noble.Peripheral) => void = null;
private initialised: boolean = false;
private enabled: boolean = false;
private os: string = platform();
constructor() {
super();
this.enabled = this.state;
noble.on("stateChange", () => {
if (this.enabled !== this.state) {
this.enabled = this.state;
this.emit(NobleAdapter.EVENT_ENABLED, this.enabled);
}
});
}
private get state(): boolean {
return (noble.state === "poweredOn");
}
private init(completeFn: () => any): void {
if (this.initialised) return completeFn();
noble.on("discover", deviceInfo => {
if (this.discoverFn) this.discoverFn(deviceInfo);
});
this.initialised = true;
completeFn();
}
private checkForError(errorFn, continueFn?, delay?: number) {
return function(error) {
if (error) errorFn(error);
else if (typeof continueFn === "function") {
const args = [].slice.call(arguments, 1);
if (delay === null) continueFn.apply(this, args);
else setTimeout(() => continueFn.apply(this, args), delay);
}
};
}
private bufferToDataView(buffer: Buffer): DataView {
// Buffer to ArrayBuffer
const arrayBuffer = new Uint8Array(buffer).buffer;
return new DataView(arrayBuffer);
}
private dataViewToBuffer(dataView: DataView): Buffer {
// DataView to TypedArray
const typedArray = new Uint8Array(dataView.buffer);
return new Buffer(typedArray);
}
private validDevice(deviceInfo: noble.Peripheral, serviceUUIDs: Array<string>): boolean {
if (serviceUUIDs.length === 0) {
// Match any device
return true;
}
if (!deviceInfo.advertisement.serviceUuids) {
// No advertised services, no match
return false;
}
const advertisedUUIDs = deviceInfo.advertisement.serviceUuids.map(serviceUUID => {
return getCanonicalUUID(serviceUUID);
});
return serviceUUIDs.some(serviceUUID => {
// An advertised UUID matches our search UUIDs
return (advertisedUUIDs.indexOf(serviceUUID) >= 0);
});
}
private deviceToBluetoothDevice(deviceInfo): Partial<BluetoothDevice> {
const deviceID = (deviceInfo.address && deviceInfo.address !== "unknown") ? deviceInfo.address : deviceInfo.id;
const serviceUUIDs = [];
if (deviceInfo.advertisement.serviceUuids) {
deviceInfo.advertisement.serviceUuids.forEach(serviceUUID => {
serviceUUIDs.push(getCanonicalUUID(serviceUUID));
});
}
const manufacturerData = new Map();
if (deviceInfo.advertisement.manufacturerData) {
// First 2 bytes are 16-bit company identifier
const company = deviceInfo.advertisement.manufacturerData.readUInt16LE(0);
// Remove company ID
const buffer = deviceInfo.advertisement.manufacturerData.slice(2);
manufacturerData.set(("0000" + company.toString(16)).slice(-4), this.bufferToDataView(buffer));
}
const serviceData = new Map();
if (deviceInfo.advertisement.serviceData) {
deviceInfo.advertisement.serviceData.forEach(serviceAdvert => {
serviceData.set(getCanonicalUUID(serviceAdvert.uuid), this.bufferToDataView(serviceAdvert.data));
});
}
return {
id: deviceID,
name: deviceInfo.advertisement.localName,
_serviceUUIDs: serviceUUIDs,
adData: {
rssi: deviceInfo.rssi,
txPower: deviceInfo.advertisement.txPowerLevel,
serviceData: serviceData,
manufacturerData: manufacturerData
}
};
}
public getEnabled(completeFn: (enabled: boolean) => void) {
function stateCB() {
completeFn(this.state);
}
if (noble.state === "unknown" || noble.state === "poweredOff") {
// tslint:disable-next-line:no-string-literal
noble["once"]("stateChange", stateCB.bind(this));
} else {
stateCB.call(this);
}
}
public startScan(serviceUUIDs: Array<string>, foundFn: (device: Partial<BluetoothDevice>) => void, completeFn?: () => void, errorFn?: (errorMsg: string) => void): void {
this.discoverFn = deviceInfo => {
if (this.validDevice(deviceInfo, serviceUUIDs)) {
const device = this.deviceToBluetoothDevice(deviceInfo);
if (!this.deviceHandles[device.id]) {
this.deviceHandles[device.id] = deviceInfo;
// Only call the found function the first time we find a valid device
foundFn(device);
}
}
};
this.init(() => {
this.deviceHandles = {};
function stateCB() {
if (this.state === true) {
// Noble doesn't correctly match short and canonical UUIDs on Linux, so we need to check ourselves
// Continually scan to pick up all advertised UUIDs
noble.startScanning([], true, this.checkForError(errorFn, completeFn));
} else {
errorFn("adapter not enabled");
}
}
if (noble.state === "unknown" || noble.state === "poweredOff") {
// tslint:disable-next-line:no-string-literal
noble["once"]("stateChange", stateCB.bind(this));
} else {
stateCB.call(this);
}
});
}
public stopScan(_errorFn?: (errorMsg: string) => void): void {
this.discoverFn = null;
noble.stopScanning();
}
public connect(handle: string, connectFn: () => void, disconnectFn: () => void, errorFn?: (errorMsg: string) => void): void {
const baseDevice = this.deviceHandles[handle];
baseDevice.removeAllListeners("connect");
baseDevice.removeAllListeners("disconnect");
baseDevice.once("connect", connectFn);
baseDevice.once("disconnect", () => {
this.serviceHandles = {};
this.characteristicHandles = {};
this.descriptorHandles = {};
this.charNotifies = {};
disconnectFn();
});
baseDevice.connect(this.checkForError(errorFn));
}
public disconnect(handle: string, errorFn?: (errorMsg: string) => void): void {
const baseDevice = this.deviceHandles[handle];
baseDevice.disconnect(this.checkForError(errorFn));
}
public discoverServices(handle: string, serviceUUIDs: Array<string>, completeFn: (services: Array<Partial<BluetoothRemoteGATTService>>) => void, errorFn?: (errorMsg: string) => void): void {
const baseDevice = this.deviceHandles[handle];
baseDevice.discoverServices([], this.checkForError(errorFn, services => {
const discovered = [];
services.forEach(serviceInfo => {
const serviceUUID = getCanonicalUUID(serviceInfo.uuid);
if (serviceUUIDs.length === 0 || serviceUUIDs.indexOf(serviceUUID) >= 0) {
if (!this.serviceHandles[serviceUUID]) this.serviceHandles[serviceUUID] = serviceInfo;
discovered.push({
uuid: serviceUUID,
primary: true
});
}
});
completeFn(discovered);
}));
}
public discoverIncludedServices(handle: string, serviceUUIDs: Array<string>, completeFn: (services: Array<Partial<BluetoothRemoteGATTService>>) => void, errorFn?: (errorMsg: string) => void): void {
const serviceInfo = this.serviceHandles[handle];
serviceInfo.discoverIncludedServices([], this.checkForError(errorFn, services => {
const discovered = [];
services.forEach(service => {
const serviceUUID = getCanonicalUUID(service.uuid);
if (serviceUUIDs.length === 0 || serviceUUIDs.indexOf(serviceUUID) >= 0) {
if (!this.serviceHandles[serviceUUID]) this.serviceHandles[serviceUUID] = service;
discovered.push({
uuid: serviceUUID,
primary: false
});
}
}, this);
completeFn(discovered);
}));
}
public discoverCharacteristics(handle: string, characteristicUUIDs: Array<string>, completeFn: (characteristics: Array<Partial<BluetoothRemoteGATTCharacteristic>>) => void, errorFn?: (errorMsg: string) => void): void {
const serviceInfo = this.serviceHandles[handle];
serviceInfo.discoverCharacteristics([], this.checkForError(errorFn, characteristics => {
const discovered = [];
characteristics.forEach(characteristicInfo => {
const charUUID = getCanonicalUUID(characteristicInfo.uuid);
if (characteristicUUIDs.length === 0 || characteristicUUIDs.indexOf(charUUID) >= 0) {
if (!this.characteristicHandles[charUUID]) this.characteristicHandles[charUUID] = characteristicInfo;
discovered.push({
uuid: charUUID,
properties: {
broadcast: (characteristicInfo.properties.indexOf("broadcast") >= 0),
read: (characteristicInfo.properties.indexOf("read") >= 0),
writeWithoutResponse: (characteristicInfo.properties.indexOf("writeWithoutResponse") >= 0),
write: (characteristicInfo.properties.indexOf("write") >= 0),
notify: (characteristicInfo.properties.indexOf("notify") >= 0),
indicate: (characteristicInfo.properties.indexOf("indicate") >= 0),
authenticatedSignedWrites: (characteristicInfo.properties.indexOf("authenticatedSignedWrites") >= 0),
reliableWrite: (characteristicInfo.properties.indexOf("reliableWrite") >= 0),
writableAuxiliaries: (characteristicInfo.properties.indexOf("writableAuxiliaries") >= 0)
}
});
characteristicInfo.on("data", (data, isNotification) => {
if (isNotification === true && typeof this.charNotifies[charUUID] === "function") {
const dataView = this.bufferToDataView(data);
this.charNotifies[charUUID](dataView);
}
});
}
}, this);
completeFn(discovered);
}));
}
public discoverDescriptors(handle: string, descriptorUUIDs: Array<string>, completeFn: (descriptors: Array<Partial<BluetoothRemoteGATTDescriptor>>) => void, errorFn?: (errorMsg: string) => void): void {
const characteristicInfo = this.characteristicHandles[handle];
characteristicInfo.discoverDescriptors(this.checkForError(errorFn, descriptors => {
const discovered = [];
descriptors.forEach(descriptorInfo => {
const descUUID = getCanonicalUUID(descriptorInfo.uuid);
if (descriptorUUIDs.length === 0 || descriptorUUIDs.indexOf(descUUID) >= 0) {
const descHandle = characteristicInfo.uuid + "-" + descriptorInfo.uuid;
if (!this.descriptorHandles[descHandle]) this.descriptorHandles[descHandle] = descriptorInfo;
discovered.push({
uuid: descUUID
});
}
}, this);
completeFn(discovered);
}));
}
public readCharacteristic(handle: string, completeFn: (value: DataView) => void, errorFn?: (errorMsg: string) => void): void {
this.characteristicHandles[handle].read(this.checkForError(errorFn, data => {
const dataView = this.bufferToDataView(data);
completeFn(dataView);
}));
}
public writeCharacteristic(handle: string, value: DataView, completeFn?: () => void, errorFn?: (errorMsg: string) => void, withoutResponse?: boolean): void {
const buffer = this.dataViewToBuffer(value);
const characteristic = this.characteristicHandles[handle];
if (withoutResponse === undefined) {
// writeWithoutResponse and authenticatedSignedWrites don't require a response
withoutResponse = characteristic.properties.indexOf("writeWithoutResponse") >= 0
|| characteristic.properties.indexOf("authenticatedSignedWrites") >= 0;
}
// Add a small delay for writing without response when not on MacOS
const delay = (this.os !== "darwin" && withoutResponse) ? 25 : null;
characteristic.write(buffer, withoutResponse, this.checkForError(errorFn, completeFn, delay));
}
public enableNotify(handle: string, notifyFn: (value: DataView) => void, completeFn?: () => void, errorFn?: (errorMsg: string) => void): void {
if (this.charNotifies[handle]) {
this.charNotifies[handle] = notifyFn;
return completeFn();
}
this.characteristicHandles[handle].once("notify", state => {
if (state !== true) return errorFn("notify failed to enable");
this.charNotifies[handle] = notifyFn;
completeFn();
});
this.characteristicHandles[handle].notify(true, this.checkForError(errorFn));
}
public disableNotify(handle: string, completeFn?: () => void, errorFn?: (errorMsg: string) => void): void {
if (!this.charNotifies[handle]) {
return completeFn();
}
this.characteristicHandles[handle].once("notify", state => {
if (state !== false) return errorFn("notify failed to disable");
if (this.charNotifies[handle]) delete this.charNotifies[handle];
completeFn();
});
this.characteristicHandles[handle].notify(false, this.checkForError(errorFn));
}
public readDescriptor(handle: string, completeFn: (value: DataView) => void, errorFn?: (errorMsg: string) => void): void {
this.descriptorHandles[handle].readValue(this.checkForError(errorFn, data => {
const dataView = this.bufferToDataView(data);
completeFn(dataView);
}));
}
public writeDescriptor(handle: string, value: DataView, completeFn?: () => void, errorFn?: (errorMsg: string) => void): void {
const buffer = this.dataViewToBuffer(value);
this.descriptorHandles[handle].writeValue(buffer, this.checkForError(errorFn, completeFn));
}
}
/**
* @hidden
*/
export const adapter = new NobleAdapter(); | the_stack |
import { PdfDockStyle, PdfAlignmentStyle, TemplateType } from './enum';
import { PointF, SizeF } from './../drawing/pdf-drawing';
import { PdfGraphics } from './../graphics/pdf-graphics';
import { PdfTemplate } from './../graphics/figures/pdf-template';
import { PdfPageLayer } from './pdf-page-layer';
import { PdfPage } from './pdf-page';
import { PdfDocument } from './../document/pdf-document';
import { RectangleF } from './../drawing/pdf-drawing';
import { PdfSection } from './pdf-section';
/**
* Describes a `page template` object that can be used as header/footer, watermark or stamp.
*/
export class PdfPageTemplateElement {
// Fields
/**
* `Layer type` of the template.
* @private
*/
private isForeground : boolean;
/**
* `Docking style`.
* @private
*/
private dockStyle : PdfDockStyle;
/**
* `Alignment style`.
* @private
*/
private alignmentStyle : PdfAlignmentStyle;
/**
* `PdfTemplate` object.
* @private
*/
private pdfTemplate : PdfTemplate;
/**
* Usage `type` of this template.
* @private
*/
private templateType : TemplateType;
/**
* `Location` of the template on the page.
* @private
*/
private currentLocation : PointF;
// Properties
/**
* Gets or sets the `dock style` of the page template element.
* @private
*/
public get dock() : PdfDockStyle {
return this.dockStyle;
}
public set dock(value : PdfDockStyle) {
// if (this.dockStyle !== value && this.Type === TemplateType.None) {
this.dockStyle = value;
// Reset alignment.
this.resetAlignment();
// }
}
/**
* Gets or sets `alignment` of the page template element.
* @private
*/
public get alignment() : PdfAlignmentStyle {
return this.alignmentStyle;
}
public set alignment(value : PdfAlignmentStyle) {
// if (this.alignmentStyle !== value) {
this.setAlignment(value);
// }
}
/**
* Indicates whether the page template is located `in front of the page layers or behind of it`.
* @private
*/
public get foreground() : boolean {
return this.isForeground;
}
public set foreground(value : boolean) {
// if (this.foreground !== value) {
this.isForeground = value;
// }
}
/**
* Indicates whether the page template is located `behind of the page layers or in front of it`.
* @private
*/
public get background() : boolean {
return !this.isForeground;
}
public set background(value : boolean) {
this.isForeground = !value;
}
/**
* Gets or sets `location` of the page template element.
* @private
*/
public get location() : PointF {
return this.currentLocation;
}
public set location(value : PointF) {
if (this.type === TemplateType.None) {
this.currentLocation = value;
} else {
//
}
}
/**
* Gets or sets `X` co-ordinate of the template element on the page.
* @private
*/
public get x() : number {
let value : number = (typeof this.currentLocation !== 'undefined') ? this.currentLocation.x : 0;
return value;
}
public set x(value : number) {
if (this.type === TemplateType.None) {
this.currentLocation.x = value;
} else {
//
}
}
/**
* Gets or sets `Y` co-ordinate of the template element on the page.
* @private
*/
public get y() : number {
let value : number = (typeof this.currentLocation !== 'undefined') ? this.currentLocation.y : 0;
return value;
}
public set y(value : number) {
if (this.type === TemplateType.None) {
this.currentLocation.y = value;
} else {
//
}
}
/**
* Gets or sets `size` of the page template element.
* @private
*/
public get size() : SizeF {
return this.template.size;
}
public set size(value : SizeF) {
if (this.type === TemplateType.None) {
this.template.reset(value);
}
}
/**
* Gets or sets `width` of the page template element.
* @private
*/
public get width() : number {
return this.template.width;
}
public set width(value : number) {
if (this.template.width !== value && this.type === TemplateType.None) {
let size : SizeF = this.template.size;
size.width = value;
this.template.reset(size);
}
}
/**
* Gets or sets `height` of the page template element.
* @private
*/
public get height() : number {
return this.template.height;
}
public set height(value : number) {
if (this.template.height !== value && this.type === TemplateType.None) {
let size : SizeF = this.template.size;
size.height = value;
this.template.reset(size);
}
}
/**
* Gets `graphics` context of the page template element.
* @private
*/
public get graphics() : PdfGraphics {
return this.template.graphics;
}
/**
* Gets Pdf `template` object.
* @private
*/
public get template() : PdfTemplate {
// if (typeof this.pdfTemplate === 'undefined' || this.pdfTemplate == null) {
// this.pdfTemplate = new PdfTemplate(this.size);
// }
return this.pdfTemplate;
}
/**
* Gets or sets `type` of the usage of this page template.
* @private
*/
public get type() : TemplateType {
return this.templateType;
}
public set type(value : TemplateType) {
this.updateDocking(value);
this.templateType = value;
}
/**
* Gets or sets `bounds` of the page template.
* @public
*/
public get bounds() : RectangleF {
return new RectangleF(new PointF(this.x, this.y), this.size);
}
public set bounds(value : RectangleF) {
if (this.type === TemplateType.None) {
this.location = new PointF(value.x, value.y);
this.size = new SizeF(value.width, value.height);
}
}
// constructor
/**
* Creates a new page template.
* @param bounds Bounds of the template.
*/
public constructor(bounds : RectangleF)
/**
* Creates a new page template.
* @param bounds Bounds of the template.
* @param page Page of the template.
*/
public constructor(bounds : RectangleF, page : PdfPage)
/**
* Creates a new page template.
* @param location Location of the template.
* @param size Size of the template.
*/
public constructor(location : PointF, size : SizeF)
/**
* Creates a new page template.
* @param location Location of the template.
* @param size Size of the template.
* @param page Page of the template.
*/
public constructor(location : PointF, size : SizeF, page : PdfPage)
/**
* Creates a new page template.
* @param size Size of the template.
*/
public constructor(size : SizeF)
/**
* Creates a new page template.
* @param width Width of the template.
* @param height Height of the template.
*/
public constructor(width : number, height : number)
/**
* Creates a new page template.
* @param width Width of the template.
* @param height Height of the template.
* @param page The Current Page object.
*/
public constructor(width : number, height : number, page : PdfPage)
/**
* Creates a new page template.
* @param x X co-ordinate of the template.
* @param y Y co-ordinate of the template.
* @param width Width of the template.
* @param height Height of the template.
*/
public constructor(x : number, y : number, width : number, height : number)
/**
* Creates a new page template.
* @param x X co-ordinate of the template.
* @param y Y co-ordinate of the template.
* @param width Width of the template.
* @param height Height of the template.
* @param page The Current Page object.
*/
public constructor(x : number, y : number, width : number, height : number, page : PdfPage)
/* tslint:disable */
public constructor(arg1 : number|PointF|SizeF|RectangleF, arg2 ?: number|SizeF|PdfPage, arg3 ?: number|PdfPage, arg4 ?: number, arg5 ?: PdfPage) {
if (arg1 instanceof RectangleF && typeof arg2 === 'undefined') {
this.InitiateBounds(arg1.x, arg1.y, arg1.width, arg1.height, null);
} else if (arg1 instanceof RectangleF && arg2 instanceof PdfPage && typeof arg3 === 'undefined') {
this.InitiateBounds(arg1.x, arg1.y, arg1.width, arg1.height, arg2);
} else if (arg1 instanceof PointF && arg2 instanceof SizeF && typeof arg3 === 'undefined') {
this.InitiateBounds(arg1.x, arg1.y, arg2.width, arg2.height, null);
} else if (arg1 instanceof PointF && arg2 instanceof SizeF && arg3 instanceof PdfPage && typeof arg4 === 'undefined') {
this.InitiateBounds(arg1.x, arg1.y, arg2.width, arg2.height, arg3);
} else if (arg1 instanceof SizeF && typeof arg2 === 'undefined') {
this.InitiateBounds(0, 0, arg1.width, arg1.height , null);
} else if (typeof arg1 === 'number' && typeof arg2 === 'number' && typeof arg3 === 'undefined') {
this.InitiateBounds(0, 0, arg1, arg2, null);
} else if (typeof arg1 === 'number' && typeof arg2 === 'number' && arg3 instanceof PdfPage && typeof arg4 === 'undefined') {
this.InitiateBounds(0, 0, arg1, arg2, arg3);
} else if (typeof arg1 === 'number' && typeof arg2 === 'number' && typeof arg3 === 'number' && typeof arg4 === 'number' && typeof arg5 === 'undefined') {
this.InitiateBounds(arg1, arg2, arg3, arg4, null);
} else {
this.InitiateBounds(arg1 as number, arg2 as number, arg3 as number, arg4 as number, null);
// this.graphics.colorSpace = this.page.document.colorSpace;
}
/* tslint:enable */
}
/**
* `Initialize Bounds` Initialize the bounds value of the template.
* @private
*/
private InitiateBounds(arg1 : number, arg2 : number, arg3 : number, arg4 : number , arg5 : PdfPage) : void {
this.x = arg1 as number;
this.y = arg2 as number;
this.pdfTemplate = new PdfTemplate(arg3 as number, arg4 as number);
// this.graphics.colorSpace = this.page.document.colorSpace;
}
/**
* `Updates Dock` property if template is used as header/footer.
* @private
*/
private updateDocking(type : TemplateType) : void {
if (type !== TemplateType.None) {
switch (type) {
case TemplateType.Top:
this.dock = PdfDockStyle.Top;
break;
case TemplateType.Bottom:
this.dock = PdfDockStyle.Bottom;
break;
case TemplateType.Left:
this.dock = PdfDockStyle.Left;
break;
case TemplateType.Right:
this.dock = PdfDockStyle.Right;
break;
}
this.resetAlignment();
}
}
/**
* `Resets alignment` of the template.
* @private
*/
private resetAlignment() : void {
this.alignment = PdfAlignmentStyle.None;
}
/**
* `Sets alignment` of the template.
* @private
*/
private setAlignment(alignment : PdfAlignmentStyle) : void {
if (this.dock === PdfDockStyle.None) {
this.alignmentStyle = alignment;
} else {
// Template is docked and alignment has been changed.
let canBeSet : boolean = false;
switch (this.dock) {
case PdfDockStyle.Left:
canBeSet = (alignment === PdfAlignmentStyle.TopLeft || alignment === PdfAlignmentStyle.MiddleLeft ||
alignment === PdfAlignmentStyle.BottomLeft || alignment === PdfAlignmentStyle.None);
break;
case PdfDockStyle.Top:
canBeSet = (alignment === PdfAlignmentStyle.TopLeft || alignment === PdfAlignmentStyle.TopCenter ||
alignment === PdfAlignmentStyle.TopRight || alignment === PdfAlignmentStyle.None);
break;
case PdfDockStyle.Right:
canBeSet = (alignment === PdfAlignmentStyle.TopRight || alignment === PdfAlignmentStyle.MiddleRight ||
alignment === PdfAlignmentStyle.BottomRight || alignment === PdfAlignmentStyle.None);
break;
case PdfDockStyle.Bottom:
canBeSet = (alignment === PdfAlignmentStyle.BottomLeft || alignment === PdfAlignmentStyle.BottomCenter
|| alignment === PdfAlignmentStyle.BottomRight || alignment === PdfAlignmentStyle.None);
break;
case PdfDockStyle.Fill:
canBeSet = (alignment === PdfAlignmentStyle.MiddleCenter || alignment === PdfAlignmentStyle.None);
break;
}
if (canBeSet) {
this.alignmentStyle = alignment;
}
}
}
/**
* Draws the template.
* @private
*/
public draw(layer : PdfPageLayer, document : PdfDocument) : void {
let page : PdfPage = layer.page as PdfPage;
let bounds : RectangleF = this.calculateBounds(page, document);
if (bounds.x === -0) {
bounds.x = 0;
}
layer.graphics.drawPdfTemplate(this.template, new PointF(bounds.x, bounds.y), new SizeF(bounds.width, bounds.height));
}
/**
* Calculates bounds of the page template.
* @private
*/
private calculateBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let result : RectangleF = this.bounds;
if (this.alignmentStyle !== PdfAlignmentStyle.None) {
result = this.getAlignmentBounds(page, document);
} else if (this.dockStyle !== PdfDockStyle.None) {
result = this.getDockBounds(page, document);
}
return result;
}
/**
* Calculates bounds according to the alignment.
* @private
*/
private getAlignmentBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let result : RectangleF = this.bounds;
if (this.type === TemplateType.None) {
result = this.getSimpleAlignmentBounds(page, document);
} else {
result = this.getTemplateAlignmentBounds(page, document);
}
return result;
}
/**
* Calculates bounds according to the alignment.
* @private
*/
private getSimpleAlignmentBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let bounds : RectangleF = this.bounds;
let pdfSection : PdfSection = page.section;
let actualBounds : RectangleF = pdfSection.getActualBounds(document, page, false);
let x : number = this.x as number;
let y : number = this.y as number;
switch (this.alignmentStyle) {
case PdfAlignmentStyle.TopLeft:
x = 0;
y = 0;
break;
case PdfAlignmentStyle.TopCenter:
x = (actualBounds.width - this.width) / 2;
y = 0;
break;
case PdfAlignmentStyle.TopRight:
x = actualBounds.width - this.width;
y = 0;
break;
case PdfAlignmentStyle.MiddleLeft:
x = 0;
y = (actualBounds.height - this.height) / 2;
break;
case PdfAlignmentStyle.MiddleCenter:
x = (actualBounds.width - this.width) / 2;
y = (actualBounds.height - this.height) / 2;
break;
case PdfAlignmentStyle.MiddleRight:
x = actualBounds.width - this.width;
y = (actualBounds.height - this.height) / 2;
break;
case PdfAlignmentStyle.BottomLeft:
x = 0;
y = actualBounds.height - this.height;
break;
case PdfAlignmentStyle.BottomCenter:
x = (actualBounds.width - this.width) / 2;
y = actualBounds.height - this.height;
break;
case PdfAlignmentStyle.BottomRight:
x = actualBounds.width - this.width;
y = actualBounds.height - this.height;
break;
}
bounds.x = x;
bounds.y = y;
return bounds;
}
/**
* Calculates bounds according to the alignment.
* @private
*/
private getTemplateAlignmentBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let result : RectangleF = this.bounds;
let section : PdfSection = page.section;
let actualBounds : RectangleF = section.getActualBounds(document, page, false);
let x : number = this.x;
let y : number = this.y;
switch (this.alignmentStyle) {
case PdfAlignmentStyle.TopLeft:
if (this.type === TemplateType.Left) {
x = -actualBounds.x;
y = 0;
} else if (this.type === TemplateType.Top) {
x = -actualBounds.x;
y = -actualBounds.y;
}
break;
case PdfAlignmentStyle.TopCenter:
x = (actualBounds.width - this.width) / 2;
y = -actualBounds.y;
break;
case PdfAlignmentStyle.TopRight:
if (this.type === TemplateType.Right) {
x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;
y = 0;
} else if (this.type === TemplateType.Top) {
x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;
y = -actualBounds.y;
}
break;
case PdfAlignmentStyle.MiddleLeft:
x = -actualBounds.x;
y = (actualBounds.height - this.height) / 2;
break;
case PdfAlignmentStyle.MiddleCenter:
x = (actualBounds.width - this.width) / 2;
y = (actualBounds.height - this.height) / 2;
break;
case PdfAlignmentStyle.MiddleRight:
x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;
y = (actualBounds.height - this.height) / 2;
break;
case PdfAlignmentStyle.BottomLeft:
if (this.type === TemplateType.Left) {
x = -actualBounds.x;
y = actualBounds.height - this.height;
} else if (this.type === TemplateType.Bottom) {
x = -actualBounds.x;
y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;
}
break;
case PdfAlignmentStyle.BottomCenter:
x = (actualBounds.width - this.width) / 2;
y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;
break;
case PdfAlignmentStyle.BottomRight:
if (this.type === TemplateType.Right) {
x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;
y = actualBounds.height - this.height;
} else if (this.type === TemplateType.Bottom) {
x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;
y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;
}
break;
}
result.x = x;
result.y = y;
return result;
}
/**
* Calculates bounds according to the docking.
* @private
*/
private getDockBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let result : RectangleF = this.bounds;
if (this.type === TemplateType.None) {
result = this.getSimpleDockBounds(page, document);
} else {
result = this.getTemplateDockBounds(page, document);
}
return result;
}
/**
* Calculates bounds according to the docking.
* @private
*/
private getSimpleDockBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let result : RectangleF = this.bounds;
let section : PdfSection = page.section;
let actualBounds : RectangleF = section.getActualBounds(document, page, false);
let x : number = this.x;
let y : number = this.y;
let width : number = this.width;
let height : number = this.height;
switch (this.dockStyle) {
case PdfDockStyle.Left:
x = 0;
y = 0;
width = this.width;
height = actualBounds.height;
break;
case PdfDockStyle.Top:
x = 0;
y = 0;
width = actualBounds.width;
height = this.height;
break;
case PdfDockStyle.Right:
x = actualBounds.width - this.width;
y = 0;
width = this.width;
height = actualBounds.height;
break;
case PdfDockStyle.Bottom:
x = 0;
y = actualBounds.height - this.height;
width = actualBounds.width;
height = this.height;
break;
case PdfDockStyle.Fill:
x = 0;
x = 0;
width = actualBounds.width;
height = actualBounds.height;
break;
}
result = new RectangleF(x, y, width, height);
return result;
}
/**
* Calculates template bounds basing on docking if template is a page template.
* @private
*/
private getTemplateDockBounds(page : PdfPage, document : PdfDocument) : RectangleF {
let result : RectangleF = this.bounds;
let section : PdfSection = page.section;
let actualBounds : RectangleF = section.getActualBounds(document, page, false);
let actualSize : SizeF = section.pageSettings.getActualSize();
let x : number = this.x;
let y : number = this.y;
let width : number = this.width;
let height : number = this.height;
switch (this.dockStyle) {
case PdfDockStyle.Left:
x = -actualBounds.x;
y = 0;
width = this.width;
height = actualBounds.height;
break;
case PdfDockStyle.Top:
x = -actualBounds.x;
y = -actualBounds.y;
width = actualSize.width;
height = this.height;
if (actualBounds.height < 0) {
y = -actualBounds.y + actualSize.height;
}
break;
case PdfDockStyle.Right:
x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;
y = 0;
width = this.width;
height = actualBounds.height;
break;
case PdfDockStyle.Bottom:
x = -actualBounds.x;
y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;
width = actualSize.width;
height = this.height;
if (actualBounds.height < 0) {
y -= actualSize.height;
}
break;
case PdfDockStyle.Fill:
x = 0;
x = 0;
width = actualBounds.width;
height = actualBounds.height;
break;
}
result = new RectangleF(x, y, width, height);
return result;
}
} | the_stack |
import debug from 'debug'
import ETHProvider from 'eth-provider'
import fs from 'fs-extra'
import json from 'jsonfile'
import Level from 'level'
import ora from 'ora'
import os from 'os'
import path from 'path'
import shell from 'shelljs'
import contractor from 'truffle-contract'
import Web3 from 'web3'
import GitHelper from './lib/git'
import IPLDHelper from './lib/ipld'
import LineHelper from './lib/line'
const _timeout = async (duration: any): Promise<void> => {
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
resolve()
}, duration)
})
}
export default class Helper {
// name and url
public name: string
public url: string
// address and path shortcuts
public address: string
public path: string
// config
public config: any
// lib
public debug: any
public line: LineHelper
public git: GitHelper
public ipld: IPLDHelper
// db
private _db: any
// provider and web3
private _provider: any
private _web3: any
// artifacts and contracts
private _repo!: any
private _kernel!: any
constructor(name: string = '_', url: string) {
// name and url
this.name = name
this.url = url
// address and path shortcuts
this.address = this.url.split('://')[1]
this.path = path.resolve(process.env.GIT_DIR as string)
// config
this.config = this._config()
// lib
this.debug = debug('pando')
this.line = new LineHelper()
this.git = new GitHelper(this)
this.ipld = new IPLDHelper(this)
}
// OK
public async initialize(): Promise<void> {
// create dirs
fs.ensureDirSync(path.join(this.path, 'refs', 'remotes', this.name))
fs.ensureDirSync(path.join(this.path, 'pando', 'refs'))
// load db
this._db = Level(path.join(this.path, 'pando', 'refs', this.address))
// initialize web3
this._provider = await this._ethConnect()
this._web3 = new Web3(this._provider)
// initialize repo contract
this._repo = { artifact: undefined, contract: undefined }
// tslint:disable-next-line:no-submodule-imports
this._repo.artifact = contractor(require('@pando/repository/abi/PandoRepository.json'))
this._repo.artifact.setProvider(this._provider)
this._repo.artifact.defaults({ from: this.config.ethereum.account })
this._repo.artifact.autoGas = true
this._repo.artifact.gasMultiplier = 3
this._repo.contract = await this._repo.artifact.at(this.address)
// initialize kernel contract
this._kernel = { artifact: undefined, contract: undefined }
// tslint:disable-next-line:no-submodule-imports
this._kernel.artifact = contractor(require('@pando/repository/abi/Kernel.json'))
this._kernel.artifact.setProvider(this._provider)
this._kernel.artifact.defaults({ from: this.config.ethereum.account })
this._kernel.artifact.autoGas = true
this._kernel.artifact.gasMultiplier = 3
this._kernel.contract = await this._kernel.artifact.at(await this._repo.contract.kernel())
}
// OK
public async run(): Promise<void> {
while (true) {
const cmd = await this.line.next()
switch (this._cmd(cmd)) {
case 'capabilities':
await this._handleCapabilities()
break
case 'list for-push':
await this._handleList({ forPush: true })
break
case 'list':
await this._handleList()
break
case 'fetch':
await this._handleFetch(cmd)
break
case 'push':
await this._handlePush(cmd)
break
case 'end':
this._exit()
case 'unknown':
throw new Error('Unknown command: ' + cmd)
}
}
}
/***** commands handling methods *****/
// OK
private async _handleCapabilities(): Promise<void> {
this.debug('cmd', 'capabilities')
// this._send('option')
this._send('fetch')
this._send('push')
this._send('')
}
// OK
private async _handleList({ forPush = false }: { forPush?: boolean } = {}): Promise<void> {
forPush ? this.debug('cmd', 'list', 'for-push') : this.debug('cmd, list')
const refs = await this._fetchRefs()
// tslint:disable-next-line:forin
for (const ref in refs) {
this._send(this.ipld.cidToSha(refs[ref]) + ' ' + ref)
}
// force HEAD to master and update once pando handle symbolic refs
this._send('@refs/heads/master' + ' ' + 'HEAD')
this._send('')
}
// OK
private async _handleFetch(line: string): Promise<void> {
this.debug('cmd', line)
while (true) {
const [cmd, oid, name] = line.split(' ')
await this._fetch(oid, name)
line = await this.line.next()
if (line === '') break
}
this._send('')
}
// OK
private async _handlePush(line: string): Promise<void> {
this.debug('cmd', line)
while (true) {
const [src, dst] = line.split(' ')[1].split(':')
if (src === '') {
await this._delete(dst)
} else {
await this._push(src, dst)
}
line = await this.line.next()
if (line === '') break
}
this._send('')
}
/***** refs db methods *****/
// OK
private async _fetchRefs(): Promise<object> {
this.debug('fetching remote refs from chain')
let start
let block
let events
const ops: object[] = []
const updates: object = {}
const spinner = ora('Fetching remote refs from chain [this may take a while]').start()
try {
start = await this._db.get('@block')
} catch (err) {
if (err.message === 'Key not found in database [@block]') {
start = 0
} else {
throw err
}
}
try {
block = await this._web3.eth.getBlockNumber()
events = await this._repo.contract.getPastEvents('UpdateRef', {
fromBlock: start,
toBlock: 'latest',
})
for (const event of events) {
updates[event.args.ref] = event.args.hash
}
// tslint:disable-next-line:forin
for (const ref in updates) {
ops.push({ type: 'put', key: ref, value: updates[ref] })
}
ops.push({ type: 'put', key: '@block', value: block })
await this._db.batch(ops)
spinner.succeed('Remote refs fetched from chain')
return this._getRefs()
} catch (err) {
spinner.fail('Failed to fetch remote refs from chain')
throw err
}
}
// OK
private async _getRefs(): Promise<object> {
this.debug('reading refs from local db')
const refs: any = {}
return new Promise<object>((resolve, reject) => {
this._db
.createReadStream()
.on('data', ref => {
if (ref.key !== '@block') refs[ref.key] = ref.value
})
.on('error', err => {
reject(err)
})
.on('end', () => {
//
})
.on('close', () => {
resolve(refs)
})
})
}
/***** core methods *****/
// OK
private async _fetch(oid: string, ref: string): Promise<void> {
this.debug('fetching', ref, oid, this.ipld.shaToCid(oid))
await this.git.download(oid)
}
// OK
private async _push(src: string, dst: string): Promise<void> {
this.debug('pushing', src, 'to', dst)
return new Promise<void>(async (resolve, reject) => {
let spinner
let head
let txHash
let mapping: any = {}
const puts: any = []
const pins: any = []
try {
const refs = await this._getRefs()
const remote: any = refs[dst]
const srcBranch = src.split('/').pop()
const dstBranch = dst.split('/').pop()
const revListCmd = remote ? `git rev-list --left-only ${srcBranch}...${this.name}/${dstBranch}` : 'git rev-list --all'
const commits = shell
.exec(revListCmd, { silent: true })
.stdout.split('\n')
.slice(0, -1)
// checking permissions
try {
spinner = ora(`Checking permissions over ${this.address}`).start()
if (process.env.PANDO_OPEN_PR) {
if (await this._kernel.contract.hasPermission(this.config.ethereum.account, this.address, await this._repo.contract.OPEN_PR_ROLE(), '0x0')) {
spinner.succeed(`You have open PR permission over ${this.address}`)
} else {
spinner.fail(`You do not have open PR permission over ${this.address}`)
this._die()
}
} else {
if (await this._kernel.contract.hasPermission(this.config.ethereum.account, this.address, await this._repo.contract.PUSH_ROLE(), '0x0')) {
spinner.succeed(`You have push permission over ${this.address}`)
} else {
spinner.fail(`You do not have push permission over ${this.address}. Try to run 'git pando pr open' to open a push request.`)
this._die()
}
}
} catch (err) {
spinner.fail(`Failed to check permissions over ${this.address}: ` + err.message)
this._die()
}
// collect git objects
try {
spinner = ora('Collecting git objects [this may take a while]').start()
for (const commit of commits) {
const _mapping = await this.git.collect(commit, mapping)
mapping = { ...mapping, ..._mapping }
}
head = this.ipld.shaToCid(commits[0])
// tslint:disable-next-line:forin
for (const entry in mapping) {
puts.push(this.ipld.put(mapping[entry]))
}
spinner.succeed('Git objects collected')
} catch (err) {
spinner.fail('Failed to collect git objects: ' + err.message)
this._die()
}
// upload git objects
try {
spinner = ora('Uploading git objects to IPFS').start()
await Promise.all(puts)
spinner.succeed('Git objects uploaded to IPFS')
} catch (err) {
spinner.fail('Failed to upload git objects to IPFS: ' + err.message)
this._die()
}
// pin git objects
try {
// tslint:disable-next-line:forin
for (const entry in mapping) {
pins.push(this.ipld.pin(entry))
}
spinner = ora('Pinning git objects to IPFS').start()
await Promise.all(pins)
spinner.succeed('Git objects pinned to IPFS')
} catch (err) {
spinner.fail('Failed to pin git objects to IPFS: ' + err.message)
this._die()
}
// register on chain
if (!process.env.PANDO_OPEN_PR) {
try {
spinner = ora(`Registering ref ${dst} ${head} on-chain`).start()
this._repo.contract
.push(dst, head)
.on('error', err => {
if (!err.message.includes('Failed to subscribe to new newBlockHeaders to confirm the transaction receipts')) {
spinner.fail(`Failed to register ref ${dst} ${head} on-chain: ` + err.message)
this._die()
}
})
.on('transactionHash', hash => {
txHash = hash
spinner.text = `Registering ref ${dst} ${head} on-chain through tx ${txHash}`
})
.then(receipt => {
spinner.succeed(`Ref ${dst} ${head} registered on-chain through tx ${txHash}`)
this._send(`ok ${dst}`)
resolve()
})
.catch(err => {
spinner.fail(`Failed to register ref ${dst} ${head} on-chain: ` + err.message)
this._die()
})
} catch (err) {
spinner.fail(`Failed to register ref ${dst} ${head} on-chain: ` + err.message)
this._die()
}
} else {
try {
spinner = ora(`Opening PR for ${dst} ${head} on-chain`).start()
this._repo.contract
.openPR(process.env.PANDO_PR_TITLE, process.env.PANDO_PR_DESCRIPTION || '', dst, head)
.on('error', err => {
if (!err.message.includes('Failed to subscribe to new newBlockHeaders to confirm the transaction receipts')) {
spinner.fail(`Failed to open PR for ${dst} ${head} on-chain: ` + err.message)
this._die()
}
})
.on('transactionHash', hash => {
txHash = hash
spinner.text = `Opening PR for ${dst} ${head} on-chain through tx ${txHash}`
})
.then(receipt => {
const id = receipt.logs.filter(l => l.event === 'OpenPR')[0].args.id
spinner.succeed(`PR #${id} for ${dst} ${head} opened on-chain through tx ${txHash}`)
this._send(`error ${dst} Relax! This is because you do not have push permission: PR #${id} has been opened for you instead`)
resolve()
})
.catch(err => {
spinner.fail(`Failed to open PR for ${dst} ${head} on-chain: ` + err.message)
this._die()
})
} catch (err) {
spinner.fail(`Failed to open PR for ${dst} ${head} on-chain: ` + err.message)
this._die()
}
}
} catch (err) {
this._die(err.message)
}
})
}
// TODO
private async _delete(dst: string): Promise<void> {
this.debug('deleting', dst)
}
/***** utility methods *****/
// OK
private async _ethConnect(): Promise<any> {
this.debug('connecting to gateway', this.config.ethereum.gateway)
const provider = ETHProvider(this.config.ethereum.gateway)
const spinner = ora('Connecting to Ethereum').start()
while (true) {
try {
const accounts = await provider.send('eth_accounts')
spinner.stop()
for (const account of accounts) {
if (account === this.config.ethereum.account) return provider
}
this._die("Failed to access your Ethereum account. Update your gateway configuration or run 'git pando config' to select another account.")
} catch (err) {
if (err.code === 4100 || err.code === 4001) {
spinner.text = `Error connecting to Ethereum. ${err.message}.`
await _timeout(2000)
} else {
spinner.stop()
this._die('Failed to connect to Ethereum. Make sure your Ethereum gateway is running.')
}
}
}
}
// OK
private _config(): any {
const LOCAL = path.join(this.path, 'pando', '.pandorc')
const GLOBAL = path.join(os.homedir(), '.pandorc')
if (fs.pathExistsSync(LOCAL)) return json.readFileSync(LOCAL)
if (fs.pathExistsSync(GLOBAL)) return json.readFileSync(GLOBAL)
this._die("No configuration file found. Run 'git-pando config' and come back to us.")
}
// OK
private _cmd(line: string): string {
if (line === 'capabilities') {
return 'capabilities'
} else if (line === 'list for-push') {
return 'list for-push'
} else if (line === 'list') {
return 'list'
} else if (line.startsWith('option')) {
return 'option'
} else if (line.startsWith('fetch')) {
return 'fetch'
} else if (line.startsWith('push')) {
return 'push'
} else if (line === '') {
return 'end'
} else {
return 'unknown'
}
}
// OK
private _send(message): void {
// tslint:disable-next-line:no-console
console.log(message)
}
// OK
private _die(message?: string): void {
// tslint:disable-next-line:no-console
if (message) console.error(message)
process.exit(1)
}
// OK
private _exit(): void {
process.exit(0)
}
} | the_stack |
import {
JSONExt, JSONObject
} from '@phosphor/coreutils';
import {
Fields, Datastore, RegisterField, TextField
} from '@phosphor/datastore';
import {
DisposableDelegate, IDisposable
} from '@phosphor/disposable';
import {
Panel, Widget
} from '@phosphor/widgets';
import * as CodeMirror from 'codemirror';
import {
COLLABORATOR_ID, COLLABORATOR_COLOR, COLLABORATOR_NAME
} from './collaborator';
/**
* The time that a collaborator name hover persists.
*/
const HOVER_TIMEOUT = 1000;
/**
* A schema for an editor model. Currently contains two fields, the current
* value and whether the model is read only. Other fields could include
* language, mimetype, and collaborator cursors.
*/
export const EDITOR_SCHEMA = {
id: 'editor',
fields: {
readOnly: Fields.Boolean(),
text: Fields.Text(),
collaborators: Fields.Map<ICollaboratorState>()
}
};
/**
* An interface representing a location in an editor.
*/
export interface IPosition extends JSONObject {
/**
* The cursor line number.
*/
readonly line: number;
/**
* The cursor column number.
*/
readonly column: number;
}
/**
* An interface representing a user selection.
*/
export interface ITextSelection extends JSONObject {
/**
* The start of the selection.
*/
readonly start: IPosition;
/**
* The end of the selection.
*/
readonly end: IPosition;
}
/**
* An interface representing collaborator cursor state.
*/
export interface ICollaboratorState extends JSONObject {
/**
* The current cursor selections.
*/
selections: ITextSelection[];
/**
* A display name for the collaborator.
*/
name: string;
/**
* A display color for the collaborator.
*/
color: string;
}
/**
* A widget which hosts a collaborative CodeMirror text editor.
*/
export class CodeMirrorEditor extends Panel {
/**
* Create a new editor widget.
*
* @param datastore: a datastore which holds an editor table using `EDITOR_SCHEMA`.
*
* @param record: the record to watch in the editor table.
*/
constructor(datastore: Datastore, record: string) {
super();
this.addClass('content');
this._store = datastore;
this._record = record;
// Get initial values for the editor
let editorTable = this._store.get(EDITOR_SCHEMA);
let initialValue = editorTable.get(record)!.text;
let readOnly = editorTable.get(record)!.readOnly;
// Set up the DOM structure
this._editorWidget = new Widget();
this._checkWidget = new Widget();
this._checkWidget.node.style.height = `${this._toolbarHeight}px`;
this._checkWidget.addClass('read-only-check');
this._checkWidget.node.textContent = 'Read Only';
this._check = document.createElement('input');
this._check.type = 'checkbox';
this._check.checked = readOnly;
this._checkWidget.node.appendChild(this._check);
this.addWidget(this._checkWidget);
this.addWidget(this._editorWidget);
// Listen to changes in the checkbox.
this._check.onchange = this._onChecked.bind(this);
// Create the editor instance.
this._editor = CodeMirror(this._editorWidget.node, {
value: initialValue,
lineNumbers: true,
readOnly
});
// Listen for changes on the editor model.
CodeMirror.on(
this._editor.getDoc(),
'beforeChange',
this._onEditorChange.bind(this)
);
// Listen for changes to the editor cursors.
CodeMirror.on(
this._editor,
'cursorActivity',
this._onCursorActivity.bind(this)
);
// Listen for changes on the datastore.
datastore.changed.connect(this._onDatastoreChange, this);
}
/**
* Undo the last user action.
*/
undo(): void {
let id = this._undo.pop();
if (id) {
this._redo.push(id);
void this._store.undo(id);
}
}
/**
* Redo the last user action.
*/
redo(): void {
let id = this._redo.pop();
if (id) {
this._undo.push(id);
void this._store.redo(id);
}
}
/**
* Whether the editor is currently focused.
*/
hasFocus(): boolean {
return this.node.contains(document.activeElement);
}
/**
* Handle the DOM events for the editor.
*
* @param event - The DOM event sent to the editor.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the editor's DOM node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'scroll':
this._clearHover();
break;
default:
break;
}
}
/**
* A message handler invoked on a `'resize'` message.
*
* @param msg - the resize message.
*/
protected onResize(msg: Widget.ResizeMessage): void {
if (msg.width >= 0 && msg.height >= 0) {
this._editor.setSize(msg.width, msg.height - this._toolbarHeight);
} else if (this.isVisible) {
this._editor.setSize(null, null);
}
this._editor.refresh();
this._clearHover();
}
/**
* Handle a `after-show` message for the editor.
*/
protected onAfterShow() {
this._editor.refresh();
}
/**
* Handle a `after-attach` message for the editor.
*/
protected onAfterAttach() {
this.node.addEventListener('scroll', this, true);
}
/**
* Handle a `before-detach` message for the editor.
*/
protected onBeforeDetach() {
this.node.removeEventListener('scroll', this, true);
}
/**
* Handle a local check event.
*/
private _onChecked(): void {
// If this was a remote change, we are done.
if (this._changeGuard) {
return;
}
// Update the readonly state
this._editor.setOption('readOnly', this._check.checked);
// Update the table to broadcast the change.
let editorTable = this._store.get(EDITOR_SCHEMA);
let id = this._store.beginTransaction();
editorTable.update({
[this._record]: {
readOnly: this._check.checked
}
});
this._store.endTransaction();
// Update the undo/redo stack.
this._undo.push(id);
this._redo.length = 0;
}
/**
* Handle a local editor change.
*
* @param doc - the CodeMirror doc which changed.
*
* @param change - the CodeMirror change payload.
*/
private _onEditorChange(doc: CodeMirror.Doc, change: CodeMirror.EditorChange): void {
// If this was a remote change, we are done.
if (this._changeGuard) {
return;
}
let editorTable = this._store.get(EDITOR_SCHEMA);
let start = doc.indexFromPos(change.from);
let end = doc.indexFromPos(change.to);
let text = change.text.join('\n');
// If this was a local change, update the table.
let id = this._store.beginTransaction();
editorTable.update({
[this._record]: {
text: {
index: start,
remove: end - start,
text: text,
}
}
});
this._store.endTransaction();
// Update the undo/redo stack.
this._undo.push(id);
this._redo.length = 0;
}
/**
* Respond to a change in the editor cursors.
*/
private _onCursorActivity(): void {
// Only add selections inf the editor has focus. This avoids unwanted
// triggering of cursor activity due to other collaborator actions.
if (this._editor.hasFocus()) {
let selections = Private.getSelections(this._editor.getDoc());
let name = COLLABORATOR_NAME;
let color = COLLABORATOR_COLOR;
let editorTable = this._store.get(EDITOR_SCHEMA);
this._store.beginTransaction();
editorTable.update({
[this._record]: { collaborators: {
[COLLABORATOR_ID]: { name, color, selections } }
}
});
this._store.endTransaction();
}
}
/**
* Respond to a change on the datastore.
*
* @param store - the datastore which changed.
*
* @param change - the change content.
*/
private _onDatastoreChange(store: Datastore, change: Datastore.IChangedArgs): void {
// Ignore changes that have already been applied locally.
if (change.type === 'transaction' && change.storeId === store.id) {
return;
}
let doc = this._editor.getDoc();
// Apply text field changes to the editor.
let c = change.change['editor'];
if (c && c[this._record] && c[this._record].text) {
let textChanges = c[this._record].text as TextField.Change;
textChanges.forEach(tc => {
// Convert the change data to codemirror range and inserted text.
let from = doc.posFromIndex(tc.index);
let to = doc.posFromIndex(tc.index + tc.removed.length);
let replacement = tc.inserted;
// Apply the operation, setting the change guard so we can ignore
// the change signals from codemirror.
this._changeGuard = true;
doc.replaceRange(replacement, from, to, '+input');
this._changeGuard = false;
});
}
// If the readonly state has changed, update the check box, setting the
// change guard so we can ignore it in the onchange event.
if(c && c[this._record] && c[this._record].readOnly) {
this._changeGuard = true;
let checkChange = c[this._record].readOnly as RegisterField.Change<boolean>;
this._check.checked = checkChange.current;
// Update the readonly state
this._editor.setOption('readOnly', this._check.checked);
this._changeGuard = false;
}
// If the collaborator state has changed, rerender any selections.
if(c && c[this._record] && c[this._record].collaborators) {
let record = store.get(EDITOR_SCHEMA).get(this._record)!;
let { collaborators } = record;
this._clearAllSelections();
let ids = Object.keys(collaborators);
for (let id of ids) {
if (id !== COLLABORATOR_ID) {
this._markSelections(id, collaborators[id]!);
}
}
}
}
/**
* Clean currently shown selections for the editor.
*/
private _clearAllSelections() {
this._clearHover();
let ids = Object.keys(this._selectionMarkers);
for (let id of ids) {
this._clearSelections(id);
}
}
/**
* Clean currently shown selections for a given collaborator.
*/
private _clearSelections(id: string) {
let ids = Object.keys(this._selectionMarkers);
if (this._hoverId === id) {
this._clearHover();
}
for (let id of ids) {
let markers = this._selectionMarkers[id]!;
markers.forEach(marker => {
marker.clear();
});
delete this._selectionMarkers[id];
}
}
/**
* Marks selections.
*/
private _markSelections(
uuid: string,
collaborator: ICollaboratorState
) {
let markers: CodeMirror.TextMarker[] = [];
let doc = this._editor.getDoc();
// Style each selection for the uuid.
collaborator.selections.forEach(selection => {
// Only render selections if the start is not equal to the end.
// In that case, we don't need to render the cursor.
if (!JSONExt.deepEqual(selection.start, selection.end)) {
// Selections only appear to render correctly if the anchor
// is before the head in the document. That is, reverse selections
// do not appear as intended.
let forward: boolean =
selection.start.line < selection.end.line ||
(selection.start.line === selection.end.line &&
selection.start.column <= selection.end.column);
let anchor = Private.toCodeMirrorPosition(
forward ? selection.start : selection.end
);
let head = Private.toCodeMirrorPosition(
forward ? selection.end : selection.start
);
let markerOptions = Private.toTextMarkerOptions(collaborator);
markers.push(doc.markText(anchor, head, markerOptions));
} else {
let caret = this._getCaret(uuid, collaborator);
markers.push(
doc.setBookmark(Private.toCodeMirrorPosition(selection.end), {
widget: caret
})
);
}
});
this._selectionMarkers[uuid] = markers;
// Set a timer to auto-dispose of these markers, cleaning up after
// collaborators who might have left. We choose a random time between one
// and two minutes to avoid racing between active collaborators.
if (this._timers[uuid]) {
window.clearTimeout(this._timers[uuid]);
}
this._timers[uuid] = window.setTimeout(
() => {
this._clearSelections(uuid);
delete this._timers[uuid];
},
60*1000*(1 + Math.random())
);
}
/**
* Construct a caret element representing the position
* of a collaborator's cursor.
*/
private _getCaret(uuid: string, collaborator: ICollaboratorState): HTMLElement {
let { name, color } = collaborator;
let hoverTimeout: number;
let caret: HTMLElement = document.createElement('span');
caret.className = 'collaborator-cursor';
caret.style.borderBottomColor = color;
caret.onmouseenter = () => {
this._clearHover();
let rect = caret.getBoundingClientRect();
// Construct and place the hover box.
let hover = document.createElement('div');
hover.className = 'collaborator-cursor-hover';
hover.style.left = String(rect.left) + 'px';
hover.style.top = String(rect.bottom) + 'px';
hover.textContent = name;
hover.style.backgroundColor = color;
// If the user mouses over the hover, take over the timer.
hover.onmouseenter = () => {
window.clearTimeout(hoverTimeout);
};
hover.onmouseleave = () => {
hoverTimeout = window.setTimeout(() => {
this._clearHover();
}, HOVER_TIMEOUT);
};
document.body.appendChild(hover);
this._hoverId = uuid;
this._hover = new DisposableDelegate(() => {
window.clearTimeout(hoverTimeout);
document.body.removeChild(hover);
});
};
caret.onmouseleave = () => {
hoverTimeout = window.setTimeout(() => {
this._clearHover();
}, HOVER_TIMEOUT);
};
return caret;
}
/**
* If there is currently a hover box of a collaborator name, clear it.
*/
private _clearHover(): void {
this._hoverId = '';
if (this._hover) {
this._hover.dispose();
this._hover = null;
}
}
/**
* Converts an editor selection to a code mirror selection.
*/
private _changeGuard: boolean = false;
private _check: HTMLInputElement;
private _checkWidget: Widget;
private _editor: CodeMirror.Editor;
private _editorWidget: Widget;
private _hover: IDisposable | null = null;
private _hoverId: string = '';
private _record: string;
private _selectionMarkers: {
[key: string]: CodeMirror.TextMarker[] | undefined;
} = {};
private _store: Datastore;
private _timers: { [key: string]: number } = {};
private _toolbarHeight = 24;
private _undo: string[] = [];
private _redo: string[] = [];
}
/**
* A namespace for module-private functionality.
*/
namespace Private {
/**
* Create CodeMirror text marker options for a collaborator.
*/
export function toTextMarkerOptions(
collaborator: ICollaboratorState
): CodeMirror.TextMarkerOptions {
let r = parseInt(collaborator.color.slice(1, 3), 16);
let g = parseInt(collaborator.color.slice(3, 5), 16);
let b = parseInt(collaborator.color.slice(5, 7), 16);
let css = `background-color: rgba( ${r}, ${g}, ${b}, 0.15)`;
return {
title: collaborator.name,
css
};
}
/**
* Convert an editor position to a code mirror position.
*/
export function toCodeMirrorPosition(position: IPosition) {
return {
line: position.line,
ch: position.column
};
}
/**
* Converts a code mirror selection to an editor selection.
*/
export function toSelection(
selection: { anchor: CodeMirror.Position, head: CodeMirror.Position }
): ITextSelection {
return {
start: toPosition(selection.anchor),
end: toPosition(selection.head)
};
}
/**
* Convert a code mirror position to an editor position.
*/
export function toPosition(position: CodeMirror.Position): IPosition {
return {
line: position.line,
column: position.ch
};
}
/**
* Gets the selections for all the cursors, never `null` or empty.
*/
export function getSelections(doc: CodeMirror.Doc): ITextSelection[] {
let selections = doc.listSelections();
if (selections.length > 0) {
return selections.map(selection => Private.toSelection(selection));
}
let cursor = doc.getCursor();
let selection = Private.toSelection({ anchor: cursor, head: cursor });
return [selection];
}
} | the_stack |
import type {
__INTERNAL_REMIRROR_IDENTIFIER_KEY__,
RemirrorIdentifier,
} from '@remirror/core-constants';
import type {
CommandFunctionProps,
EditorSchema,
EditorState,
EditorView,
Mark,
ProsemirrorCommandFunction,
ProsemirrorNode,
ResolvedPos,
Selection,
} from '@remirror/pm';
import type { MarkSpec, NodeSpec } from '@remirror/pm/model';
import type { Decoration, NodeView } from '@remirror/pm/view';
import type { Literal, ObjectMark, ProsemirrorAttributes } from '@remirror/types';
import type { FromToProps, MarkWithAttributes, NodeWithAttributes } from './props-types';
/**
* A JSON representation of the prosemirror Node.
*
* @remarks
* This is used to represent the top level doc nodes content.
*/
export interface RemirrorJSON {
type: string;
marks?: Array<ObjectMark | string>;
text?: string;
content?: RemirrorJSON[];
attrs?: Record<string, Literal>;
}
export interface StateJSON {
/**
* This allows for plugin state to be stored, although this is not currently
* used in remirror.
*/
[key: string]: unknown;
/**
* The main `ProseMirror` doc.
*/
doc: RemirrorJSON;
/**
* The current selection.
*/
selection: FromToProps;
}
/**
* The matches array. `matches[0]` is the full match.
*/
type GetAttributesFunction = (matches: string[]) => ProsemirrorAttributes | undefined;
/**
* A function which takes a regex match array (strings) or a single string match
* and transforms it into an `Attributes` object.
*/
export type GetAttributes = ProsemirrorAttributes | GetAttributesFunction;
export interface GetAttributesProps {
/**
* A helper function for setting the attributes for a transformation .
*/
getAttributes: GetAttributes;
}
/**
* Supported content for the remirror editor.
*
* @remarks
*
* Content can either be
* - a string (which will be parsed by the stringHandler)
* - JSON object matching Prosemirror expected shape
* - A top level ProsemirrorNode
*
* @template Schema - the underlying editor schema.
*/
export type RemirrorContentType<Schema extends EditorSchema = EditorSchema> =
| string
| RemirrorJSON
| ProsemirrorNode<Schema>
| EditorState<Schema>;
export interface KeyBindingProps<Schema extends EditorSchema = EditorSchema>
extends CommandFunctionProps<Schema> {
/**
* A method to run the next (lower priority) command in the chain of
* keybindings.
*
* @remarks
*
* This can be used to chain together keyboard commands between extensions.
* It's possible that you will need to combine actions when a key is pressed
* while still running the default action. This method allows for the
* greater degree of control.
*
* By default, matching keyboard commands from the different extension are
* chained together (in order of priority) until one returns `true`. Calling
* `next` changes this default behaviour. The default keyboard chaining
* stops and you are given full control of the keyboard command chain.
*/
next: () => boolean;
}
/**
* The command function passed to any of the keybindings.
*/
export type KeyBindingCommandFunction<Schema extends EditorSchema = EditorSchema> = (
params: KeyBindingProps<Schema>,
) => boolean;
/**
* Some commonly used keybinding names to help with auto complete.
*/
export type KeyBindingNames =
| 'Enter'
| 'ArrowDown'
| 'ArrowUp'
| 'ArrowLeft'
| 'ArrowRight'
| 'PageUp'
| 'PageDown'
| 'Home'
| 'End'
| 'Escape'
| 'Delete'
| 'Backspace'
| 'Tab'
| 'Shift-Tab';
/**
* A map of keyboard bindings and their corresponding command functions (a.k.a
* editing actions).
*
* @template Schema - the underlying editor schema.
*
* @remarks
*
* Each keyboard binding returns an object mapping the keys pressed to the
* {@link KeyBindingCommandFunction}. By default the highest priority extension
* will be run first. If it returns true, then nothing else will be run after.
* If it returns `false` then the next (lower priority) extension defining the
* same keybinding will be run.
*
* It is possible to combine the commands being run by using the `next`
* parameter. When called it will run the keybinding command function for the
* proceeding (lower priority) extension. The act of calling the `next` method
* will prevent the default flow from executing.
*/
export type KeyBindings<Schema extends EditorSchema = EditorSchema> = Partial<
Record<KeyBindingNames, KeyBindingCommandFunction<Schema>>
> &
Record<string, KeyBindingCommandFunction<Schema>>;
export type ProsemirrorKeyBindings<Schema extends EditorSchema = EditorSchema> = Record<
string,
ProsemirrorCommandFunction<Schema>
>;
export interface DOMCompatibleAttributes {
[attribute: string]: string | number | undefined;
}
/**
* Defines the return type of the toDOM methods for both nodes and marks
*
* @remarks
*
* This differs from the default Prosemirror type definition which seemed didn't
* work at the time of writing.
*
* Additionally we don't want to support domNodes in the toDOM spec since this
* will create problems once SSR is fully supported
*
* DOMOutputSpec is a description of a DOM structure. Can be either a string,
* which is interpreted as a text node, a DOM node (not supported by remirror),
* which is interpreted as itself, a {dom: Node, contentDOM: ?Node} object (not
* supported by remirror), or an array (DOMOutputSpecArray).
*
* An array (DOMOutputSpecArray) describes a DOM element. The first value in the
* array should be a string—the name of the DOM element, optionally prefixed by
* a namespace URL and a space. If the second element is plain object (DOMCompatibleAttributes),
* it is interpreted as a set of attributes for the element. Any elements
* after that (including the 2nd if it's not an attribute object) are
* interpreted as children of the DOM elements, and must either be valid
* DOMOutputSpec values, or the number zero.
*
* The number zero (pronounced “hole”) is used to indicate the place where a
* node's child nodes should be inserted. If it occurs in an output spec, it
* should be the only child element in its parent node.
*/
export type DOMOutputSpec = string | DOMOutputSpecArray;
type DOMOutputSpecArray =
| [string, ...DOMOutputSpec[]]
| [string, DOMCompatibleAttributes, ...DOMOutputSpec[]]
| [string, 0]
| [string, DOMCompatibleAttributes, 0];
/**
* The schema spec definition for a node extension
*/
export interface NodeExtensionSpec
extends Partial<
Pick<
NodeSpec,
| 'content'
| 'marks'
| 'group'
| 'inline'
| 'atom'
| 'attrs'
| 'selectable'
| 'draggable'
| 'code'
| 'defining'
| 'isolating'
| 'parseDOM'
| 'toDebugString'
| 'allowGapCursor'
>
> {
/**
* Defines the default way a node of this type should be serialized to
* DOM/HTML (as used by [[`DOMSerializer.fromSchema`]].
*
* Should return a [[`DOMOutputSpec`]] that describes a DOM node, with an
* optional number zero (“hole”) in it to indicate where the node's content
* should be inserted.
*/
toDOM?: (node: NodeWithAttributes) => DOMOutputSpec;
}
export type NodeSpecOverride = Pick<
NodeSpec,
| 'content'
| 'marks'
| 'group'
| 'inline'
| 'atom'
| 'selectable'
| 'draggable'
| 'code'
| 'defining'
| 'isolating'
| 'parseDOM'
>;
/**
* The schema spec definition for a mark extension
*/
export interface MarkExtensionSpec
extends Pick<MarkSpec, 'attrs' | 'inclusive' | 'excludes' | 'group' | 'spanning' | 'parseDOM'> {
/**
* Defines the default way marks of this type should be serialized to
* DOM/HTML.
*/
toDOM?: (mark: MarkWithAttributes, inline: boolean) => DOMOutputSpec;
}
export type MarkSpecOverride = Pick<
MarkSpec,
'inclusive' | 'excludes' | 'group' | 'spanning' | 'parseDOM'
>;
/**
* The method signature used to call the Prosemirror `nodeViews`
*
* @param node - the node which uses this nodeView
* @param view - the editor view used by this nodeView
* @param getPos - a utility method to get the absolute cursor position of the
* node.
* @param decorations - a list of the decorations affecting this node view (in
* case the node view needs to update it's presentation)
*/
export type NodeViewMethod<View extends NodeView = NodeView> = (
node: ProsemirrorNode,
view: EditorView,
getPos: (() => number) | boolean,
decorations: Decoration[],
) => View;
/**
* The core shape of any remirror specific object.
*/
export interface RemirrorIdentifierShape {
[__INTERNAL_REMIRROR_IDENTIFIER_KEY__]: RemirrorIdentifier;
}
/**
* A parameter for a non empty selection which defines the anchor (the non
* movable part of the selection) and the head (the movable part of the
* selection).
*/
export interface AnchorHeadProps {
/**
* The non-movable part of the selection.
*/
anchor: number;
/**
* The movable part of the selection.
*/
head: number;
}
/**
* The type of arguments acceptable for a selection.
*
* - Can be a selection
* - A range of `{ from: number; to: number }`
* - A single position with a `number`
* - `'start' | 'end' | 'all'`
* - { anchor: number, head: number }
*/
export type PrimitiveSelection =
| Selection
| FromToProps
| AnchorHeadProps
| number
| ResolvedPos
| 'start'
| 'end'
| 'all';
/**
* A dynamic attributes creator. This is used to create attributes that are
* dynamically set when a node is first added to the dom.
*/
export type DynamicAttributeCreator = (nodeOrMark: ProsemirrorNode | Mark) => string;
/**
* The configuration object for adding extra attributes to the node or mark in
* the editor schema.
*
* Please note that using this will alter the schema, so changes here can cause
* breaking changes for users if not managed carefully.
*
* TODO #462 is being added to support migrations so that breaking changes can
* be handled automatically.
*/
export interface SchemaAttributesObject {
/**
* The default value for the attribute being added, if set to `null` then the
* initial value for any nodes is not required.
*
* If set to `undefined` then a value must be provided whenever a node or mark
* that has this extra attribute is created. ProseMirror will throw if the
* value isn't required. Make sure you know what you're doing before setting
* it to undefined as it could cause unintended errors.
*
* This can also be a function which enables dynamically setting the attribute
* based on the value returned.
*/
default: string | null | DynamicAttributeCreator;
/**
* A function used to extract the attribute from the dom and must be applied
* to the `parseDOM` method.
*
* If a string is set this will automatically call
* `domNode.getAttribute('<name>')`.
*/
parseDOM?: ((domNode: HTMLElement) => unknown) | string;
/**
* Takes the node attributes and applies them to the dom.
*
* This is called in the `toDOM` method.
*
* - If a string is set this will always be the constant value set in the dom.
* - If a tuple with two items is set then the first `string` is the attribute
* to set in the dom and the second string is the value that will be stored.
*
* Return undefined from the function call to skip adding the attribute.
*/
toDOM?:
| string
| [string, string?]
| Record<string, string>
| ((
attrs: ProsemirrorAttributes,
options: NodeMarkOptions,
) => string | [string, string?] | Record<string, string> | null | undefined);
}
export interface NodeMarkOptions {
node?: ProsemirrorNode;
mark?: Mark;
}
export interface ApplySchemaAttributes {
/**
* A function which returns the object of defaults. Since this is for extra
* attributes a default must be provided.
*/
defaults: () => Record<string, { default?: string | null }>;
/**
* Read a value from the dome and convert it into prosemirror attributes.
*/
parse: (domNode: Node | string) => ProsemirrorAttributes;
/**
* Take the node attributes and create the object of string attributes for
* storage on the dom node.
*/
dom: (nodeOrMark: ProsemirrorNode | Mark) => Record<string, string>;
}
/**
* A mapping of the attribute name to it's default, getter and setter. If the
* value is set to a string then it will be resolved as the `default`.
*
* If it is set to a function then it will be a dynamic node or mark.
*/
export type SchemaAttributes = Record<
string,
SchemaAttributesObject | string | DynamicAttributeCreator
>; | the_stack |
// taze: $, JQuery from //third_party/javascript/typings/jquery:jquery_without_externs
// taze: jstree from //third_party/javascript/typings/jstree:jstree
// taze: saveAs from //third_party/javascript/typings/file_saver:file_saver
import {Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {MatDialog, MatDialogConfig} from '@angular/material/dialog';
import {MatSnackBar} from '@angular/material/snack-bar';
// to backend.
import {v4 as uuid} from 'uuid';
import {ReplaySubject} from 'rxjs';
import {filter, switchMap, take, takeUntil} from 'rxjs/operators';
import {DEFAULT_PROJECT_ID_PREFIX, DEFAULT_PROJECT_NAME_PREFIX, MessageTypes, POPUP_DIALOG_DEFAULT_DIMENSION, SNACKBAR_DURATION_MS} from '../constants/constants';
import {ExportImportProjectRequest, ProjectListResponse, ProjectRecord, UuidToBase64ImgResponse} from '../constants/interfaces';
import {JsTreeAction, JsTreeInternalNode, JsTreeNode, NodeParentPair} from '../constants/jstree';
import {BackendManagerService} from '../services/backend_manager_service';
import {ControlMessageService} from '../services/control_message_service';
import {convertToJsonTreeFormat, convertToJsTreeFormat, emptyTreeExample, reconstructJsTreeData, TestCaseManagerService} from '../services/test_case_manager_service';
import {ActionEditDialog} from './action_edit_dialog';
import {ExportGoogle3Dialog} from './export_google3_dialog';
import {ImportDialog} from './import_dialog';
import {ImportProjectDialog} from './import_project_dialog';
import {NewProjectDialog} from './new_project_dialog';
import {ShareWithProjectDialog} from './share_with_project_dialog';
declare var $: any;
declare var saveAs: any;
/**
* Test case explorer component responsible for drawing test case tree.
*/
@Component({
selector: 'test-explorer',
templateUrl: './test_explorer.ng.html',
styleUrls: ['./test_explorer.css']
})
export class TestExplorer implements OnInit, OnDestroy {
@ViewChild('jsTree', {static: true}) jsTreeEl!: ElementRef;
jsTree!: any;
private readonly destroyed = new ReplaySubject<void>(1);
treeUUID: string = '';
searchStr = '';
selectedProject: ProjectRecord = {
projectName: '',
projectId: '',
shareWith: '',
};
defaultProjectId: string = '';
defaultProjectName: string = '';
projectList: ProjectRecord[] = [];
currentUser: string = '';
menuItems = {
'open': {
'action': this.openLoadAction.bind(this),
'label': 'Open',
'icon': 'fa fa-share-alt-square',
},
'add': {
'action': this.addAction.bind(this),
'label': 'Add',
'icon': 'fa fa-plug',
},
'newFolder': {
'action': this.newFolderAction.bind(this),
'label': 'New Folder',
'icon': 'fa fa-folder-open-o',
},
'play': {
'action': this.playAll.bind(this),
'label': 'Play',
'icon': 'fa fa-play',
},
'edit': {
'action': this.editAction.bind(this),
'label': 'Edit',
'icon': 'fa fa-pencil-square-o'
},
'delete': {
'action': this.deleteAction.bind(this),
'label': 'Delete',
'icon': 'fa fa-trash',
},
'import': {
'action': this.importAction.bind(this),
'label': 'Import',
'icon': 'fa fa-envelope-open',
},
'rename': {
'action': this.renameAction.bind(this),
'label': 'Rename',
'icon': 'fa fa-tag'
},
'moveTo': {
'action': this.moveAction.bind(this),
'label': 'MoveTo',
'icon': 'fa fa-paper-plane-o'
},
'download': {
'action': this.downloadAction.bind(this),
'label': 'Download',
'icon': 'fa fa-download'
},
'exportToGoogle3': {
'action': this.exportAction.bind(this),
'label': 'Export to Google3',
'icon': 'fa fa-cloud-upload'
}
};
constructor(
public dialog: MatDialog,
private readonly testCaseManagerService: TestCaseManagerService,
private readonly backendManagerService: BackendManagerService,
private readonly controlMessageService: ControlMessageService,
private readonly snackBar: MatSnackBar, private readonly ngZone: NgZone) {
}
ngOnInit() {
this.backendManagerService.getCurrentUser()
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
this.currentUser = data.name;
this.defaultProjectId = DEFAULT_PROJECT_ID_PREFIX + this.currentUser;
this.defaultProjectName =
DEFAULT_PROJECT_NAME_PREFIX + this.currentUser;
this.selectedProject.projectId = this.defaultProjectId;
this.selectedProject.projectName = this.defaultProjectName;
this.initiateProject();
});
this.controlMessageService.getControlMessageSubject()
.pipe(
filter(
msg => (msg.messageType === MessageTypes.ADD_NODE_TO_TREE) ||
(msg.messageType === MessageTypes.REFRESH_TEST_CASE_TREE)),
takeUntil(this.destroyed))
.subscribe(data => {
if (data.messageType === MessageTypes.ADD_NODE_TO_TREE) {
// `unknown`.
// tslint:disable:no-any no-unnecessary-type-assertion
const newNode: NodeParentPair = JSON.parse(data.extra) as any;
// tslint:enable:no-any no-unnecessary-type-assertion
this.jsTree.jstree('create_node', newNode.parentId, newNode.node);
} else {
this.refreshTree(false);
}
});
}
setupDataTree() {
const jsTreeObj: any = $(this.jsTreeEl.nativeElement);
this.jsTree = jsTreeObj.jstree({
'core': {
'themes': {
'dots': false,
},
'data': {},
'check_callback': this.isValidCB,
},
'search': {
'case_insensitive': true,
'show_only_matches': true,
},
'plugins': ['wholerow', 'dnd', 'contextmenu', 'sort', 'search'],
'contextmenu': {items: this.menuItems},
});
this.refreshTree(false);
this.addEventHooks();
}
/**
* Before call {@code refreshTree}, {@code this.selectedProject.projectId}
* need to be the correct one.
*/
refreshTree(isNewWorkspace: boolean) {
this.testCaseManagerService
.getTestCasesListByProjectId(this.selectedProject.projectId)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
if (data.uuid) {
this.treeUUID = data.uuid;
}
if (data.treeDetails) {
// `unknown`.
// tslint:disable:no-any no-unnecessary-type-assertion
this.updateDataTree(
convertToJsTreeFormat(JSON.parse(data.treeDetails) as any),
isNewWorkspace);
// tslint:enable:no-any no-unnecessary-type-assertion
} else {
this.saveEmptyTreeToBackend();
}
});
}
searchTree() {
this.jsTree.jstree('search', this.searchStr);
}
saveTreeToBackend() {
// _model holds the jstree internal state. It is the only place(that I can
// find) that holds the data object with original json passed and is up to
// date.
const modelData = this.getJsTreeInstance()['_model'].data;
const data = reconstructJsTreeData(modelData, '#');
this.getJsTreeInstance()['settings'].core.data = data;
const jsonData = convertToJsonTreeFormat(data);
console.log('saveTreeToBackend');
this.testCaseManagerService
.updateTestCaseTree(
jsonData, this.treeUUID, this.selectedProject.projectId)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe();
}
saveEmptyTreeToBackend() {
// Need directly call the save to backend, otherwise update won't pick up
// the latest jsTree data from ['_model'].data, pass in the empty treeUUID,
// backend will generate a new UUID for the tree.
this.testCaseManagerService
.updateTestCaseTree(
emptyTreeExample(), /* treeUUID */ '',
this.selectedProject.projectId)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(() => {
this.updateDataTree(convertToJsTreeFormat(emptyTreeExample()), false);
this.refreshTree(false);
});
}
addEventHooks() {
this.jsTree.on(
'move_node.jstree create_node.jstree delete_node.jstree refresh.jstree, rename_node.jstree',
this.saveTreeToBackend.bind(this));
this.jsTree.on('select_node.jstree', (e: unknown, action: JsTreeAction) => {
const node = action.node;
if (!node.original.isFolder && action.event &&
action.event.type !== 'contextmenu') {
if (!confirm('Do you wish to load this test case?')) {
return;
}
const uuid = this.getUUIDFromNode(node);
this.backendManagerService.loadWorkflow(uuid)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
});
}
getJsTreeInstance(): any {
// jstree(true) returns an existing instance instead of creating a new
// instance.
return this.jsTree.jstree(true);
}
// tslint:disable:no-any no typing info available for jstree.
isValidCB(
op: string, nodeDragged: unknown, parentNode: unknown,
currentPosition: unknown, more: CheckMore): boolean {
// tslint:enable:no-any
if (op === 'move_node' && more && more.dnd && more.ref &&
more.ref.original && !more.ref.original.isFolder) {
return false;
}
return true;
}
updateDataTree(jsTreeNode: JsTreeNode, isNewWorkspace: boolean) {
// 'settings' is an internal field that contains some desired jstree
// properties.
this.getJsTreeInstance()['settings'].core.data = jsTreeNode;
this.getJsTreeInstance().refresh(
/* skip_loading */ false, /* forget_state */ true);
if (isNewWorkspace) {
this.backendManagerService.createNewWorkSpace()
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(() => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
}
getUUIDFromNode(node: JsTreeInternalNode) {
let uuid = node.id;
// if it has additional data that means that it is an action,
// rather than just a folder, so it's additional data
// is the uuid needed to retrieve those actions
// from the database
if (node.original.additionalData &&
node.original.additionalData.length > 0) {
uuid = node.original.additionalData[0];
}
return uuid;
}
getCurrentNode(nodeRef: unknown): JsTreeInternalNode {
const nodes = this.getJsTreeInstance().get_selected(nodeRef);
if (nodes.length > 0) {
return nodes[0];
}
throw new Error('cannot get selected node reference.');
}
openLoadAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
if (currentNode.original.isFolder) {
this.snackBar.open(
'Open operation cannot be performed on a folder!', 'OK',
{duration: SNACKBAR_DURATION_MS});
return;
}
const uuid = this.getUUIDFromNode(currentNode);
this.backendManagerService.loadWorkflow(uuid)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
addAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
if (currentNode.original.isFolder) {
this.snackBar.open(
'Add operation cannot be performed on a folder!', 'OK',
{duration: SNACKBAR_DURATION_MS});
return;
}
const uuid = this.getUUIDFromNode(currentNode);
this.backendManagerService.addActionByUUID(uuid)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
editAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
this.ngZone.run(() => {
const dialogRef = this.dialog.open(
ActionEditDialog,
{width: '800px', data: {uuid: this.getUUIDFromNode(currentNode)}});
dialogRef.afterClosed().subscribe(data => {
if (data) {
if (data.deleted) {
this.jsTree.jstree('delete_node', currentNode);
} else if (data.name !== currentNode.text) {
currentNode.original.text = data.name;
this.jsTree.jstree('rename_node', currentNode, data.name);
}
}
});
});
}
newFolderAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
if (!currentNode.original.isFolder) {
this.snackBar.open(
'New Folder operation can only be performed on a folder!', 'OK',
{duration: SNACKBAR_DURATION_MS});
return;
}
this.createFolder(currentNode.id, 'New Folder');
}
createFolder(parentId: string, name: string) {
const newNode = new JsTreeNode(name, uuid() as string);
this.jsTree.jstree('create_node', parentId, newNode);
}
playAll(nodeRef: unknown) {
}
deleteAction(nodeRef: unknown) {
if (confirm('Are you sure you wish to delete this?')) {
this.jsTree.jstree('delete_node', this.getCurrentNode(nodeRef));
}
}
importAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
if (!currentNode.original.isFolder) {
this.snackBar.open(
'New Folder operation can only be performed on a folder!', 'OK',
{duration: SNACKBAR_DURATION_MS});
return;
}
this.ngZone.run(() => {
const dialogRef = this.dialog.open(
ImportDialog,
{width: POPUP_DIALOG_DEFAULT_DIMENSION.width, data: {}});
dialogRef.afterClosed().subscribe(data => {
if (data) {
for (const node of data) {
this.jsTree.jstree('create_node', currentNode.id, node);
}
}
});
});
}
renameAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
const uuid = this.getUUIDFromNode(currentNode);
this.jsTree.jstree(
'edit', currentNode, null,
(node: JsTreeInternalNode, status: boolean) => {
if (status && node) {
if (!node.original.isFolder) {
this.backendManagerService.getActionDetails(uuid)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
data.name = node.text;
this.backendManagerService.updateActionMetadata(data)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe();
});
}
node.original.text = node.text;
this.saveTreeToBackend();
}
});
}
moveAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
if (currentNode.original.isFolder) {
this.snackBar.open(
'CopyTo operation cannot be performed on a folder!', 'OK',
{duration: SNACKBAR_DURATION_MS});
return;
}
const uuid = this.getUUIDFromNode(currentNode);
this.ngZone.run(() => {
const dialogRef = this.dialog.open(ActionEditDialog, {
width: '800px',
data: {
uuid,
isSaveWorkflow: true,
isMoveAction: true,
},
});
dialogRef.afterClosed().subscribe((data) => {
if (!data) {
return;
}
this.jsTree.jstree(
'move_node', currentNode, data.parentId, 'last',
(node: JsTreeInternalNode, parentNode: JsTreeInternalNode,
position: unknown) => {
if (node.text === data.name) {
return;
}
this.backendManagerService.updateActionMetadata(data.metadata)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe();
node.original.text = data.name;
this.jsTree.jstree('rename_node', node, data.name);
});
});
});
}
downloadTest(
uuid: string, filename: string, filterTopLevelWorkflow: boolean) {
this.backendManagerService.exportTestCase(uuid).subscribe(data => {
if (filterTopLevelWorkflow && !data.isTopLevelWorkflow) return;
const formatted = JSON.stringify(data, null, 2);
const exportData =
new Blob([formatted + '\n'], {type: 'application/octet-stream'});
saveAs(exportData, filename);
});
}
downloadRefImgs(uuidStr: string) {
this.backendManagerService.exportRefImagesForWorkflow(uuidStr)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
const uuidStrToBase64: UuidToBase64ImgResponse = data.uuidTobase64Img;
this.exportRefImgs(uuidStrToBase64);
});
}
exportRefImgs(uuidStrToBase64: UuidToBase64ImgResponse) {
for (const uuid of Object.keys(uuidStrToBase64)) {
const imgBase64Str = uuidStrToBase64[uuid];
const blobData = this.convertBase64ToBlobData(imgBase64Str);
const blob = new Blob(blobData, {type: 'image/png'});
saveAs(blob, uuid);
}
}
convertBase64ToBlobData(imgBase64Str: string) {
const sliceSize = 512;
const byteCharacters = atob(imgBase64Str);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const byteCharactersSlice =
byteCharacters.slice(offset, offset + sliceSize);
const byteNumbersSlice = new Array(byteCharactersSlice.length);
for (let i = 0; i < byteCharactersSlice.length; i++) {
byteNumbersSlice[i] = byteCharactersSlice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbersSlice);
byteArrays.push(byteArray);
}
return byteArrays;
}
downloadAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
console.log('Start download action');
if (currentNode.original.isFolder) {
this.downloadActionInFolder(currentNode.id);
this.snackBar.open(
'Batch export only download top level workflow!', 'OK',
{duration: SNACKBAR_DURATION_MS});
return;
}
// Only filter by toplevel when it is a batch download
this.downloadActionByUUID(currentNode.id, currentNode.text, false);
}
downloadActionInFolder(uuid: string) {
const currentNode = this.getJsTreeInstance().get_node(uuid);
for (let i = 0; i < currentNode.children.length; i++) {
const childNode =
this.getJsTreeInstance().get_node(currentNode.children[i]);
if (childNode.original.isFolder) {
this.downloadActionInFolder(currentNode.children[i]);
} else {
this.downloadActionByUUID(
currentNode.children[i], childNode.text, true);
}
}
}
downloadActionByUUID(
uuid: string, fileName: string, filterTopLevelWorkflow: boolean) {
const testcaseId =
this.getUUIDFromNode(this.getJsTreeInstance().get_node(uuid));
this.downloadTest(testcaseId, fileName, filterTopLevelWorkflow);
this.downloadRefImgs(uuid);
}
exportAction(nodeRef: unknown) {
const currentNode = this.getCurrentNode(nodeRef);
const uuid = this.getUUIDFromNode(currentNode);
this.backendManagerService.exportTestCase(uuid).subscribe(returnedData => {
let google3Path = '';
google3Path = returnedData.additionalData.filePath;
this.ngZone.run(() => {
this.dialog.open(
ExportGoogle3Dialog,
{width: '800px', data: {actionId: uuid, google3Path}});
});
});
}
exportCurrentProject() {
const exportProjectReq: ExportImportProjectRequest = {
projectId: this.selectedProject.projectId,
projectName: this.selectedProject.projectName,
zipFileName: '',
};
this.backendManagerService.exportCurrentProject(exportProjectReq);
}
exportTopLevelTests() {
const exportProjectReq: ExportImportProjectRequest = {
projectId: this.selectedProject.projectId,
projectName: this.selectedProject.projectName,
zipFileName: '',
};
this.backendManagerService.exportTopLevelTests(exportProjectReq);
}
getAllActionId(node: JsTreeNode, actionIdList: string[]) {
if (node.additionalData && node.additionalData.length > 0) {
const uuid = node.additionalData[0];
actionIdList.push(uuid);
}
if (node.children && node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
this.getAllActionId(node.children[i], actionIdList);
}
}
}
openNewProjectDialog() {
const dialogConfig = new MatDialogConfig();
dialogConfig.width = POPUP_DIALOG_DEFAULT_DIMENSION.width;
const dialogRef = this.dialog.open(NewProjectDialog, dialogConfig);
dialogRef.afterClosed().subscribe(data => {
if (data) {
this.selectedProject = data;
this.controlMessageService.sendRefreshTestCaseTreeMsg();
}
});
}
openShareProjectDialog() {
const dialogConfig = new MatDialogConfig();
dialogConfig.width = POPUP_DIALOG_DEFAULT_DIMENSION.width;
dialogConfig.data = this.selectedProject;
const dialogRef = this.dialog.open(ShareWithProjectDialog, dialogConfig);
dialogRef.afterClosed().subscribe();
}
openImportProjectDialog() {
const dialogConfig = new MatDialogConfig();
dialogConfig.width = POPUP_DIALOG_DEFAULT_DIMENSION.width;
this.dialog.open(ImportProjectDialog, dialogConfig);
}
getProjectList() {
this.backendManagerService.getProjectList()
.pipe(take(1), takeUntil(this.destroyed))
.subscribe((data: ProjectListResponse) => {
this.projectList = data.projectList;
});
}
selectProject(project: ProjectRecord) {
this.backendManagerService.setCurrentProject(project.projectId)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe((data: ProjectListResponse) => {
if (data.success) {
this.selectedProject = data.projectList[0];
this.refreshTree(true);
}
});
}
deleteProject(project: ProjectRecord, event: MouseEvent) {
event.stopPropagation();
if (this.selectedProject.projectId === project.projectId) {
alert('You cannot delete the current project');
return;
}
if (confirm(
'Are you sure you want to delete project ' + project.projectName +
'?')) {
this.backendManagerService.deleteProject(project.projectId)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe((data: ProjectListResponse) => {
if (data.success) {
this.getProjectList();
}
});
this.testCaseManagerService.deleteTestCaseTree(project.projectId)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe();
}
}
/**
* Initialize project. Set to the default one with name {@code
* this.defaultProjectName}. If the default one doesn't exist, it will be
* created with projectId is a UUID.
*/
initiateProject() {
console.log('init project');
this.backendManagerService.getProjectList()
.pipe(
switchMap((data: ProjectListResponse) => {
let defaultProjectId = this.defaultProjectId;
if (data.success && data.projectList.length > 0) {
defaultProjectId = data.projectList[0].projectId;
}
return this.backendManagerService.setCurrentProject(
defaultProjectId);
}),
take(1),
takeUntil(this.destroyed),
)
.subscribe((data: ProjectListResponse) => {
this.projectList = data.projectList;
this.selectedProject = data.projectList[0];
this.setupDataTree();
});
}
ngOnDestroy() {
// Unsubscribe all pending subscriptions.
this.destroyed.next();
if (this.jsTree) {
this.jsTree.off();
}
}
}
interface CheckMore {
dnd?: boolean;
ref?: {original?: {isFolder?: boolean}};
} | the_stack |
import { $O, auto, Auto, o, ObserverTarget } from 'wana/core'
let runs: number
let prevRuns: number
function expectRuns(n: number) {
expect(runs).toBe(prevRuns + n)
prevRuns = runs
}
let runner: Auto
let ctx = o({
effect: () => {},
})
beforeEach(() => {
if (runner) {
runner.dispose()
ctx.effect = () => {}
}
// Synchronously run the effect when it changes.
runner = auto(
() => {
ctx.effect()
runs++
},
{
sync: true,
onError(error) {
// Reset the observer on error.
ctx.effect = () => {}
this.rerun()
throw error
},
}
)
})
describe('auto()', () => {
it('ignores any mutations made inside its callback', () => {
const state = o({ count: 0 })
withEffect(() => {
if (state.count < 5) {
state.count++
}
})
expect(state.count).toBe(1)
expect(getObservers(state, 'count').size).toBe(1)
state.count += 1
expect(state.count).toBe(3)
expect(getObservers(state, 'count').size).toBe(1)
})
it('unsubscribes from observables when an error is thrown', () => {
const a = o({ count: 0 })
const b = o({ count: 1 })
withEffect(() => {
if (!a.count) return
if (a.count == b.count) {
throw Error()
}
})
expect(getObservers(a, 'count').size).toBe(1)
expect(getObservers(b, 'count').size).toBe(0)
try {
a.count++
} catch {
expect(getObservers(a, 'count').size).toBe(0)
expect(getObservers(b, 'count').size).toBe(0)
}
expect.assertions(4)
})
describe('objects', () => {
let obj: any
beforeEach(() => {
obj = o({})
})
test('get', () => {
withEffect(() => obj.a)
obj.a = 1 // add our key
expectRuns(1)
obj.a = 1 // set our key (no change)
expectRuns(0)
obj.a = 2 // set our key
expectRuns(1)
delete obj.a // delete our key
expectRuns(1)
obj.b = 1 // add other key
expectRuns(0)
obj.b = 1 // set other key (no change)
expectRuns(0)
obj.b = 2 // set other key
expectRuns(0)
delete obj.b // delete other key
expectRuns(0)
})
test('in', () => {
withEffect(() => 'a' in obj)
obj.a = 1 // add our key
expectRuns(1)
obj.a = 1 // set our key (no change)
expectRuns(0)
obj.a = 2 // set our key
expectRuns(1)
delete obj.a // delete our key
expectRuns(1)
obj.b = 1 // add other key
expectRuns(0)
obj.b = 1 // set other key (no change)
expectRuns(0)
obj.b = 2 // set other key
expectRuns(0)
delete obj.b // delete other key
expectRuns(0)
})
})
describe('arrays', () => {
let arr: any[]
beforeEach(() => {
arr = o([])
})
test('.length', () => {
withEffect(() => arr.length)
arr.pop() // empty pop
expectRuns(0)
arr.push(1, 2) // push many
expectRuns(1)
arr.pop() // pop one
expectRuns(1)
arr.unshift(1, 2) // unshift many
expectRuns(1)
arr.splice(0, 0) // empty splice
expectRuns(0)
arr.splice(1, 1) // remove one
expectRuns(1)
arr.splice(2, 0, 3, 4) // insert two
expectRuns(1)
arr.splice(1, 1, 3) // remove one, insert one
expectRuns(0)
arr.shift() // shift one
expectRuns(1)
ensureReversed() // not reversed yet
expectRuns(0)
ensureSorted() // not sorted yet
expectRuns(0)
arr.length = 0 // truncate to length of 0
expectRuns(1)
arr.length = 2 // expand to length of 2
expectRuns(1)
arr[2] = 1 // set new index
expectRuns(1)
arr[1] = 1 // fill hole
expectRuns(0)
arr[1] = 2 // set old index
expectRuns(0)
arr[1] = 2 // set old index (no change)
expectRuns(0)
})
test('.concat()', () => {
const left = arr
const right: any[] = o([])
withEffect(() => left.concat(right))
left.push(1)
expectRuns(1)
right.push(1)
expectRuns(1)
})
test('.forEach()', () => {
withEffect(() => arr.forEach(() => {}))
wholeMutations()
})
test('.keys()', () => {
withEffect(() => arr.keys())
wholeMutations()
})
function ensureReversed() {
const old = [...arr]
arr.reverse()
expect(arr).not.toEqual(old)
}
function ensureSorted() {
const old = [...arr]
arr.sort()
expect(arr).not.toEqual(old)
}
function wholeMutations() {
arr.pop() // empty pop
expectRuns(0)
arr.push(1, 2) // push many
expectRuns(1)
arr.pop() // pop one
expectRuns(1)
arr.unshift(1, 2) // unshift many
expectRuns(1)
arr.splice(0, 0) // empty splice
expectRuns(0)
arr.splice(1, 1) // remove one
expectRuns(1)
arr.splice(2, 0, 3, 4) // insert two
expectRuns(1)
arr.splice(1, 1, 3) // remove one, insert one
expectRuns(1)
arr.shift() // shift one
expectRuns(1)
ensureReversed() // not reversed yet
expectRuns(1)
ensureSorted() // not sorted yet
expectRuns(1)
arr.sort() // already sorted
expectRuns(1)
arr.length = 0 // truncate to length of 0
expectRuns(1)
arr.length = 2 // expand to length of 2
expectRuns(0)
arr[2] = 1 // set new index
expectRuns(1)
arr[1] = 1 // fill hole
expectRuns(1)
arr[1] = 2 // set old index
expectRuns(1)
arr[1] = 2 // set old index (no change)
expectRuns(0)
}
})
describe('sets', () => {
let set: Set<any>
beforeEach(() => {
set = o(new Set())
set.add(1).add(2)
})
test('.forEach()', () => {
withEffect(() => set.forEach(() => {}))
set.add(3) // add unknown value
expectRuns(1)
set.add(3) // add known value
expectRuns(0)
set.delete(3) // delete known value
expectRuns(1)
set.delete(3) // delete unknown value
expectRuns(0)
expect(set.size).not.toBe(0)
set.clear() // clear values
expectRuns(1)
expect(set.size).toBe(0)
set.clear() // clear when empty
expectRuns(0)
})
test('.size', () => {
withEffect(() => set.size)
set.add(3) // add unknown value
expectRuns(1)
set.add(3) // add known value
expectRuns(0)
set.delete(3) // delete known value
expectRuns(1)
set.delete(3) // delete unknown value
expectRuns(0)
expect(set.size).not.toBe(0)
set.clear() // clear values
expectRuns(1)
expect(set.size).toBe(0)
set.clear() // clear when empty
expectRuns(0)
})
})
describe('maps', () => {
let map: Map<any, any>
beforeEach(() => {
map = o(new Map())
map.set(1, 2)
})
const key = {}
test('.has()', () => {
withEffect(() => map.has(key))
map.set(key, 1) // add our key
expectRuns(1)
map.set(key, 1) // set our key (no change)
expectRuns(0)
map.set(key, 2) // set our key
expectRuns(1)
map.delete(key) // delete our key
expectRuns(1)
map.set(0, 1) // add other key
expectRuns(0)
map.set(0, 1) // set other key (no change)
expectRuns(0)
map.set(0, 2) // set other key
expectRuns(0)
map.delete(0) // delete other key
expectRuns(0)
expect(map.size).not.toBe(0)
map.clear() // clear other values
expectRuns(0)
expect(map.size).toBe(0)
map.clear() // clear when empty
expectRuns(0)
map.set(key, 1) // re-add our key for next test
expectRuns(1)
map.clear() // clear our value
expectRuns(1)
})
test('.get()', () => {
withEffect(() => map.get(key))
map.set(key, 1) // add our key
expectRuns(1)
map.set(key, 1) // set our key (no change)
expectRuns(0)
map.set(key, 2) // set our key
expectRuns(1)
map.delete(key) // delete our key
expectRuns(1)
map.set(0, 1) // add other key
expectRuns(0)
map.set(0, 1) // set other key (no change)
expectRuns(0)
map.set(0, 2) // set other key
expectRuns(0)
map.delete(0) // delete other key
expectRuns(0)
expect(map.size).not.toBe(0)
map.clear() // clear other values
expectRuns(0)
expect(map.size).toBe(0)
map.clear() // clear when empty
expectRuns(0)
map.set(key, 1) // re-add our key for next test
expectRuns(1)
map.clear() // clear our value
expectRuns(1)
})
test('[Symbol.iterator]()', () => {
withEffect(() => {
for (const _entry of map) {
break
}
})
map.set(key, 1) // add a key
expectRuns(1)
map.set(key, 1) // set a key (no change)
expectRuns(0)
map.set(key, 2) // set a key
expectRuns(1)
map.delete(key) // delete a key
expectRuns(1)
expect(map.size).not.toBe(0)
map.clear() // clear all values
expectRuns(1)
expect(map.size).toBe(0)
map.clear() // clear when empty
expectRuns(0)
})
test('.forEach()', () => {
withEffect(() => map.forEach(() => {}))
map.set(key, 1) // add a key
expectRuns(1)
map.set(key, 1) // set a key (no change)
expectRuns(0)
map.set(key, 2) // set a key
expectRuns(1)
map.delete(key) // delete a key
expectRuns(1)
expect(map.size).not.toBe(0)
map.clear() // clear all values
expectRuns(1)
expect(map.size).toBe(0)
map.clear() // clear when empty
expectRuns(0)
})
test('.size', () => {
withEffect(() => map.size)
map.set(key, 1) // add a key
expectRuns(1)
map.set(key, 1) // set a key (no change)
expectRuns(0)
map.set(key, 2) // set a key
expectRuns(0)
map.delete(key) // delete a key
expectRuns(1)
expect(map.size).not.toBe(0)
map.clear() // clear all values
expectRuns(1)
expect(map.size).toBe(0)
map.clear() // clear when empty
expectRuns(0)
})
})
})
// Replace the effect and reset the run count.
function withEffect(effect: () => void) {
ctx.effect = effect
prevRuns = runs = 0
}
export function getObservers(state: ObserverTarget, key: string | typeof $O) {
return state[$O]!.get(key)
} | the_stack |
import {html} from '@polymer/polymer';
import './styles';
import '../../../components/tf_wbr_string/tf-wbr-string';
export const template = html`
<style include="vz-projector-styles"></style>
<style>
.container {
padding: 5px 20px 20px 20px;
}
input[type='file'] {
display: none;
}
.file-name {
margin-right: 10px;
}
.dirs {
color: rgba(0, 0, 0, 0.7);
font-size: 12px;
}
.dirs table tr {
vertical-align: top;
}
.dirs table tr td {
padding-bottom: 10px;
}
paper-item {
--paper-item-disabled: {
border-bottom: 1px solid black;
justify-content: center;
font-size: 12px;
line-height: normal;
min-height: 0px;
}
}
.item-details {
margin-left: 5px;
color: gray;
font-size: 12px;
}
paper-input {
font-size: 15px;
--paper-input-container: {
padding: 5px 0;
}
--paper-input-container-label-floating: {
white-space: normal;
line-height: normal;
}
}
paper-dropdown-menu {
width: 100%;
--paper-input-container: {
padding: 5px 0;
}
--paper-input-container-input: {
font-size: 15px;
}
--paper-input-container-label-floating: {
white-space: normal;
line-height: normal;
}
}
paper-dropdown-menu paper-item {
justify-content: space-between;
}
.title {
align-items: center;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
color: black;
display: flex;
font-weight: 500;
height: 59px;
padding-left: 20px;
}
#normalize-data-checkbox {
margin: 10px 0;
}
#projector-config-template {
--paper-input-container-input: {
line-height: 13px;
font-family: monospace;
font-size: 12px;
}
}
#generate-share-url {
padding: 16px;
margin-left: 24px;
}
#projector-share-button-container {
margin: 10px 0;
}
.metadata-editor,
.supervise-settings,
.colorlabel-container {
display: flex;
}
#labelby {
width: 100px;
margin-right: 10px;
}
#colorby {
width: calc(100% - 110px);
}
[hidden] {
display: none;
}
.supervise-settings paper-dropdown-menu {
width: 100px;
margin-right: 10px;
}
.supervise-settings paper-input {
width: calc(100% - 110px);
}
.metadata-editor paper-dropdown-menu {
width: 100px;
margin-right: 10px;
}
.metadata-editor paper-input {
width: calc(100% - 110px);
}
.config-checkbox {
display: inline-block;
font-size: 11px;
margin-left: 10px;
}
.projector-config-options {
margin-top: 12px;
}
.projector-config-dialog-container {
padding: 24px;
}
.code {
background-color: #f7f7f7;
display: table;
font-family: monospace;
margin-top: 7px;
padding: 15px;
}
.delimiter {
color: #b71c1c;
}
.button-container {
flex: 1 100%;
margin-right: 5px;
}
.button-container paper-button {
min-width: 50px;
width: 100%;
}
#label-button {
margin-right: 0px;
}
.upload-step {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
}
.upload-step paper-button {
margin-left: 30px;
}
.step-label {
color: rgb(38, 180, 226);
}
.scrollable-container {
margin-top: 0;
min-width: 400px;
}
#projectorConfigDialog p {
margin: 8px 0 8px;
}
.data-step {
margin-top: 40px;
}
.data-step-contents {
display: table;
width: 100%;
}
.data-step-contents-contents {
display: table-cell;
margin-top: 6px;
}
.data-step-contents-upload {
display: table-cell;
text-align: right;
vertical-align: bottom;
}
#demo-data-buttons-container {
display: none;
margin-top: 10px;
}
</style>
<div class="title">DATA</div>
<div class="container">
<!-- List of runs -->
<template is="dom-if" if="[[_hasChoices(runNames)]]">
<paper-dropdown-menu
no-animations
label="[[_getNumRunsLabel(runNames)]] found"
>
<paper-listbox
attr-for-selected="value"
class="dropdown-content"
selected="{{selectedRun}}"
slot="dropdown-content"
>
<template is="dom-repeat" items="[[runNames]]">
<paper-item value="[[item]]" label="[[item]]">
[[item]]
</paper-item>
</template>
</paper-listbox>
</paper-dropdown-menu>
</template>
<template is="dom-if" if="[[tensorNames]]">
<!-- List of tensors in checkpoint -->
<paper-dropdown-menu
no-animations
label="[[_getNumTensorsLabel(tensorNames)]] found"
>
<paper-listbox
attr-for-selected="value"
class="dropdown-content"
selected="{{selectedTensor}}"
slot="dropdown-content"
>
<template is="dom-repeat" items="[[tensorNames]]">
<paper-item value="[[item.name]]" label="[[item.name]]">
[[item.name]]
<span class="item-details">
[[item.shape.0]]x[[item.shape.1]]
</span>
</paper-item>
</template>
</paper-listbox>
</paper-dropdown-menu>
</template>
<div hidden$="[[!_hasChoices(colorOptions)]]">
<div class="colorlabel-container">
<!-- Label by -->
<paper-dropdown-menu id="labelby" no-animations label="Label by">
<paper-listbox
attr-for-selected="value"
class="dropdown-content"
selected="{{selectedLabelOption}}"
slot="dropdown-content"
>
<template is="dom-repeat" items="[[labelOptions]]">
<paper-item value="[[item]]" label="[[item]]">
[[item]]
</paper-item>
</template>
</paper-listbox>
</paper-dropdown-menu>
<!-- Color by -->
<paper-dropdown-menu id="colorby" no-animations label="Color by">
<paper-listbox
attr-for-selected="value"
class="dropdown-content"
selected="{{selectedColorOptionName}}"
slot="dropdown-content"
>
<template is="dom-repeat" items="[[colorOptions]]">
<paper-item
class$="[[getSeparatorClass(item.isSeparator)]]"
value="[[item.name]]"
label="[[item.name]]"
disabled="[[item.isSeparator]]"
>
[[item.name]]
<span class="item-details">[[item.desc]]</span>
</paper-item>
</template>
</paper-listbox>
</paper-dropdown-menu>
</div>
<div hidden$="[[!showForceCategoricalColorsCheckbox]]">
<paper-checkbox id="force-categorical-checkbox"
>Use categorical coloring</paper-checkbox
>
<paper-icon-button icon="help" class="help-icon"></paper-icon-button>
<paper-tooltip
position="bottom"
animation-delay="0"
fit-to-visible-bounds
>
For metadata fields that have many unique values we use a gradient
color map by default. This checkbox allows you to force categorical
coloring by a given metadata field.
</paper-tooltip>
</div>
<template dom-if="[[colorLegendRenderInfo]]">
<vz-projector-legend
render-info="[[colorLegendRenderInfo]]"
></vz-projector-legend>
</template>
</div>
<template is="dom-if" if="[[_hasChoice(labelOptions)]]">
<!-- Supervise by -->
<div hidden$="[[!showSuperviseSettings]]" class="supervise-settings">
<paper-dropdown-menu no-animations label="Supervise with">
<paper-listbox
attr-for-selected="value"
class="dropdown-content"
on-selected-item-changed="superviseColumnChanged"
selected="{{superviseColumn}}"
slot="dropdown-content"
>
<template is="dom-repeat" items="[[metadataFields]]">
<paper-item value="[[item]]" label="[[item]]">
[[item]]
</paper-item>
</template>
</paper-listbox>
</paper-dropdown-menu>
<paper-input
value="{{superviseInput}}"
label="{{superviseInputLabel}}"
on-change="superviseInputChange"
on-input="superviseInputTyping"
>
</paper-input>
</div>
<!-- Edit by -->
<div class="metadata-editor">
<paper-dropdown-menu no-animations label="Edit by">
<paper-listbox
attr-for-selected="value"
class="dropdown-content"
slot="dropdown-content"
on-selected-item-changed="metadataEditorColumnChange"
selected="{{metadataEditorColumn}}"
>
<template is="dom-repeat" items="[[metadataFields]]">
<paper-item value="[[item]]" label="[[item]]">
[[item]]
</paper-item>
</template>
</paper-listbox>
</paper-dropdown-menu>
<paper-input
value="{{metadataEditorInput}}"
label="{{metadataEditorInputLabel}}"
on-input="metadataEditorInputChange"
on-keydown="metadataEditorInputKeydown"
>
</paper-input>
</div>
</template>
<div id="demo-data-buttons-container">
<span class="button-container">
<paper-tooltip
position="bottom"
animation-delay="0"
fit-to-visible-bounds
>
Load data from your computer
</paper-tooltip>
<paper-button id="upload" class="ink-button" on-tap="_openDataDialog"
>Load</paper-button
>
</span>
<span id="publish-container" class="button-container">
<paper-tooltip
position="bottom"
animation-delay="0"
fit-to-visible-bounds
>
Publish your embedding visualization and data
</paper-tooltip>
<paper-button
id="host-embedding"
class="ink-button"
on-tap="_openConfigDialog"
>Publish</paper-button
>
</span>
<span class="button-container">
<paper-tooltip
position="bottom"
animation-delay="0"
fit-to-visible-bounds
>
Download the metadata with applied modifications
</paper-tooltip>
<paper-button class="ink-button" on-click="downloadMetadataClicked"
>Download</paper-button
>
<a href="#" id="downloadMetadataLink" hidden></a>
</span>
<span id="label-button" class="button-container">
<paper-tooltip
position="bottom"
animation-delay="0"
fit-to-visible-bounds
>
Label selected metadata
</paper-tooltip>
<paper-button
class="ink-button"
on-click="metadataEditorButtonClicked"
disabled="[[metadataEditorButtonDisabled]]"
>Label</paper-button
>
</span>
</div>
<div>
<paper-dialog id="dataDialog" with-backdrop>
<h2>Load data from your computer</h2>
<paper-dialog-scrollable class="scrollable-container">
<div class="data-step" id="upload-tensors-step-container">
<div class="upload-step">
<div>
<b
><span class="step-label">Step 1:</span> Load a TSV file of
vectors.</b
>
</div>
</div>
<div class="data-step-contents">
<div class="data-step-contents-contents">
Example of 3 vectors with dimension 4:
<div class="code">
0.1<span class="delimiter"> </span>0.2<span class="delimiter">
</span
>0.5<span class="delimiter"> </span>0.9<br />
0.2<span class="delimiter"> </span>0.1<span class="delimiter">
</span
>5.0<span class="delimiter"> </span>0.2<br />
0.4<span class="delimiter"> </span>0.1<span class="delimiter">
</span
>7.0<span class="delimiter"> </span>0.8
</div>
</div>
<div class="data-step-contents-upload">
<paper-button
id="upload-tensors"
title="Choose a TSV tensor file"
>Choose file</paper-button
>
<input type="file" id="file" name="file" />
</div>
</div>
</div>
<div class="data-step">
<div class="upload-step">
<div>
<span class="step-label" id="upload-metadata-label"
><b>Step 2</b> (optional):</span
>
<b>Load a TSV file of metadata.</b>
</div>
</div>
<div class="data-step-contents">
<div class="data-step-contents-contents">
Example of 3 data points and 2 columns.<br />
<i
>Note: If there is more than one column, the first row will be
parsed as column labels.</i
>
<div class="code">
<b>Pokémon<span class="delimiter"> </span>Species</b><br />
Wartortle<span class="delimiter"> </span>Turtle<br />
Venusaur<span class="delimiter"> </span>Seed<br />
Charmeleon<span class="delimiter"> </span>Flame
</div>
</div>
<div class="data-step-contents-upload">
<paper-button
id="upload-metadata"
title="Choose a TSV metadata file"
class="ink-button"
>Choose file</paper-button
>
<input type="file" id="file-metadata" name="file-metadata" />
</div>
</div>
</div>
</paper-dialog-scrollable>
<div class="dismiss-dialog-note">Click outside to dismiss.</div>
</paper-dialog>
<paper-dialog id="projectorConfigDialog" with-backdrop>
<h2>Publish your embedding visualization and data</h2>
<paper-dialog-scrollable class="scrollable-container">
<div>
<p>
If you'd like to share your visualization with the world, follow
these simple steps. See
<a
target="_blank"
rel="noopener noreferrer"
href="https://www.tensorflow.org/get_started/embedding_viz"
>this tutorial</a
>
for more.
</p>
<h4><span class="step-label">Step 1:</span> Make data public</h4>
<p>
Host tensors, metadata, sprite image, and bookmarks TSV files
<i>publicly</i> on the web.
</p>
<p>
One option is using a
<a
target="_blank"
href="https://gist.github.com/"
rel="noopener noreferrer"
>github gist</a
>. If you choose this approach, make sure to link directly to the
raw file.
</p>
</div>
<div>
<h4><span class="step-label">Step 2:</span> Projector config</h4>
<div class="projector-config-options">
<i>Optional:</i>
<div class="config-checkbox">
<paper-checkbox id="config-metadata-checkbox" checked
>Metadata</paper-checkbox
>
</div>
<div class="config-checkbox">
<paper-checkbox id="config-sprite-checkbox"
>Sprite</paper-checkbox
>
</div>
<div class="config-checkbox">
<paper-checkbox id="config-bookmarks-checkbox"
>Bookmarks</paper-checkbox
>
</div>
</div>
</div>
<paper-textarea
id="projector-config-template"
label="template_projector_config.json"
></paper-textarea>
<div>
<h4>
<span class="step-label">Step 3:</span> Host projector config
</h4>
After you have hosted the projector config JSON file you built
above, paste the URL to the config below.
</div>
<paper-input
id="projector-config-url"
label="Path to projector config"
></paper-input>
<paper-input
id="projector-share-url"
label="Your shareable URL"
readonly
></paper-input>
<div id="projector-share-button-container">
<a
target="_blank"
id="projector-share-url-link"
rel="noopener noreferrer"
>
<paper-button title="Test your shareable URL" class="ink-button"
>Test your shareable URL</paper-button
>
</a>
</div>
</paper-dialog-scrollable>
<div class="dismiss-dialog-note">Click outside to dismiss.</div>
</paper-dialog>
</div>
<paper-checkbox id="normalize-data-checkbox" checked="{{normalizeData}}">
Sphereize data
<paper-icon-button icon="help" class="help-icon"></paper-icon-button>
<paper-tooltip
position="bottom"
animation-delay="0"
fit-to-visible-bounds
>
The data is normalized by shifting each point by the centroid and making
it unit norm.
</paper-tooltip>
</paper-checkbox>
<div class="dirs">
<table>
<tr>
<td>Checkpoint:</td>
<td>
<span id="checkpoint-file">
<tf-wbr-string
title="[[projectorConfig.modelCheckpointPath]]"
delimiter-pattern="[[_wordDelimiter]]"
value="[[projectorConfig.modelCheckpointPath]]"
></tf-wbr-string>
</span>
</td>
</tr>
<tr>
<td>Metadata:</td>
<td>
<span id="metadata-file">
<tf-wbr-string
title="[[metadataFile]]"
delimiter-pattern="[[_wordDelimiter]]"
value="[[metadataFile]]"
></tf-wbr-string>
</span>
</td>
</tr>
</table>
</div>
</div>
`; | the_stack |
import {
Get,
HttpCode,
Body,
Controller,
Param,
Post,
Delete,
UseGuards,
Req,
NotFoundException,
BadRequestException,
ForbiddenException,
HttpStatus,
Inject,
forwardRef,
} from '@nestjs/common'
import {
ApiOkResponse,
ApiBearerAuth,
ApiCreatedResponse,
ApiNoContentResponse,
ApiExcludeEndpoint,
ApiTags,
ApiResponse,
} from '@nestjs/swagger'
import { Flight, FlightLeg } from './flight.model'
import {
AKUREYRI_FLIGHT_CODES,
ALLOWED_CONNECTING_FLIGHT_CODES,
FlightService,
REYKJAVIK_FLIGHT_CODES,
} from './flight.service'
import {
FlightViewModel,
CreateFlightBody,
GetFlightParams,
GetFlightLegsBody,
ConfirmInvoiceBody,
CreateFlightParams,
GetUserFlightsParams,
DeleteFlightParams,
DeleteFlightLegParams,
CheckFlightParams,
CheckFlightBody,
} from './dto'
import { Discount, DiscountService } from '../discount'
import { AuthGuard } from '../common'
import { NationalRegistryService } from '../nationalRegistry'
import type { HttpRequest } from '../../app.types'
@ApiTags('Flights')
@Controller('api/public')
@UseGuards(AuthGuard)
@ApiBearerAuth()
export class PublicFlightController {
constructor(
private readonly flightService: FlightService,
@Inject(forwardRef(() => DiscountService))
private readonly discountService: DiscountService,
private readonly nationalRegistryService: NationalRegistryService,
) {}
private async validateConnectionFlights(
discount: Discount,
discountCode: string,
flightLegs: FlightLeg[],
): Promise<string> {
const flightLegCount = flightLegs.length
const connectionDiscountCode = this.discountService.filterConnectionDiscountCodes(
discount.connectionDiscountCodes,
discountCode,
)
if (!connectionDiscountCode) {
throw new ForbiddenException(
'The provided discount code is either not intended for connecting flights or is expired',
)
}
const connectingId = connectionDiscountCode.flightId
// Make sure that all the flightLegs contain valid airports and valid airports only
// Note: at this point, none of the flightLegs contain Reykjavík
const ALLOWED_FLIGHT_CODES = [
...AKUREYRI_FLIGHT_CODES,
...ALLOWED_CONNECTING_FLIGHT_CODES,
]
for (const flightLeg of flightLegs) {
if (
!ALLOWED_FLIGHT_CODES.includes(flightLeg.origin) ||
!ALLOWED_FLIGHT_CODES.includes(flightLeg.destination)
) {
throw new ForbiddenException(
`A flightleg contains invalid flight code/s [${flightLeg.origin}, ${flightLeg.destination}]. Allowed flight codes: [${ALLOWED_FLIGHT_CODES}]`,
)
}
}
// Make sure the flightLegs are chronological
const chronoLogicallegs = flightLegs.sort((a, b) => {
const adate = new Date(Date.parse(a.date.toString()))
const bdate = new Date(Date.parse(b.date.toString()))
return adate.getTime() - bdate.getTime()
})
let incomingLeg = {
origin: chronoLogicallegs[0].origin,
destination: chronoLogicallegs[0].destination,
date: new Date(Date.parse(chronoLogicallegs[0].date.toString())),
}
// Validate the first chronological flightLeg of the connection flight
let isConnectingFlight = await this.flightService.isFlightLegConnectingFlight(
connectingId,
incomingLeg as FlightLeg, // must have date, destination and origin
)
// If round-trip
if (
chronoLogicallegs[0].origin ===
chronoLogicallegs[flightLegCount - 1].destination
) {
// Find a valid connection for the return trip to Akureyri
incomingLeg = {
origin: chronoLogicallegs[flightLegCount - 1].origin,
destination: chronoLogicallegs[flightLegCount - 1].destination,
date: new Date(
Date.parse(chronoLogicallegs[flightLegCount - 1].date.toString()),
),
}
// Lazy evaluation makes this cheap
isConnectingFlight =
isConnectingFlight &&
(await this.flightService.isFlightLegConnectingFlight(
connectingId,
incomingLeg as FlightLeg,
))
}
if (!isConnectingFlight) {
throw new ForbiddenException(
'User does not meet the requirements for a connecting flight for this flight. Must be 48 hours or less between flight and connectingflight. Each connecting flight must go from/to Akureyri',
)
}
return connectingId
}
@Post('discounts/:discountCode/isValidConnectionFlight')
@ApiResponse({
status: 200,
description: 'Input flight is eligible for discount as a connection flight',
})
@ApiResponse({
status: 400,
description:
'User does not have any flights that may correspond to connection flight',
})
@ApiResponse({
status: 403,
description:
'The provided discount code is either not intended for connecting flights or is expired',
})
@HttpCode(200)
@ApiOkResponse()
async checkFlightStatus(
@Param() params: CheckFlightParams,
@Body() body: CheckFlightBody,
@Req() request: HttpRequest,
): Promise<void> {
const discount = await this.discountService.getDiscountByDiscountCode(
params.discountCode,
)
if (!discount) {
throw new BadRequestException('Discount code is invalid')
}
await this.validateConnectionFlights(
discount,
params.discountCode,
body.flightLegs as FlightLeg[],
)
}
@Post('discounts/:discountCode/flights')
@ApiCreatedResponse({ type: FlightViewModel })
async create(
@Param() params: CreateFlightParams,
@Body() flight: CreateFlightBody,
@Req() request: HttpRequest,
): Promise<FlightViewModel> {
const discount = await this.discountService.getDiscountByDiscountCode(
params.discountCode,
)
if (!discount) {
throw new BadRequestException('Discount code is invalid')
}
const user = await this.nationalRegistryService.getUser(discount.nationalId)
if (!user) {
throw new NotFoundException(`User not found`)
}
if (
new Date(flight.bookingDate).getFullYear().toString() !==
new Date(Date.now()).getFullYear().toString()
) {
throw new BadRequestException(
'Flight cannot be booked outside the current year',
)
}
const meetsADSRequirements = this.flightService.isADSPostalCode(
user.postalcode,
)
if (!meetsADSRequirements) {
throw new ForbiddenException('User postalcode does not meet conditions')
}
let connectingFlight = false
let isConnectable = true
let connectingId = undefined
const hasReykjavik = flight.flightLegs.some(
(flightLeg) =>
REYKJAVIK_FLIGHT_CODES.includes(flightLeg.origin) ||
REYKJAVIK_FLIGHT_CODES.includes(flightLeg.destination),
)
const hasAkureyri = flight.flightLegs.some(
(flightLeg) =>
AKUREYRI_FLIGHT_CODES.includes(flightLeg.origin) ||
AKUREYRI_FLIGHT_CODES.includes(flightLeg.destination),
)
if (!hasReykjavik && hasAkureyri) {
connectingId = await this.validateConnectionFlights(
discount,
params.discountCode,
flight.flightLegs as FlightLeg[],
)
} else if (hasReykjavik) {
if (discount.discountCode !== params.discountCode) {
throw new ForbiddenException(
'This discount code is only intended for connecting flights',
)
}
const {
unused: flightLegsLeft,
} = await this.flightService.countThisYearsFlightLegsByNationalId(
discount.nationalId,
)
if (flightLegsLeft < flight.flightLegs.length) {
throw new ForbiddenException('Flight leg quota is exceeded')
}
if (!hasAkureyri) {
isConnectable = false
}
} else {
throw new ForbiddenException(
'Eligible flights must be from/to Reykjavík or be connecting flights from/to Akureyri',
)
}
if (connectingId) {
connectingFlight = true
isConnectable = false
}
const newFlight = await this.flightService.create(
flight,
user,
request.airline,
isConnectable,
connectingId,
)
await this.discountService.useDiscount(
params.discountCode,
discount.nationalId,
newFlight.id,
connectingFlight,
)
return new FlightViewModel(newFlight)
}
@Get('flights/:flightId')
@ApiOkResponse({ type: FlightViewModel })
async getFlightById(
@Param() params: GetFlightParams,
@Req() request: HttpRequest,
): Promise<FlightViewModel> {
const flight = await this.flightService.findOne(
params.flightId,
request.airline,
)
if (!flight) {
throw new NotFoundException(`Flight<${params.flightId}> not found`)
}
return new FlightViewModel(flight)
}
@Delete('flights/:flightId')
@HttpCode(204)
@ApiNoContentResponse()
async delete(
@Param() params: DeleteFlightParams,
@Req() request: HttpRequest,
): Promise<void> {
const flight = await this.flightService.findOne(
params.flightId,
request.airline,
)
if (!flight) {
throw new NotFoundException(`Flight<${params.flightId}> not found`)
}
await this.discountService.reactivateDiscount(flight.id)
await this.flightService.delete(flight)
}
@Delete('flights/:flightId/flightLegs/:flightLegId')
@HttpCode(204)
@ApiNoContentResponse()
async deleteFlightLeg(
@Param() params: DeleteFlightLegParams,
@Req() request: HttpRequest,
): Promise<void> {
const flight = await this.flightService.findOne(
params.flightId,
request.airline,
)
if (!flight) {
throw new NotFoundException(`Flight<${params.flightId}> not found`)
}
const flightLeg = await flight.flightLegs.find(
(flightLeg) => flightLeg.id === params.flightLegId,
)
if (!flightLeg) {
throw new NotFoundException(
`FlightLeg<${params.flightLegId}> not found for Flight<${flight.id}>`,
)
}
await this.flightService.deleteFlightLeg(flightLeg)
}
}
@Controller('api/private')
export class PrivateFlightController {
constructor(private readonly flightService: FlightService) {}
@Get('flights')
@ApiExcludeEndpoint()
get(): Promise<Flight[]> {
return this.flightService.findAll()
}
@Post('flightLegs')
@ApiExcludeEndpoint()
getFlightLegs(@Body() body: GetFlightLegsBody | {}): Promise<FlightLeg[]> {
return this.flightService.findAllLegsByFilter(body)
}
@Post('flightLegs/confirmInvoice')
@ApiExcludeEndpoint()
async confirmInvoice(
@Body() body: ConfirmInvoiceBody | {},
): Promise<FlightLeg[]> {
let flightLegs = await this.flightService.findAllLegsByFilter(body)
flightLegs = await this.flightService.finalizeCreditsAndDebits(flightLegs)
return flightLegs
}
@Get('users/:nationalId/flights')
@ApiExcludeEndpoint()
getUserFlights(@Param() params: GetUserFlightsParams): Promise<Flight[]> {
return this.flightService.findThisYearsFlightsByNationalId(
params.nationalId,
)
}
} | the_stack |
import { DemoSharedBase } from '../utils';
import { ImageSource, ObservableArray, Screen, Color, Application } from '@nativescript/core';
import Chart from 'chart.js';
let Matter;
import { Canvas, ImageAsset } from '@nativescript/canvas';
import { flappyBird, arc, arcTo, cancelParticlesColor, cancelParticlesLarge, cancelRain, cancelRainbowOctopus, cancelSwarm, clip, cloth, colorRain, createLinearGradient, createRadialGradient, ellipse, fillPath, fillRule, filterBlur, imageBlock, imageSmoothingEnabled, imageSmoothingQuality, isPointInStrokeTouch, lineWidth, march, multiStrokeStyle, particlesColor, particlesLarge, patternWithCanvas, rainbowOctopus, scale, shadowBlur, shadowColor, swarm, textAlign, touchParticles } from './canvas2d';
declare var NSData, interop, NSString, malloc, TNSCanvas;
//const CanvasWorker = require('nativescript-worker-loader!./canvas.worker.js');
import Vex from 'vexflow';
import { handleVideo, cancelInteractiveCube, cancelMain, cubeRotation, cubeRotationRotation, drawElements, drawModes, imageFilter, interactiveCube, main, textures } from './webgl';
import { cancelEnvironmentMap, cancelFog, draw_image_space, draw_instanced, environmentMap, fog } from './webgl2';
declare var com, java;
let zen3d;
import * as Svg from '@nativescript/canvas/SVG';
import { issue54 } from './issues';
export class DemoSharedCanvas extends DemoSharedBase {
private canvas: any;
private svg: Svg.Svg;
private svg2: Svg.Svg;
private svg3: Svg.Svg;
private svg4: Svg.Svg;
canvasLoaded(args) {
this.canvas = args.object;
console.log('canvas ready');
this.draw();
}
svgViewLoaded(args) {
const view = args.object;
console.log('svg ready', view.id);
this.drawSvg(this.svg, view.id);
}
svg2ViewLoaded(args) {
this.svg2 = args.object;
console.log('svg2 ready');
this.set('src2', 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg');
}
drawTransformMatrixSvg() {
this.set(
'src',
`<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="10" width="30" height="20" fill="green" />
<!--
In the following example we are applying the matrix:
[a c e] [3 -1 30]
[b d f] => [1 3 40]
[0 0 1] [0 0 1]
which transform the rectangle as such:
top left corner: oldX=10 oldY=10
newX = a * oldX + c * oldY + e = 3 * 10 - 1 * 10 + 30 = 50
newY = b * oldX + d * oldY + f = 1 * 10 + 3 * 10 + 40 = 80
top right corner: oldX=40 oldY=10
newX = a * oldX + c * oldY + e = 3 * 40 - 1 * 10 + 30 = 140
newY = b * oldX + d * oldY + f = 1 * 40 + 3 * 10 + 40 = 110
bottom left corner: oldX=10 oldY=30
newX = a * oldX + c * oldY + e = 3 * 10 - 1 * 30 + 30 = 30
newY = b * oldX + d * oldY + f = 1 * 10 + 3 * 30 + 40 = 140
bottom right corner: oldX=40 oldY=30
newX = a * oldX + c * oldY + e = 3 * 40 - 1 * 30 + 30 = 120
newY = b * oldX + d * oldY + f = 1 * 40 + 3 * 30 + 40 = 170
-->
<rect x="10" y="10" width="30" height="20" fill="red"
transform="matrix(3 1 -1 3 30 40)" />
</svg>`
);
}
drawTransformTranslateSvg() {
/// translate transform
this.set(
'src',
`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<!-- No translation -->
<rect x="5" y="5" width="40" height="40" fill="green" />
<!-- Horizontal translation -->
<rect x="5" y="5" width="40" height="40" fill="blue"
transform="translate(50)" />
<!-- Vertical translation -->
<rect x="5" y="5" width="40" height="40" fill="red"
transform="translate(0 50)" />
<!-- Both horizontal and vertical translation -->
<rect x="5" y="5" width="40" height="40" fill="yellow"
transform="translate(50,50)" />
</svg>
`
);
}
drawTransformScaleSvg() {
this.set(
'src',
`
<svg viewBox="-50 -50 100 100" xmlns="http://www.w3.org/2000/svg">
<!-- uniform scale -->
<circle cx="0" cy="0" r="10" fill="red"
transform="scale(4)" />
<!-- vertical scale -->
<circle cx="0" cy="0" r="10" fill="yellow"
transform="scale(1,4)" />
<!-- horizontal scale -->
<circle cx="0" cy="0" r="10" fill="pink"
transform="scale(4,1)" />
<!-- No scale -->
<circle cx="0" cy="0" r="10" fill="black" />
</svg>
`
);
}
drawTransformRotateSvg() {
this.set(
'src',
`
<svg viewBox="-12 -2 34 14" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="10" height="10" />
<!-- rotation is done around the point 0,0 -->
<rect x="0" y="0" width="10" height="10" fill="red"
transform="rotate(100)" />
<!-- rotation is done around the point 10,10 -->
<rect x="0" y="0" width="10" height="10" fill="green"
transform="rotate(100,10,10)" />
</svg>
`
);
}
drawTransformSkewX() {
this.set(
'src',
`
<svg viewBox="-5 -5 10 10" xmlns="http://www.w3.org/2000/svg">
<rect x="-3" y="-3" width="6" height="6" />
<rect x="-3" y="-3" width="6" height="6" fill="red"
transform="skewX(30)" />
</svg>
`
);
}
drawTransformSkewY() {
this.set(
'src',
`
<svg viewBox="-5 -5 10 10" xmlns="http://www.w3.org/2000/svg">
<rect x="-3" y="-3" width="6" height="6" />
<rect x="-3" y="-3" width="6" height="6" fill="red"
transform="skewY(30)" />
</svg>
`
);
}
drawSvg(args: Svg.Svg, id) {
switch (id) {
case '1':
this.set('src1', 'https://upload.wikimedia.org/wikipedia/commons/8/85/Australian_Census_2011_demographic_map_-_Australia_by_SLA_-_BCP_field_0001_Total_Persons_Males.svg');
break;
case '2':
this.set('src2', 'https://upload.wikimedia.org/wikipedia/commons/4/4c/The_Hague%2C_Netherlands%2C_the_old_city_center.svg');
break;
case '3':
this.set('src3', 'https://upload.wikimedia.org/wikipedia/commons/7/7c/Map_of_the_world_by_the_US_Gov_as_of_2016_no_legend.svg');
break;
case '4':
this.set('src4', 'https://upload.wikimedia.org/wikipedia/commons/9/9d/The_Rhodopes_on_The_Paths_Of_Orpheus_And_Eurydice_Project_Map.svg');
break;
}
//this.drawTransformSkewY();
//this.set('src','https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/car.svg');
//this.set('src','http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/a/a0/Location_map_San_Francisco_Bay_Area.svg');
//this.set('src','https://upload.wikimedia.org/wikipedia/commons/4/4c/The_Hague%2C_Netherlands%2C_the_old_city_center.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/6/6c/Trajans-Column-lower-animated.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/7/7c/Map_of_the_world_by_the_US_Gov_as_of_2016_no_legend.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/b/b6/Moldova_%281483%29-en.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/9/95/Kaiserstandarte_Version1.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/f/ff/1_42_polytope_7-cube.svg');
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/1/1c/KINTETSU23000_20140424A.svg');
//this.set('src', 'https://raw.githubusercontent.com/RazrFalcon/resvg/7b26adbcc9698dcca687214c84d216794f60a5be/tests/svg/e-radialGradient-013.svg');
//this.set('src','https://upload.wikimedia.org/wikipedia/commons/c/c1/Propane_flame_contours-en.svg')
//this.set('src','https://upload.wikimedia.org/wikipedia/commons/9/9d/The_Rhodopes_on_The_Paths_Of_Orpheus_And_Eurydice_Project_Map.svg')
//this.set('src', 'https://upload.wikimedia.org/wikipedia/commons/7/7c/Map_of_the_world_by_the_US_Gov_as_of_2016_no_legend.svg');
//this.set('src','https://upload.wikimedia.org/wikipedia/commons/7/78/61453-Planeta_berria_2006an.svg')
// https://upload.wikimedia.org/wikipedia/commons/6/61/Figure_in_Manga_style.svg
// https://upload.wikimedia.org/wikipedia/commons/a/a0/Plan_des_Forts_de_Lyon_premi%C3%A8re_ceinture_-_OSM.svg
/*this.set('src', `
<svg viewBox="0 0 100 100">
<!-- No translation -->
<rect x="5" y="5" width="40" height="40" fill="green" />
<!-- Horizontal translation -->
<rect x="5" y="5" width="40" height="40" fill="blue"
transform="translate(50)" />
<!-- Vertical translation -->
<rect x="5" y="5" width="40" height="40" fill="red"
transform="translate(0 50)" />
<!-- Both horizontal and vertical translation -->
<rect x="5" y="5" width="40" height="40" fill="yellow"
transform="translate(50,50)" />
</svg>
`) */
/*
const circle = new Svg.Circle();
circle.cx = 100;
circle.cy = 100;
circle.r = 50;
circle.fill = 'gold';
circle.id = 'circle';
args.addChild(circle);
const rect = new Svg.Rect();
rect.x = 0;
rect.y = 200;
rect.width = 300;
rect.height = 300;
rect.stroke = 'green';
rect.fill = 'black';
rect.id = 'rect';
args.addChild(rect);
const image = new Svg.Image();
image.href = 'https://source.unsplash.com/1600x900/?water';
image.x = 0;
image.y = 600;
image.width = 500;
image.height = 500;
args.addChild(image);
const image2 = new Svg.Image();
image2.href = 'https://source.unsplash.com/1600x900/?nature';
image2.x = 600;
image2.y = 600;
image2.width = 500;
image2.height = 500;
args.addChild(image2);
const path = new Svg.Path();
path.d = "M150 0 L75 200 L225 200 Z";
args.addChild(path);
const ellipse = new Svg.Ellipse();
ellipse.cx = 500;
ellipse.cy = 80;
ellipse.rx = 100;
ellipse.ry = 50;
ellipse.setInlineStyle('fill:yellow;stroke:purple;stroke-width:2');
args.addChild(ellipse);
const line = new Svg.Line();
line.x1 = 0;
line.y1 = 0;
line.x2 = 200;
line.y2 = 200;
line.setInlineStyle('stroke:rgb(255,0,0);stroke-width:2');
args.addChild(line);
const polygon = new Svg.Polygon();
polygon.points = "200,10 250,190 160,210";
polygon.setInlineStyle('fill:lime;stroke:purple;stroke-width:1');
args.addChild(polygon);
const polyline = new Svg.Polyline();
polyline.points = "20,20 40,25 60,40 80,120 120,140 200,180";
polyline.setInlineStyle("fill:none;stroke:black;stroke-width:3");
args.addChild(polyline);
const text = new Svg.Text();
text.text = "I love SVG!";
text.x = 0;
text.y = 15;
args.addChild(text);
const g = new Svg.G();
const path1 = new Svg.Path();
path1.d = "M5 20 l215 0";
path1.stroke = "red";
const path2 = new Svg.Path();
path2.d = "M5 40 l215 0";
path2.stroke = "black";
const path3 = new Svg.Path();
path3.d = "M5 60 l215 0";
path3.stroke = "blue";
g.addChildren(path1, path2, path3);
args.addChild(g);
*/
}
urlTests() {
this.urlConstructor();
this.urlHash();
this.urlHost();
this.urlHostname();
this.urlHref();
this.urlOrigin();
this.urlPassword();
this.urlPathname();
this.urlProtocol();
this.urlSearch();
this.urlUsername();
}
urlConstructor() {
let m = 'https://developer.mozilla.org';
let a = new URL("/", m); // => 'https://developer.mozilla.org/'
let b = new URL(m); // => 'https://developer.mozilla.org/'
new URL('en-US/docs', b); // => 'https://developer.mozilla.org/en-US/docs'
let d = new URL('/en-US/docs', b); // => 'https://developer.mozilla.org/en-US/docs'
new URL('/en-US/docs', d); // => 'https://developer.mozilla.org/en-US/docs'
new URL('/en-US/docs', a); // => 'https://developer.mozilla.org/en-US/docs'
new URL('/en-US/docs', "https://developer.mozilla.org/fr-FR/toto");
// => 'https://developer.mozilla.org/en-US/docs'
try {
new URL('/en-US/docs', ''); // Raises a TypeError exception as '' is not a valid URL
} catch (e) {
console.log(e);
}
try {
new URL('/en-US/docs'); // Raises a TypeError exception as '/en-US/docs' is not a valid URL
} catch (e) {
console.log(e);
}
new URL('http://www.example.com',); // => 'http://www.example.com/'
new URL('http://www.example.com', b); // => 'http://www.example.com/'
new URL("//foo.com", "https://example.com") // => 'https://foo.com' (see relative URLs)
}
urlHash() {
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/href#Examples');
console.log(url.hash); // Logs: '#Examples'
}
urlHost() {
let url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/host');
console.log(url.host); // "developer.mozilla.org"
url = new URL('https://developer.mozilla.org:443/en-US/docs/Web/API/URL/host');
console.log(url.host); // "developer.mozilla.org"
// The port number is not included because 443 is the scheme's default port
url = new URL('https://developer.mozilla.org:4097/en-US/docs/Web/API/URL/host');
console.log(url.host); // "developer.mozilla.org:4097"
}
urlHostname() {
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname');
console.log(url.hostname); // Logs: 'developer.mozilla.org'
}
urlHref() {
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/href');
console.log(url.href); // Logs: 'https://developer.mozilla.org/en-US/docs/Web/API/URL/href'
}
urlOrigin() {
const url = new URL("blob:https://mozilla.org:443/")
console.log(url.origin); // Logs 'https://mozilla.org'
}
urlPassword() {
const url = new URL('https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/password');
console.log(url.password) // Logs "flabada"
}
urlPathname() {
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname?q=value');
console.log(url.pathname); // Logs "/en-US/docs/Web/API/URL/pathname"
}
urlPort() {
const url = new URL('https://mydomain.com:80/svn/Repos/');
console.log(url.port); // Logs '80'
}
urlProtocol() {
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol');
console.log(url.protocol); // Logs "https:"
}
urlSearch() {
const url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/search?q=123');
console.log(url.search); // Logs "?q=123"
}
urlUsername() {
const url = new URL('https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/username');
console.log(url.username) // Logs "anonymous"
}
draw() {
this.urlTests();
//const str = new java.lang.String()
// const ctx = this.canvas.getContext('2d');
// ctx.font = '50px serif';
// ctx.fillText('Hello world', 50, 90);
/* const ctx = this.canvas.getContext('2d');
// Moved square
ctx.translate(110, 30);
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 80, 80);
// Reset current transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
// Unmoved square
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, 80, 80); */
//filterBlur(this.canvas);
//handleVideo(this.canvas);
// const worker = new CanvasWorker();
// canvas.parent.on(GestureTypes.touch as any, (args: TouchGestureEventData) => {
// var x = args.getX() * Screen.mainScreen.scale,
// y = (args.getY() * Screen.mainScreen.scale);
// worker.postMessage({event: 'touch', x, y})
// });
// if (isAndroid) {
// canvas.android.setHandleInvalidationManually(true);
// (com.github.triniwiz.canvas.CanvasView as any).getViews().put(
// `${canvas._domId}`, new java.lang.ref.WeakReference(canvas.android)
// );
// } else {
// canvas.ios.handleInvalidationManually = true;
// canvas.ios.moveOffMain();
// Canvas.getViews().setObjectForKey(canvas.ios, `${canvas._domId}`);
// }
// const w = canvas.getMeasuredWidth(),
// h = canvas.getMeasuredHeight();
// worker.postMessage({id: `${canvas._domId}`, width: w, height: h});
// worker.onerror = msg => {
// console.log('error', msg);
// }
// swarm(canvas);
// touchParticles(canvas);
// var map = L.map('map', {
// center: [51.505, -0.09],
// zoom: 13
// });
//this.vexFlow(this.canvas);
// canvas.android.setHandleInvalidationManually(true);
//const ctx = canvas.getContext('2d');
// fillRule(this.canvas);
//const ctx = this.canvas.getContext('2d');
//clip(this.canvas);
//fillStyle(this.canvas);
// font(this.canvas);
// globalAlpha(this.canvas);
//globalCompositeOperation(this.canvas);
//imageSmoothingEnabled(this.canvas);
//imageSmoothingQuality(this.canvas);
//lineCap(this.canvas);
//lineDashOffset(this.canvas);
//lineJoin(this.canvas);
//lineWidth(this.canvas);
// miterLimit(this.canvas);
//shadowBlur(this.canvas);
//shadowColor(this.canvas);
//shadowOffsetX(this.canvas);
//shadowOffsetY(this.canvas);
// strokeStyle(this.canvas);
//multiStrokeStyle(this.canvas);
//textAlign(this.canvas)
//arc(this.canvas);
//arcMultiple(this.canvas);
//arcTo(this.canvas);
// arcToAnimation(this.canvas);
// ellipse(this.canvas);
//fillPath(this.canvas);
//imageBlock(this.canvas);
//scale(this.canvas);
//pattern(this.canvas);
//patternWithCanvas(this.canvas);
//isPointInStrokeTouch(this.canvas);
//createLinearGradient(this.canvas);
//createRadialGradient(this.canvas);
//march(this.canvas);
//this.putImageDataDemo(this.canvas);
// this.drawImage(this.canvas);
// ctx.fillStyle = 'blue';
// ctx.fillRect(0,0,400,400)
//ellipse(this.canvas);
//this.drawPatternWithCanvas(this.canvas);
//this.clock(this.canvas);
//this.solar(this.canvas);
//console.log('ready ??');
//this.coloredParticles(this.canvas);
//this.ball(this.canvas)
//swarm(this.canvas);
//this.bubbleChart(this.canvas);
//this.donutChart(this.canvas);
//canvas.page.actionBarHidden = true;
//this.hBarChart(this.canvas);
//this.bubbleChart(this.canvas);
//this.dataSets(this.canvas);
//this.chartJS(this.canvas);
//clear(null)
//points(this.canvas)
//textures(this.canvas);
//scaleTriangle(this.canvas);
//setTimeout(()=>{
//colorRain(this.canvas);
//particlesLarge(this.canvas);
//rainbowOctopus(this.canvas);
//particlesColor(this.canvas);
//cloth(this.canvas);
//touchParticles(this.canvas);
//swarm(this.canvas);
//textures(this.canvas)
//drawModes(this.canvas,'triangles')
//drawElements(this.canvas)
// ctx = canvas.getContext("2d") as any;
//swarm(this.canvas);
// canvas.nativeView.handleInvalidationManually = true;
// setTimeout(() => {
//draw_instanced(this.canvas);
//draw_image_space(this.canvas);
//fog(this.canvas);
//environmentMap(this.canvas);
//cubeRotationRotation(this.canvas);
//main(this.canvas);
// imageFilter(this.canvas);
// interactiveCube(this.canvas);
//textures(this.canvas);
//drawElements(this.canvas)
//drawModes(this.canvas,'triangles')
//fog(this.canvas);
// }, 1000);
//cubeRotation(this.canvas);
//},3000)
// drawModes(this.canvas,'triangles')
//cubeRotation(this.canvas);
//main(this.canvas)
//this.pointStyle(this.canvas);
// this.matterJSExample(this.canvas);
//this.matterJSCar(this.canvas);
//this.multiCanvas(this.canvas);
// triangle(this.canvas);
//this.zen3dCube(this.canvas);
this.zen3dGeometryLoaderGltf(this.canvas);
//this.playCanvas(this.canvas);
//this.drawRandomFullscreenImage(this.canvas);
//issue54(this.canvas);
}
drawRandomFullscreenImage(canvas) {
const width = Screen.mainScreen.widthPixels;
const height = Screen.mainScreen.heightPixels;
const ctx = canvas.getContext('2d');
const image = new Image();
image.onload = () => {
ctx.drawImage(image, 0, 0);
};
image.src = `https://source.unsplash.com/random/${width}x${height}`;
}
playCanvas(canvas) {
require('@nativescript/canvas-polyfill');
const pc = require('playcanvas');
const app = new pc.Application(canvas, {});
// fill the available space at full resolution
app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW);
app.setCanvasResolution(pc.RESOLUTION_AUTO);
// ensure canvas is resized when window changes size
window.addEventListener('resize', () => app.resizeCanvas());
// create box entity
const box = new pc.Entity('cube');
box.addComponent('model', {
type: 'box',
});
app.root.addChild(box);
// create camera entity
const camera = new pc.Entity('camera');
camera.addComponent('camera', {
clearColor: new pc.Color(0.1, 0.1, 0.1),
});
app.root.addChild(camera);
camera.setPosition(0, 0, 3);
// create directional light entity
const light = new pc.Entity('light');
light.addComponent('light');
app.root.addChild(light);
light.setEulerAngles(45, 0, 0);
// rotate the box according to the delta time since the last frame
app.on('update', (dt) => box.rotate(10 * dt, 20 * dt, 30 * dt));
app.start();
}
gridLoaded(args) {
const grid = args.object;
this.removeClipping(grid);
// d3 example
/*
const d3 = require('d3');
const svg = d3.create('svg')
.attr("viewBox", [0, 0, 975, 610])
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round");
svg.append('circle').attr('cx', 2).attr('cy', 2).attr('r', 40).style('fill', 'blue');
svg.append('circle').attr('cx', 140).attr('cy', 70).attr('r', 40).style('fill', 'red');
svg.append('circle').attr('cx', 300).attr('cy', 100).attr('r', 40).style('fill', 'green');
grid.addChild(svg['_groups'][0][0].nativeElement);
*/
}
svgLoaded(args) {
const svg = args.object;
this.removeClipping(svg);
}
removeClipping(view) {
if (view.android) {
if (view.nativeView.setClipChildren) {
view.nativeView.setClipChildren(false);
}
if (view.nativeView.setClipToPadding) {
view.nativeView.setClipToPadding(false);
}
}
}
getWidth() {
return Screen.mainScreen.widthPixels;
}
getHeight() {
return Screen.mainScreen.heightPixels - 300;
}
ctx: CanvasRenderingContext2D;
zen3dCube(canvas) {
if (zen3d === undefined) {
zen3d = require('zen-3d');
(global as any).zen3d = zen3d;
}
var gl = canvas.getContext('webgl2', {
antialias: true,
alpha: false,
stencil: true,
});
const { drawingBufferWidth, drawingBufferHeight } = gl;
let width = drawingBufferWidth;
let height = drawingBufferHeight;
var glCore = new zen3d.WebGLCore(gl);
glCore.state.colorBuffer.setClear(0.1, 0.1, 0.1, 1);
var backRenderTarget = new zen3d.RenderTargetBack(canvas);
var scene = new zen3d.Scene();
var geometry = new zen3d.CubeGeometry(8, 8, 8);
var material = new zen3d.PBRMaterial();
var mesh = new zen3d.Mesh(geometry, material);
scene.add(mesh);
var ambientLight = new zen3d.AmbientLight(0xffffff);
scene.add(ambientLight);
var directionalLight = new zen3d.DirectionalLight(0xffffff);
directionalLight.position.set(-5, 5, 5);
directionalLight.lookAt(new zen3d.Vector3(), new zen3d.Vector3(0, 1, 0));
scene.add(directionalLight);
var camera = new zen3d.Camera();
camera.position.set(0, 10, 30);
camera.lookAt(new zen3d.Vector3(0, 0, 0), new zen3d.Vector3(0, 1, 0));
camera.setPerspective((45 / 180) * Math.PI, width / height, 1, 1000);
scene.add(camera);
function loop(count) {
requestAnimationFrame(loop);
mesh.euler.y = (count / 1000) * 0.5; // rotate cube
scene.updateMatrix();
scene.updateLights();
glCore.renderTarget.setRenderTarget(backRenderTarget);
glCore.clear(true, true, false);
glCore.render(scene, camera);
}
requestAnimationFrame(loop);
function onWindowResize() {
width = window.innerWidth || 2;
height = window.innerHeight || 2;
camera.setPerspective((45 / 180) * Math.PI, width / height, 1, 1000);
backRenderTarget.resize(width, height);
}
window.addEventListener('resize', onWindowResize, false);
}
zen3dGeometryLoaderGltf(canvas) {
if (zen3d === undefined) {
zen3d = require('zen-3d');
(global as any).zen3d = zen3d;
}
const zen3dRoot = '~/assets/file-assets/zen3d/';
require('./zen3d/js/objects/SkyBox.js');
require('./zen3d/js/loaders/GLTFLoader.js');
require('./zen3d/js/controls/OrbitControls.js');
var renderer = new zen3d.Renderer(canvas);
let gl = canvas.getContext('webgl2');
if (!gl) {
gl = canvas.getContext('webgl');
}
const { drawingBufferWidth, drawingBufferHeight } = gl;
let width = drawingBufferWidth;
let height = drawingBufferHeight;
var scene = new zen3d.Scene();
var file = '~/assets/three/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf';
var cube_texture = zen3d.TextureCube.fromSrc([zen3dRoot + 'Bridge2/posx.jpg', zen3dRoot + 'Bridge2/negx.jpg', zen3dRoot + 'Bridge2/posy.jpg', zen3dRoot + 'Bridge2/negy.jpg', zen3dRoot + 'Bridge2/posz.jpg', zen3dRoot + 'Bridge2/negz.jpg']);
var sky_box = new zen3d.SkyBox(cube_texture);
sky_box.level = 4;
let objectMaterial;
// var nanobar = new Nanobar();
// nanobar.el.style.background = "gray";
var loadingManager = new zen3d.LoadingManager(
function () {
// nanobar.go(100);
// nanobar.el.style.background = "transparent";
},
function (url, itemsLoaded, itemsTotal) {
if (itemsLoaded < itemsTotal) {
// nanobar.go(itemsLoaded / itemsTotal * 100);
}
}
);
var loader = new zen3d.GLTFLoader(loadingManager);
loader.load(file, function (result) {
// add mesh to scene
let object = result.scene.children[0];
objectMaterial = object.material;
objectMaterial.envMap = cube_texture;
objectMaterial.envMapIntensity = 1;
object.scale.set(10, 10, 10);
object.euler.z = -Math.PI / 6;
scene.add(object);
});
// top light
var directionalLight = new zen3d.DirectionalLight(0xbbbbff, 0.5);
directionalLight.euler.set(Math.PI / 2, 0, 0);
scene.add(directionalLight);
// bottom light
var directionalLight = new zen3d.DirectionalLight(0x444422, 0.5);
directionalLight.euler.set(-Math.PI / 2, 0, 0);
scene.add(directionalLight);
var camera = new zen3d.Camera();
camera.outputEncoding = zen3d.TEXEL_ENCODING_TYPE.GAMMA;
camera.position.set(-15, 10, 90);
camera.lookAt(new zen3d.Vector3(0, 0, 0), new zen3d.Vector3(0, 1, 0));
camera.setPerspective((45 / 180) * Math.PI, width / height, 1, 8000);
camera.add(sky_box);
scene.add(camera);
var controller = new zen3d.OrbitControls(camera, canvas);
controller.enablePan = false;
function loop(count) {
requestAnimationFrame(loop);
controller.update();
renderer.render(scene, camera);
}
loop(0);
function onWindowResize() {
width = drawingBufferWidth;
height = drawingBufferHeight;
camera.setPerspective((45 / 180) * Math.PI, width / height, 1, 8000);
renderer.backRenderTarget.resize(width, height);
}
window.addEventListener('resize', onWindowResize, false);
}
async drawImage(context) {
var sun = await ImageSource.fromUrl('https://mdn.mozillademos.org/files/1456/Canvas_sun.png');
context.drawImage(sun, 0, 0);
}
decoder() {
// let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]);
//
// console.log( new TextDecoder().decode(uint8Array) ); // 你好
let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8'
console.log(utf8decoder.encoding);
let u8arr = new Uint8Array([240, 160, 174, 183]);
let i8arr = new Int8Array([-16, -96, -82, -73]);
let u16arr = new Uint16Array([41200, 47022]);
let i16arr = new Int16Array([-24336, -18514]);
let i32arr = new Int32Array([-1213292304]);
console.log(utf8decoder.decode(u8arr));
console.log(utf8decoder.decode(i8arr));
console.log(utf8decoder.decode(u16arr));
console.log(utf8decoder.decode(i16arr));
console.log(utf8decoder.decode(i32arr));
let win1251decoder = new TextDecoder('windows-1251');
let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
console.log(win1251decoder.decode(bytes)); // Привет, мир!
}
putImageDataDemo(canvas) {
const ctx = canvas.getContext('2d');
ctx.rect(10, 10, 100, 100);
ctx.fill();
let imageData = ctx.getImageData(60, 60, 200, 100);
ctx.putImageData(imageData, 150, 10);
}
onLayout(args) {
console.log('onLayout');
}
vexFlow(canvas) {
const VF = Vex.Flow as any;
const renderer = new VF.Renderer(canvas, VF.Renderer.Backends.CANVAS);
// Configure the rendering context.
renderer.resize(500, 500);
const context = renderer.getContext();
context.setFont('Arial', 10, '').setBackgroundFillStyle('#eed');
// Create a stave of width 400 at position 10, 40 on the canvas.
const stave = new VF.Stave(10, 40, 400);
// Add a clef and time signature.
stave.addClef('treble').addTimeSignature('4/4');
// Connect it to the rendering context and draw!
stave.setContext(context).draw();
}
coloredParticles(canvas) {
var ctx = canvas.getContext('2d'),
particles = [],
patriclesNum = 100,
w = canvas.width,
h = canvas.height,
colors = ['#f35d4f', '#f36849', '#c0d988', '#6ddaf1', '#f1e85b'];
function Factory() {
this.x = Math.round(Math.random() * w);
this.y = Math.round(Math.random() * h);
this.rad = Math.round(Math.random() * 1) + 1;
this.rgba = colors[Math.round(Math.random() * 3)];
this.vx = Math.round(Math.random() * 3) - 1.5;
this.vy = Math.round(Math.random() * 3) - 1.5;
}
function draw() {
ctx.clearRect(0, 0, w, h);
ctx.globalCompositeOperation = 'lighter';
for (var i = 0; i < patriclesNum; i++) {
var temp = particles[i];
var factor = 1;
for (var j = 0; j < patriclesNum; j++) {
var temp2 = particles[j];
ctx.lineWidth = 0.5;
if (temp.rgba == temp2.rgba && findDistance(temp, temp2) < 50) {
ctx.strokeStyle = temp.rgba;
ctx.beginPath();
ctx.moveTo(temp.x, temp.y);
ctx.lineTo(temp2.x, temp2.y);
ctx.stroke();
factor++;
}
}
ctx.fillStyle = temp.rgba;
ctx.strokeStyle = temp.rgba;
ctx.beginPath();
ctx.arc(temp.x, temp.y, temp.rad * factor, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(temp.x, temp.y, (temp.rad + 5) * factor, 0, Math.PI * 2, true);
ctx.stroke();
ctx.closePath();
temp.x += temp.vx;
temp.y += temp.vy;
if (temp.x > w) temp.x = 0;
if (temp.x < 0) temp.x = w;
if (temp.y > h) temp.y = 0;
if (temp.y < 0) temp.y = h;
}
}
function findDistance(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
function init() {
for (var i = 0; i < patriclesNum; i++) {
particles.push(new Factory());
}
}
function loop() {
draw();
requestAnimationFrame(loop);
}
init();
loop();
}
ball(canvas) {
const ctx = canvas.getContext('2d');
let raf;
let running = false;
const ball = {
x: 100,
y: 100,
vx: 5,
vy: 1,
radius: 25,
color: 'blue',
draw: function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
},
};
function clear() {
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function draw() {
clear();
ball.draw();
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
ball.vy = -ball.vy;
}
if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
ball.vx = -ball.vx;
}
raf = window.requestAnimationFrame(draw);
}
ball.draw();
raf = window.requestAnimationFrame(draw);
running = true;
}
matterJSCar(canvas) {
/*
if (Matter === undefined) {
Matter = require('matter-js');
}
const car = function () {
const Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Composites = Matter.Composites,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
World = Matter.World,
Bodies = Matter.Bodies;
// create engine
const engine = Engine.create(),
world = engine.world;
// create renderer
const render = Render.create({
canvas,
engine: engine,
options: {
width: 800,
height: 600,
showAngleIndicator: true,
showCollisions: true,
},
});
Render.run(render);
// create runner
const runner = Runner.create();
Runner.run(runner, engine);
// add bodies
World.add(world, [
// walls
Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),
Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),
Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),
Bodies.rectangle(0, 300, 50, 600, { isStatic: true }),
]);
let scale = 0.9;
World.add(world, Composites.car(150, 100, 150 * scale, 30 * scale, 30 * scale));
scale = 0.8;
World.add(world, Composites.car(350, 300, 150 * scale, 30 * scale, 30 * scale));
World.add(world, [
Bodies.rectangle(200, 150, 400, 20, {
isStatic: true,
angle: Math.PI * 0.06,
}),
Bodies.rectangle(500, 350, 650, 20, {
isStatic: true,
angle: -Math.PI * 0.06,
}),
Bodies.rectangle(300, 560, 600, 20, {
isStatic: true,
angle: Math.PI * 0.04,
}),
]);
// add mouse control
const mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false,
},
},
});
World.add(world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 600 },
});
// context for MatterTools.Demo
return {
engine: engine,
runner: runner,
render: render,
canvas: render.canvas,
stop: function () {
Matter.Render.stop(render);
Matter.Runner.stop(runner);
},
};
};
car();
*/
}
matterJSExample(canvas) {
/*
if (Matter === undefined) {
Matter = require('matter-js');
}
// module aliases
const Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies;
// create an engine
const engine = Engine.create();
// create a renderer
const render = Render.create({
canvas,
engine: engine,
});
// create two boxes and a ground
var boxA = Bodies.rectangle(400, 200, 80, 80);
var boxB = Bodies.rectangle(450, 50, 80, 80);
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });
// add all of the bodies to the world
World.add(engine.world, [boxA, boxB, ground]);
// run the engine
Engine.run(engine);
// run the renderer
Render.run(render);
*/
}
multiCanvas(canvas) {
if (canvas.id === 'canvas1') {
swarm(canvas);
}
if (canvas.id === 'canvas2') {
this.clock(canvas);
}
if (canvas.id === 'canvas3') {
this.solar(canvas);
}
if (canvas.id === 'canvas4') {
main(this.canvas);
}
}
pointStyle(canvas) {
const color = Chart.helpers.color;
const createConfig = (colorName) => {
return {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
data: [this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor()],
backgroundColor: color(this.chartColors[colorName]).alpha(0.5).rgbString(),
borderColor: this.chartColors[colorName],
borderWidth: 1,
pointStyle: 'rectRot',
pointRadius: 5,
pointBorderColor: 'rgb(0, 0, 0)',
},
],
},
options: {
responsive: true,
legend: {
labels: {
usePointStyle: false,
},
},
scales: {
xAxes: [
{
display: true,
scaleLabel: {
display: true,
labelString: 'Month',
},
},
],
yAxes: [
{
display: true,
scaleLabel: {
display: true,
labelString: 'Value',
},
},
],
},
title: {
display: true,
text: 'Normal Legend',
},
},
};
};
function createPointStyleConfig(colorName) {
var config = createConfig(colorName);
config.options.legend.labels.usePointStyle = true;
config.options.title.text = 'Point Style Legend';
return config;
}
[
{
id: 'chart-legend-normal',
config: createConfig('red'),
},
{
id: 'chart-legend-pointstyle',
config: createPointStyleConfig('blue'),
},
].forEach(function (details) {
var ctx = canvas.getContext('2d');
new Chart(ctx, details.config);
});
}
lineBoundaries(canvas) {
var presets = this.chartColors;
var inputs = {
min: -100,
max: 100,
count: 8,
decimals: 2,
continuity: 1,
};
const generateData = (config?) => {
return this.utils.numbers(Chart.helpers.merge(inputs, config || {}));
};
const generateLabels = (config?) => {
return this.utils.months(
Chart.helpers.merge(
{
count: inputs.count,
section: 3,
},
config || {}
)
);
};
var options = {
maintainAspectRatio: false,
spanGaps: false,
elements: {
line: {
tension: 0.000001,
},
},
plugins: {
filler: {
propagate: false,
},
},
scales: {
xAxes: [
{
ticks: {
autoSkip: false,
maxRotation: 0,
},
},
],
},
};
[false, 'origin', 'start', 'end'].forEach((boundary, index) => {
// reset the random seed to generate the same data for all charts
this.utils.srand(8);
new Chart(canvas, {
type: 'line',
data: {
labels: generateLabels(),
datasets: [
{
backgroundColor: this.utils.transparentize(presets.red),
borderColor: presets.red,
data: generateData(),
label: 'Dataset',
fill: boundary,
},
],
},
options: Chart.helpers.merge(options, {
title: {
text: 'fill: ' + boundary,
display: true,
},
}),
});
});
// eslint-disable-next-line no-unused-vars
function toggleSmooth(btn) {
var value = btn.classList.toggle('btn-on');
Chart.helpers.each(Chart.instances, function (chart) {
chart.options.elements.line.tension = value ? 0.4 : 0.000001;
chart.update();
});
}
const randomize = () => {
var seed = this.utils.rand();
Chart.helpers.each(Chart.instances, (chart) => {
this.utils.srand(seed);
chart.data.datasets.forEach(function (dataset) {
dataset.data = generateData();
});
chart.update();
});
};
}
drawPatternWithCanvas(canvas) {
const patternCanvas = Canvas.createCustomView();
const patternContext = patternCanvas.getContext('2d') as any;
// Give the pattern a width and height of 50
patternCanvas.width = 50;
patternCanvas.height = 50;
// patternCanvas.getContext('2d') as any;
const scale = Screen.mainScreen.scale;
// Give the pattern a background color and draw an arc
patternContext.fillStyle = '#fec';
patternContext.fillRect(0, 0, patternCanvas.width * scale, patternCanvas.height * scale);
patternContext.arc(0, 0, 50 * scale, 0, 0.5 * Math.PI);
patternContext.stroke();
// Create our primary canvas and fill it with the pattern
const ctx = canvas.getContext('2d');
ctx.fillStyle = ctx.createPattern(patternCanvas, 'repeat');
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
donutChart(canvas) {
var randomScalingFactor = function () {
return Math.round(Math.random() * 100);
};
var config = {
type: 'doughnut',
data: {
datasets: [
{
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()],
backgroundColor: [this.chartColors.red, this.chartColors.orange, this.chartColors.yellow, this.chartColors.green, this.chartColors.blue],
label: 'Dataset 1',
},
],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Doughnut Chart',
},
animation: {
animateScale: true,
animateRotate: true,
},
},
};
const myDoughnut = new Chart(canvas, config);
function randomizeData() {
config.data.datasets.forEach(function (dataset) {
dataset.data = dataset.data.map(function () {
return randomScalingFactor();
});
});
myDoughnut.update();
}
var colorNames = Object.keys(this.chartColors);
const addDataset = () => {
var newDataset = {
backgroundColor: [],
data: [],
label: 'New dataset ' + config.data.datasets.length,
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
var colorName = colorNames[index % colorNames.length];
var newColor = this.chartColors[colorName];
newDataset.backgroundColor.push(newColor);
}
config.data.datasets.push(newDataset);
myDoughnut.update();
};
const addData = () => {
if (config.data.datasets.length > 0) {
config.data.labels.push('data #' + config.data.labels.length);
var colorName = colorNames[config.data.datasets[0].data.length % colorNames.length];
var newColor = this.chartColors[colorName];
config.data.datasets.forEach(function (dataset) {
dataset.data.push(randomScalingFactor());
dataset.backgroundColor.push(newColor);
});
myDoughnut.update();
}
};
function removeDataset() {
config.data.datasets.splice(0, 1);
myDoughnut.update();
}
function removeData() {
config.data.labels.splice(-1, 1); // remove the label first
config.data.datasets.forEach(function (dataset) {
dataset.data.pop();
dataset.backgroundColor.pop();
});
myDoughnut.update();
}
function changeCircleSize() {
if (myDoughnut.options.circumference === Math.PI) {
myDoughnut.options.circumference = 2 * Math.PI;
myDoughnut.options.rotation = -Math.PI / 2;
} else {
myDoughnut.options.circumference = Math.PI;
myDoughnut.options.rotation = -Math.PI;
}
myDoughnut.update();
}
setTimeout(() => {
addData();
}, 3000);
}
clock(canvas) {
let scale = false;
var ctx = canvas.getContext('2d');
ctx.scale(3, 3);
function clock() {
var now = new Date();
ctx.save();
ctx.clearRect(0, 0, 150, 150);
ctx.translate(75, 75);
ctx.scale(0.4, 0.4);
ctx.rotate(-Math.PI / 2);
ctx.strokeStyle = 'black';
ctx.fillStyle = 'white';
ctx.lineWidth = 8;
ctx.lineCap = 'round';
// Hour marks
ctx.save();
for (var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate(Math.PI / 6);
ctx.moveTo(100, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.restore();
// Minute marks
ctx.save();
ctx.lineWidth = 5;
for (i = 0; i < 60; i++) {
if (i % 5 != 0) {
ctx.beginPath();
ctx.moveTo(117, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.rotate(Math.PI / 30);
}
ctx.restore();
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
hr = hr >= 12 ? hr - 12 : hr;
ctx.fillStyle = 'black';
// write Hours
ctx.save();
ctx.rotate(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec);
ctx.lineWidth = 14;
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(80, 0);
ctx.stroke();
ctx.restore();
// write Minutes
ctx.save();
ctx.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec);
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(-28, 0);
ctx.lineTo(112, 0);
ctx.stroke();
ctx.restore();
// Write seconds
ctx.save();
ctx.rotate((sec * Math.PI) / 30);
ctx.strokeStyle = '#D40000';
ctx.fillStyle = '#D40000';
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(83, 0);
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, 10, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.arc(95, 0, 10, 0, Math.PI * 2, true);
ctx.stroke();
ctx.fillStyle = 'rgba(0, 0, 0, 0)';
ctx.arc(0, 0, 3, 0, Math.PI * 2, true);
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.lineWidth = 14;
ctx.strokeStyle = '#325FA2';
ctx.arc(0, 0, 142, 0, Math.PI * 2, true);
ctx.stroke();
ctx.restore();
requestAnimationFrame(clock);
}
requestAnimationFrame(clock);
}
async solar(canvas) {
var sun = new ImageAsset();
var moon = new ImageAsset();
var earth = new ImageAsset();
try {
await sun.loadFromUrlAsync('https://mdn.mozillademos.org/files/1456/Canvas_sun.png');
await moon.loadFromUrlAsync('https://mdn.mozillademos.org/files/1443/Canvas_moon.png');
await earth.loadFromUrlAsync('https://mdn.mozillademos.org/files/1429/Canvas_earth.png');
} catch (e) {
console.log('solar error:', e);
}
var ctx = canvas.getContext('2d');
//ctx.scale(3, 3);
function init() {
window.requestAnimationFrame(draw);
}
let didScale = false;
function draw() {
if (!ctx) {
return;
}
ctx.globalCompositeOperation = 'destination-over';
ctx.clearRect(0, 0, 300, 300); // clear canvas
ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
ctx.save();
ctx.translate(150, 150);
// Earth
var time = new Date();
ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds());
ctx.translate(105, 0);
ctx.fillRect(0, -12, 40, 24); // Shadow
ctx.drawImage(earth, -12, -12);
// Moon
ctx.save();
ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds());
ctx.translate(0, 28.5);
ctx.drawImage(moon, -3.5, -3.5);
ctx.restore();
ctx.restore();
ctx.beginPath();
ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit
ctx.stroke();
ctx.drawImage(sun, 0, 0, 300, 300);
// if (!didScale) {
// ctx.scale(canvas.clientWidth / 300, canvas.clientHeight / 300);
// didScale = true;
// }
window.requestAnimationFrame(draw);
}
init();
}
/* TODO after SVG
import * as d3 from 'd3';
d3Example(canvas){
var mouse = [480, 250],
count = 0;
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var g = svg.selectAll("g")
.data(d3.range(25))
.enter().append("g")
.attr("transform", "translate(" + mouse + ")");
g.append("rect")
.attr("rx", 6)
.attr("ry", 6)
.attr("x", -12.5)
.attr("y", -12.5)
.attr("width", 25)
.attr("height", 25)
.attr("transform", function(d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; })
.style("fill", d3.scale.category20c());
g.datum(function(d) {
return {center: mouse.slice(), angle: 0};
});
svg.on("mousemove", function() {
mouse = d3.mouse(this);
});
d3.timer(function() {
count++;
g.attr("transform", function(d, i) {
d.center[0] += (mouse[0] - d.center[0]) / (i + 5);
d.center[1] += (mouse[1] - d.center[1]) / (i + 5);
d.angle += Math.sin((count + i) / 10) * 7;
return "translate(" + d.center + ")rotate(" + d.angle + ")";
});
});
}
*/
chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)',
};
MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
COLORS = ['#4dc9f6', '#f67019', '#f53794', '#537bc4', '#acc236', '#166a8f', '#00a950', '#58595b', '#8549ba'];
utils = {
// Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
srand: function (seed) {
this._seed = seed;
},
rand: function (min?, max?) {
var seed = this._seed;
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
this._seed = (seed * 9301 + 49297) % 233280;
return min + (this._seed / 233280) * (max - min);
},
numbers: function (config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 1;
var from = cfg.from || [];
var count = cfg.count || 8;
var decimals = cfg.decimals || 8;
var continuity = cfg.continuity || 1;
var dfactor = Math.pow(10, decimals) || 0;
var data = [];
var i, value;
for (i = 0; i < count; ++i) {
value = (from[i] || 0) + this.rand(min, max);
if (this.rand() <= continuity) {
data.push(Math.round(dfactor * value) / dfactor);
} else {
data.push(null);
}
}
return data;
},
labels: function (config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 100;
var count = cfg.count || 8;
var step = (max - min) / count;
var decimals = cfg.decimals || 8;
var dfactor = Math.pow(10, decimals) || 0;
var prefix = cfg.prefix || '';
var values = [];
var i;
for (i = min; i < max; i += step) {
values.push(prefix + Math.round(dfactor * i) / dfactor);
}
return values;
},
months: (config) => {
var cfg = config || {};
var count = cfg.count || 12;
var section = cfg.section;
var values = [];
var i, value;
for (i = 0; i < count; ++i) {
value = this.MONTHS[Math.ceil(i) % 12];
values.push(value.substring(0, section));
}
return values;
},
color: (index) => {
return this.COLORS[index % this.COLORS.length];
},
transparentize: (color, opacity?) => {
var alpha = (opacity === undefined ? 0.5 : 1 - opacity) * 255;
const c = new Color(color);
const newColor = new Color(alpha, c.r, c.g, c.b);
return `rgba(${newColor.r},${newColor.g},${newColor.b},${newColor.a / 255})`;
},
};
randomScalingFactor() {
return Math.round(Math.random() * 100);
}
polarChart(canvas) {
var DATA_COUNT = 7;
this.utils.srand(110);
function colorize(opaque, hover, ctx) {
var v = ctx.dataset.data[ctx.dataIndex];
var c = v < 35 ? '#D60000' : v < 55 ? '#F46300' : v < 75 ? '#0358B6' : '#44DE28';
var opacity = hover ? 1 - Math.abs(v / 150) - 0.2 : 1 - Math.abs(v / 150);
return opaque ? c : this.utils.transparentize(c, opacity);
}
function hoverColorize(ctx) {
return colorize(false, true, ctx);
}
function generateData() {
return this.utils.numbers({
count: DATA_COUNT,
min: 0,
max: 100,
});
}
var data = {
datasets: [
{
data: generateData(),
},
],
};
var options = {
legend: false,
tooltips: false,
elements: {
arc: {
backgroundColor: colorize.bind(null, false, false),
hoverBackgroundColor: hoverColorize,
},
},
};
var chart = new Chart(canvas, {
type: 'polarArea',
data: data,
options: options,
});
// eslint-disable-next-line no-unused-vars
function randomize() {
chart.data.datasets.forEach(function (dataset) {
dataset.data = generateData();
});
chart.update();
}
// eslint-disable-next-line no-unused-vars
var addData = function () {
var newData = Math.round(Math.random() * 100);
chart.data.datasets[0].data.push(newData);
chart.update();
};
// eslint-disable-next-line no-unused-vars
function removeData() {
chart.data.datasets[0].data.pop();
chart.update();
}
setTimeout(() => {
addData();
setTimeout(() => {
randomize();
setTimeout(() => {
removeData();
}, 3000);
}, 3000);
}, 3000);
}
bubbleChart(canvas) {
var DATA_COUNT = 16;
var MIN_XY = -150;
var MAX_XY = 100;
this.utils.srand(110);
function colorize(opaque, context) {
var value = context.dataset.data[context.dataIndex];
var x = value.x / 100;
var y = value.y / 100;
var r = x < 0 && y < 0 ? 250 : x < 0 ? 150 : y < 0 ? 50 : 0;
var g = x < 0 && y < 0 ? 0 : x < 0 ? 50 : y < 0 ? 150 : 250;
var b = x < 0 && y < 0 ? 0 : x > 0 && y > 0 ? 250 : 150;
var a = opaque ? 1 : (0.5 * value.v) / 1000;
return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
}
const generateData = () => {
var data = [];
var i;
for (i = 0; i < DATA_COUNT; ++i) {
data.push({
x: this.utils.rand(MIN_XY, MAX_XY),
y: this.utils.rand(MIN_XY, MAX_XY),
v: this.utils.rand(0, 1000),
});
}
return data;
};
var data = {
datasets: [
{
data: generateData(),
},
{
data: generateData(),
},
],
};
var options = {
aspectRatio: canvas.width / canvas.height,
devicePixelRatio: 1,
legend: false,
tooltips: false,
responsive: true,
elements: {
point: {
backgroundColor: colorize.bind(null, false),
borderColor: colorize.bind(null, true),
borderWidth: function (context) {
return Math.min(Math.max(1, context.datasetIndex + 1), 8);
},
hoverBackgroundColor: 'transparent',
hoverBorderColor: (context) => {
return this.utils.color(context.datasetIndex);
},
hoverBorderWidth: function (context) {
var value = context.dataset.data[context.dataIndex];
return Math.round((8 * value.v) / 1000);
},
radius: function (context) {
var value = context.dataset.data[context.dataIndex];
var size = context.chart.width;
var base = Math.abs(value.v) / 1000;
return (size / 24) * base;
},
},
},
};
var chart = new Chart(canvas.getContext('2d'), {
type: 'bubble',
data: data,
options: options,
});
// eslint-disable-next-line no-unused-vars
function randomize() {
chart.data.datasets.forEach(function (dataset) {
dataset.data = generateData();
});
chart.update();
}
// eslint-disable-next-line no-unused-vars
function addDataset() {
chart.data.datasets.push({
data: generateData(),
});
chart.update();
}
// eslint-disable-next-line no-unused-vars
function removeDataset() {
chart.data.datasets.shift();
chart.update();
}
setTimeout(() => {
addDataset();
}, 5000);
}
hBarChart(canvas) {
var color = Chart.helpers.color;
var horizontalBarChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'Dataset 1',
backgroundColor: this.utils.transparentize(this.chartColors.red, 0.5),
borderColor: this.chartColors.red,
borderWidth: 1,
data: [this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor()],
},
{
label: 'Dataset 2',
backgroundColor: this.utils.transparentize(this.chartColors.blue, 0.5),
borderColor: this.chartColors.blue,
data: [this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor()],
},
],
};
const myHorizontalBar = new Chart(canvas, {
type: 'horizontalBar',
data: horizontalBarChartData,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each horizontal bar to be 2px wide
elements: {
rectangle: {
borderWidth: 2,
},
},
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'right',
},
title: {
display: true,
text: 'Chart.js Horizontal Bar Chart',
},
},
});
const randomizeData = () => {
var zero = Math.random() < 0.2;
horizontalBarChartData.datasets.forEach((dataset) => {
dataset.data = dataset.data.map(() => {
return zero ? 0.0 : this.randomScalingFactor();
});
});
myHorizontalBar.update();
};
var colorNames = Object.keys(this.chartColors);
const addDataset = () => {
var colorName = colorNames[horizontalBarChartData.datasets.length % colorNames.length];
var dsColor = this.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (horizontalBarChartData.datasets.length + 1),
backgroundColor: color(dsColor).alpha(0.5).rgbString(),
borderColor: dsColor,
data: [],
};
for (var index = 0; index < horizontalBarChartData.labels.length; ++index) {
newDataset.data.push(this.randomScalingFactor());
}
horizontalBarChartData.datasets.push(newDataset);
myHorizontalBar.update();
};
const addData = () => {
if (horizontalBarChartData.datasets.length > 0) {
var month = this.MONTHS[horizontalBarChartData.labels.length % this.MONTHS.length];
horizontalBarChartData.labels.push(month);
for (var index = 0; index < horizontalBarChartData.datasets.length; ++index) {
horizontalBarChartData.datasets[index].data.push(this.randomScalingFactor());
}
myHorizontalBar.update();
}
};
function removeDataset() {
horizontalBarChartData.datasets.pop();
myHorizontalBar.update();
}
function removeData() {
horizontalBarChartData.labels.splice(-1, 1); // remove the label first
horizontalBarChartData.datasets.forEach(function (dataset) {
dataset.data.pop();
});
myHorizontalBar.update();
}
}
dataSets(canvas) {
var presets = this.chartColors;
var inputs = {
min: 20,
max: 80,
count: 8,
decimals: 2,
continuity: 1,
};
const generateData = () => {
return this.utils.numbers(inputs);
};
const generateLabels = () => {
return this.utils.months({ count: inputs.count });
};
this.utils.srand(42);
var data = {
labels: generateLabels(),
datasets: [
{
backgroundColor: this.utils.transparentize(presets.red),
borderColor: presets.red,
data: generateData(),
hidden: true,
label: 'D0',
},
{
backgroundColor: this.utils.transparentize(presets.orange),
borderColor: presets.orange,
data: generateData(),
label: 'D1',
fill: '-1',
},
{
backgroundColor: this.utils.transparentize(presets.yellow),
borderColor: presets.yellow,
data: generateData(),
hidden: true,
label: 'D2',
fill: 1,
},
{
backgroundColor: this.utils.transparentize(presets.green),
borderColor: presets.green,
data: generateData(),
label: 'D3',
fill: '-1',
},
{
backgroundColor: this.utils.transparentize(presets.blue),
borderColor: presets.blue,
data: generateData(),
label: 'D4',
fill: '-1',
},
{
backgroundColor: this.utils.transparentize(presets.grey),
borderColor: presets.grey,
data: generateData(),
label: 'D5',
fill: '+2',
},
{
backgroundColor: this.utils.transparentize(presets.purple),
borderColor: presets.purple,
data: generateData(),
label: 'D6',
fill: false,
},
{
backgroundColor: this.utils.transparentize(presets.red),
borderColor: presets.red,
data: generateData(),
label: 'D7',
fill: 8,
},
{
backgroundColor: this.utils.transparentize(presets.orange),
borderColor: presets.orange,
data: generateData(),
hidden: true,
label: 'D8',
fill: 'end',
},
],
};
var options = {
responsive: true,
maintainAspectRatio: false,
spanGaps: false,
elements: {
line: {
tension: 0.000001,
},
},
scales: {
yAxes: [
{
stacked: true,
},
],
},
plugins: {
filler: {
propagate: false,
},
'samples-filler-analyser': {
target: 'chart-analyser',
},
},
};
var chart = new Chart(canvas, {
type: 'line',
data: data,
options: options,
});
// eslint-disable-next-line no-unused-vars
function togglePropagate(btn) {
chart.options.plugins.filler.propagate = btn.classList.toggle('btn-on');
chart.update();
}
// eslint-disable-next-line no-unused-vars
function toggleSmooth(btn) {
var value = btn.classList.toggle('btn-on');
chart.options.elements.line.tension = value ? 0.4 : 0.000001;
chart.update();
}
// eslint-disable-next-line no-unused-vars
function randomize() {
chart.data.datasets.forEach(function (dataset) {
dataset.data = generateData();
});
chart.update();
}
}
chartJSPie(canvas) {
var config = {
type: 'pie',
data: {
datasets: [
{
data: [this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor(), this.randomScalingFactor()],
backgroundColor: [this.chartColors.red, this.chartColors.orange, this.chartColors.yellow, this.chartColors.green, this.chartColors.blue],
label: 'Dataset 1',
},
],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
responsive: true,
maintainAspectRatio: false,
},
};
const myPie = new Chart(canvas.getContext('2d'), config);
}
chart;
chartJS(canvas) {
var ctx = canvas.getContext('2d');
if (this.chart) {
this.chart.resize();
} else {
this.chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)'],
borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)'],
borderWidth: 1,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
}
}
toggle(args) {
//vm.set("show", !vm.get("show"));
// drawPatternWithCanvas(canvas);
}
clear2D(canvas) {
const ctx = canvas.getContext('2d');
ctx.fillColor = 'black';
ctx.strokeColor = 'black';
ctx.clearRect(0, 0, canvas.getMeasuredWidth(), canvas.getMeasuredHeight());
}
clearGL(canvas) {
const ctx = canvas.getContext('webgl');
ctx.clearColor(1, 1, 1, 1);
ctx.clear(ctx.COLOR_BUFFER_BIT);
}
clearGL2(canvas) {
const ctx = canvas.getContext('webgl2');
ctx.clearColor(1, 1, 1, 1);
ctx.clear(ctx.COLOR_BUFFER_BIT);
}
changeTextColor(value) {
this.set('textColor', value);
}
last;
cleanup() {
switch (this.last) {
case 'swarm':
cancelSwarm();
break;
case 'colorRain':
cancelRain();
break;
case 'particlesLarge':
cancelParticlesLarge();
break;
case 'rainbowOctopus':
cancelRainbowOctopus();
break;
case 'particlesColor':
cancelParticlesColor();
break;
case 'textures':
break;
case 'drawElements':
break;
case 'interactiveCube':
cancelInteractiveCube();
break;
case 'main':
cancelMain();
break;
case 'draw_instanced':
break;
case 'draw_image_space':
break;
case 'fog':
cancelFog();
break;
case 'environmentMap':
cancelEnvironmentMap();
break;
default:
break;
}
}
save2D() {
if (!this.last) {
this.canvas.getContext('2d').save();
}
}
restore2D() {
this.canvas.getContext('2d').restore();
}
tap(args) {
const type = args.view.bindingContext.type || null;
this.changeTextColor('white');
this.cleanup();
switch (type) {
case 'swarm':
this.save2D();
this.clear2D(this.canvas);
this.restore2D();
swarm(this.canvas);
this.changeTextColor('white');
this.last = 'swarm';
break;
case 'colorRain':
this.save2D();
this.clear2D(this.canvas);
this.restore2D();
colorRain(this.canvas);
this.changeTextColor('white');
this.last = 'colorRain';
break;
case 'particlesLarge':
this.save2D();
this.clear2D(this.canvas);
this.restore2D();
particlesLarge(this.canvas);
this.changeTextColor('black');
this.last = 'particlesLarge';
break;
case 'rainbowOctopus':
this.save2D();
this.clear2D(this.canvas);
this.restore2D();
rainbowOctopus(this.canvas);
this.changeTextColor('black');
this.last = 'rainbowOctopus';
break;
case 'particlesColor':
this.save2D();
this.clear2D(this.canvas);
this.restore2D();
particlesColor(this.canvas);
this.changeTextColor('white');
this.last = 'particlesColor';
break;
case 'textures':
this.clearGL(this.canvas);
textures(this.canvas);
this.changeTextColor('white');
this.last = 'textures';
break;
case 'drawElements':
this.clearGL(this.canvas);
drawElements(this.canvas);
this.changeTextColor('black');
this.last = 'drawElements';
break;
case 'drawModes':
this.clearGL(this.canvas);
drawModes(this.canvas);
this.changeTextColor('black');
this.last = 'drawModes';
break;
case 'interactiveCube':
this.clearGL(this.canvas);
interactiveCube(this.canvas);
this.last = 'interactiveCube';
break;
case 'main':
this.clearGL(this.canvas);
main(this.canvas);
this.changeTextColor('white');
break;
case 'draw_instanced':
this.clearGL2(this.canvas);
draw_instanced(this.canvas);
this.last = 'draw_instanced';
break;
case 'draw_image_space':
this.clearGL2(this.canvas);
draw_image_space(this.canvas);
this.last = 'draw_image_space';
break;
case 'cubeRotationRotation':
this.clearGL2(this.canvas);
cubeRotationRotation(this.canvas);
this.last = 'draw_image_space';
this.changeTextColor('black');
break;
case 'fog':
this.clearGL2(this.canvas);
fog(this.canvas);
this.last = 'fog';
break;
case 'environmentMap':
this.clearGL2(this.canvas);
environmentMap(this.canvas);
this.last = 'environmentMap';
break;
default:
break;
}
}
clear(args) {
// ctx.clearRect(0, 0, canvas.getMeasuredWidth(), canvas.getMeasuredHeight());
// ctx.fillStyle = 'red'
///ctx.fillRect(0, 0, canvas.getMeasuredWidth(), canvas.getMeasuredHeight());
//const imageData = ctx.createImageData(100, 100);
/*
// Iterate through every pixel
for (let i = 0; i < imageData.data.length; i += 4) {
// Modify pixel data
imageData.data[i] = 190; // R value
imageData.data[i + 1] = 0; // G value
imageData.data[i + 2] = 210; // B value
imageData.data[i + 3] = 255; // A value
}
ctx.createImageData(imageData);
// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);
*/
}
show: boolean = true;
textColor: string = 'black';
items = new ObservableArray([
{ name: '2D Swarm', type: 'swarm' },
{ name: '2D ColorRain', type: 'colorRain' },
{ name: '2D Particles Large', type: 'particlesLarge' },
{ name: '2D Rainbow Octopus', type: 'rainbowOctopus' },
{ name: '2D Particles Color', type: 'particlesColor' },
{ name: 'WEBGL textures', type: 'textures' },
{ name: 'WEBGL Draw Elements', type: 'drawElements' },
{ name: 'WEBGL Draw Modes', type: 'drawModes' },
{ name: 'WEBGL InteractiveCube', type: 'interactiveCube' },
{ name: 'WEBGL Cube Rotation With Image', type: 'main' },
{ name: 'WEBGL2 Draw Instanced', type: 'draw_instanced' },
{ name: 'WEBGL2 Draw ImageSpace', type: 'draw_image_space' },
{
name: 'WEBGL2 Cube Rotation With Cube Roating inside',
type: 'cubeRotationRotation',
},
{ name: 'WEBGL2 Fog', type: 'fog' },
{
name: 'WEBGL2 Environment Map Roatating Cube',
type: 'environmentMap',
},
]);
arcAnimation(ctx) {
ctx.scale(2, 2);
const mouse = { x: 0, y: 0 };
let r = 100; // Radius
const p0 = { x: 0, y: 50 };
const p1 = { x: 100, y: 100 };
const p2 = { x: 150, y: 50 };
const p3 = { x: 200, y: 100 };
const labelPoint = function (p, offset, i = 0) {
const { x, y } = offset;
ctx.beginPath();
ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
ctx.fill('');
ctx.fillText(`${i}:(${p.x}, ${p.y})`, p.x + x, p.y + y);
};
const drawPoints = function (points) {
for (let i = 0; i < points.length; i++) {
var p = points[i];
labelPoint(p, { x: 0, y: -20 }, i);
}
};
// Draw arc
const drawArc = function ([p0, p1, p2], r) {
ctx.beginPath();
ctx.moveTo(p0.x, p0.y);
ctx.arcTo(p1.x, p1.y, p2.x, p2.y, r);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
};
let t0 = 0;
let rr = 0; // the radius that changes over time
let a = 0; // angle
let PI2 = Math.PI * 2;
const loop = (t) => {
t0 = t / 1000;
a = t0 % PI2;
rr = Math.abs(Math.cos(a) * r);
ctx.clearRect(0, 0, this.canvas.getMeasuredWidth(), this.canvas.getMeasuredHeight());
drawArc([p1, p2, p3], rr);
drawPoints([p1, p2, p3]);
requestAnimationFrame(loop);
};
loop(0);
}
} | the_stack |
export namespace EventManagementModels {
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}
/**
*
* @export
* @interface BaseEvent
*/
export interface BaseEvent {
/**
* Unique identifier of the event type (filterable, not updatable)
* @type {string}
* @memberof BaseEvent
*/
typeId?: string;
/**
* Correlation ID of the event. It can be used to group related events (filterable, not updatable)
* @type {string}
* @memberof BaseEvent
*/
correlationId?: string;
/**
* Timestamp attached to the event in UTC format (filterable, not updatable)
* @type {string}
* @memberof BaseEvent
*/
timestamp: string;
/**
* Entity attached to the event (filterable, not updatable)
* @type {string}
* @memberof BaseEvent
*/
entityId: string;
}
/**
*
* @export
* @interface BaseEventResponse
*/
export interface BaseEventResponse {
/**
* Unique identifier of the event
* @type {string}
* @memberof BaseEventResponse
*/
id: string;
/**
* Unique identifier of the event type (filterable, not updatable)
* @type {string}
* @memberof BaseEventResponse
*/
typeId: string;
/**
* Correlation ID of the event. It can be used to group related events (filterable, not updatable)
* @type {string}
* @memberof BaseEventResponse
*/
correlationId: string;
/**
* Timestamp attached to the event in UTC format (filterable, not updatable)
* @type {string}
* @memberof BaseEventResponse
*/
timestamp: string;
/**
* Entity attached to the event (filterable, not updatable)
* @type {string}
* @memberof BaseEventResponse
*/
entityId: string;
/**
* Incremental counter for optimistic concurrency control
* @type {number}
* @memberof BaseEventResponse
*/
etag: number;
/**
*
* @type {SharingResource}
* @memberof BaseEventResponse
*/
sharing?: SharingResource;
/**
*
* @type {BaseEventResponseLinks}
* @memberof BaseEventResponse
*/
_links: BaseEventResponseLinks;
}
/**
*
* @export
* @interface BaseEventResponseLinks
*/
export interface BaseEventResponseLinks {
/**
*
* @type {RelSelf}
* @memberof BaseEventResponseLinks
*/
self?: RelSelf;
}
/**
* Details about an event within a bulk create job
* @export
* @interface CreateEventDetailedDescription
*/
export interface CreateEventDetailedDescription {
/**
* created event resource or the input event in case of failure
* @type {string}
* @memberof CreateEventDetailedDescription
*/
event?: string;
/**
* status code of event creation
* @type {string}
* @memberof CreateEventDetailedDescription
*/
resultCode?: string;
/**
* details about failing event creation
* @type {string}
* @memberof CreateEventDetailedDescription
*/
errorMessage?: string;
}
/**
*
* @export
* @interface CreateEventsJob
*/
export interface CreateEventsJob {
/**
* - List of events to create
* @type {Array<CustomEvent>}
* @memberof CreateEventsJob
*/
events: Array<CustomEvent>;
}
/**
* Details about the job in case of FINISHED and FINISHED_WITH_ERROR
* @export
* @interface CreateJobDetails
*/
export interface CreateJobDetails {
/**
*
* @type {Array<CreateEventDetailedDescription>}
* @memberof CreateJobDetails
*/
resultDescription?: Array<CreateEventDetailedDescription>;
}
/**
*
* @export
* @interface CreateJobResource
*/
export interface CreateJobResource extends JobResource {
/**
*
* @type {CreateJobDetails}
* @memberof CreateJobResource
*/
details?: CreateJobDetails;
}
/**
* @export
* @namespace CreateJobResource
*/
export namespace CreateJobResource {}
/**
*
* @export
* @interface CustomEvent
*/
export interface CustomEvent extends BaseEvent {}
/**
*
* @export
* @interface CustomEventCreated
*/
export interface CustomEventCreated extends BaseEventResponse {}
/**
*
* @export
* @interface CustomEventResponse
*/
export interface CustomEventResponse extends BaseEventResponse {}
/**
*
* @export
* @interface CustomEventUpdated
*/
export interface CustomEventUpdated extends BaseEventResponse {}
/**
*
* @export
* @interface DeleteEventsJob
*/
export interface DeleteEventsJob {
/**
* - The `timestamp` property can be filtered by `before`, `after` and `between` functions. - At least `typeId` property must be provided in filter expression. - Multiple `typeId` expressions (by using and, or logical operators) in filter parameter is not allowed. Only equality function is supported on it. - Negation of `typeId` in filter expression is not allowed.
* @type {any}
* @memberof DeleteEventsJob
*/
filter: any;
}
/**
* Details about the job in case of FINISHED and FINISHED_WITH_ERROR
* @export
* @interface DeleteJobDetails
*/
export interface DeleteJobDetails {
/**
* status code describes the job's execution result
* @type {string}
* @memberof DeleteJobDetails
*/
resultCode?: string;
/**
* information about - how many events deleted or - what error happened
* @type {string}
* @memberof DeleteJobDetails
*/
resultDescription?: string;
}
/**
*
* @export
* @interface DeleteJobResource
*/
export interface DeleteJobResource extends JobResource {
/**
*
* @type {DeleteJobDetails}
* @memberof DeleteJobResource
*/
details?: DeleteJobDetails;
}
/**
* @export
* @namespace DeleteJobResource
*/
export namespace DeleteJobResource {}
/**
*
* @export
* @interface Errors
*/
export interface Errors extends Array<ErrorsInner> {}
/**
*
* @export
* @interface ErrorsInner
*/
export interface ErrorsInner {
/**
*
* @type {string}
* @memberof ErrorsInner
*/
logref?: string;
/**
*
* @type {string}
* @memberof ErrorsInner
*/
message?: string;
}
/**
*
* @export
* @interface EventType
*/
export interface EventType {
/**
* ID of the created event type
* @type {string}
* @memberof EventType
*/
id?: string;
/**
* Name of the event type
* @type {string}
* @memberof EventType
*/
name: string;
/**
* Parent event type ID
* @type {string}
* @memberof EventType
*/
parentId?: string;
/**
* Time to live in days
* @type {number}
* @memberof EventType
*/
ttl?: number;
/**
* Scope of the event type
* @type {string}
* @memberof EventType
*/
scope?: EventType.ScopeEnum;
/**
*
* @type {Array<Field>}
* @memberof EventType
*/
fields: Array<Field>;
}
/**
* @export
* @namespace EventType
*/
export namespace EventType {
/**
* @export
* @enum {string}
*/
export enum ScopeEnum {
LOCAL = "LOCAL",
GLOBAL = "GLOBAL",
}
}
/**
*
* @export
* @interface EventTypePatch
*/
export interface EventTypePatch {
/**
* Type of the operation to be made
* @type {string}
* @memberof EventTypePatch
*/
op: EventTypePatch.OpEnum;
/**
* Identifying a specific attribute/field whereon the operation should be made
* @type {string}
* @memberof EventTypePatch
*/
path: string;
/**
* New value for the given attribute or the field, that should be added, depending on the *op* value
* @type {string}
* @memberof EventTypePatch
*/
value: string;
}
/**
* @export
* @namespace EventTypePatch
*/
export namespace EventTypePatch {
/**
* @export
* @enum {string}
*/
export enum OpEnum {
Add = "add",
Replace = "replace",
}
}
/**
*
* @export
* @interface EventTypeResponse
*/
export interface EventTypeResponse {
/**
* ID of the created event type
* @type {string}
* @memberof EventTypeResponse
*/
id: string;
/**
* Name of the event type
* @type {string}
* @memberof EventTypeResponse
*/
name: string;
/**
* Parent event type ID
* @type {string}
* @memberof EventTypeResponse
*/
parentId: string;
/**
* Time to live in days
* @type {number}
* @memberof EventTypeResponse
*/
ttl: number;
/**
*
* @type {number}
* @memberof EventTypeResponse
*/
etag: number;
/**
* The owner who created the event type
* @type {string}
* @memberof EventTypeResponse
*/
owner: string;
/**
* Scope of the event type
* @type {string}
* @memberof EventTypeResponse
*/
scope: EventTypeResponse.ScopeEnum;
/**
*
* @type {Array<Field>}
* @memberof EventTypeResponse
*/
fields: Array<Field>;
/**
*
* @type {SharingResource}
* @memberof EventTypeResponse
*/
sharing?: SharingResource;
/**
*
* @type {EventTypeResponseLinks}
* @memberof EventTypeResponse
*/
_links: EventTypeResponseLinks;
}
/**
* @export
* @namespace EventTypeResponse
*/
export namespace EventTypeResponse {
/**
* @export
* @enum {string}
*/
export enum ScopeEnum {
LOCAL = "LOCAL",
GLOBAL = "GLOBAL",
}
}
/**
*
* @export
* @interface EventTypeResponseLinks
*/
export interface EventTypeResponseLinks {
/**
*
* @type {RelSelf}
* @memberof EventTypeResponseLinks
*/
self?: RelSelf;
/**
*
* @type {RelEvents}
* @memberof EventTypeResponseLinks
*/
events?: RelEvents;
}
/**
*
* @export
* @interface Field
*/
export interface Field {
/**
*
* @type {string}
* @memberof Field
*/
name: string;
/**
*
* @type {boolean}
* @memberof Field
*/
filterable?: boolean;
/**
*
* @type {boolean}
* @memberof Field
*/
required?: boolean;
/**
*
* @type {boolean}
* @memberof Field
*/
updatable?: boolean;
/**
* Note that the LINK type is not a plain HREF. The value for the LINK type should be given between quotation marks.
* @type {string}
* @memberof Field
*/
type: Field.TypeEnum;
/**
* This field is applicable only if the field's type is ENUM, otherwise it should be skipped. The values must be strings.
* @type {Array<string>}
* @memberof Field
*/
values?: Array<string>;
}
/**
* @export
* @namespace Field
*/
export namespace Field {
/**
* @export
* @enum {string}
*/
export enum TypeEnum {
STRING = "STRING",
INTEGER = "INTEGER",
DOUBLE = "DOUBLE",
BOOLEAN = "BOOLEAN",
LINK = "LINK",
TIMESTAMP = "TIMESTAMP",
UUID = "UUID",
ENUM = "ENUM",
}
}
/**
*
* @export
* @interface InfoResponse
*/
export interface InfoResponse {
/**
*
* @type {InfoResponseSelf}
* @memberof InfoResponse
*/
self?: InfoResponseSelf;
/**
*
* @type {InfoResponseEvents}
* @memberof InfoResponse
*/
events?: InfoResponseEvents;
/**
*
* @type {InfoResponseEventTypes}
* @memberof InfoResponse
*/
eventTypes?: InfoResponseEventTypes;
/**
*
* @type {InfoResponseDeleteEventsJobs}
* @memberof InfoResponse
*/
deleteEventsJobs?: InfoResponseDeleteEventsJobs;
/**
*
* @type {InfoResponseCreateEventsJobs}
* @memberof InfoResponse
*/
createEventsJobs?: InfoResponseCreateEventsJobs;
}
/**
*
* @export
* @interface InfoResponseCreateEventsJobs
*/
export interface InfoResponseCreateEventsJobs {
/**
*
* @type {string}
* @memberof InfoResponseCreateEventsJobs
*/
href?: string;
/**
*
* @type {boolean}
* @memberof InfoResponseCreateEventsJobs
*/
templated?: boolean;
}
/**
*
* @export
* @interface InfoResponseDeleteEventsJobs
*/
export interface InfoResponseDeleteEventsJobs {
/**
*
* @type {string}
* @memberof InfoResponseDeleteEventsJobs
*/
href?: string;
/**
*
* @type {boolean}
* @memberof InfoResponseDeleteEventsJobs
*/
templated?: boolean;
}
/**
*
* @export
* @interface InfoResponseEventTypes
*/
export interface InfoResponseEventTypes {
/**
*
* @type {string}
* @memberof InfoResponseEventTypes
*/
href?: string;
/**
*
* @type {boolean}
* @memberof InfoResponseEventTypes
*/
templated?: boolean;
}
/**
*
* @export
* @interface InfoResponseEvents
*/
export interface InfoResponseEvents {
/**
*
* @type {string}
* @memberof InfoResponseEvents
*/
href?: string;
/**
*
* @type {boolean}
* @memberof InfoResponseEvents
*/
templated?: boolean;
}
/**
*
* @export
* @interface InfoResponseSelf
*/
export interface InfoResponseSelf {
/**
*
* @type {string}
* @memberof InfoResponseSelf
*/
href?: string;
}
/**
*
* @export
* @interface JobResource
*/
export interface JobResource {
/**
* Unique identifier of the job
* @type {string}
* @memberof JobResource
*/
id?: string;
/**
* State of the job
* @type {string}
* @memberof JobResource
*/
state?: JobResource.StateEnum;
}
/**
* @export
* @namespace JobResource
*/
export namespace JobResource {
/**
* @export
* @enum {string}
*/
export enum StateEnum {
ACCEPTED = "ACCEPTED",
INPROGRESS = "IN_PROGRESS",
FINISHED = "FINISHED",
FINISHEDWITHERROR = "FINISHED_WITH_ERROR",
}
}
/**
*
* @export
* @interface MindsphereStandardEvent
*/
export interface MindsphereStandardEvent extends BaseEvent {
/**
*
* @type {number}
* @memberof MindsphereStandardEvent
*/
severity?: number;
/**
*
* @type {string}
* @memberof MindsphereStandardEvent
*/
description?: string;
/**
*
* @type {string}
* @memberof MindsphereStandardEvent
*/
code?: string;
/**
*
* @type {string}
* @memberof MindsphereStandardEvent
*/
source?: string;
/**
*
* @type {boolean}
* @memberof MindsphereStandardEvent
*/
acknowledged?: boolean;
}
/**
*
* @export
* @interface MindsphereStandardEventResponse
*/
export interface MindsphereStandardEventResponse extends BaseEventResponse {
/**
*
* @type {number}
* @memberof MindsphereStandardEventResponse
*/
severity?: number;
/**
*
* @type {string}
* @memberof MindsphereStandardEventResponse
*/
description?: string;
/**
*
* @type {string}
* @memberof MindsphereStandardEventResponse
*/
code?: string;
/**
*
* @type {string}
* @memberof MindsphereStandardEventResponse
*/
source?: string;
/**
*
* @type {boolean}
* @memberof MindsphereStandardEventResponse
*/
acknowledged?: boolean;
}
/**
*
* @export
* @interface Page
*/
export interface Page {
/**
*
* @type {number}
* @memberof Page
*/
size?: number;
/**
*
* @type {number}
* @memberof Page
*/
totalElements?: number;
/**
*
* @type {number}
* @memberof Page
*/
totalPages?: number;
/**
*
* @type {number}
* @memberof Page
*/
number?: number;
}
/**
*
* @export
* @interface PagingLinks
*/
export interface PagingLinks {
/**
*
* @type {RelFirst}
* @memberof PagingLinks
*/
first?: RelFirst;
/**
*
* @type {SelfLink}
* @memberof PagingLinks
*/
self?: SelfLink;
/**
*
* @type {RelNext}
* @memberof PagingLinks
*/
next?: RelNext;
/**
*
* @type {RelPrev}
* @memberof PagingLinks
*/
prev?: RelPrev;
/**
*
* @type {RelLast}
* @memberof PagingLinks
*/
last?: RelLast;
}
/**
*
* @export
* @interface QueryEventTypesResponse
*/
export interface QueryEventTypesResponse {
/**
*
* @type {QueryEventTypesResponseEmbedded}
* @memberof QueryEventTypesResponse
*/
_embedded?: QueryEventTypesResponseEmbedded;
/**
*
* @type {PagingLinks}
* @memberof QueryEventTypesResponse
*/
_links?: PagingLinks;
/**
*
* @type {Page}
* @memberof QueryEventTypesResponse
*/
page?: Page;
}
/**
*
* @export
* @interface QueryEventTypesResponseEmbedded
*/
export interface QueryEventTypesResponseEmbedded {
/**
*
* @type {Array<EventTypeResponse>}
* @memberof QueryEventTypesResponseEmbedded
*/
eventTypes?: Array<EventTypeResponse>;
}
/**
*
* @export
* @interface QueryEventsResponse
*/
export interface QueryEventsResponse {
/**
*
* @type {QueryEventsResponseEmbedded}
* @memberof QueryEventsResponse
*/
_embedded?: QueryEventsResponseEmbedded;
/**
*
* @type {PagingLinks}
* @memberof QueryEventsResponse
*/
_links?: PagingLinks;
/**
*
* @type {Page}
* @memberof QueryEventsResponse
*/
page?: Page;
}
/**
*
* @export
* @interface QueryEventsResponseEmbedded
*/
export interface QueryEventsResponseEmbedded {
/**
*
* @type {Array<MindsphereStandardEventResponse>}
* @memberof QueryEventsResponseEmbedded
*/
events?: Array<MindsphereStandardEventResponse>;
}
/**
*
* @export
* @interface RelEvents
*/
export interface RelEvents {
/**
*
* @type {string}
* @memberof RelEvents
*/
href?: string;
}
/**
*
* @export
* @interface RelFirst
*/
export interface RelFirst {
/**
*
* @type {string}
* @memberof RelFirst
*/
href?: string;
}
/**
*
* @export
* @interface RelLast
*/
export interface RelLast {
/**
*
* @type {string}
* @memberof RelLast
*/
href?: string;
}
/**
*
* @export
* @interface RelNext
*/
export interface RelNext {
/**
*
* @type {string}
* @memberof RelNext
*/
href?: string;
}
/**
*
* @export
* @interface RelPrev
*/
export interface RelPrev {
/**
*
* @type {string}
* @memberof RelPrev
*/
href?: string;
}
/**
*
* @export
* @interface RelSelf
*/
export interface RelSelf {
/**
*
* @type {string}
* @memberof RelSelf
*/
href?: string;
}
/**
*
* @export
* @interface SelfLink
*/
export interface SelfLink {
/**
*
* @type {string}
* @memberof SelfLink
*/
href?: string;
/**
*
* @type {boolean}
* @memberof SelfLink
*/
templated?: boolean;
}
/**
* Contains sharing information. This sharing information will be available only if 'includeShared' query parameter is 'true' in request.
* @export
* @interface SharingResource
*/
export interface SharingResource {
/**
* List of sharing modes applicable for this resource. The currently supported modes are SHARER, RECEIVER and DEFAULT. SHARER means this resource is shared by my tenant. RECEIVER means this resource is shared with my tenant. DEFAULT means this resource is provide by default. An empty array means this resource is not shared. New modes might be introduced later and clients must expect additional items to be contained in the array.
* @type {Array<string>}
* @memberof SharingResource
*/
modes?: Array<SharingResource.ModesEnum>;
}
/**
* @export
* @namespace SharingResource
*/
export namespace SharingResource {
/**
* @export
* @enum {string}
*/
export enum ModesEnum {
SHARER = "SHARER",
RECEIVER = "RECEIVER",
DEFAULT = "DEFAULT",
}
}
// ! fix: compatibility with old naming
export interface Billboard extends InfoResponse {}
export interface EmbeddedEventsTypesList extends QueryEventTypesResponse {}
export interface EmbeddedEventsList extends QueryEventsResponse {}
} | the_stack |
import { graphql, GraphQLID, GraphQLSchema, printSchema } from "graphql";
import Knex from "knex";
import { has, map, sortBy } from "lodash";
import {
mapArgs,
mapDataSource,
MappedMultiSourceUnionQueryOperation,
MappedSingleSourceQueryOperation,
mapSchema,
operationPresets,
SingleSourceQueryOperationResolver,
useDatabaseConnector,
mapFields,
mapAssociations,
types,
} from "..";
import { setupDepartmentSchema, teardownDepartmentSchema } from "./helpers/setup-department-schema";
import { setupKnex } from "./helpers/setup-knex";
import { MappedDataSource } from "../MappedDataSource";
import { getCount } from "./knex-helpers";
import { removeErrorCodes } from "./helpers/snapshot-sanitizers";
import {
setupUserSchema,
teardownUserSchema,
mapUsersDataSource,
insertFewUsers,
mapUsersDataSourceWithJSONFields,
} from "./helpers/setup-user-schema";
import { Maybe } from "../utils/util-types";
let knex: Knex;
jest.setTimeout(30000);
describe("Integration scenarios", () => {
beforeAll(() => {
knex = setupKnex();
useDatabaseConnector(knex);
});
afterAll(async () => {
await knex.destroy();
});
describe("Conventionally mapped data source", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSource();
schema = mapSchema(operationPresets.defaults(users));
});
afterAll(async () => {
await teardownUserSchema(knex);
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("singular query operation without params", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: {}) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("singular query operation with params", async () => {
const r2 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
name
}
}
`,
);
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
test("singular query operation for non-existent row", async () => {
const r3 = await graphql(
schema,
`
query {
findOneUser(where: { id: 10 }) {
id
name
}
}
`,
);
expect(r3.errors).not.toBeDefined();
expect(r3.data!.findOneUser).toBeNull();
});
test("batch query operation without args", async () => {
const r4 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
id
name
}
}
`,
);
expect(r4.errors).not.toBeDefined();
expect(r4).toMatchSnapshot();
});
test("batch query operations with arguments", async () => {
const r5 = await graphql(
schema,
`
query {
findManyUsers(where: { id: 1 }) {
id
name
}
}
`,
);
expect(r5.errors).not.toBeDefined();
expect(r5).toMatchSnapshot();
});
});
describe("Conventionally mapped data source with JSON fields", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSourceWithJSONFields();
schema = mapSchema(operationPresets.defaults(users));
});
afterAll(async () => {
await teardownUserSchema(knex);
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("singular query operation without params", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: {}) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("singular query operation with params", async () => {
const r2 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
test("batch query operation without args", async () => {
const r4 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r4.errors).not.toBeDefined();
expect(r4).toMatchSnapshot();
});
test("batch query operations with arguments", async () => {
const r5 = await graphql(
schema,
`
query {
findManyUsers(where: { id: 1 }) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r5.errors).not.toBeDefined();
expect(r5).toMatchSnapshot();
});
});
describe("Paginated queries", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await setupUserSchema(knex);
users = mapUsersDataSource();
schema = mapSchema([operationPresets.paginatedFindManyOperation(users)]);
});
afterAll(async () => {
await teardownUserSchema(knex);
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
});
describe("Custom column field mapping", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await knex.schema.createTable("customers", t => {
t.increments("pk");
t.string("first_name");
t.string("last_name");
});
const fields = mapFields({
id: {
sourceColumn: "pk",
type: types.intId,
},
firstName: {
sourceColumn: "first_name",
type: types.string,
},
lastName: {
sourceColumn: "last_name",
type: types.string,
},
});
users = mapDataSource({
name: {
mapped: "User",
stored: "customers",
},
fields,
});
schema = mapSchema(operationPresets.defaults(users));
await knex("customers").insert([
{ pk: 1, first_name: "John", last_name: "Doe" },
{ pk: 2, first_name: "Jane", last_name: "Doe" },
]);
});
afterAll(async () => {
await knex.schema.dropTable("customers");
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("singular query operation", async () => {
const r1 = await graphql(schema, "query { findOneUser(where: {}) { id, firstName, lastName }}");
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const r2 = await graphql(schema, "query { findOneUser(where: {id: 2}) { id, firstName, lastName }}");
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
test("batch query operation", async () => {
const r3 = await graphql(schema, "query { findManyUsers(where: {}) { id, firstName, lastName }}");
expect(r3.errors).not.toBeDefined();
expect(r3).toMatchSnapshot();
});
test("custom mapping of arguments", async () => {
const argMapping = mapArgs({
fullName: {
description: "Full name of user",
type: types.string,
interceptQuery: (qb: Knex.QueryBuilder, value: Maybe<string>) => {
if (!value) return qb;
const names = value.split(" ");
return qb.where({
first_name: names[0],
last_name: names[1],
});
},
},
});
const schema = mapSchema([
new MappedSingleSourceQueryOperation({
name: "findUsersByFullName",
rootSource: users,
singular: true,
args: argMapping,
}),
]);
const r3 = await graphql(
schema,
`
query {
findUsersByFullName(fullName: "John Doe") {
id
firstName
lastName
}
}
`,
);
expect(r3.errors).not.toBeDefined();
expect(r3).toMatchSnapshot();
});
});
describe("Computed fields mapping", () => {
let schema: GraphQLSchema;
beforeAll(async () => {
await knex.schema.createTable("users", t => {
t.increments("id");
t.string("first_name");
t.string("last_name");
t.integer("parent_id")
.unsigned()
.references("id")
.inTable("users");
});
const users: any = mapDataSource({
name: "User",
fields: mapFields({
id: { type: types.intId },
first_name: { type: types.string },
last_name: { type: types.string },
full_name: {
type: types.string,
dependencies: ["first_name", "last_name"],
derive: ({ first_name, last_name }: any) => {
return `${first_name} ${last_name}`;
},
reduce: (row: any, fullName: string) => {
[row.first_name, row.last_name] = fullName.split(" ");
},
},
}),
associations: mapAssociations({
parent: {
target: () => users,
singular: true,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "parent_id",
inRelated: "id",
},
},
children: {
target: () => users,
singular: false,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "id",
inRelated: "parent_id",
},
},
}),
});
schema = mapSchema(operationPresets.query.defaults(users));
await knex("users").insert([
{
id: 1,
first_name: "John",
last_name: "Doe",
},
{
id: 2,
parent_id: 1,
first_name: "Jane",
last_name: "Doe",
},
{
id: 3,
parent_id: 2,
first_name: "John",
last_name: "Delta",
},
]);
});
test("singular query operation", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: {}) {
id
full_name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("nested singular query operation", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
first_name
full_name
parent {
id
first_name
last_name
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const r2 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
first_name
full_name
parent(where: { id: 1 }) {
full_name
children {
id
full_name
children {
id
full_name
}
}
}
}
}
`,
);
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
afterAll(async () => {
await knex.schema.dropTable("users");
});
test("batch query operation", async () => {
const r1 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
id
first_name
full_name
parent {
id
first_name
last_name
}
children {
id
full_name
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
});
describe("Multi-source operations", () => {
describe("Union query", () => {
let generatedSchema: GraphQLSchema;
let students: MappedDataSource, staff: MappedDataSource;
beforeAll(async () => {
await knex.schema.createTable("students", t => {
t.increments("id");
t.string("name");
t.integer("completion_year");
});
await knex.schema.createTable("staff", t => {
t.increments("id");
t.string("name");
t.string("designation");
});
await knex("students").insert([
{
name: "ram",
completion_year: 2009,
},
{
name: "abhi",
completion_year: 2010,
},
]);
await knex("staff").insert([
{
name: "rahman",
designation: "Principal",
},
{
name: "akbar",
designation: "Teacher",
},
]);
students = mapDataSource({
name: "Student",
fields: mapFields({
id: {
type: types.intId,
},
name: {
type: types.string,
},
completion_year: {
type: types.number,
},
}),
});
staff = mapDataSource({
name: { stored: "staff", mapped: "Staff" },
fields: mapFields({
id: {
type: types.intId,
},
name: {
type: types.string,
},
designation: {
type: types.string,
},
}),
});
generatedSchema = mapSchema([
new MappedMultiSourceUnionQueryOperation({
dataSources: () => ({
students: {
selection: () => students,
},
staff: {
selection: () => staff,
},
}),
unionMode: "union",
name: `findManyUsers`,
singular: false,
shallow: false,
description: undefined,
}),
]);
});
afterAll(async () => {
await knex.schema.dropTable("students");
await knex.schema.dropTable("staff");
});
test("generated schema", () => {
expect(printSchema(generatedSchema)).toMatchSnapshot();
});
test("batch query operation", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findManyUsers(where: {}) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(sortBy(r1.data!.findManyUsers, "name")).toMatchSnapshot();
});
});
});
describe("Data sources associated by joins", () => {
[
["with primary key", true],
["without primary key", false],
].forEach(([d1, hasPrimaryKey]) => {
describe(d1 as string, () => {
let tags: MappedDataSource, products: MappedDataSource, departments: MappedDataSource;
let generatedSchema: GraphQLSchema;
beforeAll(async () => {
await setupDepartmentSchema(knex);
await knex("tags").insert([{ name: "imported" }, { name: "third-party" }]);
await knex("departments").insert([{ name: "textile" }, { name: "heavy goods" }]);
await knex("products").insert([
{ name: "silk gown", department_id: 1 },
{ name: "steel welding machine", department_id: 2 },
{ name: "harpoon launcher", department_id: 2 },
{ name: "bulldozer", department_id: 2 },
{ name: "tractor", department_id: 2 },
]);
await knex("product_tag_associators").insert([
{ product_id: 1, tag_id: 1 },
{ product_id: 2, tag_id: 2 },
{ product_id: 2, tag_id: 1 },
]);
const fields = mapFields({
id: {
type: types.intId,
isPrimary: hasPrimaryKey ? true : undefined,
},
name: {
type: types.string,
},
});
// @snippet:start mapAssociation_multiJoin_custom
/// import {mapDataSource, mapAssociations} from "greldal";
tags = mapDataSource({
name: "Tag",
fields,
associations: mapAssociations({
products: {
target: () => products,
singular: false,
fetchThrough: [
{
join: joinBuilder =>
joinBuilder
.leftOuterJoin("product_tag_associators", "tag_id", "=", "id")
.leftOuterJoin("products", "id", "=", "product_id"),
},
],
},
}),
});
// @snippet:end
// @snippet:start mapAssociation_leftOuterJoin_default
/// import {mapDataSource, mapAssociations} from "greldal";
products = mapDataSource({
name: "Product",
fields,
associations: mapAssociations({
department: {
target: () => departments,
singular: true,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "department_id",
inRelated: "id",
},
},
}),
});
// @snippet:end
departments = mapDataSource({
name: "Department",
fields,
associations: mapAssociations({
products: {
target: () => products,
singular: false,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "id",
inRelated: "department_id",
},
},
}),
});
generatedSchema = mapSchema([
...operationPresets.defaults(tags),
...operationPresets.defaults(departments),
...operationPresets.defaults(products),
]);
});
afterAll(async () => {
await teardownDepartmentSchema(knex);
});
test("generated schema", () => {
expect(printSchema(generatedSchema)).toMatchSnapshot();
});
test("query operations involving auto-inferred binary joins", async () => {
const r1 = await graphql(
generatedSchema,
// @snippet:start mapAssociation_leftOuterJoin_default_query
`
query {
findOneProduct(where: {}) {
id
name
department(where: {}) {
id
name
}
}
}
`,
// @snippet:end
);
expect(r1).toMatchSnapshot();
const r2 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { id: 1 }) {
id
name
products(where: {}) {
id
name
}
}
}
`,
);
expect(r2).toMatchSnapshot();
const r3 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { name: "heavy goods" }) {
id
name
products(where: {}) {
id
name
}
}
}
`,
);
expect(r3).toMatchSnapshot();
});
test("query operations involving user specified complex joins", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findManyTags(where: {}) {
id
name
products(where: {}) {
id
name
}
}
}
`,
);
expect(r1).toMatchSnapshot();
});
});
});
});
describe("Data sources linked by side-loadable associations", () => {
let generatedSchema: GraphQLSchema;
beforeAll(async () => {
await setupDepartmentSchema(knex);
await knex("tags").insert([{ name: "imported" }, { name: "third-party" }]);
await knex("departments").insert([{ name: "textile" }, { name: "heavy goods" }]);
await knex("products").insert([
{ name: "silk gown", department_id: 1 },
{ name: "steel welding machine", department_id: 2 },
]);
await knex("product_tag_associators").insert([
{ product_id: 1, tag_id: 1 },
{ product_id: 2, tag_id: 2 },
{ product_id: 2, tag_id: 1 },
]);
const fields = {
id: {
type: types.intId,
},
name: {
type: types.string,
},
};
// @snippet:start mapAssociation_sideLoading
/// import {mapDataSource, mapAssociations} from "greldal";
const departments = mapDataSource({
name: "Department",
fields: mapFields(fields),
associations: mapAssociations({
products: {
target: () => products,
singular: false,
associatorColumns: {
inSource: "id",
inRelated: "department_id",
},
fetchThrough: [
// We can define multiple side-loading strategies here.
//
// When user queried by id of department, then we don't have to wait for the query on departments to complete
// before we start fetching products. In case of preFetch strategy, these queries can happen in parallel, because
// given the parameters used to query the data source we can start a parallel query to fetch all the products in
// matching departments
{
useIf(operation) {
return has(operation.args, ["where", "id"]);
},
preFetch(operation) {
// What preFetch returns is a MappedForeignOperation - which basically points to another operation
// in the related data source (findManyProducts) and the arguments needed to initiate this operation.
const args: any = operation.args;
const department_id: string = args.where.id;
return {
operation: findManyProducts,
args: {
where: {
department_id,
},
},
};
},
},
// However if the query parameters to departments are not enough to identify which products we need to fetch,
// we can wait for the departments
{
postFetch(_operation, parents) {
// As above, we are instructing GRelDAL to initiate another operation in a foreign data source.
// However, in this case this body will execute once the query on parents has finished. So we have an array of
// fetched parents at our disposal which we can use to identify additional arguments to narrow down the
// subset of products to fetch.
return {
operation: findManyProductsByDepartmentIdList,
args: {
department_ids: map(parents, "id"),
},
};
},
},
],
},
}),
});
// @snippet:end
const products = mapDataSource({
name: "Product",
fields: mapFields({
...fields,
department_id: {
type: types.number,
},
}),
});
const findOneProduct = operationPresets.query.findOneOperation(products);
const findManyProducts = operationPresets.query.findManyOperation(products);
const args = mapArgs({
department_ids: {
type: types.array(types.number),
},
});
const findManyProductsByDepartmentIdList = new MappedSingleSourceQueryOperation({
rootSource: products,
name: `findManyProductsByDepartmentIdList`,
args,
resolver(ctx) {
return new SingleSourceQueryOperationResolver(ctx);
},
rootQuery(_dataSource, args, ahv) {
return products.rootQueryBuilder(ahv).whereIn("department_id", args.department_ids as number[]);
},
singular: false,
shallow: false,
description: undefined,
});
generatedSchema = mapSchema([...operationPresets.defaults(departments), findOneProduct, findManyProducts]);
});
afterAll(async () => {
await teardownDepartmentSchema(knex);
});
test("pre-fetch queries", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { id: 1 }) {
id
name
products(where: {}) {
id
name
department_id
}
}
}
`,
);
expect(r1).toMatchSnapshot();
});
test("post-fetch queries", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { name: "textile" }) {
id
name
products(where: {}) {
id
name
department_id
}
}
}
`,
);
expect(r1).toMatchSnapshot();
});
});
describe("Mutation Presets", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await knex.schema.createTable("users", t => {
t.increments("id");
t.string("name");
t.text("addr");
});
users = mapDataSource({
name: "User",
fields: mapFields({
id: {
type: types.intId,
isPrimary: true,
},
name: {
type: types.string,
},
address: {
type: types.string,
sourceColumn: "addr",
},
}),
});
schema = mapSchema([
...operationPresets.query.defaults(users),
...operationPresets.mutation.defaults(users),
]);
});
afterAll(async () => {
await knex.schema.dropTable("users");
});
describe("Insertion", () => {
describe("Singular", () => {
it("Inserts mapped entity", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertOneUser(
entity: { id: 1, name: "Sherlock Holmes", address: "221 B Baker Street" }
) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const numRows = await getCount(knex("users"));
expect(numRows).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertOneUser(
entity: { id: 1, name: "Sherlock Holmes", address: "221 B Baker Street" }
) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
describe("Batch", () => {
it("Inserts mapped entities", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertManyUsers(
entities: [
{ id: 2, name: "John Doe", address: "A B C" }
{ id: 3, name: "Jane Doe", address: "A B C" }
]
) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const numRows = getCount(knex("users").whereIn("id", [2, 3]));
expect(numRows).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertManyUsers(
entities: [
{ id: 4, name: "John Doe", address: "A B C" }
{ id: 4, name: "Jane Doe", address: "A B C" }
]
) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
});
describe("Update", () => {
beforeEach(async () => {
await knex("users").insert([
{
id: 5,
name: "Ali",
addr: "A B C",
},
{
id: 6,
name: "Ram",
addr: "A B C",
},
]);
});
afterEach(async () => {
await knex("users").del();
});
describe("Singular", () => {
it("Updates mapped entity", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateOneUser(where: { id: 5 }, update: { name: "Rahman" }) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const row = await knex("users").where({ id: 5 });
expect(row).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateOneUser(where: { id: 5 }, update: { id: 6 }) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
describe("Batch", () => {
it("Updates mapped entities", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateManyUsers(where: { address: "A B C" }, update: { address: "D E F" }) {
id
name
address
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const n1 = await getCount(knex("users").where({ addr: "A B C" }));
expect(n1).toMatchSnapshot();
const n2 = await getCount(knex("users").where({ addr: "D E F" }));
expect(n2).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateManyUsers(where: { id: 5 }, update: { id: 6 }) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
});
describe("Deletion", () => {
beforeEach(async () => {
await knex("users").insert([
{
id: 11,
name: "Ramesh",
addr: "H J K",
},
{
id: 12,
name: "Akbar",
addr: "H J K",
},
{
id: 13,
name: "Grisham",
addr: "P Q R",
},
{
id: 14,
name: "Gautam",
addr: "P Q R",
},
]);
});
afterEach(async () => {
await knex("users").delete();
});
describe("Singular", () => {
it("Deletes mapped entity", async () => {
const prevCount = await getCount(knex("users"));
const matchCount = await getCount(knex("users").where({ addr: "P Q R" }));
expect(matchCount).toBeGreaterThan(0);
const r1 = await graphql(
schema,
`
mutation {
deleteOneUser(where: { address: "P Q R" }) {
id
name
address
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const count = await getCount(knex("users"));
expect(count).toBe(prevCount - 1);
});
});
describe("Batch", () => {
it("Deletes mapped entities", async () => {
const prevCount = await getCount(knex("users"));
const matchCount = await getCount(
knex("users")
.where({ addr: "H J K" })
.count(),
);
const r1 = await graphql(
schema,
`
mutation {
deleteManyUsers(where: { address: "H J K" }) {
id
name
address
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const count = await getCount(knex("users"));
expect(count).toBe(prevCount - matchCount);
});
});
});
});
}); | the_stack |
// tslint:disable:no-console
import * as ts from 'typescript'
import * as terser from 'terser'
import { inspect } from 'util'
import { resolve, dirname, relative } from 'path'
type PackageJson = {
main: string
// only package.json
typings?: string
bundleDependencies: string[]
decentralandLibrary?: any
}
type SceneJson = {
main: string
}
type DecentralandLib = {
name?: string
typings?: string
main: string
}
type ProjectConfig = ts.ParsedCommandLine & { libs: DecentralandLib[]; isDecentralandLib: boolean }
// nameCache for the minifier
const nameCache = {}
const WATCH = process.argv.indexOf('--watch') !== -1 || process.argv.indexOf('-w') !== -1
// PRODUCTION == true : makes the compiler to prefer .min.js files while importing and produces a minified output
const PRODUCTION = !WATCH && (process.argv.indexOf('--production') !== -1 || process.env.NODE_ENV === 'production')
const watchedFiles = new Set<string>()
type FileMap = ts.MapLike<{ version: number }>
async function compile() {
// current working directory
let CWD = process.cwd()
ts.sys.getCurrentDirectory = () => CWD
ts.sys.resolvePath = (path: string) => resolve(ts.sys.getCurrentDirectory(), path)
{
// Read the target folder, if specified.
// -p --project, like typescript
const projectArgIndex = Math.max(process.argv.indexOf('-p'), process.argv.indexOf('--project'))
if (projectArgIndex != -1 && process.argv.length > projectArgIndex) {
const folder = resolve(process.cwd(), process.argv[projectArgIndex + 1])
if (ts.sys.directoryExists(folder)) {
CWD = folder
} else {
throw new Error(`Folder ${folder} does not exist!.`)
}
}
}
console.log(`> Working directory: ${ts.sys.getCurrentDirectory()}`)
let packageJson: PackageJson | null = null
let sceneJson: SceneJson | null = null
if (resolveFile('package.json')) {
packageJson = JSON.parse(loadArtifact('package.json'))
packageJson!.bundleDependencies = packageJson!.bundleDependencies || []
}
if (resolveFile('scene.json')) {
sceneJson = JSON.parse(loadArtifact('scene.json'))
}
const cfg = getConfiguration(packageJson, sceneJson)
console.log('')
if (cfg.fileNames.length === 0) {
console.error('! Error: There are no matching .ts files to process')
process.exit(4)
}
const files: FileMap = {}
// initialize the list of files
cfg.fileNames.forEach((fileName) => {
files[fileName] = { version: 0 }
})
// Create the language service host to allow the LS to communicate with the host
const services = ts.createLanguageService(
{
getScriptFileNames: () => cfg.fileNames,
getScriptVersion: (fileName) => files[fileName] && files[fileName].version.toString(),
getScriptSnapshot: (fileName) => {
if (!ts.sys.fileExists(fileName)) {
return undefined
}
if (WATCH) {
watchFile(fileName, services, files, cfg)
}
return ts.ScriptSnapshot.fromString(ts.sys.readFile(fileName)!.toString())
},
getCurrentDirectory: ts.sys.getCurrentDirectory,
getCompilationSettings: () => cfg.options,
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
readDirectory: ts.sys.readDirectory
},
ts.createDocumentRegistry()
)
if (WATCH) {
// Now let's watch the files
cfg.fileNames.forEach((fileName) => {
watchFile(fileName, services, files, cfg)
})
}
// First time around, emit all files
const diagnostics = await emitFile(cfg.fileNames[0], services, cfg)
if (!WATCH && diagnostics.length) {
throw new Error(`! Error: compilation finished with ${diagnostics.length} errors`)
}
}
function watchFile(fileName: string, services: ts.LanguageService, files: FileMap, cfg: ProjectConfig) {
if (!watchedFiles.has(fileName)) {
watchedFiles.add(fileName)
files[fileName] = { version: 0 }
// Add a watch on the file to handle next change
ts.sys.watchFile!(
fileName,
(fileName, type) => {
// Update the version to signal a change in the file
files[fileName].version++
// write the changes to disk
emitFile(fileName, services, cfg)
},
250
)
}
}
async function minify(files: string | string[] | { [file: string]: string }) {
const result = await terser.minify(files, {
ecma: 5,
nameCache,
mangle: {
toplevel: false,
module: false,
eval: true,
keep_classnames: true,
keep_fnames: true,
reserved: ['global', 'globalThis', 'define']
},
compress: {
passes: 2
},
format: {
ecma: 5,
comments: /^!/,
beautify: false
},
sourceMap: false,
toplevel: false
})
return result
}
async function emitFile(fileName: string, services: ts.LanguageService, cfg: ProjectConfig) {
let output = services.getEmitOutput(fileName)
if (!output.emitSkipped) {
console.log(`> processing ${fileName.replace(ts.sys.getCurrentDirectory(), '')}`)
} else {
console.log(`> processing ${fileName.replace(ts.sys.getCurrentDirectory(), '')} failed`)
}
const diagnostics = logErrors(services)
type OutFile = {
readonly path: string
definition?: {
path: string
content: string
}
content?: string
sha256?: string
}
const loadedLibs: OutFile[] = []
function loadDclLib(lib: string) {
const path = resolveFile(lib)
if (path) {
const json: OutFile[] = JSON.parse(loadArtifact(lib))
loadedLibs.push(...json)
return true
}
return false
}
function loadJsLib(lib: string) {
const path = resolveFile(lib)
if (path) {
const content = loadArtifact(lib)
loadedLibs.push({
path: relative(ts.sys.getCurrentDirectory(), path),
content,
sha256: ts.sys.createSHA256Hash!(content)
})
return true
}
return false
}
function loadLibOrJs(lib: string) {
if (PRODUCTION) {
// prefer .min.js when available for PRODUCTION builds
return loadDclLib(lib + '.lib') || loadJsLib(lib.replace(/\.js$/, '.min.js')) || loadJsLib(lib) || false
} else {
return loadDclLib(lib + '.lib') || loadJsLib(lib) || false
}
}
cfg.libs.forEach((lib) => {
if (!loadLibOrJs(lib.main)) {
console.error(`! Error: could not load lib: ${lib.main}`)
}
})
const out = new Map<string, OutFile>()
function getOutFile(path: string) {
let f = out.get(path)
if (!f) {
f = { path }
out.set(path, f)
}
return f
}
function normalizePath(path: string) {
return path.replace(ts.sys.getCurrentDirectory(), '')
}
for (let o of output.outputFiles) {
if (o.name.endsWith('.d.ts')) {
const filePath = o.name.replace(/\.d\.ts$/, '.js')
const f = getOutFile(filePath)
f.definition = {
content: o.text,
path: o.name
}
} else {
const f = getOutFile(o.name)
f.content = o.text
}
}
for (let [, file] of out) {
if (file.path.endsWith('.js') && file.content && !file.path.endsWith('.min.js')) {
loadedLibs.push({
path: relative(ts.sys.getCurrentDirectory(), fileName),
content: file.content,
sha256: ts.sys.createSHA256Hash!(file.content)
})
const ret: string[] = []
for (let { path, content, sha256 } of loadedLibs) {
const code = content + '\n//# sourceURL=dcl://' + path
ret.push(`/*! ${JSON.stringify(path)} ${sha256 || ''} */ eval(${JSON.stringify(code)})`)
}
file.content = ret.join('\n')
// emit lib file if it is a decentraland lib
const deps = getOutFile(file.path + '.lib')
deps.content = JSON.stringify(loadedLibs, null, 2)
if (PRODUCTION || cfg.isDecentralandLib) {
// minify && source map
const minifiedFile = getOutFile(cfg.isDecentralandLib ? file.path.replace(/\.js$/, '.min.js') : file.path)
console.log(`> minifying ${normalizePath(minifiedFile.path)}`)
try {
const minificationResult = await minify(loadedLibs.map(($) => $.content).join(';\n'))
minifiedFile.content = minificationResult.code
minifiedFile.sha256 = ts.sys.createSHA256Hash!(minificationResult.code!)
// we don't want to always embed the source map in every scene. thus,
// a new file is generated. This is controlled by the minify function
if (minificationResult.map) {
const f = getOutFile(file.path.replace(/\.js$/, '.js.map'))
f.content =
typeof minificationResult.map === 'string'
? minificationResult.map
: JSON.stringify(minificationResult.map)
}
} catch (e) {
console.error('! Error:')
console.error(e)
}
}
}
}
for (let [, file] of out) {
ensureDirectoriesExist(dirname(file.path))
if (file.content) {
console.log(`> writing ${normalizePath(file.path)}`)
ts.sys.writeFile(file.path, file.content)
}
if (file.definition) {
console.log(`> writing ${normalizePath(file.definition.path)}`)
ts.sys.writeFile(file.definition.path, file.definition.content)
}
}
if (WATCH) {
console.log('\nThe compiler is watching file changes...\n')
}
return diagnostics
}
function logErrors(services: ts.LanguageService) {
let allDiagnostics = services
.getCompilerOptionsDiagnostics()
.concat(services.getProgram()!.getGlobalDiagnostics())
.concat(services.getProgram()!.getSemanticDiagnostics())
.concat(services.getProgram()!.getSyntacticDiagnostics())
allDiagnostics.forEach(printDiagnostic)
return allDiagnostics
}
function getConfiguration(packageJson: PackageJson | null, sceneJson: SceneJson | null): ProjectConfig {
const host: ts.ParseConfigHost = {
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
readDirectory: ts.sys.readDirectory
}
const tsconfigPath = ts.sys.resolvePath('tsconfig.json')
const tsconfigContent = ts.sys.readFile(tsconfigPath)
if (!tsconfigContent) {
console.error(`! Error: missing tsconfig.json file`)
process.exit(1)
}
const parsed = ts.parseConfigFileTextToJson('tsconfig.json', tsconfigContent)
if (parsed.error) {
printDiagnostic(parsed.error)
process.exit(1)
}
const tsconfig = ts.parseJsonConfigFileContent(parsed.config, host, ts.sys.getCurrentDirectory(), {}, 'tsconfig.json')
let hasError = false
// should this project be compiled as a lib? or as a scene?
let isDecentralandLib = false
if (tsconfig.options.target !== ts.ScriptTarget.ES5) {
console.error('! Error: tsconfig.json: Decentraland only allows ES5 targets')
hasError = true
}
if (tsconfig.options.module !== ts.ModuleKind.AMD) {
console.error('! Error: tsconfig.json: Decentraland only allows AMD modules')
hasError = true
}
if (!tsconfig.options.outFile) {
console.error('! Error: tsconfig.json: invalid or missing outFile')
hasError = true
}
const libs: DecentralandLib[] = []
const bundledLibs: string[] = []
if (packageJson) {
if (packageJson.decentralandLibrary) {
isDecentralandLib = true
} else {
isDecentralandLib = false
if (packageJson.bundleDependencies instanceof Array) {
packageJson.bundleDependencies.forEach(($, ix) => {
if (typeof $ == 'string') {
bundledLibs.push($)
} else {
console.error(
`! Error: package.json .bundleDependencies must be an array of strings. The element number bundleDependencies[${ix}] is not a string.`
)
hasError = true
}
})
} else if (packageJson.bundleDependencies) {
console.error(`! Error: package.json .bundleDependencies must be an array of strings.`)
hasError = true
}
}
}
if (isDecentralandLib && sceneJson) {
console.error('! Error: project of type decentralandLibrary must not have scene.json')
process.exit(1)
}
if (!isDecentralandLib && !sceneJson) {
console.error('! Error: project of type scene must have a scene.json')
process.exit(1)
}
if (isDecentralandLib && !packageJson) {
console.error('! Error: project of type decentralandLibrary requires a package.json')
process.exit(1)
}
if (tsconfig.options.outFile) {
const outFile = ts.sys.resolvePath(tsconfig.options.outFile)
if (!outFile) {
console.error(`! Error: field "outFile" in tsconfig.json cannot be resolved.`)
hasError = true
} else {
if (isDecentralandLib) {
validatePackageJsonForLibrary(packageJson!, outFile)
} else {
validateSceneJson(sceneJson!, outFile)
}
}
}
if (!isDecentralandLib && process.env.NO_DEFAULT_LIBS !== '1') {
// most of the decentraland scenes require the following libraries.
// (order matters, do not change the order)
libs.unshift({ main: process.env.AMD_PATH || 'decentraland-ecs/artifacts/amd.js' }) // 2nd place
libs.unshift({ main: process.env.ECS_PATH || 'decentraland-ecs/dist/src/index.js' }) // 1st place
}
let hasCustomLibraries = false
bundledLibs.forEach((libName) => {
let resolved: string | null = null
try {
resolved = require.resolve(libName + '/package.json', { paths: [ts.sys.getCurrentDirectory()] })
} catch (e) {
console.error(`! Error: dependency ${libName} not found (is it installed?)`)
hasError = true
}
if (resolved) {
try {
const libPackageJson = JSON.parse(ts.sys.readFile(resolved)!)
const decentralandLibrary = libPackageJson.decentralandLibrary
let main: string | null = null
let typings: string | null = null
if (!decentralandLibrary) {
throw new Error(`field "decentralandLibrary" is missing in package.json`)
}
if (!libPackageJson.main) {
throw new Error(`field "main" is missing in package.json`)
} else {
main = resolve(dirname(resolved), decentralandLibrary.main || libPackageJson.main)
if (!ts.sys.fileExists(main)) {
throw new Error(`main file ${main} not found`)
}
}
if (!libPackageJson.typings) {
throw new Error(`field "typings" is missing in package.json`)
} else {
typings = resolve(dirname(resolved), decentralandLibrary.typings || libPackageJson.typings)
if (!ts.sys.fileExists(typings)) {
throw new Error(`typings file ${typings} not found`)
}
}
libs.push({ main, typings, name: libPackageJson.name })
hasCustomLibraries = true
} catch (e) {
console.error(`! Error in library ${libName}: ${e.message}`)
hasError = true
}
}
})
if (libs.length && isDecentralandLib) {
console.log(
'! Error: this project of type decentralandLibrary includes bundleDependencies. bundleDependencies are only allowed in scenes.'
)
process.exit(1)
}
if (hasError) {
console.log('tsconfig.json:')
console.log(inspect(tsconfig, false, 10, true))
process.exit(1)
}
// the new code generation as libraries enables us to leverage source maps
// source map config is overwritten for that reason.
if (isDecentralandLib) {
tsconfig.options.inlineSourceMap = true
tsconfig.options.inlineSources = true
tsconfig.options.sourceMap = false
tsconfig.options.removeComments = false
tsconfig.options.declaration = true
delete tsconfig.options.declarationDir
}
function ensurePathsTopLevelNames(options: any, topLevelName: string) {
options.paths = options.paths || {}
options.baseUrl = options.baseUrl || '.'
if (!options.paths.hasOwnProperty(topLevelName)) {
options.paths[topLevelName] = []
}
return options.paths[topLevelName]
}
if (hasCustomLibraries) {
let shouldRewriteTsconfig = false
libs.forEach((lib) => {
if (lib.name) {
const tsOptions = ensurePathsTopLevelNames(tsconfig.options, lib.name)
const tsRawOptions = ensurePathsTopLevelNames(tsconfig.raw!.compilerOptions, lib.name)
if (lib.typings) {
const relativePath = relative(dirname(tsconfigPath), lib.typings)
// check if it is in the processed configuration
if (!tsOptions.includes(relativePath)) {
tsOptions.push(relativePath)
shouldRewriteTsconfig = true
}
// check if it is in the raw configuration (tsconfig.json contents)
if (!tsRawOptions.includes(relativePath)) {
console.warn(`! Warning: ${relativePath} is missing in tsconfig.json paths`)
tsRawOptions.push(relativePath)
shouldRewriteTsconfig = true
}
}
}
})
// if we had to add a dependency resolution path, we will have to rewrite the tsconfig.json
if (shouldRewriteTsconfig) {
ts.sys.writeFile(tsconfigPath, JSON.stringify(tsconfig.raw, null, 2))
}
}
return Object.assign(tsconfig, { libs, isDecentralandLib })
}
function printDiagnostic(diagnostic: ts.Diagnostic) {
let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
if (diagnostic.file) {
let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!)
console.log(
` Error ${diagnostic.file.fileName.replace(ts.sys.getCurrentDirectory(), '')} (${line + 1},${
character + 1
}): ${message}`
)
} else {
console.log(` Error: ${message}`)
}
}
function loadArtifact(path: string): string {
try {
const resolved = resolveFile(path)
if (resolved) {
return ts.sys.readFile(resolved)!
}
throw new Error()
} catch (e) {
console.error(`! Error: ${path} not found. ` + e)
process.exit(2)
}
}
function resolveFile(path: string): string | null {
let ecsPackageAMD = ts.sys.resolvePath(path)
if (ts.sys.fileExists(ecsPackageAMD)) {
return ecsPackageAMD
}
ecsPackageAMD = ts.sys.resolvePath('node_modules/' + path)
if (ts.sys.fileExists(ecsPackageAMD)) {
return ecsPackageAMD
}
ecsPackageAMD = ts.sys.resolvePath('../node_modules/' + path)
if (ts.sys.fileExists(ecsPackageAMD)) {
return ecsPackageAMD
}
ecsPackageAMD = ts.sys.resolvePath('../../node_modules/' + path)
if (ts.sys.fileExists(ecsPackageAMD)) {
return ecsPackageAMD
}
return null
}
function ensureDirectoriesExist(folder: string) {
if (!ts.sys.directoryExists(folder)) {
// resolve takes a relative path, so we won't pass CWD to it.
ensureDirectoriesExist(resolve(folder, '..'))
ts.sys.createDirectory(folder)
}
}
function validatePackageJsonForLibrary(packageJson: PackageJson, outFile: string) {
if (!packageJson.main) {
throw new Error(`field "main" in package.json is missing.`)
} else {
const mainFile = ts.sys.resolvePath(packageJson.main)
if (!mainFile) {
throw new Error(`! Error: field "main" in package.json cannot be resolved.`)
}
if (outFile !== mainFile) {
const help = `(${outFile.replace(ts.sys.getCurrentDirectory(), '')} != ${mainFile.replace(
ts.sys.getCurrentDirectory(),
''
)})`
throw new Error(`! Error: tsconfig.json .outFile is not equal to package.json .main\n ${help}`)
}
}
if (!packageJson.typings) {
throw new Error(`field "typings" in package.json is missing.`)
} else {
const typingsFile = ts.sys.resolvePath(packageJson.typings)
if (!typingsFile) {
throw new Error(`! Error: field "typings" in package.json cannot be resolved.`)
}
const resolvedTypings = outFile.replace(/\.js$/, '.d.ts')
if (resolvedTypings !== typingsFile) {
const help = `(${resolvedTypings.replace(ts.sys.getCurrentDirectory(), '')} != ${typingsFile.replace(
ts.sys.getCurrentDirectory(),
''
)})`
throw new Error(`! Error: package.json .typings does not match the emited file\n ${help}`)
}
}
}
function validateSceneJson(sceneJson: SceneJson, outFile: string) {
if (!sceneJson.main) {
console.dir(sceneJson)
throw new Error(`field "main" in scene.json is missing.`)
} else {
const mainFile = ts.sys.resolvePath(sceneJson.main)
if (!mainFile) {
throw new Error(`! Error: field "main" in scene.json cannot be resolved.`)
}
if (outFile !== mainFile) {
const help = `(${outFile.replace(ts.sys.getCurrentDirectory(), '')} != ${mainFile.replace(
ts.sys.getCurrentDirectory(),
''
)})`
throw new Error(`! Error: tsconfig.json .outFile is not equal to scene.json .main\n ${help}`)
}
}
}
// Start the watcher
compile().catch((e) => {
console.error(e)
process.exit(1)
}) | the_stack |
import objectValues from '../polyfills/objectValues.js';
import keyMap from '../jsutils/keyMap.js';
import inspect from '../jsutils/inspect.js';
import mapValue from '../jsutils/mapValue.js';
import invariant from '../jsutils/invariant.js';
import devAssert from '../jsutils/devAssert.js';
import { Kind } from '../language/kinds.js';
import { TokenKind } from '../language/tokenKind.js';
import { dedentBlockStringValue } from '../language/blockString.js';
import { isTypeDefinitionNode, isTypeExtensionNode } from '../language/predicates.js';
import { assertValidSDLExtension } from '../validation/validate.js';
import { getDirectiveValues } from '../execution/values.js';
import { specifiedScalarTypes, isSpecifiedScalarType } from '../type/scalars.js';
import { introspectionTypes, isIntrospectionType } from '../type/introspection.js';
import { GraphQLDirective, GraphQLDeprecatedDirective } from '../type/directives.js';
import { assertSchema, GraphQLSchema } from '../type/schema.js';
import { isScalarType, isObjectType, isInterfaceType, isUnionType, isListType, isNonNullType, isEnumType, isInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType } from '../type/definition.js';
import { valueFromAST } from './valueFromAST.js';
/**
* Produces a new schema given an existing schema and a document which may
* contain GraphQL type extensions and definitions. The original schema will
* remain unaltered.
*
* Because a schema represents a graph of references, a schema cannot be
* extended without effectively making an entire copy. We do not know until it's
* too late if subgraphs remain unchanged.
*
* This algorithm copies the provided schema, applying extensions while
* producing the copy. The original schema remains unaltered.
*
* Accepts options as a third argument:
*
* - commentDescriptions:
* Provide true to use preceding comments as the description.
*
*/
export function extendSchema(schema, documentAST, options) {
assertSchema(schema);
devAssert(documentAST != null && documentAST.kind === Kind.DOCUMENT, 'Must provide valid Document AST.');
if (options?.assumeValid !== true && options?.assumeValidSDL !== true) {
assertValidSDLExtension(documentAST, schema);
}
const schemaConfig = schema.toConfig();
const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);
return schemaConfig === extendedConfig ? schema : new GraphQLSchema(extendedConfig);
}
/**
* @internal
*/
export function extendSchemaImpl(schemaConfig, documentAST, options) {
// Collect the type definitions and extensions found in the document.
const typeDefs = [];
const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can
// have the same name. For example, a type named "skip".
const directiveDefs = [];
let schemaDef; // Schema extensions are collected which may add additional operation types.
const schemaExtensions = [];
for (const def of documentAST.definitions) {
if (def.kind === Kind.SCHEMA_DEFINITION) {
schemaDef = def;
} else if (def.kind === Kind.SCHEMA_EXTENSION) {
schemaExtensions.push(def);
} else if (isTypeDefinitionNode(def)) {
typeDefs.push(def);
} else if (isTypeExtensionNode(def)) {
const extendedTypeName = def.name.value;
const existingTypeExtensions = typeExtensionsMap[extendedTypeName];
typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def];
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
directiveDefs.push(def);
}
} // If this document contains no new types, extensions, or directives then
// return the same unmodified GraphQLSchema instance.
if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) {
return schemaConfig;
}
const typeMap = Object.create(null);
for (const existingType of schemaConfig.types) {
typeMap[existingType.name] = extendNamedType(existingType);
}
for (const typeNode of typeDefs) {
const name = typeNode.name.value;
typeMap[name] = stdTypeMap[name] ?? buildType(typeNode);
}
const operationTypes = {
// Get the extended root operation types.
query: schemaConfig.query && replaceNamedType(schemaConfig.query),
mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),
subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),
// Then, incorporate schema definition and all schema extensions.
...(schemaDef && getOperationTypes([schemaDef])),
...getOperationTypes(schemaExtensions)
}; // Then produce and return a Schema config with these types.
return {
description: schemaDef?.description?.value,
...operationTypes,
types: objectValues(typeMap),
directives: [...schemaConfig.directives.map(replaceDirective), ...directiveDefs.map(buildDirective)],
extensions: undefined,
astNode: schemaDef ?? schemaConfig.astNode,
extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),
assumeValid: options?.assumeValid ?? false
}; // Below are functions used for producing this schema that have closed over
// this scope and have access to the schema, cache, and newly defined types.
function replaceType(type) {
if (isListType(type)) {
return new GraphQLList(replaceType(type.ofType));
} else if (isNonNullType(type)) {
return new GraphQLNonNull(replaceType(type.ofType));
}
return replaceNamedType(type);
}
function replaceNamedType(type) {
// Note: While this could make early assertions to get the correctly
// typed values, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
return typeMap[type.name];
}
function replaceDirective(directive) {
const config = directive.toConfig();
return new GraphQLDirective({ ...config,
args: mapValue(config.args, extendArg)
});
}
function extendNamedType(type) {
if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {
// Builtin types are not extended.
return type;
}
if (isScalarType(type)) {
return extendScalarType(type);
}
if (isObjectType(type)) {
return extendObjectType(type);
}
if (isInterfaceType(type)) {
return extendInterfaceType(type);
}
if (isUnionType(type)) {
return extendUnionType(type);
}
if (isEnumType(type)) {
return extendEnumType(type);
}
if (isInputObjectType(type)) {
return extendInputObjectType(type);
} // Not reachable. All possible types have been considered.
invariant(false, 'Unexpected type: ' + inspect(type));
}
function extendInputObjectType(type) {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLInputObjectType({ ...config,
fields: () => ({ ...mapValue(config.fields, field => ({ ...field,
type: replaceType(field.type)
})),
...buildInputFieldMap(extensions)
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions)
});
}
function extendEnumType(type) {
const config = type.toConfig();
const extensions = typeExtensionsMap[type.name] ?? [];
return new GraphQLEnumType({ ...config,
values: { ...config.values,
...buildEnumValueMap(extensions)
},
extensionASTNodes: config.extensionASTNodes.concat(extensions)
});
}
function extendScalarType(type) {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLScalarType({ ...config,
extensionASTNodes: config.extensionASTNodes.concat(extensions)
});
}
function extendObjectType(type) {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLObjectType({ ...config,
interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)],
fields: () => ({ ...mapValue(config.fields, extendField),
...buildFieldMap(extensions)
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions)
});
}
function extendInterfaceType(type) {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLInterfaceType({ ...config,
interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)],
fields: () => ({ ...mapValue(config.fields, extendField),
...buildFieldMap(extensions)
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions)
});
}
function extendUnionType(type) {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLUnionType({ ...config,
types: () => [...type.getTypes().map(replaceNamedType), ...buildUnionTypes(extensions)],
extensionASTNodes: config.extensionASTNodes.concat(extensions)
});
}
function extendField(field) {
return { ...field,
type: replaceType(field.type),
args: mapValue(field.args, extendArg)
};
}
function extendArg(arg) {
return { ...arg,
type: replaceType(arg.type)
};
}
function getOperationTypes(nodes) {
const opTypes = {};
for (const node of nodes) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const operationTypesNodes = node.operationTypes ?? [];
for (const operationType of operationTypesNodes) {
opTypes[operationType.operation] = getNamedType(operationType.type);
}
} // Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
return opTypes;
}
function getNamedType(node) {
const name = node.name.value;
const type = stdTypeMap[name] ?? typeMap[name];
if (type === undefined) {
throw new Error(`Unknown type: "${name}".`);
}
return type;
}
function getWrappedType(node) {
if (node.kind === Kind.LIST_TYPE) {
return new GraphQLList(getWrappedType(node.type));
}
if (node.kind === Kind.NON_NULL_TYPE) {
return new GraphQLNonNull(getWrappedType(node.type));
}
return getNamedType(node);
}
function buildDirective(node) {
const locations = node.locations.map(({
value
}) => value);
return new GraphQLDirective({
name: node.name.value,
description: getDescription(node, options),
locations,
isRepeatable: node.repeatable,
args: buildArgumentMap(node.arguments),
astNode: node
});
}
function buildFieldMap(nodes) {
const fieldConfigMap = Object.create(null);
for (const node of nodes) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const nodeFields = node.fields ?? [];
for (const field of nodeFields) {
fieldConfigMap[field.name.value] = {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
type: getWrappedType(field.type),
description: getDescription(field, options),
args: buildArgumentMap(field.arguments),
deprecationReason: getDeprecationReason(field),
astNode: field
};
}
}
return fieldConfigMap;
}
function buildArgumentMap(args) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const argsNodes = args ?? [];
const argConfigMap = Object.create(null);
for (const arg of argsNodes) {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type = getWrappedType(arg.type);
argConfigMap[arg.name.value] = {
type,
description: getDescription(arg, options),
defaultValue: valueFromAST(arg.defaultValue, type),
astNode: arg
};
}
return argConfigMap;
}
function buildInputFieldMap(nodes) {
const inputFieldMap = Object.create(null);
for (const node of nodes) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const fieldsNodes = node.fields ?? [];
for (const field of fieldsNodes) {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type = getWrappedType(field.type);
inputFieldMap[field.name.value] = {
type,
description: getDescription(field, options),
defaultValue: valueFromAST(field.defaultValue, type),
astNode: field
};
}
}
return inputFieldMap;
}
function buildEnumValueMap(nodes) {
const enumValueMap = Object.create(null);
for (const node of nodes) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const valuesNodes = node.values ?? [];
for (const value of valuesNodes) {
enumValueMap[value.name.value] = {
description: getDescription(value, options),
deprecationReason: getDeprecationReason(value),
astNode: value
};
}
}
return enumValueMap;
}
function buildInterfaces(nodes) {
const interfaces = [];
for (const node of nodes) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const interfacesNodes = node.interfaces ?? [];
for (const type of interfacesNodes) {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable
// results.
interfaces.push(getNamedType(type));
}
}
return interfaces;
}
function buildUnionTypes(nodes) {
const types = [];
for (const node of nodes) {
/* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */
const typeNodes = node.types ?? [];
for (const type of typeNodes) {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable
// results.
types.push(getNamedType(type));
}
}
return types;
}
function buildType(astNode) {
const name = astNode.name.value;
const description = getDescription(astNode, options);
const extensionNodes = typeExtensionsMap[name] ?? [];
switch (astNode.kind) {
case Kind.OBJECT_TYPE_DEFINITION:
{
const extensionASTNodes = extensionNodes;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLObjectType({
name,
description,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes
});
}
case Kind.INTERFACE_TYPE_DEFINITION:
{
const extensionASTNodes = extensionNodes;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLInterfaceType({
name,
description,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes
});
}
case Kind.ENUM_TYPE_DEFINITION:
{
const extensionASTNodes = extensionNodes;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLEnumType({
name,
description,
values: buildEnumValueMap(allNodes),
astNode,
extensionASTNodes
});
}
case Kind.UNION_TYPE_DEFINITION:
{
const extensionASTNodes = extensionNodes;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLUnionType({
name,
description,
types: () => buildUnionTypes(allNodes),
astNode,
extensionASTNodes
});
}
case Kind.SCALAR_TYPE_DEFINITION:
{
const extensionASTNodes = extensionNodes;
return new GraphQLScalarType({
name,
description,
astNode,
extensionASTNodes
});
}
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
{
const extensionASTNodes = extensionNodes;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLInputObjectType({
name,
description,
fields: () => buildInputFieldMap(allNodes),
astNode,
extensionASTNodes
});
}
} // Not reachable. All possible type definition nodes have been considered.
invariant(false, 'Unexpected type definition node: ' + inspect(astNode));
}
}
const stdTypeMap = keyMap(specifiedScalarTypes.concat(introspectionTypes), type => type.name);
/**
* Given a field or enum value node, returns the string value for the
* deprecation reason.
*/
function getDeprecationReason(node) {
const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);
return deprecated?.reason;
}
/**
* Given an ast node, returns its string description.
* @deprecated: provided to ease adoption and will be removed in v16.
*
* Accepts options as a second argument:
*
* - commentDescriptions:
* Provide true to use preceding comments as the description.
*
*/
export function getDescription(node, options) {
if (node.description) {
return node.description.value;
}
if (options?.commentDescriptions === true) {
const rawValue = getLeadingCommentBlock(node);
if (rawValue !== undefined) {
return dedentBlockStringValue('\n' + rawValue);
}
}
}
function getLeadingCommentBlock(node) {
const loc = node.loc;
if (!loc) {
return;
}
const comments = [];
let token = loc.startToken.prev;
while (token != null && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {
const value = String(token.value);
comments.push(value);
token = token.prev;
}
return comments.length > 0 ? comments.reverse().join('\n') : undefined;
} | the_stack |
module TDev.RT.Charts {
export class Point {
constructor (public x: number, public y: number) { }
}
export class CanvasChart {
public lineColor = "#f00";
public gridColor = "#ccc";
public backgroundColor :string = undefined;
public axesColor = "#fff";
public gridLineWidth = 1;
public graphLineWidth = 2;
public axesFontSize = 6;
public gridRows = 11;
public gridCols = 11;
public area = true;
// Variables used for data configuration.
private points: Point[];
// Variables used for canvas / drawing.
private canvas : HTMLCanvasElement;
private context: CanvasRenderingContext2D;
// Variables used for grid creation.
private gridWidth: number;
private gridHeight: number;
// Variables that control the rendered area.
private chartWidth: number;
private chartHeight: number;
private scaleXMin: number;
private scaleXMax: number;
private scaleYMin: number;
private scaleYMax: number;
// Variables that control styling.
private axesPaddingX: number;
private axesPaddingY: number;
constructor() {
this.axesPaddingX = 20;
this.axesPaddingY = 30;
}
public drawChart(canvas: HTMLCanvasElement, points: TDev.RT.Charts.Point[]) {
this.initialize(canvas, points);
if (this.points.length < 2) return;
// Sort the points so our line doesn't cross.
this.points.sort(function (left, right) {
if (left.x > right.x) {
return 1;
}
if (left.x < right.x) {
return -1;
}
return 0;
});
// Determine the scale for drawing axes / points.
this.calculateScale();
this.drawAxes();
this.drawChartGrid();
this.drawGraphPoints();
}
private initialize(canvas: HTMLCanvasElement, points: Point[]) {
this.canvas = canvas;
this.context = this.canvas.getContext("2d");
this.points = points;
// Calculate the area that the graph/chart will be drawn in.
this.chartWidth = canvas.width - this.axesPaddingY;
this.chartHeight = canvas.height - this.axesPaddingX;
this.context.save();
this.context.clearRect(0, 0, canvas.width, canvas.height);
}
private drawChartGrid() {
if (this.backgroundColor) {
this.context.save();
this.context.fillStyle = this.backgroundColor;
this.context.fillRect(0, 0, this.chartWidth, this.chartHeight);
this.context.restore();
}
this.context.save();
this.context.strokeStyle = this.gridColor;
this.context.lineWidth = this.gridLineWidth;
this.context.strokeRect(0, 0, this.chartWidth, this.chartHeight);
var tipLength = 5;
for (var i = 0; i < this.gridCols; i++) {
this.context.beginPath();
this.context.moveTo(i * this.gridWidth, this.chartHeight);
this.context.lineTo(i * this.gridWidth, this.chartHeight - tipLength);
this.context.stroke();
this.context.beginPath();
this.context.moveTo(i * this.gridWidth, 0);
this.context.lineTo(i * this.gridWidth, tipLength);
this.context.stroke();
}
for (var i = 0; i < this.gridRows; i++) {
this.context.beginPath();
this.context.moveTo(0, i * this.gridHeight);
this.context.lineTo(tipLength, i * this.gridHeight);
this.context.stroke();
this.context.beginPath();
this.context.moveTo(this.chartWidth, i * this.gridHeight);
this.context.lineTo(this.chartWidth - tipLength, i * this.gridHeight);
this.context.stroke();
}
this.context.restore();
}
////drawAxes
// Draws the axes based on how the chart is configured
// Parameters : none
// Returns : none
//
// Notes: This could have a better handling for determining how to
// label the axes, for example, it could determine the scales and
// so forth for the font size and positioning.
private drawAxes() {
this.context.save();
var xRange = this.scaleXMax - this.scaleXMin;
var yRange = this.scaleYMax - this.scaleYMin;
var xUnit = xRange / this.gridCols;
var yUnit = yRange / this.gridRows;
this.context.fillStyle = this.axesColor;
this.context.font = this.axesFontSize + "pt Arial";
// Draw the y-axes labels.
var text = '';
for (var i = 0; i <= this.gridRows; i++) {
text = Math_.round_with_precision(this.scaleYMax - (i * yUnit), 2).toString();
var y = i * this.gridHeight + this.axesFontSize / 2;
if (i === this.gridRows)
y -= this.axesFontSize / 2;
else if (i === 0)
y += this.axesFontSize / 2;
this.context.fillText(text, this.chartWidth + 5, y);
}
// Draw the x-axis labels
for (i = 0; i <= this.gridCols; i++) {
text = Math_.round_with_precision(this.scaleXMin + (i * xUnit), 2).toString();
this.context.fillText(text, i * this.gridWidth, this.chartHeight + (this.axesPaddingX - this.axesFontSize));
}
this.context.restore();
}
////calculateScale
// Determines what the axes should be for graphing
//
// Parameters:
// points - Array of points with x and y values
//
// Returns: none
private calculateScale() {
this.scaleXMin = this.points[0].x;
this.scaleXMax = this.points[0].x;
this.scaleYMax = this.points[0].y;
this.scaleYMin = this.points[0].y;
for (var j = 0, len2 = this.points.length; j < len2; j++) {
if (this.scaleXMax < this.points[j].x) {
this.scaleXMax = this.points[j].x;
}
if (this.scaleYMax < this.points[j].y) {
this.scaleYMax = this.points[j].y;
}
if (this.scaleXMin > this.points[j].x) {
this.scaleXMin = this.points[j].x;
}
if (this.scaleYMin > this.points[j].y) {
this.scaleYMin = this.points[j].y;
}
}
// update axis to look better
var rx = CanvasChart.generateSteps(this.scaleXMin, this.scaleXMax, this.gridCols);
this.scaleXMin = rx[0];
this.scaleXMax = rx[1];
this.gridCols = rx[2];
var ry = CanvasChart.generateSteps(this.scaleYMin, this.scaleYMax, this.gridRows);
this.scaleYMin = ry[0];
this.scaleYMax = ry[1];
this.gridRows = ry[2];
// avoid empty interval
if (this.scaleXMin === this.scaleXMax) {
this.scaleXMin = 0.5;
this.scaleXMax = 0.5;
}
if (this.scaleYMin === this.scaleYMax) {
this.scaleYMin = 0.5;
this.scaleYMax = 0.5;
}
// Calculate the grid for background / scale.
this.gridWidth = this.chartWidth / this.gridCols; // This is the width of the grid cells (background and axes).
this.gridHeight = this.chartHeight / this.gridRows; // This is the height of the grid cells (background axes).
}
static generateSteps(start: number, end: number, numberOfTicks: number) : number[] {
var bases = [1, 5, 2, 3]; // Tick bases selection
var currentBase: number;
var n: number;
var intervalSize: number, upperBound: number, lowerBound: number;
var nIntervals: number, nMaxIntervals: number;
var the_intervalsize = 0.1;
var exponentYmax =
Math.floor(Math.max(Math_.log10(Math.abs(start)), Math_.log10(Math.abs(end))));
var mantissaYmax = end / Math.pow(10.0, exponentYmax);
// now check if numbers can be cleaned...
// make it pretty
var significative_numbers = Math.min(3, Math.abs(exponentYmax) + 1);
var expo = Math.pow(10.0, significative_numbers);
var start_norm = Math.abs(start) * expo;
var end_norm = Math.abs(end) * expo;
var mant_norm = Math.abs(mantissaYmax) * expo;
// trunc ends
var ip_start, ip_end;
var start = ip_start = Math.floor(start_norm * Math_.sign(start));
var end = ip_end = Math.ceil(end_norm * Math_.sign(end));
mantissaYmax = Math.ceil(mant_norm);
nMaxIntervals = 0;
for (var k = 0; k < bases.length; ++k)
{
// Loop initialisation
currentBase = bases[k];
n = 4; // This value only allows results smaller than about 1000 = 10^n
do // Tick vector length reduction
{
--n;
intervalSize = currentBase * Math.pow(10.0, exponentYmax - n);
upperBound =
Math.ceil(mantissaYmax * Math.pow(10.0, n) / currentBase)
* intervalSize;
nIntervals =
Math.ceil((upperBound - start) / intervalSize);
lowerBound = upperBound - nIntervals * intervalSize;
}
while (nIntervals > numberOfTicks);
if (nIntervals > nMaxIntervals) {
nMaxIntervals = nIntervals;
ip_start = ip_start = lowerBound;
ip_end = upperBound;
the_intervalsize = intervalSize;
}
}
// trunc ends
if (start < 0)
start = Math.floor(ip_start) / expo;
else
start = Math.ceil(ip_start) / expo;
if (end < 0)
end = Math.floor(ip_end) / expo;
else
end = Math.ceil(ip_end) / expo;
return [start, end, nMaxIntervals];
}
////graphPoints
// Draws the points on a chart.
//
// Parameters:
// points - An array of points to draw.
//
// Returns: none
private drawGraphPoints() {
this.context.save();
// Determine the scaling factor based on the min / max ranges.
var xRange = this.scaleXMax - this.scaleXMin;
var yRange = this.scaleYMax - this.scaleYMin;
var xFactor = this.chartWidth / xRange;
var yFactor = this.chartHeight / yRange;
var draw = (close: boolean) => {
var nextX = (this.points[0].x - this.scaleXMin) * xFactor;
var nextY = (this.points[0].y - this.scaleYMin) * yFactor;
var startX = nextX;
var startY = nextY;
this.context.moveTo(nextX, this.chartHeight - nextY);
for (var i = 1, len = this.points.length; i < len; i++) {
nextX = (this.points[i].x - this.scaleXMin) * xFactor,
nextY = (this.points[i].y - this.scaleYMin) * yFactor;
this.context.lineTo(nextX, (this.chartHeight - nextY));
}
if (close) {
this.context.lineTo(nextX, this.chartHeight);
this.context.lineTo(startX, this.chartHeight);
this.context.closePath();
}
}
// If we use a 'miterlimit' of .5 the elbow width, the elbow covers the line.
this.context.miterLimit = this.graphLineWidth / 4;
this.context.strokeStyle = this.lineColor;
this.context.lineWidth = this.graphLineWidth;
if (this.area) {
this.context.fillStyle = this.lineColor;
this.context.globalAlpha = 0.3;
this.context.beginPath();
draw(true);
this.context.fill();
this.context.globalAlpha = 1;
}
this.context.beginPath();
draw(false);
this.context.stroke();
this.context.restore();
}
}
} | the_stack |
import fs from "fs";
import path from "path";
import * as appsync from "@aws-cdk/aws-appsync-alpha";
import { serializeFunction } from "@functionless/nodejs-closure-serializer";
import {
AssetHashType,
aws_apigateway,
aws_dynamodb,
aws_events_targets,
aws_lambda,
CfnResource,
DockerImage,
Reference,
Resource,
SecretValue,
TagManager,
Token,
Tokenization,
} from "aws-cdk-lib";
import { IDestination } from "aws-cdk-lib/aws-lambda";
import {
EventBridgeDestination,
LambdaDestination,
} from "aws-cdk-lib/aws-lambda-destinations";
import type { Context } from "aws-lambda";
// eslint-disable-next-line import/no-extraneous-dependencies
import AWS from "aws-sdk";
import { Construct } from "constructs";
import { ApiGatewayVtlIntegration } from "./api";
import type { AppSyncVtlIntegration } from "./appsync";
import { ASL } from "./asl";
import { validateFunctionlessNode } from "./declaration";
import { ErrorCodes, formatErrorMessage, SynthError } from "./error-code";
import {
IEventBus,
isEventBus,
Event,
EventBusTargetIntegration,
Rule,
PredicateRuleBase,
} from "./event-bridge";
import { makeEventBusIntegration } from "./event-bridge/event-bus";
import { CallExpr, Expr, isVariableReference } from "./expression";
import { isErr, isNativeFunctionDecl } from "./guards";
import {
Integration,
IntegrationImpl,
INTEGRATION_TYPE_KEYS,
isIntegration,
} from "./integration";
import { isStepFunction } from "./step-function";
import { isTable } from "./table";
import { AnyFunction, anyOf } from "./util";
export function isFunction<Payload = any, Output = any>(
a: any
): a is IFunction<Payload, Output> {
return a?.kind === "Function";
}
export type AnyLambda = Function<any, any>;
export interface FunctionEventBusTargetProps
extends Omit<aws_events_targets.LambdaFunctionProps, "event"> {}
export type FunctionClosure<in Payload, out Output> = (
payload: Payload,
context: Context
) => Promise<Output>;
const FUNCTION_CLOSURE_FLAG = "__functionlessClosure";
/**
* Returns the payload type on the {@link IFunction}.
*/
export type FunctionPayloadType<Func extends IFunction<any, any>> = [
Func
] extends [IFunction<infer P, any>]
? P
: never;
/**
* Returns the output type on the {@link IFunction}.
*/
export type FunctionOutputType<Func extends IFunction<any, any>> = [
Func
] extends [IFunction<any, infer O>]
? O
: never;
type FunctionAsyncOnFailureDestination<Payload> =
| aws_lambda.FunctionProps["onFailure"]
| IEventBus<AsyncResponseFailureEvent<Payload>>
| IFunction<AsyncResponseFailure<Payload>, any>;
type FunctionAsyncOnSuccessDestination<Payload, Output> =
| aws_lambda.FunctionProps["onSuccess"]
| IEventBus<AsyncResponseSuccessEvent<Payload, Output>>
| IFunction<AsyncResponseSuccess<Payload, Output>, any>;
/**
* Wrapper around {@link aws_lambda.EventInvokeConfigOptions} which allows users to provide Functionless
* {@link EventBus} and {@link Function} for the onSuccess and onFailure async event destinations.
*/
export interface EventInvokeConfigOptions<Payload, Output>
extends Omit<aws_lambda.EventInvokeConfigOptions, "onSuccess" | "onFailure"> {
onSuccess?: FunctionAsyncOnSuccessDestination<Payload, Output>;
onFailure?: FunctionAsyncOnFailureDestination<Payload>;
}
/**
* @typeParam Payload - The super-set payload type of the function.
* @typeParam Output - The output type of the function.
* @typeParam OutPayload - The covariant type of {@link Payload} used when the payload is output.
* For example when the Payload is sent to a {@link Function} or {@link EventBus}
* from onSuccess or onFailure event sources. This type parameter should be left
* empty to be inferred. ex: `Function<Payload1, Output1 | Output2>`.
*/
export interface IFunction<in Payload, Output>
extends Integration<
"Function",
ConditionalFunction<Payload, Output>,
EventBusTargetIntegration<Payload, FunctionEventBusTargetProps | undefined>
> {
readonly functionlessKind: typeof Function.FunctionlessType;
readonly kind: typeof Function.FunctionlessType;
readonly resource: aws_lambda.IFunction;
(...args: Parameters<ConditionalFunction<Payload, Output>>): ReturnType<
ConditionalFunction<Payload, Output>
>;
/**
* Event Source for the {@link Function} onSuccess async invocation destination.
*
* For Lambda, the onSuccess destination is not enabled by default.
* It must first be configured via either the {@link Function} constructor
* or by using {@link IFunction.enableAsyncInvoke} and that destination must match the bus provided here.
*
* ```ts
* const bus = new EventBus(stack, 'bus');
* new Function(stack, 'func', { onSuccess: bus }, async () => {});
* ```
*
* or
*
* ```ts
* const bus = new EventBus(stack, 'bus');
* const func = new Function(stack, 'func', async () => {});
* // if onSuccess or onFailure is already set, this will fail.
* func.enableAsyncInvoke({ onSuccess: bus });
* ```
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations
*
* The rule returned will contain the logic:
*
* ```ts
* when(id, event => event.source === "lambda"
* && event["detail-type"] === "Lambda Function Invocation Result - Success"
* && event.resources.includes(this.resource.functionArn))
* ```
*/
onSuccess<OutPayload extends Payload>(
bus: IEventBus<AsyncResponseSuccessEvent<OutPayload, Output>>,
id: string
): Rule<AsyncResponseSuccessEvent<OutPayload, Output>>;
/**
* Event Source for the {@link Function} onFailure async invocation destination.
*
* The onFailure destination is not enabled by default.
* It must first be configured via either the {@link Function} constructor
* or by using {@link IFunction.enableAsyncInvoke} and that destination must match the bus provided here.
*
* ```ts
* const bus = new EventBus(stack, 'bus');
* new Function(stack, 'func', { onFailure: bus }, async () => {});
* ```
*
* or
*
* ```ts
* const bus = new EventBus(stack, 'bus');
* const func = new Function(stack, 'func', async () => {});
* // if onSuccess or onFailure is already set, this will fail.
* func.enableAsyncInvoke({ onFailure: bus });
* ```
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations
*
* The rule returned will contain the logic:
*
* ```ts
* when(id, event => event.source === "lambda"
* && event["detail-type"] === "Lambda Function Invocation Result - Failure"
* && event.resources.includes(this.resource.functionArn))
* ```
*/
onFailure<OutPayload extends Payload>(
bus: IEventBus<AsyncResponseFailureEvent<OutPayload>>,
id: string
): Rule<AsyncResponseFailureEvent<OutPayload>>;
/**
* Set the async invocation options on a function. Can be use to enable and set the onSuccess and onFailure destinations.
*
* Wraps {@link aws_lambda.IFunction.configureAsyncInvoke} provided by CDK to support Functionless resources directly.
*
* If onSuccess or onFailure were already set either through {@link FunctionProps} or {@link IFunction.enableAsyncInvoke}
* This method will fail.
*/
enableAsyncInvoke<OutPayload extends Payload>(
config: EventInvokeConfigOptions<OutPayload, Output>
): void;
readonly eventBus: EventBusTargetIntegration<
Payload,
FunctionEventBusTargetProps | undefined
>;
}
export interface AsyncResponseBase<P> {
version: string;
/**
* ISO 8601
*/
timestamp: string;
requestPayload: P;
responseContext: {
statusCode: number;
executedVersion: "$LATEST" | string;
functionError: string;
};
}
export type AsyncFunctionResponseEvent<P, O> =
| AsyncResponseSuccessEvent<P, O>
| AsyncResponseFailureEvent<P>;
export interface AsyncResponseSuccess<P, O> extends AsyncResponseBase<P> {
responsePayload: O;
requestContext: {
requestId: string;
functionArn: string;
condition: "Success";
approximateInvokeCount: number;
};
}
export interface AsyncResponseFailure<P> extends AsyncResponseBase<P> {
requestContext: {
requestId: string;
functionArn: string;
condition: "RetriesExhausted" | "EventAgeExceeded" | string;
approximateInvokeCount: number;
};
responsePayload: {
errorMessage: string;
errorType: string;
stackTrace: string[];
};
}
export interface AsyncResponseSuccessEvent<P, O>
extends Event<
AsyncResponseSuccess<P, O>,
"Lambda Function Invocation Result - Success",
"lambda"
> {}
export interface AsyncResponseFailureEvent<P>
extends Event<
AsyncResponseFailure<P>,
"Lambda Function Invocation Result - Failure",
"lambda"
> {}
abstract class FunctionBase<in Payload, Out>
implements
IFunction<Payload, Out>,
Integration<"Function", ConditionalFunction<Payload, Out>>
{
readonly kind = "Function" as const;
readonly native: NativeIntegration<ConditionalFunction<Payload, Out>>;
readonly functionlessKind = "Function";
public static readonly FunctionlessType = "Function";
readonly appSyncVtl: AppSyncVtlIntegration;
readonly apiGWVtl: ApiGatewayVtlIntegration;
// @ts-ignore - this makes `F` easily available at compile time
readonly __functionBrand: ConditionalFunction<Payload, Out>;
constructor(readonly resource: aws_lambda.IFunction) {
const functionName = this.resource.functionName;
// Native is used when this function is called from another lambda function's serialized closure.
// define this here to closure the functionName without using `this`
this.native = {
/**
* Wire up permissions for this function to be called by the calling function
*/
bind: (context: Function<any, any>) => {
this.resource.grantInvoke(context.resource);
},
/**
* Code that runs once per lambda invocation
* The pre-warm client supports singleton invocation of clients (or other logic) across all integrations in the caller function.
*/
preWarm: (preWarmContext: NativePreWarmContext) => {
preWarmContext.getOrInit(PrewarmClients.LAMBDA);
},
/**
* This method is called from the calling runtime lambda code (context) to invoke this lambda function.
*/
call: async (args, prewarmContext) => {
const [payload] = args;
const lambdaClient = prewarmContext.getOrInit(PrewarmClients.LAMBDA);
const response = (
await lambdaClient
.invoke({
FunctionName: functionName,
...(payload ? { Payload: JSON.stringify(payload) } : undefined),
})
.promise()
).Payload?.toString();
return response ? JSON.parse(response) : undefined;
},
};
this.appSyncVtl = {
dataSourceId: () => resource.node.addr,
dataSource(api, id) {
return new appsync.LambdaDataSource(api, id, {
api,
lambdaFunction: resource,
});
},
request(call, context) {
const payloadArg = call.getArgument("payload");
const payload = payloadArg?.expr
? context.eval(payloadArg.expr)
: "$null";
const request = context.var(
`{"version": "2018-05-29", "operation": "Invoke", "payload": ${payload}}`
);
return context.json(request);
},
};
this.apiGWVtl = {
renderRequest: (call, context) => {
const payloadArg = call.getArgument("payload");
return payloadArg?.expr ? context.exprToJson(payloadArg.expr) : "$null";
},
createIntegration: (options) => {
this.resource.grantInvoke(options.credentialsRole);
return new aws_apigateway.LambdaIntegration(this.resource, {
...options,
proxy: false,
passthroughBehavior: aws_apigateway.PassthroughBehavior.NEVER,
});
},
};
}
public asl(call: CallExpr, context: ASL) {
const payloadArg = call.getArgument("payload")?.expr;
this.resource.grantInvoke(context.role);
return {
Type: "Task" as const,
Resource: "arn:aws:states:::lambda:invoke",
Parameters: {
FunctionName: this.resource.functionName,
[`Payload${payloadArg && isVariableReference(payloadArg) ? ".$" : ""}`]:
payloadArg ? ASL.toJson(payloadArg) : undefined,
},
ResultSelector: "$.Payload",
};
}
protected static normalizeAsyncDestination<P, O>(
destination:
| FunctionAsyncOnSuccessDestination<P, O>
| FunctionAsyncOnFailureDestination<P>
): IDestination | undefined {
return destination === undefined
? undefined
: isEventBus<
| IEventBus<AsyncResponseSuccessEvent<P, O>>
| IEventBus<AsyncResponseFailureEvent<P>>
>(destination)
? new EventBridgeDestination(destination.resource)
: isFunction<
FunctionPayloadType<Extract<typeof destination, IFunction<any, any>>>,
FunctionOutputType<Extract<typeof destination, IFunction<any, any>>>
>(destination)
? new LambdaDestination(destination.resource)
: destination;
}
public enableAsyncInvoke<OutPayload extends Payload>(
config: EventInvokeConfigOptions<OutPayload, Out>
): void {
this.resource.configureAsyncInvoke({
...config,
onSuccess: FunctionBase.normalizeAsyncDestination<OutPayload, Out>(
config.onSuccess
),
onFailure: FunctionBase.normalizeAsyncDestination<OutPayload, Out>(
config.onFailure
),
});
}
public onSuccess<OutPayload extends Payload>(
bus: IEventBus<AsyncResponseSuccessEvent<OutPayload, Out>>,
id: string
): Rule<AsyncResponseSuccessEvent<OutPayload, Out>> {
return new PredicateRuleBase<AsyncResponseSuccessEvent<OutPayload, Out>>(
bus.resource,
id,
bus,
/**
* when(event => event.source === "lambda"
* && event["detail-type"] === "Lambda Function Invocation Result - Success"
* && event.resources.includes(this.resource.functionArn))
*/
{
doc: {
source: { value: "lambda" },
"detail-type": {
value: "Lambda Function Invocation Result - Success",
},
resources: { value: this.resource.functionArn },
},
}
);
}
public onFailure<OutPayload extends Payload>(
bus: IEventBus<AsyncResponseFailureEvent<OutPayload>>,
id: string
): Rule<AsyncResponseFailureEvent<OutPayload>> {
return new PredicateRuleBase<AsyncResponseFailureEvent<OutPayload>>(
bus.resource,
id,
bus,
/**
* when(event => event.source === "lambda"
* && event["detail-type"] === "Lambda Function Invocation Result - Failure"
* && event.resources.includes(this.resource.functionArn))
*/
{
doc: {
source: { value: "lambda" },
"detail-type": {
value: "Lambda Function Invocation Result - Failure",
},
resources: { value: this.resource.functionArn },
},
}
);
}
public readonly eventBus = makeEventBusIntegration<
Payload,
FunctionEventBusTargetProps | undefined
>({
target: (props, targetInput) =>
new aws_events_targets.LambdaFunction(this.resource, {
...props,
event: targetInput,
}),
});
}
interface FunctionBase<in Payload, Out> {
(...args: Parameters<ConditionalFunction<Payload, Out>>): ReturnType<
ConditionalFunction<Payload, Out>
>;
}
const PromisesSymbol = Symbol.for("functionless.Function.promises");
export interface FunctionProps<in P = any, O = any, OutP extends P = P>
extends Omit<
aws_lambda.FunctionProps,
"code" | "handler" | "runtime" | "onSuccess" | "onFailure"
> {
/**
* Method which allows runtime computation of AWS client configuration.
* ```ts
* new Lambda(clientConfigRetriever('LAMBDA'))
* ```
*
* @param clientName optionally return a different client config based on the {@link ClientName}.
*
*/
clientConfigRetriever?: (
clientName: ClientName | string
) => Omit<AWS.Lambda.ClientConfiguration, keyof AWS.Lambda.ClientApiVersions>;
/**
* The destination for failed invocations.
*
* Supports use of Functionless {@link IEventBus} or {@link IFunction}.
*
* ```ts
* const bus = new EventBus<>
* ```
*
* @default - no destination
*/
onSuccess?: FunctionAsyncOnSuccessDestination<OutP, O>;
/**
* The destination for successful invocations.
*
* @default - no destination
*/
onFailure?: FunctionAsyncOnFailureDestination<OutP>;
}
const isNativeFunctionOrError = anyOf(isErr, isNativeFunctionDecl);
/**
* A type-safe NodeJS Lambda Function generated from the closure provided.
*
* Can be called from within an {@link AppsyncResolver}.
*
* For example:
* ```ts
* const getPerson = new Function<string, Person>(stack, 'func', async () => {
* // get person logic
* });
*
* new AppsyncResolver(() => {
* return getPerson("value");
* })
* ```
*
* Can wrap an existing {@link aws_lambda.Function}.
*
* ```ts
* const getPerson = Function.fromFunction<string, Person>(
* new aws_lambda.Function(..)
* );
* ```
*/
export class Function<
in Payload,
Out,
OutPayload extends Payload = Payload
> extends FunctionBase<Payload, Out> {
/**
* Dangling promises which are processing Function handler code from the function serializer.
* To correctly resolve these for CDK synthesis, either use `asyncSynth()` or use `cdk synth` in the CDK cli.
* https://twitter.com/samgoodwin89/status/1516887131108438016?s=20&t=7GRGOQ1Bp0h_cPsJgFk3Ww
*/
public static readonly promises: Promise<any>[] = ((global as any)[
PromisesSymbol
] = (global as any)[PromisesSymbol] ?? []);
/**
* Wrap a {@link aws_lambda.Function} with Functionless.
*
* A wrapped function can be invoked, but the code is provided in the CDK Construct.
*/
public static fromFunction<Payload = any, Out = any>(
func: aws_lambda.IFunction
): ImportedFunction<Payload, Out> {
return new ImportedFunction<Payload, Out>(func);
}
/**
* Create a lambda function using a native typescript closure.
*
* ```ts
* new Function<{ val: string }, string>(this, 'myFunction', async (event) => event.val);
* ```
*/
constructor(
scope: Construct,
id: string,
func: FunctionClosure<Payload, Out>
);
constructor(
scope: Construct,
id: string,
props: FunctionProps<Payload, Out, OutPayload>,
func: FunctionClosure<Payload, Out>
);
/**
* @private
*/
constructor(
resource: Construct,
id: string,
propsOrFunc:
| FunctionProps<Payload, Out, OutPayload>
| FunctionClosure<Payload, Out>,
funcOrNothing?: FunctionClosure<Payload, Out>
) {
const func = validateFunctionlessNode(
isNativeFunctionOrError(propsOrFunc)
? propsOrFunc
: isNativeFunctionOrError(funcOrNothing)
? funcOrNothing
: undefined,
"Function",
isNativeFunctionDecl
);
const props = isNativeFunctionOrError(propsOrFunc)
? undefined
: (propsOrFunc as FunctionProps<Payload, Out, OutPayload>);
const callbackLambdaCode = new CallbackLambdaCode(func.closure, {
clientConfigRetriever: props?.clientConfigRetriever,
});
const { onSuccess, onFailure, ...restProps } = props ?? {};
const _resource = new aws_lambda.Function(resource, id!, {
...restProps,
runtime: aws_lambda.Runtime.NODEJS_14_X,
handler: "index.handler",
code: callbackLambdaCode,
onSuccess: FunctionBase.normalizeAsyncDestination<OutPayload, Out>(
onSuccess
),
onFailure: FunctionBase.normalizeAsyncDestination<OutPayload, Out>(
onFailure
),
});
// Poison pill that forces Function synthesis to fail when the closure serialization has not completed.
// Closure synthesis runs async, but CDK does not normally support async.
// In order for the synthesis to complete successfully
// 1. Use autoSynth `new App({ autoSynth: true })` or `new App()` with the CDK Cli (`cdk synth`)
// 2. Use `await asyncSynth(app)` exported from Functionless in place of `app.synth()`
// 3. Manually await on the closure serializer promises `await Promise.all(Function.promises)`
// https://github.com/functionless/functionless/issues/128
_resource.node.addValidation({
validate: () =>
this.resource.node.metadata.find(
(m) => m.type === FUNCTION_CLOSURE_FLAG
)
? []
: [
formatErrorMessage(
ErrorCodes.Function_Closure_Serialization_Incomplete
),
],
});
super(_resource);
// retrieve and bind all found native integrations. Will fail if the integration does not support native integration.
const nativeIntegrationsPrewarm = func.integrations.flatMap(
({ integration, args }) => {
const integ = new IntegrationImpl(integration).native;
integ.bind(this, args);
return integ.preWarm ? [integ.preWarm] : [];
}
);
// Start serializing process, add the callback to the promises so we can later ensure completion
Function.promises.push(
callbackLambdaCode.generate(nativeIntegrationsPrewarm)
);
}
}
/**
* A {@link Function} which wraps a CDK function.
*
* An imported function can be invoked, but the code is provided in the CDK Construct.
*/
export class ImportedFunction<Payload, Out> extends FunctionBase<Payload, Out> {
/**
* Use {@link Function.fromFunction}
* @internal
*/
constructor(func: aws_lambda.IFunction) {
return super(func) as unknown as ImportedFunction<Payload, Out>;
}
}
type ConditionalFunction<Payload, Out> = [Payload] extends [undefined]
? (payload?: Payload) => Out
: (payload: Payload) => Out;
interface CallbackLambdaCodeProps extends PrewarmProps {}
/**
* A special lambda code wrapper that serializes whatever closure it is given.
*
* Caveat: Relies on async functions which may not finish when using CDK's app.synth()
*
* Ensure the generate function's promise is completed using something like Lambda.promises and the `asyncSynth` function.
*
* Use:
* * Initialize the {@link CallbackLambdaCode} `const code = new CallbackLambdaCode()`
* * First bind the code to a Function `new aws_lambda.Function(..., { code })`
* * Then call generate `const promise = code.generate(integrations)`
*
*/
export class CallbackLambdaCode extends aws_lambda.Code {
private scope: Construct | undefined = undefined;
constructor(
private func: (preWarmContext: NativePreWarmContext) => AnyFunction,
private props?: CallbackLambdaCodeProps
) {
super();
}
public bind(scope: Construct): aws_lambda.CodeConfig {
this.scope = scope;
// Lets give the function something lightweight while we process the closure.
// https://github.com/functionless/functionless/issues/128
return aws_lambda.Code.fromInline(
"If you are seeing this in your lambda code, ensure generate is called, then consult the README, and see https://github.com/functionless/functionless/issues/128."
).bind(scope);
}
/**
* Thanks to cloudy for the help getting this to work.
* https://github.com/skyrpex/cloudy/blob/main/packages/cdk/src/aws-lambda/callback-function.ts#L518-L540
* https://twitter.com/samgoodwin89/status/1516887131108438016?s=20&t=7GRGOQ1Bp0h_cPsJgFk3Ww
*/
public async generate(
integrationPrewarms: NativeIntegration<AnyFunction>["preWarm"][]
) {
if (!this.scope) {
throw Error("Must first be bound to a Construct using .bind().");
}
const scope = this.scope;
let tokens: string[] = [];
const preWarmContext = new NativePreWarmContext(this.props);
const func = this.func(preWarmContext);
const result = await serializeFunction(
// factory function allows us to prewarm the clients and other context.
() => {
integrationPrewarms.forEach((i) => i?.(preWarmContext));
return func;
},
{
isFactoryFunction: true,
serialize: (obj) => {
if (typeof obj === "string") {
const reversed =
Tokenization.reverse(obj, { failConcat: false }) ??
Tokenization.reverseString(obj).tokens;
if (!Array.isArray(reversed) || reversed.length > 0) {
if (Array.isArray(reversed)) {
tokens = [...tokens, ...reversed.map((s) => s.toString())];
} else {
tokens = [...tokens, reversed.toString()];
}
}
} else if (typeof obj === "object") {
/**
* Remove unnecessary fields from {@link CfnResource} that bloat or fail the closure serialization.
*/
const transformCfnResource = (o: unknown): any => {
if (Resource.isResource(o as any)) {
const { node, stack, env, ...rest } = o as unknown as Resource;
return rest;
} else if (CfnResource.isCfnResource(o as any)) {
const {
stack,
node,
creationStack,
// don't need to serialize at runtime
_toCloudFormation,
// @ts-ignore - private - adds the tag manager, which we don't need
cfnProperties,
...rest
} = transformTable(o as CfnResource);
return transformTaggableResource(rest);
} else if (Token.isUnresolved(o)) {
const reversed = Tokenization.reverse(o)!;
if (Reference.isReference(reversed)) {
tokens.push(reversed.toString());
return reversed.toString();
} else if (SecretValue.isSecretValue(reversed)) {
throw new SynthError(
ErrorCodes.Unsafe_use_of_secrets,
"Found unsafe use of SecretValue token in a Function."
);
} else if ("value" in reversed) {
return (reversed as unknown as { value: any }).value;
}
// TODO: fail at runtime and warn at compiler time when a token cannot be serialized
return {};
}
return o;
};
/**
* When the StreamArn attribute is used in a Cfn template, but streamSpecification is
* undefined, then the deployment fails. Lets make sure that doesn't happen.
*/
const transformTable = (o: CfnResource): CfnResource => {
if (
o.cfnResourceType ===
aws_dynamodb.CfnTable.CFN_RESOURCE_TYPE_NAME
) {
const table = o as aws_dynamodb.CfnTable;
if (!table.streamSpecification) {
const { attrStreamArn, ...rest } = table;
return rest as unknown as CfnResource;
}
}
return o;
};
/**
* CDK Tag manager bundles in ~200kb of junk we don't need at runtime,
*/
const transformTaggableResource = (o: any) => {
if (TagManager.isTaggable(o)) {
const { tags, ...rest } = o;
return rest;
}
return o;
};
/**
* Remove unnecessary fields from {@link CfnTable} that bloat or fail the closure serialization.
*/
const transformIntegration = (integ: unknown): any => {
if (integ && isIntegration(integ)) {
const copy = {
...integ,
native: {
call: integ?.native?.call,
preWarm: integ?.native?.preWarm,
},
};
INTEGRATION_TYPE_KEYS.filter((key) => key !== "native").forEach(
(key) => delete copy[key]
);
return copy;
}
return integ;
};
/**
* TODO, make this configuration based.
* https://github.com/functionless/functionless/issues/239
*/
const transformResource = (integ: unknown): any => {
if (
integ &&
(isFunction(integ) ||
isTable(integ) ||
isStepFunction(integ) ||
isEventBus(integ))
) {
const { resource, ...rest } = integ;
return rest;
}
return integ;
};
return transformIntegration(
transformResource(transformCfnResource(obj))
);
}
return true;
},
}
);
const tokenContext = tokens.map((t) => {
const id = /\${Token\[.*\.([0-9]*)\]}/g.exec(t)?.[1];
if (!id) {
throw Error("Unrecognized token format, no id found: " + t);
}
return {
id,
token: t,
// env variables must start with a alpha character
env: `env__functionless${id}`,
};
});
// replace all tokens in the form "${Token[{anything}.{id}]}" -> process.env.env__functionless{id}
// this doesn't solve for tokens like "arn:${Token[{anything}.{id}]}:something" -> "arn:" + process.env.env__functionless{id} + ":something"
const resultText = tokenContext.reduce(
// TODO: support templated strings
(r, t) => r.split(`"${t.token}"`).join(`process.env.${t.env}`),
result.text
);
const asset = aws_lambda.Code.fromAsset("", {
assetHashType: AssetHashType.OUTPUT,
bundling: {
image: DockerImage.fromRegistry("empty"),
// This forces the bundle directory and cache key to be unique. It does nothing else.
user: scope.node.addr,
local: {
tryBundle(outdir: string) {
fs.writeFileSync(path.resolve(outdir, "index.js"), resultText);
return true;
},
},
},
});
if (!(scope instanceof aws_lambda.Function)) {
throw new Error(
"CallbackLambdaCode can only be used on aws_lambda.Function"
);
}
tokenContext.forEach((t) => scope.addEnvironment(t.env, t.token));
const funcResource = scope.node.findChild(
"Resource"
) as aws_lambda.CfnFunction;
const codeConfig = asset.bind(scope);
funcResource.code = {
s3Bucket: codeConfig.s3Location?.bucketName,
s3Key: codeConfig.s3Location?.objectKey,
s3ObjectVersion: codeConfig.s3Location?.objectVersion,
zipFile: codeConfig.inlineCode,
imageUri: codeConfig.image?.imageUri,
};
asset.bindToResource(funcResource);
// Clear the poison pill that causes the Function to fail synthesis.
scope.node.addMetadata(FUNCTION_CLOSURE_FLAG, true);
}
}
/**
* Interface to consume to add an Integration to Native Lambda Functions.
*
* ```ts
* new Function(this, 'func', () => {
* mySpecialIntegration()
* })
*
* const mySpecialIntegration = makeIntegration<() => void>({
* native: {...} // an instance of NativeIntegration
* })
* ```
*/
export interface NativeIntegration<Func extends AnyFunction> {
/**
* Called by any {@link Function} that will invoke this integration during CDK Synthesis.
* Add permissions, create connecting resources, validate.
*
* @param context - The function invoking this function.
* @param args - The functionless encoded AST form of the arguments passed to the integration.
*/
bind: (context: Function<any, any>, args: Expr[]) => void;
/**
* @param args The arguments passed to the integration function by the user.
* @param preWarmContext contains singleton instances of client and other objects initialized outside of the native
* function handler.
*/
call: (
args: Parameters<Func>,
preWarmContext: NativePreWarmContext
) => Promise<ReturnType<Func>>;
/**
* Method called outside of the handler to initialize things like the PreWarmContext
*/
preWarm?: (preWarmContext: NativePreWarmContext) => void;
}
export type ClientName =
| "LAMBDA"
| "EVENT_BRIDGE"
| "STEP_FUNCTIONS"
| "DYNAMO";
interface PrewarmProps {
clientConfigRetriever?: FunctionProps["clientConfigRetriever"];
}
export interface PrewarmClientInitializer<T, O> {
key: T;
init: (key: string, props?: PrewarmProps) => O;
}
/**
* Known, shared clients to use.
*
* Any object can be used by using the {@link PrewarmClientInitializer} interface directly.
*
* ```ts
* context.getOrInit({
* key: 'customClient',
* init: () => new anyClient()
* })
* ```
*/
export const PrewarmClients = {
LAMBDA: {
key: "LAMBDA",
init: (key, props) =>
// eslint-disable-next-line @typescript-eslint/no-require-imports, import/no-extraneous-dependencies
new (require("aws-sdk").Lambda)(props?.clientConfigRetriever?.(key)),
},
EVENT_BRIDGE: {
key: "EVENT_BRIDGE",
init: (key, props) =>
// eslint-disable-next-line @typescript-eslint/no-require-imports, import/no-extraneous-dependencies
new (require("aws-sdk").EventBridge)(props?.clientConfigRetriever?.(key)),
},
STEP_FUNCTIONS: {
key: "STEP_FUNCTIONS",
init: (key, props) =>
// eslint-disable-next-line @typescript-eslint/no-require-imports, import/no-extraneous-dependencies
new (require("aws-sdk").StepFunctions)(
props?.clientConfigRetriever?.(key)
),
},
DYNAMO: {
key: "DYNAMO",
init: (key, props) =>
// eslint-disable-next-line @typescript-eslint/no-require-imports, import/no-extraneous-dependencies
new (require("aws-sdk").DynamoDB)(props?.clientConfigRetriever?.(key)),
},
} as Record<ClientName, PrewarmClientInitializer<ClientName, any>>;
/**
* A client/object cache which Native Functions can use to
* initialize objects once and before the handler is invoked.
*
* The same instance will be passed to both the `.call` and `.prewarm` methods
* of a {@link NativeIntegration}. `prewarm` is called once when the function starts,
* before the handler.
*
* Register and initialize clients by using `getOrInit` with a key and a initializer.
*
* ```ts
* context.getOrInit(PrewarmClients.LAMBDA)
* ```
*
* or register anything by doing
*
* ```ts
* context.getOrInit({
* key: 'customClient',
* init: () => new anyClient()
* })
* ```
*
* To get without potentially initializing the client, use `get`:
*
* ```ts
* context.get("LAMBDA")
* context.get("customClient")
* ```
*/
export class NativePreWarmContext {
private readonly cache: Record<string, any>;
constructor(private props?: PrewarmProps) {
this.cache = {};
}
public get<T>(key: ClientName | string): T | undefined {
return this.cache[key];
}
public getOrInit<T>(client: PrewarmClientInitializer<any, T>): T {
if (!this.cache[client.key]) {
this.cache[client.key] = client.init(client.key, this.props);
}
return this.cache[client.key];
}
} | the_stack |
import 'graphql-import-node'; // Needed so you can import *.graphql files
import { makeBindingClass, Options } from 'graphql-binding'
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql'
import { IResolvers } from 'graphql-tools/dist/Interfaces'
import * as schema from './schema.graphql'
export interface Query {
dishes: <T = Array<Dish>>(args: { offset?: Int | null, limit?: Int | null, where?: DishWhereInput | null, orderBy?: DishOrderByInput | null }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
dishConnection: <T = DishConnection>(args: { first?: Int | null, after?: String | null, last?: Int | null, before?: String | null, where?: DishWhereInput | null, orderBy?: DishOrderByInput | null }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
dish: <T = Dish>(args: { where: DishWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
kitchenSinks: <T = Array<KitchenSink>>(args: { offset?: Int | null, limit?: Int | null, where?: KitchenSinkWhereInput | null, orderBy?: KitchenSinkOrderByInput | null }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
kitchenSink: <T = KitchenSink>(args: { where: KitchenSinkWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T>
}
export interface Mutation {
createDish: <T = Dish>(args: { data: DishCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
updateDish: <T = Dish>(args: { data: DishUpdateInput, where: DishWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
createManyDishs: <T = Array<Dish>>(args: { data: Array<DishCreateInput> }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
deleteDish: <T = StandardDeleteResponse>(args: { where: DishWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
successfulTransaction: <T = Array<Dish>>(args: { data: DishCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
failedTransaction: <T = Array<Dish>>(args: { data: DishCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
createKitchenSink: <T = KitchenSink>(args: { data: KitchenSinkCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
createManyKitchenSinks: <T = Array<KitchenSink>>(args: { data: Array<KitchenSinkCreateInput> }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
updateKitchenSink: <T = KitchenSink>(args: { data: KitchenSinkUpdateInput, where: KitchenSinkWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
deleteKitchenSink: <T = StandardDeleteResponse>(args: { where: KitchenSinkWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T>
}
export interface Subscription {}
export interface Binding {
query: Query
mutation: Mutation
subscription: Subscription
request: <T = any>(query: string, variables?: {[key: string]: any}) => Promise<T>
delegate(operation: 'query' | 'mutation', fieldName: string, args: {
[key: string]: any;
}, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<any>;
delegateSubscription(fieldName: string, args?: {
[key: string]: any;
}, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<AsyncIterator<any>>;
getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers;
}
export interface BindingConstructor<T> {
new(...args: any[]): T
}
export const Binding = makeBindingClass<BindingConstructor<Binding>>({ schema: schema as any })
/**
* Types
*/
export type DishOrderByInput = 'createdAt_ASC' |
'createdAt_DESC' |
'updatedAt_ASC' |
'updatedAt_DESC' |
'deletedAt_ASC' |
'deletedAt_DESC' |
'name_ASC' |
'name_DESC' |
'stringEnumField_ASC' |
'stringEnumField_DESC' |
'kitchenSinkId_ASC' |
'kitchenSinkId_DESC'
export type KitchenSinkOrderByInput = 'createdAt_ASC' |
'createdAt_DESC' |
'updatedAt_ASC' |
'updatedAt_DESC' |
'deletedAt_ASC' |
'deletedAt_DESC' |
'stringField_ASC' |
'stringField_DESC' |
'nullableStringField_ASC' |
'nullableStringField_DESC' |
'dateField_ASC' |
'dateField_DESC' |
'dateOnlyField_ASC' |
'dateOnlyField_DESC' |
'dateTimeField_ASC' |
'dateTimeField_DESC' |
'emailField_ASC' |
'emailField_DESC' |
'integerField_ASC' |
'integerField_DESC' |
'booleanField_ASC' |
'booleanField_DESC' |
'floatField_ASC' |
'floatField_DESC' |
'idField_ASC' |
'idField_DESC' |
'stringEnumField_ASC' |
'stringEnumField_DESC' |
'numericField_ASC' |
'numericField_DESC' |
'numericFieldCustomPrecisionScale_ASC' |
'numericFieldCustomPrecisionScale_DESC' |
'noFilterField_ASC' |
'noFilterField_DESC' |
'characterField_ASC' |
'characterField_DESC' |
'readonlyField_ASC' |
'readonlyField_DESC' |
'apiOnlyField_ASC' |
'apiOnlyField_DESC'
export type StringEnum = 'FOO' |
'BAR'
export interface ApiOnlyCreateInput {
name: String
}
export interface ApiOnlyUpdateInput {
name?: String | null
}
export interface ApiOnlyWhereInput {
id_eq?: ID_Input | null
id_in?: ID_Output[] | ID_Output | null
createdAt_eq?: DateTime | null
createdAt_lt?: DateTime | null
createdAt_lte?: DateTime | null
createdAt_gt?: DateTime | null
createdAt_gte?: DateTime | null
createdById_eq?: ID_Input | null
createdById_in?: ID_Output[] | ID_Output | null
updatedAt_eq?: DateTime | null
updatedAt_lt?: DateTime | null
updatedAt_lte?: DateTime | null
updatedAt_gt?: DateTime | null
updatedAt_gte?: DateTime | null
updatedById_eq?: ID_Input | null
updatedById_in?: ID_Output[] | ID_Output | null
deletedAt_all?: Boolean | null
deletedAt_eq?: DateTime | null
deletedAt_lt?: DateTime | null
deletedAt_lte?: DateTime | null
deletedAt_gt?: DateTime | null
deletedAt_gte?: DateTime | null
deletedById_eq?: ID_Input | null
deletedById_in?: ID_Output[] | ID_Output | null
name_eq?: String | null
name_contains?: String | null
name_startsWith?: String | null
name_endsWith?: String | null
name_in?: String[] | String | null
}
export interface ApiOnlyWhereUniqueInput {
id: ID_Output
}
export interface BaseWhereInput {
id_eq?: String | null
id_in?: String[] | String | null
createdAt_eq?: String | null
createdAt_lt?: String | null
createdAt_lte?: String | null
createdAt_gt?: String | null
createdAt_gte?: String | null
createdById_eq?: String | null
updatedAt_eq?: String | null
updatedAt_lt?: String | null
updatedAt_lte?: String | null
updatedAt_gt?: String | null
updatedAt_gte?: String | null
updatedById_eq?: String | null
deletedAt_all?: Boolean | null
deletedAt_eq?: String | null
deletedAt_lt?: String | null
deletedAt_lte?: String | null
deletedAt_gt?: String | null
deletedAt_gte?: String | null
deletedById_eq?: String | null
}
export interface DishCreateInput {
name: String
stringEnumField?: StringEnum | null
kitchenSinkId: ID_Output
}
export interface DishUpdateInput {
name?: String | null
stringEnumField?: StringEnum | null
kitchenSinkId?: ID_Input | null
}
export interface DishWhereInput {
id_eq?: ID_Input | null
id_in?: ID_Output[] | ID_Output | null
createdAt_eq?: DateTime | null
createdAt_lt?: DateTime | null
createdAt_lte?: DateTime | null
createdAt_gt?: DateTime | null
createdAt_gte?: DateTime | null
createdById_eq?: ID_Input | null
createdById_in?: ID_Output[] | ID_Output | null
updatedAt_eq?: DateTime | null
updatedAt_lt?: DateTime | null
updatedAt_lte?: DateTime | null
updatedAt_gt?: DateTime | null
updatedAt_gte?: DateTime | null
updatedById_eq?: ID_Input | null
updatedById_in?: ID_Output[] | ID_Output | null
deletedAt_all?: Boolean | null
deletedAt_eq?: DateTime | null
deletedAt_lt?: DateTime | null
deletedAt_lte?: DateTime | null
deletedAt_gt?: DateTime | null
deletedAt_gte?: DateTime | null
deletedById_eq?: ID_Input | null
deletedById_in?: ID_Output[] | ID_Output | null
name_eq?: String | null
name_contains?: String | null
name_startsWith?: String | null
name_endsWith?: String | null
name_in?: String[] | String | null
stringEnumField_eq?: StringEnum | null
stringEnumField_in?: StringEnum[] | StringEnum | null
kitchenSinkId_eq?: ID_Input | null
kitchenSinkId_in?: ID_Output[] | ID_Output | null
}
export interface DishWhereUniqueInput {
id: ID_Output
}
export interface EventObjectInput {
params: EventParamInput
}
export interface EventParamInput {
type: String
name?: String | null
value: JSONObject
}
export interface KitchenSinkCreateInput {
stringField: String
nullableStringField?: String | null
dateField?: DateTime | null
dateOnlyField?: Date | null
dateTimeField?: DateTime | null
emailField: String
integerField: Float
booleanField: Boolean
floatField: Float
jsonField?: JSONObject | null
typedJsonField?: EventObjectInput | null
idField?: ID_Input | null
stringEnumField?: StringEnum | null
numericField?: Float | null
numericFieldCustomPrecisionScale?: Float | null
noFilterField?: String | null
noSortField?: String | null
noFilterOrSortField?: String | null
stringFieldFilterEqContains?: String | null
intFieldFilterLteGte?: Float | null
characterField?: String | null
customTextFieldNoSortOrFilter?: String | null
customFieldArrayColumn?: String[] | String | null
writeonlyField?: String | null
apiOnlyField?: String | null
arrayOfStrings?: String[] | String | null
arrayOfInts?: Int[] | Int | null
}
export interface KitchenSinkUpdateInput {
stringField?: String | null
nullableStringField?: String | null
dateField?: DateTime | null
dateOnlyField?: Date | null
dateTimeField?: DateTime | null
emailField?: String | null
integerField?: Float | null
booleanField?: Boolean | null
floatField?: Float | null
jsonField?: JSONObject | null
typedJsonField?: EventObjectInput | null
idField?: ID_Input | null
stringEnumField?: StringEnum | null
numericField?: Float | null
numericFieldCustomPrecisionScale?: Float | null
noFilterField?: String | null
noSortField?: String | null
noFilterOrSortField?: String | null
stringFieldFilterEqContains?: String | null
intFieldFilterLteGte?: Float | null
characterField?: String | null
customTextFieldNoSortOrFilter?: String | null
customFieldArrayColumn?: String[] | String | null
writeonlyField?: String | null
apiOnlyField?: String | null
arrayOfStrings?: String[] | String | null
arrayOfInts?: Int[] | Int | null
}
export interface KitchenSinkWhereInput {
id_eq?: ID_Input | null
id_in?: ID_Output[] | ID_Output | null
createdAt_eq?: DateTime | null
createdAt_lt?: DateTime | null
createdAt_lte?: DateTime | null
createdAt_gt?: DateTime | null
createdAt_gte?: DateTime | null
createdById_eq?: ID_Input | null
createdById_in?: ID_Output[] | ID_Output | null
updatedAt_eq?: DateTime | null
updatedAt_lt?: DateTime | null
updatedAt_lte?: DateTime | null
updatedAt_gt?: DateTime | null
updatedAt_gte?: DateTime | null
updatedById_eq?: ID_Input | null
updatedById_in?: ID_Output[] | ID_Output | null
deletedAt_all?: Boolean | null
deletedAt_eq?: DateTime | null
deletedAt_lt?: DateTime | null
deletedAt_lte?: DateTime | null
deletedAt_gt?: DateTime | null
deletedAt_gte?: DateTime | null
deletedById_eq?: ID_Input | null
deletedById_in?: ID_Output[] | ID_Output | null
stringField_eq?: String | null
stringField_contains?: String | null
stringField_startsWith?: String | null
stringField_endsWith?: String | null
stringField_in?: String[] | String | null
nullableStringField_eq?: String | null
nullableStringField_contains?: String | null
nullableStringField_startsWith?: String | null
nullableStringField_endsWith?: String | null
nullableStringField_in?: String[] | String | null
dateField_eq?: DateTime | null
dateField_lt?: DateTime | null
dateField_lte?: DateTime | null
dateField_gt?: DateTime | null
dateField_gte?: DateTime | null
dateOnlyField_eq?: Date | null
dateOnlyField_lt?: Date | null
dateOnlyField_lte?: Date | null
dateOnlyField_gt?: Date | null
dateOnlyField_gte?: Date | null
dateTimeField_eq?: DateTime | null
dateTimeField_lt?: DateTime | null
dateTimeField_lte?: DateTime | null
dateTimeField_gt?: DateTime | null
dateTimeField_gte?: DateTime | null
emailField_eq?: String | null
emailField_contains?: String | null
emailField_startsWith?: String | null
emailField_endsWith?: String | null
emailField_in?: String[] | String | null
integerField_eq?: Int | null
integerField_gt?: Int | null
integerField_gte?: Int | null
integerField_lt?: Int | null
integerField_lte?: Int | null
integerField_in?: Int[] | Int | null
booleanField_eq?: Boolean | null
booleanField_in?: Boolean[] | Boolean | null
floatField_eq?: Float | null
floatField_gt?: Float | null
floatField_gte?: Float | null
floatField_lt?: Float | null
floatField_lte?: Float | null
floatField_in?: Float[] | Float | null
jsonField_json?: JSONObject | null
typedJsonField_json?: JSONObject | null
idField_eq?: ID_Input | null
idField_in?: ID_Output[] | ID_Output | null
stringEnumField_eq?: StringEnum | null
stringEnumField_in?: StringEnum[] | StringEnum | null
numericField_eq?: Float | null
numericField_gt?: Float | null
numericField_gte?: Float | null
numericField_lt?: Float | null
numericField_lte?: Float | null
numericField_in?: Float[] | Float | null
numericFieldCustomPrecisionScale_eq?: Float | null
numericFieldCustomPrecisionScale_gt?: Float | null
numericFieldCustomPrecisionScale_gte?: Float | null
numericFieldCustomPrecisionScale_lt?: Float | null
numericFieldCustomPrecisionScale_lte?: Float | null
numericFieldCustomPrecisionScale_in?: Float[] | Float | null
noSortField_eq?: String | null
noSortField_contains?: String | null
noSortField_startsWith?: String | null
noSortField_endsWith?: String | null
noSortField_in?: String[] | String | null
stringFieldFilterEqContains_eq?: String | null
stringFieldFilterEqContains_contains?: String | null
intFieldFilterLteGte_gte?: Int | null
intFieldFilterLteGte_lte?: Int | null
characterField_eq?: String | null
characterField_contains?: String | null
characterField_startsWith?: String | null
characterField_endsWith?: String | null
characterField_in?: String[] | String | null
readonlyField_eq?: String | null
readonlyField_contains?: String | null
readonlyField_startsWith?: String | null
readonlyField_endsWith?: String | null
readonlyField_in?: String[] | String | null
apiOnlyField_eq?: String | null
apiOnlyField_contains?: String | null
apiOnlyField_startsWith?: String | null
apiOnlyField_endsWith?: String | null
apiOnlyField_in?: String[] | String | null
arrayOfStrings_containsAll?: String[] | String | null
arrayOfStrings_containsNone?: String[] | String | null
arrayOfStrings_containsAny?: String[] | String | null
arrayOfInts_containsAll?: Int[] | Int | null
arrayOfInts_containsNone?: Int[] | Int | null
arrayOfInts_containsAny?: Int[] | Int | null
}
export interface KitchenSinkWhereUniqueInput {
id?: ID_Input | null
emailField?: String | null
}
export interface BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
}
export interface DeleteResponse {
id: ID_Output
}
export interface ApiOnly extends BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
name: String
}
export interface BaseModel extends BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
}
export interface BaseModelUUID extends BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
}
export interface DbOnly extends BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
stringField: String
}
export interface Dish extends BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
name: String
stringEnumField?: StringEnum | null
kitchenSink: KitchenSink
kitchenSinkId: String
}
export interface DishConnection {
totalCount: Int
edges: Array<DishEdge>
pageInfo: PageInfo
}
export interface DishEdge {
node: Dish
cursor: String
}
export interface EventObject {
params: EventParam
}
export interface EventParam {
type: String
name?: String | null
value: JSONObject
}
export interface KitchenSink extends BaseGraphQLObject {
id: ID_Output
createdAt: DateTime
createdById: String
updatedAt?: DateTime | null
updatedById?: String | null
deletedAt?: DateTime | null
deletedById?: String | null
version: Int
stringField: String
nullableStringField?: String | null
dateField?: DateTime | null
dateOnlyField?: Date | null
dateTimeField?: DateTime | null
emailField: String
integerField: Int
booleanField: Boolean
floatField: Float
jsonField?: JSONObject | null
typedJsonField?: EventObject | null
idField?: String | null
stringEnumField?: StringEnum | null
dishes?: Array<Dish> | null
numericField?: Float | null
numericFieldCustomPrecisionScale?: Float | null
noFilterField?: String | null
noSortField?: String | null
noFilterOrSortField?: String | null
stringFieldFilterEqContains?: String | null
intFieldFilterLteGte?: Int | null
characterField?: String | null
customTextFieldNoSortOrFilter?: String | null
customFieldArrayColumn?: Array<String> | null
customTextFieldReadOnly?: String | null
readonlyField?: String | null
apiOnlyField?: String | null
arrayOfStrings?: Array<String> | null
arrayOfInts?: Array<Int> | null
}
export interface PageInfo {
hasNextPage: Boolean
hasPreviousPage: Boolean
startCursor?: String | null
endCursor?: String | null
}
export interface StandardDeleteResponse {
id: ID_Output
}
/*
The `Boolean` scalar type represents `true` or `false`.
*/
export type Boolean = boolean
/*
A date string, such as 2007-12-03, compliant with the `full-date` format
outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for
representation of dates and times using the Gregorian calendar.
*/
export type Date = string
/*
The javascript `Date` as string. Type represents date and time as the ISO Date string.
*/
export type DateTime = Date | string
/*
The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).
*/
export type Float = number
/*
The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.
*/
export type ID_Input = string | number
export type ID_Output = string
/*
The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.
*/
export type Int = number
/*
The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
*/
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export type JsonPrimitive = string | number | boolean | null | {};
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface JsonArray extends Array<JsonValue> {}
export type JsonObject = { [member: string]: JsonValue };
export type JSONObject = JsonObject;
/*
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
*/
export type String = string | the_stack |
import { BaseProjectLibrary, Component, Template, Util } from "@igniteui/cli-core";
import * as path from "path";
describe("Unit - Base project library ", () => {
it("has correct projects.", async done => {
const mockProjects = ["angular", "jquery"];
spyOn(Util, "getDirectoryNames").and.returnValue(mockProjects);
const library = new BaseProjectLibrary("../test");
expect(library.hasProject("angular")).toBe(true);
expect(library.projectIds).toEqual(mockProjects);
expect(Util.getDirectoryNames).toHaveBeenCalledWith(path.join("../test", "projects"));
done();
});
it("gets correct custom templates", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["bar-chart", "combo"]);
// spy on require(), https://coderwall.com/p/ck7w6g/spying-on-require-with-jasmine
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(path.join(__dirname, "custom-templates"))) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "Group",
id: folder,
name: folder + "Name"
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
expect(library.getCustomTemplateNames()).toEqual(["bar-chartName", "comboName"]);
done();
});
it("gets correct templates", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["bar-chart", "combo"], ["editors"]);
// spy on require(), https://coderwall.com/p/ck7w6g/spying-on-require-with-jasmine
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(path.join(__dirname, "custom-templates"))) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "CustomGroup",
id: folder,
name: folder + "CustomName"
};
}
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "Group",
id: folder,
name: folder + "Name",
templates: folder + "Template"
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
spyOn(library, "customTemplates");
expect(library.templates.length).toEqual(3);
expect(library.templates[2].name).toEqual("comboCustomName");
expect(library.components.length).toEqual(1);
expect(library.components[0].name).toEqual("editorsName");
done();
});
it("gets correct components", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["bar-chart", "combo"]);
// spy on require(), https://coderwall.com/p/ck7w6g/spying-on-require-with-jasmine
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "Group",
name: folder + "Name"
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
expect(library.components.length).toEqual(2);
expect(library.components[0].group).toEqual("bar-chartGroup");
expect(library.components[1].name).toEqual("comboName");
done();
});
it("gets template by id and name.", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["grid", "chart"], ["awesome"]);
// spy on require(), https://coderwall.com/p/ck7w6g/spying-on-require-with-jasmine
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(path.join(__dirname, "custom-templates"))) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "CustomGroup",
id: folder,
name: folder + "CustomName"
};
}
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
templates: {
group: folder + "TemplateGroup",
id: folder + "Template",
name: folder + "TemplateName"
}
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
//get templates by id
expect(library.getTemplateById("gridTemplate")).toBeTruthy();
expect(library.getTemplateById("gridtemplate")).toBeFalsy();
expect(library.getTemplateById("awesome")).toBeTruthy();
expect(library.getTemplateById("chartTemplate")).toBe(library.templates[1]);
//get templates by name
expect(library.getTemplateByName("gridTemplateName")).toBeTruthy();
expect(library.getTemplateByName("gridtemplatename")).toBeFalsy();
expect(library.getTemplateByName("awesomeCustomName")).toBeTruthy();
expect(library.getTemplateByName("chartTemplateName")).toBe(library.templates[1]);
done();
});
it("registers a template successfully.", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["grid", "chart"], ["awesome"]);
// spy on require(), https://coderwall.com/p/ck7w6g/spying-on-require-with-jasmine
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(path.join(__dirname, "custom-templates"))) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "CustomGroup",
id: folder,
name: folder + "CustomName"
};
}
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
templates: {
components: { name: folder + "ComponentName"},
group: folder + "TemplateGroup",
id: folder + "Template",
name: folder + "TemplateName"
}
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
const mockTemplate: Template = library.templates[0];
mockTemplate.components = ["newComponent"];
mockTemplate.name = "newName";
library.registerTemplate(mockTemplate);
expect(library.getTemplateById("gridTemplate")).toBeTruthy();
expect(library.getTemplateByName("newName")).toBeTruthy();
expect(library.getComponentByName("newComponent")).toBeTruthy();
expect(library.templates.length).toEqual(3);
done();
});
it("gets [custom] component by name.", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["grid", "chart"], ["awesome"]);
// spy on require(), https://coderwall.com/p/ck7w6g/spying-on-require-with-jasmine
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(path.join(__dirname, "custom-templates"))) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "CustomGroup",
id: folder,
name: folder + "CustomName"
};
}
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
group: folder + "Group",
name: folder + "Name"
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
//get components by name
expect(library.getComponentByName("chartName")).toBeTruthy();
expect(library.getComponentByName("chartname")).toBeFalsy();
expect(library.getComponentByName("awesomeCustomName")).toBeFalsy();
expect(library.getCustomTemplateByName("awesomeCustomName")).toBeTruthy();
expect(library.getComponentByName("gridName")).toBe(library.components[0]);
done();
});
it("gets correct component groups", async done => {
const hash = ["Grids & Lists Group", "Charts Group", "Maps Group", "Gauges Group", "Data Entry & Display Group"];
spyOn(Util, "getDirectoryNames").and.returnValues
(["Grids & Lists", "Charts", "Maps", "Gauges", "Data Entry & Display"]);
const library = new BaseProjectLibrary(__dirname);
spyOn(library.groupDescriptions, "keys")
.and.returnValue(hash);
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
return {
group: folder + " Group"
};
} else {
fail("unexpected require");
}
});
spyOn(library, "components")
.and.returnValues(["IgxAutocompleteComponent", "IgxBulletGraphAnimationComponent", "IgxCalendarComponent", "IgxCarouselComponent"]);
expect(library.getComponentGroupNames()).toEqual([
"Grids & Lists Group", "Charts Group", "Maps Group", "Gauges Group", "Data Entry & Display Group"]);
done();
});
it("gets correct component names by group", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["chart", "combo", "grid"]);
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
const folder = path.basename(modulePath);
if (folder !== "grid") {
return {
description: "common description",
group: "commonGroup",
groupPriority: 1,
name: folder,
templates: []
};
}
if (folder === "grid") {
return {
description: "grid description",
group: folder + "Group",
groupPriority: 2,
name: folder,
templates: []
};
} else {
fail("unexpected require");
}
});
const expectedCommonGroup: Component[] = [
{ name: "chart", description: "common description", group: "commonGroup", groupPriority: 1, templates: [] },
{ name: "combo", description: "common description", group: "commonGroup", groupPriority: 1, templates: [] }
];
const expectedGridGroup: Component[] = [
{ name: "grid", description: "grid description", group: "gridGroup", groupPriority: 2, templates: [] }
];
const library = new BaseProjectLibrary(__dirname);
expect(library.getComponentsByGroup("commonGroup")).toEqual(expectedCommonGroup);
expect(library.getComponentsByGroup("gridGroup")).toEqual(expectedGridGroup);
done();
});
it("should sort component in a group based on priority", async done => {
spyOnProperty(BaseProjectLibrary.prototype, "components").and.returnValue([
{ name: "Component1", group: "commonGroup", groupPriority: 1 },
{ name: "Component2", group: "commonGroup", groupPriority: 20 },
{ name: "Component3", group: "commonGroup", groupPriority: 13 },
{ name: "Component4", group: "commonGroup", groupPriority: 4 },
{ name: "Component5", group: "commonGroup", groupPriority: -4 },
{ name: "Component6", group: "commonGroup", groupPriority: 0 },
{ name: "Component7", group: "commonGroup", groupPriority: 0 }
] as Component[]);
const library = new BaseProjectLibrary(__dirname);
expect(library.getComponentsByGroup("commonGroup").map(x => x.name)).toEqual(
["Component2", "Component3", "Component4", "Component1", "Component6", "Component7", "Component5"]
);
done();
});
it("gets correct project", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["chart", "combo", "grid"]);
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
return {
group: folder + "Group"
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
expect(library.getProject("grid")).toBeTruthy();
done();
});
it("has template.", async done => {
spyOn(Util, "getDirectoryNames").and.returnValues(["chart", "combo", "grid"], ["customControl"]);
spyOn(require("module"), "_load").and.callFake((modulePath: string) => {
if (modulePath.startsWith(path.join(__dirname, "custom-templates"))) {
const folder = path.basename(modulePath);
// tslint:disable-next-line:no-object-literal-type-assertion
return {
id: folder + "Custom"
};
}
if (modulePath.startsWith(__dirname)) {
const folder = path.basename(modulePath);
return {
templates: {
id: folder
}
};
} else {
fail("unexpected require");
}
});
const library = new BaseProjectLibrary(__dirname);
expect(library.hasTemplate("grid")).toBeTruthy();
expect(library.hasTemplate("combo")).toBeTruthy();
expect(library.hasTemplate("customControlCustom")).toBeTruthy();
done();
});
}); | the_stack |
/// <reference path="../../../elements.d.ts" />
import { Polymer } from "../../../../../tools/definitions/polymer";
import { PaperDropdownMenu, PaperDropdownMenuBase } from '../paper-dropdown-menu/paper-dropdown-menu';
import { PaperLibrariesSelectorBase } from '../../editpages/code-edit-pages/tools/paper-libraries-selector/paper-libraries-selector';
namespace PaperDropdownBehaviorNamespace {
export const paperDropdownBehaviorProperties: {
raised: boolean;
overflowing: boolean;
unselectable: boolean;
} = {
raised: {
type: Boolean,
value: false
},
overflowing: {
type: Boolean,
value: false
},
unselectable: {
type: Boolean,
value: false
}
} as any;
type PaperDropdownListener = (prevState: number, newState: number) => void;
export class PDB {
static properties = paperDropdownBehaviorProperties;
/**
* The start time for the current animation
*/
static _startTime: number = null;
/**
* The paper dropdown menu element
*/
static _paperDropdownEl: PaperDropdownMenu = null;
/**
* The paper menu element
*/
static _paperMenu: HTMLPaperMenuElement = null;
/**
* The dropdown selected container
*/
static _dropdownSelectedCont: HTMLElement = null;
/**
* The listeners for this element
*/
static _listeners: {
listener: PaperDropdownListener;
id: string;
thisArg: any;
}[];
/**
* Whether the menu is expanded
*/
static _expanded: boolean = false;
/**
* Whether the menu should have an indent from the left part of the screen
*/
static indent: boolean = true;
/**
* Whether the menu is disabled
*/
static disabled: boolean = false;
/**
* A function that is called whenever the dialog opens
*/
static onopen: () => void;
/**
* The listeners on clicking the items
*/
static _elementListeners: (() => void)[] = [];
/**
* Adds a listener that fires when a new value is selected
*/
static _addListener(this: PaperDropdownInstance, listener: PaperDropdownListener,
id: string, thisArg: any) {
let found = false;
for (let i = 0; i < this._listeners.length; i++) {
if (this._listeners[i].listener === listener && this._listeners[i].id === id) {
found = true;
}
}
if (!found) {
this._listeners.push({
id: id,
listener: listener,
thisArg: thisArg
});
}
};
static onValueChange(this: PaperDropdownInstance, _oldState: number|number[], _newState: number|number[]) { }
/**
* Fires all added listeners, triggers when a new value is selected
*/
static _fireListeners(this: PaperDropdownInstance, oldState: number|number[]) {
const newState = this.selected;
this._listeners.forEach((listener) => {
if (listener.id === this.id) {
listener.listener.apply(listener.thisArg, [oldState, newState]);
}
});
this.onValueChange(oldState, newState);
};
static _getMenuContent(this: PaperDropdownInstance) {
return this.getMenu().$.content.assignedNodes()[0] as HTMLElement;
}
static querySlot<K extends keyof Polymer.ElementTagNameMap>(parent: HTMLElement|Polymer.RootElement,
selector?: string, slotSelector?: string): (HTMLElement|Polymer.PolymerElement)[] | null
static querySlot<K extends keyof Polymer.ElementTagNameMap>(parent: HTMLElement|Polymer.RootElement,
selector?: K, slotSelector?: string): (Polymer.ElementTagNameMap[K])[] | null
static querySlot<K extends keyof Polymer.ElementTagNameMap>(parent: HTMLElement|Polymer.RootElement,
selector?: string, slotSelector?: string): HTMLElement[] | null
static querySlot<K extends keyof Polymer.ElementTagNameMap>(parent: HTMLElement|Polymer.RootElement,
selector: K|string = null, slotSelector: string = 'slot'): (Polymer.ElementTagNameMap[K]|HTMLElement)[] | null {
const selectFn = '$$' in parent ? (parent as any).$$ : parent.querySelector;
const slotChildren = (selectFn.bind(parent)(slotSelector) as HTMLSlotElement).assignedNodes().filter((node) => {
return node.nodeType !== node.TEXT_NODE;
}) as HTMLElement[];
if (!selector) {
return slotChildren;
}
const result = (slotChildren.map((node: HTMLElement) => {
return node.querySelectorAll(selector)
}).reduce((prev, current) => {
let arr: (HTMLElement|Polymer.ElementTagNameMap[K])[] = [];
if (prev) {
arr = arr.concat(Array.prototype.slice.apply(prev));
}
if (current) {
arr = arr.concat(Array.prototype.slice.apply(current));
}
return arr as any;
}) as any) as (Polymer.ElementTagNameMap[K]|HTMLElement)[];
if (!Array.isArray(result)) {
return Array.prototype.slice.apply(result);
}
return result;
}
static doHighlight(this: PaperDropdownInstance) {
const content = this._getMenuContent();
const paperItems = Array.prototype.slice.apply(content.querySelectorAll('paper-item'));
paperItems.forEach((paperItem: HTMLPaperItemElement, index: number) => {
const checkMark = this.querySlot(paperItem)[0] as HTMLElement;
if (!checkMark) {
return;
}
const selectedArr = Array.isArray(this.selected) ?
this.selected : [this.selected];
if (selectedArr.indexOf(index) > -1) {
checkMark.style.opacity = '1';
} else {
checkMark.style.opacity = '0';
}
});
}
static refreshListeners(this: PaperDropdownInstance) {
const content = this._getMenuContent();
const paperItems = Array.prototype.slice.apply(content.querySelectorAll('paper-item'));
const oldListeners = this._elementListeners;
this._elementListeners = [];
paperItems.forEach((paperItem: HTMLPaperItemElement, index: number) => {
oldListeners.forEach((listener) => {
paperItem.removeEventListener('click', listener);
});
const fn = () => {
const oldSelected = this.selected;
if (!this.unselectable) {
this.set('selected', index);
}
setTimeout(() => {
if (!this.unselectable) {
this.doHighlight();
}
this._fireListeners(oldSelected);
if ((this as any)._dropdownSelectChange) {
(this as any)._dropdownSelectChange(this);
}
this.close();
}, 50);
}
this._elementListeners.push(fn);
paperItem.addEventListener('click', fn);
});
};
static getMenu(this: PaperDropdownInstance) {
if (this._paperMenu) {
return this._paperMenu;
}
return (this._paperMenu = (this as any)._getMenu());
}
static attached(this: PaperDropdownMenu) {
const __this = this;
this._paperDropdownEl = this;
this._dropdownSelectedCont = this.$.dropdownSelectedCont;
if (this.getAttribute('indent') === 'false') {
this.indent = false;
}
if (this.raised) {
window.requestAnimationFrame(function(time) {
__this._animateBoxShadowIn(time, __this);
});
}
this._expanded = true;
const interval = window.setInterval(() => {
if (this.getMenu() && this._getMenuContent()) {
const content = this._getMenuContent();
if (this.overflowing) {
content.style.position = 'absolute';
}
content.style.backgroundColor = 'white';
window.clearInterval(interval);
this.close();
this.refreshListeners();
const innerInterval = window.setInterval(() => {
if (this._getMenuContent().querySelectorAll('paper-item')[0] &&
this.querySlot(this._getMenuContent().querySelectorAll('paper-item')[0]).length > 0) {
this.doHighlight();
window.clearInterval(innerInterval);
}
}, 250);
}
}, 250);
};
/**
* Animates the box-shadow in on clicking the main blue text
*/
static _animateBoxShadowIn(timestamp: number, __this: PaperDropdownInstance) {
if (!__this._startTime) {
__this._startTime = timestamp;
}
if (timestamp - 100 < __this._startTime) {
const scale = ((timestamp - __this._startTime) / 100);
let doubleScale = scale * 2;
__this._getMenuContent().style.boxShadow = '0 ' + doubleScale + 'px ' + doubleScale + 'px 0 rgba(0,0,0,0.14),' +
' 0 ' + scale + 'px ' + (5 * scale) + 'px 0 rgba(0,0,0,0.12),' +
' 0 ' + (scale * 3) + 'px ' + scale + 'px ' + -doubleScale + 'px rgba(0,0,0,0.2)';
if (!__this.indent) {
__this._dropdownSelectedCont.style.marginLeft = (scale * 15) + 'px';
}
window.requestAnimationFrame(function(time) {
__this._animateBoxShadowIn(time, __this);
});
}
else {
if (!__this.indent) {
__this._dropdownSelectedCont.style.marginLeft = '15px';
}
__this._startTime = null;
__this._getMenuContent().style.boxShadow = '0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2)';
}
};
/**
* Animates the box-shadow out on clicking the main blue text again
*/
static _animateBoxShadowOut(timestamp: number, __this: PaperDropdownInstance) {
if (!__this._startTime) {
__this._startTime = timestamp;
}
if (timestamp - 100 < __this._startTime) {
const scale = 1 - (((timestamp - __this._startTime) / 100));
let doubleScale = scale * 2;
__this.getMenu().style.boxShadow = '0 ' + doubleScale + 'px ' + doubleScale + 'px 0 rgba(0,0,0,0.14),' +
' 0 ' + scale + 'px ' + (5 * scale) + 'px 0 rgba(0,0,0,0.12),' +
' 0 ' + (scale * 3) + 'px ' + scale + 'px ' + -doubleScale + 'px rgba(0,0,0,0.2)';
if (!__this.indent) {
__this._dropdownSelectedCont.style.marginLeft = (scale * 15) + 'px';
}
window.requestAnimationFrame(function (time) {
__this._animateBoxShadowOut(time, __this);
});
}
else {
if (!__this.indent) {
__this._dropdownSelectedCont.style.marginLeft = '0';
}
__this._startTime = null;
__this.getMenu().style.boxShadow = 'rgba(0, 0, 0, 0) 0 0 0 0, rgba(0, 0, 0, 0) 0 0 0 0, rgba(0, 0, 0, 0) 0 0 0 0';
if (__this._paperDropdownEl.$.dropdownArrow) {
window.setTransform(__this._paperDropdownEl.$.dropdownArrow, 'rotate(90deg)');
}
}
};
/**
* Open the dropdown menu
*/
static open(this: PaperDropdownInstance) {
if (this.onopen) {
this.onopen();
}
this.fire('expansionStateChange', {
state: 'opening'
});
if (!this._expanded) {
this._expanded = true;
if (!this.raised) {
window.requestAnimationFrame((time) => {
this._animateBoxShadowIn(time, this);
});
}
setTimeout(() => {
const content = this._getMenuContent();
content.style.display = 'block';
const animation: {
[key: string]: any
} = {
height: content.scrollHeight
};
if (this.overflowing) {
animation['marginBottom'] = -(content.scrollHeight + 14);
}
$(content).stop().animate(animation, {
easing: 'easeOutCubic',
duration: 300,
complete: () => {
if (this.$.dropdownArrow) {
window.setTransform(this.$.dropdownArrow, 'rotate(270deg)');
}
this.fire('expansionStateChange', {
state: 'opened'
});
}
});
}, 100);
}
};
/**
* Close the dropdown menu
*/
static close(this: PaperDropdownInstance) {
return new Promise<void>((resolve) => {
if (this._expanded) {
this._expanded = false;
const animation: {
[key: string]: any;
} = {
height: 0
};
if (this.overflowing) {
animation['marginBottom'] = -15;
}
this.fire('expansionStateChange', {
state: 'closing'
});
$(this._getMenuContent()).stop().animate(animation, {
easing: 'swing',
duration: 300,
complete: () => {
this._getMenuContent().style.display = 'none';
if (!this.raised) {
window.requestAnimationFrame((time) => {
this._animateBoxShadowOut(time, this);
});
this.fire('expansionStateChange', {
state: 'closed'
});
resolve(null);
}
}
});
} else {
resolve(null);
}
});
};
/**
* Toggles the dropdown menu, tirggers on clicking the main blue text
*/
static _toggleDropdown(this: PaperDropdownInstance) {
if (!this.disabled) {
(this._expanded ? this.close() : this.open());
}
};
/**
* Gets the currently selected item(s)
* @returns {Array} The currently selected item(s) in array form
*/
static getSelected(this: PaperDropdownInstance): number[] {
if (this.shadowRoot.querySelectorAll('.iron-selected.addLibrary')) {
(this.selected as number[]).pop();
}
if (typeof this.selected === 'number') {
return [this.selected];
}
return this.selected;
};
static disable(this: PaperDropdownInstance) {
this.disabled = true;
this._expanded && this.close && this.close();
this.$.dropdownSelected.style.color = 'rgb(176, 220, 255)';
};
static enable(this: PaperDropdownInstance) {
this.disabled = false;
this.$.dropdownSelected.style.color = 'rgb(38, 153, 244)';
}
static ready(this: PaperDropdownInstance) {
this._listeners = [];
}
}
window.Polymer.PaperDropdownBehavior = PDB as PaperDropdownBehaviorBase;
}
export type PaperDropdownBehaviorBase = Polymer.El<'paper-dropdown-behavior',
typeof PaperDropdownBehaviorNamespace.PDB & typeof PaperDropdownBehaviorNamespace.paperDropdownBehaviorProperties
>;
export type PaperDropdownBehavior<T> = T & PaperDropdownBehaviorBase;
type PaperDropdownInstance = PaperDropdownBehavior<
PaperLibrariesSelectorBase|PaperDropdownMenuBase
>; | the_stack |
import * as React from 'react'
import { getWellRatio } from '../utils'
import { canPipetteUseLabware } from '../../utils'
import { MAGNETIC_MODULE_V1, MAGNETIC_MODULE_V2 } from '@opentrons/shared-data'
import { getPipetteCapacity } from '../../pipettes/pipetteData'
import {
MIN_ENGAGE_HEIGHT_V1,
MAX_ENGAGE_HEIGHT_V1,
MIN_ENGAGE_HEIGHT_V2,
MAX_ENGAGE_HEIGHT_V2,
PAUSE_UNTIL_RESUME,
PAUSE_UNTIL_TIME,
PAUSE_UNTIL_TEMP,
THERMOCYCLER_PROFILE,
} from '../../constants'
import { StepFieldName } from '../../form-types'
/*******************
** Error Messages **
********************/
export type FormErrorKey =
| 'INCOMPATIBLE_ASPIRATE_LABWARE'
| 'INCOMPATIBLE_DISPENSE_LABWARE'
| 'INCOMPATIBLE_LABWARE'
| 'WELL_RATIO_MOVE_LIQUID'
| 'PAUSE_TYPE_REQUIRED'
| 'VOLUME_TOO_HIGH'
| 'TIME_PARAM_REQUIRED'
| 'PAUSE_TEMP_PARAM_REQUIRED'
| 'MAGNET_ACTION_TYPE_REQUIRED'
| 'ENGAGE_HEIGHT_MIN_EXCEEDED'
| 'ENGAGE_HEIGHT_MAX_EXCEEDED'
| 'ENGAGE_HEIGHT_REQUIRED'
| 'MODULE_ID_REQUIRED'
| 'TARGET_TEMPERATURE_REQUIRED'
| 'BLOCK_TEMPERATURE_REQUIRED'
| 'LID_TEMPERATURE_REQUIRED'
| 'PROFILE_VOLUME_REQUIRED'
| 'PROFILE_LID_TEMPERATURE_REQUIRED'
| 'BLOCK_TEMPERATURE_HOLD_REQUIRED'
| 'LID_TEMPERATURE_HOLD_REQUIRED'
export interface FormError {
title: string
body?: React.ReactNode
dependentFields: StepFieldName[]
}
const INCOMPATIBLE_ASPIRATE_LABWARE: FormError = {
title: 'Selected aspirate labware is incompatible with selected pipette',
dependentFields: ['aspirate_labware', 'pipette'],
}
const INCOMPATIBLE_DISPENSE_LABWARE: FormError = {
title: 'Selected dispense labware is incompatible with selected pipette',
dependentFields: ['dispense_labware', 'pipette'],
}
const INCOMPATIBLE_LABWARE: FormError = {
title: 'Selected labware is incompatible with selected pipette',
dependentFields: ['labware', 'pipette'],
}
const PAUSE_TYPE_REQUIRED: FormError = {
title:
'Must either pause for amount of time, until told to resume, or until temperature reached',
dependentFields: ['pauseAction'],
}
const TIME_PARAM_REQUIRED: FormError = {
title: 'Must include hours, minutes, or seconds',
dependentFields: ['pauseAction', 'pauseHour', 'pauseMinute', 'pauseSecond'],
}
const PAUSE_TEMP_PARAM_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['pauseAction', 'pauseTemperature'],
}
const VOLUME_TOO_HIGH = (pipetteCapacity: number): FormError => ({
title: `Volume is greater than maximum pipette/tip volume (${pipetteCapacity} ul)`,
dependentFields: ['pipette', 'volume'],
})
const WELL_RATIO_MOVE_LIQUID: FormError = {
title: 'Well selection must be 1 to many, many to 1, or N to N',
dependentFields: ['aspirate_wells', 'dispense_wells'],
}
const MAGNET_ACTION_TYPE_REQUIRED: FormError = {
title: 'Action type must be either engage or disengage',
dependentFields: ['magnetAction'],
}
const ENGAGE_HEIGHT_REQUIRED: FormError = {
title: 'Engage height is required',
dependentFields: ['magnetAction', 'engageHeight'],
}
const ENGAGE_HEIGHT_MIN_EXCEEDED: FormError = {
title: 'Specified distance is below module minimum',
dependentFields: ['magnetAction', 'engageHeight'],
}
const ENGAGE_HEIGHT_MAX_EXCEEDED: FormError = {
title: 'Specified distance is above module maximum',
dependentFields: ['magnetAction', 'engageHeight'],
}
const MODULE_ID_REQUIRED: FormError = {
title:
'Module is required. Ensure the appropriate module is present on the deck and selected for this step',
dependentFields: ['moduleId'],
}
const TARGET_TEMPERATURE_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['setTemperature', 'targetTemperature'],
}
const PROFILE_VOLUME_REQUIRED: FormError = {
title: 'Volume is required',
dependentFields: ['thermocyclerFormType', 'profileVolume'],
}
const PROFILE_LID_TEMPERATURE_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['thermocyclerFormType', 'profileTargetLidTemp'],
}
const LID_TEMPERATURE_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['lidIsActive', 'lidTargetTemp'],
}
const BLOCK_TEMPERATURE_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['blockIsActive', 'blockTargetTemp'],
}
const BLOCK_TEMPERATURE_HOLD_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['blockIsActiveHold', 'blockTargetTempHold'],
}
const LID_TEMPERATURE_HOLD_REQUIRED: FormError = {
title: 'Temperature is required',
dependentFields: ['lidIsActiveHold', 'lidTargetTempHold'],
}
export type FormErrorChecker = (arg: unknown) => FormError | null
// TODO: test these
/*******************
** Error Checkers **
********************/
// TODO: real HydratedFormData type
type HydratedFormData = any
export const incompatibleLabware = (
fields: HydratedFormData
): FormError | null => {
const { labware, pipette } = fields
if (!labware || !pipette) return null
return !canPipetteUseLabware(pipette.spec, labware.def)
? INCOMPATIBLE_LABWARE
: null
}
export const incompatibleDispenseLabware = (
fields: HydratedFormData
): FormError | null => {
const { dispense_labware, pipette } = fields
if (!dispense_labware || !pipette) return null
return !canPipetteUseLabware(pipette.spec, dispense_labware.def)
? INCOMPATIBLE_DISPENSE_LABWARE
: null
}
export const incompatibleAspirateLabware = (
fields: HydratedFormData
): FormError | null => {
const { aspirate_labware, pipette } = fields
if (!aspirate_labware || !pipette) return null
return !canPipetteUseLabware(pipette.spec, aspirate_labware.def)
? INCOMPATIBLE_ASPIRATE_LABWARE
: null
}
export const pauseForTimeOrUntilTold = (
fields: HydratedFormData
): FormError | null => {
const {
pauseAction,
pauseHour,
pauseMinute,
pauseSecond,
moduleId,
pauseTemperature,
} = fields
if (pauseAction === PAUSE_UNTIL_TIME) {
// user selected pause for amount of time
const hours = parseFloat(pauseHour) || 0
const minutes = parseFloat(pauseMinute) || 0
const seconds = parseFloat(pauseSecond) || 0
const totalSeconds = hours * 3600 + minutes * 60 + seconds
return totalSeconds <= 0 ? TIME_PARAM_REQUIRED : null
} else if (pauseAction === PAUSE_UNTIL_TEMP) {
// user selected pause until temperature reached
if (moduleId == null) {
// missing module field (reached by deleting a module from deck)
return MODULE_ID_REQUIRED
}
if (!pauseTemperature) {
// missing temperature field
return PAUSE_TEMP_PARAM_REQUIRED
}
return null
} else if (pauseAction === PAUSE_UNTIL_RESUME) {
// user selected pause until resume
return null
} else {
// user did not select a pause type
return PAUSE_TYPE_REQUIRED
}
}
export const wellRatioMoveLiquid = (
fields: HydratedFormData
): FormError | null => {
const { aspirate_wells, dispense_wells } = fields
if (!aspirate_wells || !dispense_wells) return null
return getWellRatio(aspirate_wells, dispense_wells)
? null
: WELL_RATIO_MOVE_LIQUID
}
export const volumeTooHigh = (fields: HydratedFormData): FormError | null => {
const { pipette } = fields
const volume = Number(fields.volume)
const pipetteCapacity = getPipetteCapacity(pipette)
if (
!Number.isNaN(volume) &&
!Number.isNaN(pipetteCapacity) &&
volume > pipetteCapacity
) {
return VOLUME_TOO_HIGH(pipetteCapacity)
}
return null
}
export const magnetActionRequired = (
fields: HydratedFormData
): FormError | null => {
const { magnetAction } = fields
if (!magnetAction) return MAGNET_ACTION_TYPE_REQUIRED
return null
}
export const engageHeightRequired = (
fields: HydratedFormData
): FormError | null => {
const { magnetAction, engageHeight } = fields
return magnetAction === 'engage' && !engageHeight
? ENGAGE_HEIGHT_REQUIRED
: null
}
export const moduleIdRequired = (
fields: HydratedFormData
): FormError | null => {
const { moduleId } = fields
if (moduleId == null) return MODULE_ID_REQUIRED
return null
}
export const targetTemperatureRequired = (
fields: HydratedFormData
): FormError | null => {
const { setTemperature, targetTemperature } = fields
return setTemperature === 'true' && !targetTemperature
? TARGET_TEMPERATURE_REQUIRED
: null
}
export const profileVolumeRequired = (
fields: HydratedFormData
): FormError | null => {
const { thermocyclerFormType, profileVolume } = fields
return thermocyclerFormType === THERMOCYCLER_PROFILE && !profileVolume
? PROFILE_VOLUME_REQUIRED
: null
}
export const profileTargetLidTempRequired = (
fields: HydratedFormData
): FormError | null => {
const { thermocyclerFormType, profileTargetLidTemp } = fields
return thermocyclerFormType === THERMOCYCLER_PROFILE && !profileTargetLidTemp
? PROFILE_LID_TEMPERATURE_REQUIRED
: null
}
export const blockTemperatureRequired = (
fields: HydratedFormData
): FormError | null => {
const { blockIsActive, blockTargetTemp } = fields
return blockIsActive === true && !blockTargetTemp
? BLOCK_TEMPERATURE_REQUIRED
: null
}
export const lidTemperatureRequired = (
fields: HydratedFormData
): FormError | null => {
const { lidIsActive, lidTargetTemp } = fields
return lidIsActive === true && !lidTargetTemp
? LID_TEMPERATURE_REQUIRED
: null
}
export const blockTemperatureHoldRequired = (
fields: HydratedFormData
): FormError | null => {
const { blockIsActiveHold, blockTargetTempHold } = fields
return blockIsActiveHold === true && !blockTargetTempHold
? BLOCK_TEMPERATURE_HOLD_REQUIRED
: null
}
export const lidTemperatureHoldRequired = (
fields: HydratedFormData
): FormError | null => {
const { lidIsActiveHold, lidTargetTempHold } = fields
return lidIsActiveHold === true && !lidTargetTempHold
? LID_TEMPERATURE_HOLD_REQUIRED
: null
}
export const engageHeightRangeExceeded = (
fields: HydratedFormData
): FormError | null => {
const { magnetAction, engageHeight } = fields
const moduleEntity = fields.meta?.module
const model = moduleEntity?.model
if (magnetAction === 'engage') {
if (model === MAGNETIC_MODULE_V1) {
if (engageHeight < MIN_ENGAGE_HEIGHT_V1) {
return ENGAGE_HEIGHT_MIN_EXCEEDED
} else if (engageHeight > MAX_ENGAGE_HEIGHT_V1) {
return ENGAGE_HEIGHT_MAX_EXCEEDED
}
} else if (model === MAGNETIC_MODULE_V2) {
if (engageHeight < MIN_ENGAGE_HEIGHT_V2) {
return ENGAGE_HEIGHT_MIN_EXCEEDED
} else if (engageHeight > MAX_ENGAGE_HEIGHT_V2) {
return ENGAGE_HEIGHT_MAX_EXCEEDED
}
} else {
console.warn(`unhandled model for engageHeightRangeExceeded: ${model}`)
}
}
return null
}
/*******************
** Helpers **
********************/
type ComposeErrors = (
...errorCheckers: FormErrorChecker[]
) => (arg: unknown) => FormError[]
export const composeErrors: ComposeErrors = (
...errorCheckers: FormErrorChecker[]
) => value =>
errorCheckers.reduce<FormError[]>((acc, errorChecker) => {
const possibleError = errorChecker(value)
return possibleError ? [...acc, possibleError] : acc
}, []) | the_stack |
import React, { useEffect, useState, useCallback, useRef } from "react";
import ForceGraph2D from "react-force-graph-2d";
import { nodeFillColor, riskOutline } from "./graphVizualization/nodeColoring";
import { calcLinkColor } from "./graphVizualization/linkCalcs";
import { nodeSize } from "./graphVizualization/nodeCalcs";
import { updateGraph } from "./graphUpdates/updateGraph";
import { Link, VizNode, VizGraph } from "../../types/CustomTypes";
import {
GraphState,
GraphDisplayState,
GraphDisplayProps,
} from "../../types/GraphDisplayTypes";
import { colors } from "./graphVizualization/graphColors";
type ClickedNodeState = VizNode | null;
const defaultGraphDisplayState = (
lensName: string | null
): GraphDisplayState => {
return {
graphData: { nodes: [], links: [], index: {} },
curLensName: lensName,
};
};
const defaultClickedState = (): ClickedNodeState => {
return null;
};
async function updateGraphAndSetState(
lensName: any,
state: any,
setState: any
) {
if (lensName) {
await updateGraph(lensName, state as GraphState, setState); // state is safe cast
}
}
const GraphDisplay = ({ lensName, setCurNode }: GraphDisplayProps) => {
const fgRef: any = useRef(); // fix graph to canvas
const [state, setState] = useState(defaultGraphDisplayState(lensName));
const [clickedNode, setClickedNode] = useState(defaultClickedState());
const [highlightNodes, setHighlightNodes] = useState(new Set());
const [highlightLinks, setHighlightLinks] = useState(new Set());
const [hoverNode, setHoverNode] = useState(null);
const [stopEngine, setStopEngine] = useState(false);
const lastLens = useRef(lensName);
const lastInterval: any = useRef(null);
const stateRef: any = useRef(state);
// TODO is there a way to updateGraphAndSetState immediately on click?
useEffect(() => {
stateRef.current = state;
// If our lens nodes have changed clear the last interval and load the new state
if (lastLens.current !== lensName && lastInterval.current !== null) {
console.log(
"clearing interval because lens changed",
lastLens.current,
lensName
);
clearInterval(lastInterval.current);
lastInterval.current = null;
lastLens.current = lensName;
stateRef.current = defaultGraphDisplayState(lensName);
updateGraphAndSetState(
lensName,
defaultGraphDisplayState(lensName),
setState
);
}
// If there's no interval and we have a lens selected, start the interval
if (lensName && lastInterval.current === null) {
console.info("starting new interval", lensName, lastLens.current);
try {
lastLens.current = lensName;
updateGraphAndSetState(
lensName,
defaultGraphDisplayState(lensName),
setState
);
const interval = setInterval(() => {
// Invalidate the interval if the lens changes - this ensures we never race
try {
if (lastLens.current !== lensName) {
console.info(
"clearing interval",
lastLens.current,
lensName
);
clearInterval(lastInterval.current);
lastInterval.current = null;
stateRef.current =
defaultGraphDisplayState(lensName);
} else {
updateGraphAndSetState(
lensName,
stateRef.current,
setState
);
}
} catch (e) {
console.log("Error setting interval", e);
}
}, 1000);
lastInterval.current = interval;
} catch (e) {
console.debug("Error Updating Graph", e);
}
}
}, [state, lensName]);
const data = state.graphData;
const updateHighlight = useCallback(() => {
setHighlightNodes(highlightNodes);
setHighlightLinks(highlightLinks);
}, [highlightNodes, highlightLinks]);
const nodeClick = useCallback(
(_node, ctx) => {
const node = _node as any;
const links = node.links;
const neighbors = node.neighbors;
// remove neighbors and links for node detail table iteration (react can only iterate through arrays)
delete node.links;
delete node.neighbors;
setCurNode(node);
setClickedNode(node || null);
// re-add neighbors for highlighting links
node.links = links;
node.neighbors = neighbors;
},
[setCurNode, setClickedNode]
);
const nodeHover = useCallback(
(node, ctx) => {
highlightNodes.clear();
highlightLinks.clear();
if (node) {
const _node = node as any;
highlightNodes.add(_node);
if (!_node.neighbors) {
return;
}
_node.neighbors.forEach((neighbor: VizNode) => {
highlightNodes.add(neighbor);
});
_node.links.forEach((link: Link) => {
highlightLinks.add(link);
});
}
setHoverNode((node as any) || null);
updateHighlight();
},
[setHoverNode, updateHighlight, highlightLinks, highlightNodes]
);
//We only want to rerender when the id of a node changes, but we don't want to update based on any of its other attributes
let clickedNodeKey = null;
if (clickedNode !== null) {
clickedNodeKey = clickedNode.id;
}
let hoverNodeKey = null;
if (hoverNode !== null) {
hoverNodeKey = (hoverNode as any).id;
}
const nodeStyling = useCallback(
(node: any, ctx: any) => {
const NODE_R = nodeSize(node, data);
ctx.save();
node.fx = node.x;
node.fy = node.y;
ctx.beginPath();
ctx.arc(node.x, node.y, NODE_R * 1.4, 0, 2 * Math.PI, false);
ctx.fillStyle =
node === hoverNode
? colors.hoverNodeFill
: riskOutline(node.risk_score);
ctx.fill();
// Node Fill Styling
ctx.beginPath();
ctx.arc(node.x, node.y, NODE_R * 1.2, 0, 2 * Math.PI, false);
ctx.fillStyle =
node === clickedNode
? colors.clickedNode
: nodeFillColor(node.dgraph_type[0]);
ctx.fill();
// Node Label Styling
const label = node.nodeLabel;
const fontSize = Math.min(
98,
NODE_R / ctx.measureText(label).width
);
ctx.font = `${fontSize + 5}px Roboto`;
const textWidth = ctx.measureText(label).width;
const labelBkgdDimensions = [textWidth, fontSize].map(
(n) => n + fontSize * 0.2
);
ctx.fillStyle = colors.nodeLabelFill;
ctx.fillRect(
node.x - labelBkgdDimensions[0] / 2, // x coordinate
node.y - labelBkgdDimensions[1] - 2.75, // y coordinate
labelBkgdDimensions[0] + 1.25, // rectangle width
labelBkgdDimensions[1] + 5.5 // rectangle height
);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = colors.nodeLabelTxt;
ctx.fillText(label, node.x, node.y);
ctx.restore();
},
[clickedNode, data, hoverNode]
);
const linkStyling = (link: any, ctx: any) => {
ctx.save();
const MAX_FONT_SIZE = 8;
const LABEL_NODE_MARGIN = 12;
const start = link.source;
const end = link.target;
link.color = calcLinkColor(link, data);
// Ignore unbounded links
if (typeof start !== "object" || typeof end !== "object") return;
// Edge label positioning calculations
const textPos = {
x: start.x + (end.x - start.x) / 2,
y: start.y + (end.y - start.y) / 2,
};
const relLink = { x: end.x - start.x, y: end.y - start.y };
const maxTextLength =
Math.sqrt(Math.pow(relLink.x, 2) + Math.pow(relLink.y, 2)) -
LABEL_NODE_MARGIN * 8;
let textAngle = Math.atan2(relLink.y, relLink.x);
// Maintain label vertical orientation for legibility
if (textAngle > Math.PI / 2) textAngle = -(Math.PI - textAngle);
if (textAngle < -Math.PI / 2) textAngle = -(-Math.PI - textAngle);
const label = link.name;
// Estimate fontSize to fit in link length
const fontSize = Math.min(
MAX_FONT_SIZE,
maxTextLength / ctx.measureText(label).width
);
ctx.font = `${fontSize + 5}px Roboto`;
ctx.fillStyle = "#FFF";
// Draw text label
ctx.translate(textPos.x, textPos.y);
ctx.rotate(textAngle);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(label, 0.75, 3); //Content, left/right, top/bottom
ctx.restore();
};
return (
<ForceGraph2D
ref={fgRef} // fix graph to canvas
graphData={data}
nodeLabel={"nodeType"} // tooltip on hover, actual label is in nodeCanvasObject
height={800}
width={1500}
onEngineStop={() => {
if (!stopEngine) {
fgRef.current.zoomToFit(1000, 50);
setStopEngine(true);
}
}}
nodeCanvasObject={nodeStyling}
nodeCanvasObjectMode={() => "after"}
onNodeHover={nodeHover}
onNodeClick={nodeClick}
onNodeDrag={(node) => {
node.fx = node.x;
node.fy = node.y;
}}
onNodeDragEnd={(node) => {
node.fx = node.x;
node.fy = node.y;
}}
linkColor={(link) =>
highlightLinks.has(link)
? colors.highlightLink
: calcLinkColor(link as Link, data as VizGraph)
}
linkWidth={(link) => (highlightLinks.has(link) ? 5 : 4)}
linkCanvasObjectMode={() => "after"}
linkCanvasObject={linkStyling}
onLinkHover={(link) => {
highlightNodes.clear();
highlightLinks.clear();
if (link) {
highlightLinks.add(link);
highlightNodes.add(link.source);
highlightNodes.add(link.target);
}
}}
minZoom={1}
maxZoom={5}
warmupTicks={100}
cooldownTicks={100}
/>
);
};
export default GraphDisplay; | the_stack |
import { providers, BigNumberish } from "ethers";
import { Address, BigNumber, Bytes32, HexString, PublicIdentifier, SignatureString } from "./basic";
import { ConditionalTransferTypes } from "./transfers";
import { MethodResults, MethodParams } from "./methods";
import { NodeResponses } from "./node";
import { ChallengeInitiatedResponse } from "./watcher";
////////////////////////////////////////
// disputes
type InitiateChallengeParameters = {
appIdentityHash: string;
};
type CancelChallengeParameters = {
appIdentityHash: string;
};
////////////////////////////////////////
// deposit
type DepositParameters = {
amount: BigNumberish;
assetId?: Address; // if not provided, will default to 0x0 (Eth)
};
export type FreeBalanceResponse = {
freeBalance: {
[s: string]: BigNumber;
};
};
type DepositResponse = {
transaction: providers.TransactionResponse;
completed: () => Promise<FreeBalanceResponse>;
};
type CheckDepositRightsParameters = {
assetId?: Address;
};
type CheckDepositRightsResponse = {
appIdentityHash: Bytes32;
};
type RequestCollateralResponse =
| (NodeResponses.RequestCollateral & {
completed: () => Promise<FreeBalanceResponse>;
})
| undefined;
type RequestDepositRightsParameters = Omit<MethodParams.RequestDepositRights, "multisigAddress">;
type RequestDepositRightsResponse = MethodResults.RequestDepositRights;
type RescindDepositRightsParameters = Omit<MethodParams.RescindDepositRights, "multisigAddress">;
type RescindDepositRightsResponse = MethodResults.RescindDepositRights;
////////////////////////////////////////
// hashlock
type HashLockTransferParameters = {
conditionType: typeof ConditionalTransferTypes.HashLockTransfer;
amount: BigNumberish;
timelock?: BigNumberish;
lockHash: Bytes32;
recipient: PublicIdentifier;
assetId?: Address;
meta?: any;
};
type HashLockTransferResponse = {
appIdentityHash: Bytes32;
};
type ResolveHashLockTransferParameters = {
conditionType: typeof ConditionalTransferTypes.HashLockTransfer;
assetId: Address;
paymentId?: Bytes32;
preImage: Bytes32;
};
type ResolveHashLockTransferResponse = {
appIdentityHash: Bytes32;
sender: PublicIdentifier;
amount: BigNumber;
assetId: Address;
meta?: any;
};
////////////////////////////////////////
// linked transfer
type LinkedTransferParameters = {
conditionType:
| typeof ConditionalTransferTypes.LinkedTransfer
| typeof ConditionalTransferTypes.OnlineTransfer;
amount: BigNumberish;
assetId?: Address;
paymentId: Bytes32;
preImage: Bytes32;
recipient?: PublicIdentifier;
meta?: any;
};
type LinkedTransferResponse = {
appIdentityHash: Bytes32;
paymentId: Bytes32;
preImage: Bytes32;
};
type ResolveLinkedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.LinkedTransfer;
paymentId: Bytes32;
preImage: Bytes32;
};
type ResolveLinkedTransferResponse = {
appIdentityHash: Bytes32;
sender: PublicIdentifier;
paymentId: Bytes32;
amount: BigNumber;
assetId: Address;
meta?: any;
};
////////////////////////////////////////
// signed transfer
type SignedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.SignedTransfer;
amount: BigNumber;
assetId: Address;
paymentId: Bytes32;
signerAddress: Address;
chainId: number;
verifyingContract: Address;
recipient?: PublicIdentifier;
meta?: any;
};
type SignedTransferResponse = {
appIdentityHash: Bytes32;
paymentId: Bytes32;
};
type ResolveSignedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.SignedTransfer;
paymentId: Bytes32;
data: Bytes32;
signature?: SignatureString;
};
type ResolveSignedTransferResponse = {
appIdentityHash: Bytes32;
assetId: Address;
amount: BigNumber;
sender: PublicIdentifier;
meta?: any;
};
////////////////////////////////////////
// graph signed transfer
type GraphSignedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.GraphTransfer;
amount: BigNumber;
assetId: Address;
paymentId: Bytes32;
chainId: number;
verifyingContract: Address;
signerAddress: Address;
requestCID: Bytes32;
subgraphDeploymentID: Bytes32;
recipient: PublicIdentifier;
meta?: any;
};
type GraphSignedTransferResponse = {
appIdentityHash: Bytes32;
paymentId: Bytes32;
};
type ResolveGraphSignedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.GraphTransfer;
paymentId: Bytes32;
responseCID: Bytes32;
signature?: SignatureString;
};
type ResolveGraphSignedTransferResponse = {
appIdentityHash: Bytes32;
assetId: Address;
amount: BigNumber;
sender: PublicIdentifier;
meta?: any;
};
////////////////////////////////////////
// graph batched transfer
type GraphBatchedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.GraphBatchedTransfer;
amount: BigNumber;
assetId: Address;
consumerSigner: Address;
paymentId: Bytes32;
chainId: number;
verifyingContract: Address;
subgraphDeploymentID: Bytes32;
recipient: PublicIdentifier;
meta?: any;
};
type GraphBatchedTransferResponse = {
appIdentityHash: Bytes32;
paymentId: Bytes32;
};
type ResolveGraphBatchedTransferParameters = {
conditionType: typeof ConditionalTransferTypes.GraphBatchedTransfer;
paymentId: Bytes32;
requestCID: Bytes32;
responseCID: Bytes32;
totalPaid: BigNumber;
consumerSignature?: SignatureString;
attestationSignature?: SignatureString;
};
type ResolveGraphBatchedTransferResponse = {
appIdentityHash: Bytes32;
assetId: Address;
amount: BigNumber;
sender: PublicIdentifier;
meta?: any;
};
////////////////////////////////////////
// conditional transfer
type ConditionalTransferParameters =
| LinkedTransferParameters
| HashLockTransferParameters
| SignedTransferParameters
| GraphSignedTransferParameters
| GraphBatchedTransferParameters;
type ConditionalTransferResponse = {
amount: BigNumber;
appIdentityHash: Bytes32;
assetId: Address;
paymentId: Bytes32;
preImage?: Bytes32;
sender: Address;
recipient?: Address;
meta: any;
transferMeta: any;
};
////////////////////////////////////////
// resolve condition
type ResolveConditionParameters =
| ResolveHashLockTransferParameters
| ResolveLinkedTransferParameters
| ResolveSignedTransferParameters
| ResolveGraphBatchedTransferParameters
| ResolveGraphSignedTransferParameters;
// type ResolveConditionResponse =
// | ResolveHashLockTransferResponse
// | ResolveLinkedTransferResponse
// | ResolveSignedTransferResponse
// | ResolveGraphSignedTransferResponse;
type ResolveConditionResponse = {
appIdentityHash: Bytes32;
assetId: Address;
amount: BigNumber;
paymentId: Bytes32;
sender: PublicIdentifier;
meta?: any;
};
////////////////////////////////////////
// swap
type SwapParameters = {
amount: BigNumberish;
fromAssetId: Address;
swapRate: string; // DecString?
toAssetId: Address;
};
type SwapResponse = {
id: number;
nodeIdentifier: PublicIdentifier;
userIdentifier: PublicIdentifier;
multisigAddress: Address;
available: boolean;
activeCollateralizations: { [assetId: string]: boolean };
};
////////////////////////////////////////
// withdraw
type WithdrawParameters = {
amount: BigNumberish;
assetId?: Address; // if not provided, will default to 0x0 (Eth)
recipient?: Address; // if not provided, will default to signer addr
nonce?: HexString; // generated internally, end user doesn't need to provide it
};
type WithdrawResponse = {
transaction: providers.TransactionResponse;
};
////////////////////////////////////////
// transfer
type TransferParameters = MethodParams.Deposit & {
recipient: PublicIdentifier;
meta?: any;
paymentId?: Bytes32;
};
type TransferResponse = LinkedTransferResponse;
////////////////////////////////////////
// exports
export namespace PublicParams {
export type CheckDepositRights = CheckDepositRightsParameters;
export type ConditionalTransfer = ConditionalTransferParameters;
export type Deposit = DepositParameters;
export type HashLockTransfer = HashLockTransferParameters;
export type LinkedTransfer = LinkedTransferParameters;
export type RequestDepositRights = RequestDepositRightsParameters;
export type RescindDepositRights = RescindDepositRightsParameters;
export type ResolveCondition = ResolveConditionParameters;
export type ResolveHashLockTransfer = ResolveHashLockTransferParameters;
export type ResolveLinkedTransfer = ResolveLinkedTransferParameters;
export type ResolveSignedTransfer = ResolveSignedTransferParameters;
export type ResolveGraphTransfer = ResolveGraphSignedTransferParameters;
export type ResolveGraphBatchedTransfer = ResolveGraphBatchedTransferParameters;
export type SignedTransfer = SignedTransferParameters;
export type GraphBatchedTransfer = GraphBatchedTransferParameters;
export type GraphTransfer = GraphSignedTransferParameters;
export type Swap = SwapParameters;
export type Transfer = TransferParameters;
export type Withdraw = WithdrawParameters;
export type InitiateChallenge = InitiateChallengeParameters;
export type CancelChallenge = CancelChallengeParameters;
}
export type PublicParam =
| CancelChallengeParameters
| CheckDepositRightsParameters
| ConditionalTransferParameters
| DepositParameters
| HashLockTransferParameters
| InitiateChallengeParameters
| LinkedTransferParameters
| RequestDepositRightsParameters
| RescindDepositRightsParameters
| ResolveConditionParameters
| ResolveHashLockTransferParameters
| ResolveGraphSignedTransferParameters
| ResolveGraphBatchedTransferParameters
| ResolveLinkedTransferParameters
| ResolveSignedTransferParameters
| SignedTransferParameters
| GraphSignedTransferParameters
| GraphBatchedTransferParameters
| SwapParameters
| TransferParameters
| WithdrawParameters;
export namespace PublicResults {
export type CheckDepositRights = CheckDepositRightsResponse;
export type ConditionalTransfer = ConditionalTransferResponse;
export type Deposit = DepositResponse;
export type RequestCollateral = RequestCollateralResponse;
export type RequestDepositRights = RequestDepositRightsResponse;
export type RescindDepositRights = RescindDepositRightsResponse;
export type ResolveCondition = ResolveConditionResponse;
export type ResolveHashLockTransfer = ResolveHashLockTransferResponse;
export type ResolveLinkedTransfer = ResolveLinkedTransferResponse;
export type ResolveSignedTransfer = ResolveSignedTransferResponse;
export type ResolveGraphTransfer = ResolveGraphBatchedTransferResponse;
export type HashLockTransfer = HashLockTransferResponse;
export type LinkedTransfer = LinkedTransferResponse;
export type SignedTransfer = SignedTransferResponse;
export type GraphBatchedTransfer = GraphBatchedTransferResponse;
export type GraphTransfer = GraphSignedTransferResponse;
export type Swap = SwapResponse;
export type Transfer = TransferResponse;
export type Withdraw = WithdrawResponse;
export type InitiateChallenge = ChallengeInitiatedResponse;
export type CancelChallenge = providers.TransactionResponse;
}
export type PublicResult =
| CheckDepositRightsResponse
| ConditionalTransferResponse
| DepositResponse
| HashLockTransferResponse
| LinkedTransferResponse
| PublicResults.CancelChallenge
| PublicResults.InitiateChallenge
| RequestCollateralResponse
| RequestDepositRightsResponse
| RescindDepositRightsResponse
| ResolveConditionResponse
| ResolveHashLockTransferResponse
| ResolveLinkedTransferResponse
| ResolveSignedTransferResponse
| ResolveGraphSignedTransferResponse
| ResolveGraphBatchedTransferResponse
| SignedTransferResponse
| GraphBatchedTransferResponse
| GraphSignedTransferResponse
| SwapResponse
| TransferResponse
| WithdrawResponse; | the_stack |
import * as errors from 'balena-errors';
import * as memoizee from 'memoizee';
import type { InjectedDependenciesParam, InjectedOptionsParam } from '.';
const getAuth = function (
deps: InjectedDependenciesParam,
opts: InjectedOptionsParam,
) {
const { auth: authBase, pubsub, request, pine } = deps;
const { apiUrl } = opts;
const normalizeAuthError = function (err: errors.BalenaRequestError) {
if (err.statusCode === 401) {
return new errors.BalenaNotLoggedIn();
} else if (err.code === 'BalenaMalformedToken') {
return new errors.BalenaNotLoggedIn();
} else {
return err;
}
};
const wrapAuthFn = <T extends (...args: any[]) => Promise<any>>(
eventName: string,
fn: T,
): T =>
async function () {
try {
return await fn.apply(authBase, arguments);
} finally {
pubsub.publish(eventName);
}
} as T;
const auth = {
...authBase,
setKey: wrapAuthFn('auth.keyChange', authBase.setKey),
removeKey: wrapAuthFn('auth.keyChange', authBase.removeKey),
} as typeof authBase;
/**
* @namespace balena.auth.twoFactor
* @memberof balena.auth
*/
const twoFactor = (require('./2fa') as typeof import('./2fa')).default(
{
...deps,
auth,
},
opts,
);
interface WhoamiResult {
id: number;
username: string;
email: string;
}
const userWhoami = async () => {
const { body } = await request.send<WhoamiResult>({
method: 'GET',
url: '/user/v1/whoami',
baseUrl: apiUrl,
});
return body;
};
const memoizedUserWhoami = memoizee(userWhoami, {
primitive: true,
promise: true,
});
const getUserDetails = async (noCache = false) => {
if (noCache) {
memoizedUserWhoami.clear();
}
try {
return await memoizedUserWhoami();
} catch (err) {
throw normalizeAuthError(err);
}
};
/**
* @summary Return current logged in username
* @name whoami
* @public
* @function
* @memberof balena.auth
*
* @description This will only work if you used {@link balena.auth.login} to log in.
*
* @fulfil {(String|undefined)} - username, if it exists
* @returns {Promise}
*
* @example
* balena.auth.whoami().then(function(username) {
* if (!username) {
* console.log('I\'m not logged in!');
* } else {
* console.log('My username is:', username);
* }
* });
*
* @example
* balena.auth.whoami(function(error, username) {
* if (error) throw error;
*
* if (!username) {
* console.log('I\'m not logged in!');
* } else {
* console.log('My username is:', username);
* }
* });
*/
async function whoami(): Promise<string | undefined> {
try {
const userDetails = await getUserDetails();
return userDetails?.username;
} catch (err) {
if (err instanceof errors.BalenaNotLoggedIn) {
return;
}
throw err;
}
}
/**
* @summary Authenticate with the server
* @name authenticate
* @protected
* @function
* @memberof balena.auth
*
* @description You should use {@link balena.auth.login} when possible,
* as it takes care of saving the token and email as well.
*
* Notice that if `credentials` contains extra keys, they'll be discarted
* by the server automatically.
*
* @param {Object} credentials - in the form of email, password
* @param {String} credentials.email - the email
* @param {String} credentials.password - the password
*
* @fulfil {String} - session token
* @returns {Promise}
*
* @example
* balena.auth.authenticate(credentials).then(function(token) {
* console.log('My token is:', token);
* });
*
* @example
* balena.auth.authenticate(credentials, function(error, token) {
* if (error) throw error;
* console.log('My token is:', token);
* });
*/
async function authenticate(credentials: {
email: string;
password: string;
}): Promise<string> {
try {
const { body } = await request.send<string>({
method: 'POST',
baseUrl: apiUrl,
url: '/login_',
body: {
username: credentials.email,
password: String(credentials.password),
},
sendToken: false,
});
return body;
} catch (err) {
if (err.statusCode === 401) {
throw new errors.BalenaInvalidLoginCredentials();
}
if (err.statusCode === 429) {
throw new errors.BalenaTooManyRequests();
}
throw err;
}
}
/**
* @summary Login
* @name login
* @public
* @function
* @memberof balena.auth
*
* @description If the login is successful, the token is persisted between sessions.
*
* @param {Object} credentials - in the form of email, password
* @param {String} credentials.email - the email
* @param {String} credentials.password - the password
*
* @returns {Promise}
*
* @example
* balena.auth.login(credentials);
*
* @example
* balena.auth.login(credentials, function(error) {
* if (error) throw error;
* });
*/
async function login(credentials: {
email: string;
password: string;
}): Promise<void> {
memoizedUserWhoami.clear();
const token = await authenticate(credentials);
await auth.setKey(token);
}
/**
* @summary Login with a token or api key
* @name loginWithToken
* @public
* @function
* @memberof balena.auth
*
* @description Login to balena with a session token or api key instead of with credentials.
*
* @param {String} authToken - the auth token
* @returns {Promise}
*
* @example
* balena.auth.loginWithToken(authToken);
*
* @example
* balena.auth.loginWithToken(authToken, function(error) {
* if (error) throw error;
* });
*/
function loginWithToken(authToken: string): Promise<void> {
memoizedUserWhoami.clear();
return auth.setKey(authToken);
}
/**
* @summary Check if you're logged in
* @name isLoggedIn
* @public
* @function
* @memberof balena.auth
*
* @fulfil {Boolean} - is logged in
* @returns {Promise}
*
* @example
* balena.auth.isLoggedIn().then(function(isLoggedIn) {
* if (isLoggedIn) {
* console.log('I\'m in!');
* } else {
* console.log('Too bad!');
* }
* });
*
* @example
* balena.auth.isLoggedIn(function(error, isLoggedIn) {
* if (error) throw error;
*
* if (isLoggedIn) {
* console.log('I\'m in!');
* } else {
* console.log('Too bad!');
* }
* });
*/
async function isLoggedIn(): Promise<boolean> {
try {
await getUserDetails(true);
return true;
} catch (err) {
if (
err instanceof errors.BalenaNotLoggedIn ||
err instanceof errors.BalenaExpiredToken
) {
return false;
}
throw err;
}
}
/**
* @summary Get current logged in user's raw API key or session token
* @name getToken
* @public
* @function
* @memberof balena.auth
*
* @description This will only work if you used {@link balena.auth.login} to log in.
*
* @fulfil {String} - raw API key or session token
* @returns {Promise}
*
* @example
* balena.auth.getToken().then(function(token) {
* console.log(token);
* });
*
* @example
* balena.auth.getToken(function(error, token) {
* if (error) throw error;
* console.log(token);
* });
*/
function getToken(): Promise<string> {
return auth.getKey().catch(function (err) {
throw normalizeAuthError(err);
});
}
/**
* @summary Get current logged in user's id
* @name getUserId
* @public
* @function
* @memberof balena.auth
*
* @description This will only work if you used {@link balena.auth.login} to log in.
*
* @fulfil {Number} - user id
* @returns {Promise}
*
* @example
* balena.auth.getUserId().then(function(userId) {
* console.log(userId);
* });
*
* @example
* balena.auth.getUserId(function(error, userId) {
* if (error) throw error;
* console.log(userId);
* });
*/
async function getUserId(): Promise<number> {
const { id } = await getUserDetails();
return id;
}
/**
* @summary Get current logged in user's actor id
* @name getUserActorId
* @public
* @function
* @memberof balena.auth
*
* @description This will only work if you used {@link balena.auth.login} to log in.
*
* @fulfil {Number} - user id
* @returns {Promise}
*
* @example
* balena.auth.getUserActorId().then(function(userActorId) {
* console.log(userActorId);
* });
*
* @example
* balena.auth.getUserActorId(function(error, userActorId) {
* if (error) throw error;
* console.log(userActorId);
* });
*/
async function getUserActorId(): Promise<number> {
const { actor } = (await pine.get({
resource: 'user',
id: await getUserId(),
options: {
$select: 'actor',
},
}))!;
return actor;
}
/**
* @summary Get current logged in user's email
* @name getEmail
* @public
* @function
* @memberof balena.auth
*
* @description This will only work if you used {@link balena.auth.login} to log in.
*
* @fulfil {String} - user email
* @returns {Promise}
*
* @example
* balena.auth.getEmail().then(function(email) {
* console.log(email);
* });
*
* @example
* balena.auth.getEmail(function(error, email) {
* if (error) throw error;
* console.log(email);
* });
*/
async function getEmail(): Promise<string> {
const { email } = await getUserDetails();
return email;
}
/**
* @summary Logout
* @name logout
* @public
* @function
* @memberof balena.auth
*
* @returns {Promise}
*
* @example
* balena.auth.logout();
*
* @example
* balena.auth.logout(function(error) {
* if (error) throw error;
* });
*/
function logout(): Promise<void> {
memoizedUserWhoami.clear();
return auth.removeKey();
}
/**
* @summary Register a user account
* @name register
* @public
* @function
* @memberof balena.auth
*
* @param {Object} credentials - in the form of username, password and email
* @param {String} credentials.email - the email
* @param {String} credentials.password - the password
* @param {(String|undefined)} [credentials.'g-recaptcha-response'] - the captcha response
*
* @fulfil {String} - session token
* @returns {Promise}
*
* @example
* balena.auth.register({
* email: 'johndoe@gmail.com',
* password: 'secret'
* }).then(function(token) {
* console.log(token);
* });
*
* @example
* balena.auth.register({
* email: 'johndoe@gmail.com',
* password: 'secret'
* }, function(error, token) {
* if (error) throw error;
* console.log(token);
* });
*
*/
async function register(credentials: {
email: string;
password: string;
'g-recaptcha-response'?: string;
}): Promise<string> {
const { body } = await request.send({
method: 'POST',
url: '/user/register',
baseUrl: apiUrl,
body: credentials,
sendToken: false,
});
return body;
}
/**
* @summary Verifies an email
* @name verifyEmail
* @public
* @function
* @memberof balena.auth
*
* @param {Object} verificationPayload - in the form of email, and token
* @param {String} verificationPayload.email - the email
* @param {String} verificationPayload.token - the verification token
*
* @fulfil {String} - session token
* @returns {Promise}
*
* @example
* balena.auth.verifyEmail({
* email: 'johndoe@gmail.com',
* token: '5bb11d90eefb34a70318f06a43ef063f'
* }).then(function(jwt) {
* console.log(jwt);
* });
*
*/
async function verifyEmail(verificationPayload: {
email: string;
token: string;
}): Promise<string> {
const email = verificationPayload.email;
const verificationToken = verificationPayload.token;
const { body } = await request.send({
method: 'POST',
url: '/user/v1/verify-email',
body: {
verificationToken,
email,
},
baseUrl: apiUrl,
sendToken: false,
});
return body;
}
/**
* @summary Re-send verification email to the user
* @name requestVerificationEmail
* @public
* @function
* @memberof balena.auth
* @description This will only work if you used {@link balena.auth.login} to log in.
*
* @returns {Promise}
*
* @example
* balena.auth.requestVerificationEmail().then(function() {
* console.log('Requesting verification email operation complete!');
* })
*
*/
async function requestVerificationEmail() {
const id = await getUserId();
await pine.patch({
resource: 'user',
id,
body: {
has_been_sent_verification_email: true,
},
});
}
return {
twoFactor: (
require('./util/callbacks') as typeof import('./util/callbacks')
).addCallbackSupportToModule(twoFactor) as typeof twoFactor,
whoami,
authenticate,
login,
loginWithToken,
isLoggedIn,
getToken,
getUserId,
getUserActorId,
getEmail,
logout,
register,
verifyEmail,
requestVerificationEmail,
};
};
export default getAuth; | the_stack |
import { isPresent, stringify, assign, isType, getFuncName, isBlank } from '../../facade/lang';
import { StringMapWrapper, ListWrapper } from '../../facade/collections';
import { reflector } from '../reflection/reflection';
import {
DirectiveMetadata,
ComponentMetadata,
InputMetadata,
AttrMetadata,
OutputMetadata,
HostBindingMetadata,
HostListenerMetadata
} from '../directives/metadata_directives';
import {
ContentChildrenMetadata,
ViewChildrenMetadata,
ContentChildMetadata,
ViewChildMetadata
} from '../directives/metadata_di';
import { InjectMetadata, HostMetadata, SelfMetadata, SkipSelfMetadata, OptionalMetadata } from '../di/metadata';
import { ParamMetaInst, PropMetaInst, getInjectableName } from '../di/provider';
import { resolveForwardRef } from '../di/forward_ref';
import { getErrorMsg } from '../../facade/exceptions';
import { ChangeDetectionStrategy } from '../change_detection/constants';
import { Type } from '../../facade/type';
// asset:<package-name>/<realm>/<path-to-module>
// var _ASSET_URL_RE = /asset:([^\/]+)\/([^\/]+)\/(.+)/g;
// <path-to-module>/filename.js
const ASSET_URL_RE = /^(.+)\/.+\.js$/;
function _isDirectiveMetadata( type: any ): boolean {
return type instanceof DirectiveMetadata;
}
/**
* return required string map for provided local DI
* ```typescript
* // for
* constructor(@Inject('ngModel') @Self() @Optional() ngModel){}
* // it returns:
* { ngModel: '?ngModel' }
*
* // when MyComponent is
* @Component({ selector: 'myCoolCmp', template:`hello`})
* class MyComponent{}
* // for
* constructor(@Host() @Optional() myCmp: MyComponent){}
* // it returns:
* { myCmp: '^myCoolCmp' }
* ```
* @param paramsMeta
* @param idx
* @param typeOrFunc
* @returns {{[directiveName]:string}}
* @private
*/
function _transformInjectedDirectivesMeta( paramsMeta: ParamMetaInst[], idx: number, typeOrFunc: Type ): StringMap {
if ( !_isInjectableParamsDirective( paramsMeta ) ) { return }
// @TODO unite this with _extractToken from provider.ts
const injectInst = ListWrapper.find( paramsMeta, param=>param instanceof InjectMetadata ) as InjectMetadata;
const injectType = ListWrapper.find( paramsMeta, isType ) as Type;
const { token=undefined } = injectInst || { token: injectType };
// we need to decrement param count if user uses both @Inject() and :MyType
const paramsMetaLength = (injectInst && injectType)
? paramsMeta.length - 1
: paramsMeta.length;
if ( !token ) {
throw new Error(
getErrorMsg(
typeOrFunc,
`no Directive instance name provided within @Inject() or :DirectiveClass annotation missing`
)
);
}
const isHost = ListWrapper.findIndex( paramsMeta, param=>param instanceof HostMetadata ) !== -1;
const isOptional = ListWrapper.findIndex( paramsMeta, param=>param instanceof OptionalMetadata ) !== -1;
const isSelf = ListWrapper.findIndex( paramsMeta, param=>param instanceof SelfMetadata ) !== -1;
const isSkipSelf = ListWrapper.findIndex( paramsMeta, param=>param instanceof SkipSelfMetadata ) !== -1;
if ( isOptional && paramsMetaLength !== 3 ) {
throw new Error(
getErrorMsg(
typeOrFunc,
`you cannot use @Optional() without related decorator for injecting Directives. use one of @Host|@Self()|@SkipSelf() + @Optional()`
)
);
}
if ( isSelf && isSkipSelf ) {
throw new Error(
getErrorMsg(
typeOrFunc,
`you cannot provide both @Self() and @SkipSelf() with @Inject(${getFuncName( token )}) for Directive Injection`
)
);
}
if( (isHost && isSelf) || (isHost && isSkipSelf)){
throw new Error(
getErrorMsg(
typeOrFunc,
`you cannot provide both @Host(),@SkipSelf() or @Host(),@Self() with @Inject(${getFuncName( token )}) for Directive Injections`
)
);
}
const locateType = _getLocateTypeSymbol();
const optionalType = isOptional ? '?' : '';
const requireExpressionPrefix = `${ optionalType }${ locateType }`;
const directiveName = _getDirectiveName( token );
// we need to generate unique names because if we require same directive controllers,
// with different locale decorators it would merge to one which is wrong
return {
[`${directiveName}#${idx}`]: `${ requireExpressionPrefix }${ directiveName }`
};
function _getDirectiveName( token: any ): string {
return isType( resolveForwardRef( token ) )
? getInjectableName( resolveForwardRef( token ) )
: token;
}
function _getLocateTypeSymbol(): string {
if ( isSelf ) {
return '';
}
if ( isHost ) {
return '^';
}
if ( isSkipSelf ) {
return '^^';
}
}
// exit if user uses both @Inject() and :Type for DI because this is not directive injection
function _isInjectableParamsDirective( paramsMeta: ParamMetaInst[] ): boolean {
// if there is just @Inject or Type from design:paramtypes return
if ( paramsMeta.length < 2 ) {
return false;
}
if ( paramsMeta.length === 2 ) {
const injectableParamCount = paramsMeta.filter( inj => inj instanceof InjectMetadata || isType( inj ) ).length;
if ( injectableParamCount === 2 ) {
return false;
}
}
return true;
}
}
/**
* Resolve a `Type` for {@link DirectiveMetadata}.
*/
export class DirectiveResolver {
/**
* Return {@link DirectiveMetadata} for a given `Type`.
*/
resolve( type: Type ): DirectiveMetadata {
const metadata: DirectiveMetadata = this._getDirectiveMeta( type );
const propertyMetadata: {[key: string]: PropMetaInst[]} = reflector.propMetadata( type );
return this._mergeWithPropertyMetadata( metadata, propertyMetadata );
}
/**
* transform parameter annotations to required directives map so we can use it
* for DDO creation
*
* map consist of :
* - key == name of directive
* - value == Angular 1 require expression
* ```js
* {
* ngModel: 'ngModel',
* form: '^^form',
* foo: '^foo',
* moo: '?^foo',
* }
* ```
*
* @param {Type} type
* @returns {StringMap}
*/
getRequiredDirectivesMap( type: Type ): StringMap {
const metadata: DirectiveMetadata = this._getDirectiveMeta( type );
const paramMetadata = reflector.parameters( type );
if ( isPresent( paramMetadata ) ) {
return paramMetadata
.reduce( ( acc, paramMetaArr, idx )=> {
const requireExp = _transformInjectedDirectivesMeta( paramMetaArr, idx, type );
if ( isPresent( requireExp ) ) {
assign( acc, requireExp );
}
return acc;
}, {} as StringMap );
}
return {} as StringMap;
}
parseAssetUrl( cmpMetadata: ComponentMetadata ): string {
if ( isBlank( cmpMetadata.moduleId ) ) {
return '';
}
const moduleId = cmpMetadata.moduleId;
const [,urlPathMatch=''] = moduleId.match( ASSET_URL_RE ) || [];
return `${urlPathMatch}/`;
}
/**
*
* @param type
* @returns {DirectiveMetadata}
* @throws Error
* @private
*/
private _getDirectiveMeta( type: Type ): DirectiveMetadata {
const typeMetadata = reflector.annotations( resolveForwardRef( type ) );
if ( isPresent( typeMetadata ) ) {
const metadata: DirectiveMetadata = ListWrapper.find( typeMetadata, _isDirectiveMetadata );
if ( isPresent( metadata ) ) {
return metadata;
}
}
throw new Error( `No Directive annotation found on ${stringify( type )}` );
}
private _mergeWithPropertyMetadata(
directiveMetadata: DirectiveMetadata,
propertyMetadata: {[key: string]: PropMetaInst[]}
): DirectiveMetadata {
const inputs = [];
const attrs = [];
const outputs = [];
const host: {[key: string]: string} = {};
const queries: {[key: string]: any} = {};
StringMapWrapper.forEach( propertyMetadata, ( metadata: PropMetaInst[], propName: string ) => {
metadata.forEach( propMetaInst => {
if ( propMetaInst instanceof InputMetadata ) {
if ( isPresent( propMetaInst.bindingPropertyName ) ) {
inputs.push( `${propName}: ${propMetaInst.bindingPropertyName}` );
} else {
inputs.push( propName );
}
}
if ( propMetaInst instanceof AttrMetadata ) {
if ( isPresent( propMetaInst.bindingPropertyName ) ) {
attrs.push( `${propName}: ${propMetaInst.bindingPropertyName}` );
} else {
attrs.push( propName );
}
}
if ( propMetaInst instanceof OutputMetadata ) {
if ( isPresent( propMetaInst.bindingPropertyName ) ) {
outputs.push( `${propName}: ${propMetaInst.bindingPropertyName}` );
} else {
outputs.push( propName );
}
}
if ( propMetaInst instanceof HostBindingMetadata ) {
if ( isPresent( propMetaInst.hostPropertyName ) ) {
host[ `[${propMetaInst.hostPropertyName}]` ] = propName;
} else {
host[ `[${propName}]` ] = propName;
}
}
if ( propMetaInst instanceof HostListenerMetadata ) {
const args = isPresent( propMetaInst.args )
? propMetaInst.args.join( ', ' )
: '';
host[ `(${propMetaInst.eventName})` ] = `${propName}(${args})`;
}
if ( propMetaInst instanceof ContentChildrenMetadata ) {
queries[ propName ] = propMetaInst;
}
if ( propMetaInst instanceof ViewChildrenMetadata ) {
queries[ propName ] = propMetaInst;
}
if ( propMetaInst instanceof ContentChildMetadata ) {
queries[ propName ] = propMetaInst;
}
if ( propMetaInst instanceof ViewChildMetadata ) {
queries[ propName ] = propMetaInst;
}
} );
} );
return this._merge( directiveMetadata, inputs, attrs, outputs, host, queries );
}
private _merge(
dm: DirectiveMetadata,
inputs: string[],
attrs: string[],
outputs: string[],
host: {[key: string]: string},
queries: {[key: string]: any}
): DirectiveMetadata {
const mergedInputs = isPresent( dm.inputs )
? ListWrapper.concat( dm.inputs, inputs )
: inputs;
const mergedAttrs = isPresent( dm.attrs )
? ListWrapper.concat( dm.attrs, attrs )
: attrs;
const mergedOutputs = isPresent( dm.outputs )
? ListWrapper.concat( dm.outputs, outputs )
: outputs;
const mergedHost = isPresent( dm.host )
? StringMapWrapper.merge( dm.host, host )
: host;
const mergedQueries = isPresent( dm.queries )
? StringMapWrapper.merge( dm.queries, queries )
: queries;
const directiveSettings = {
selector: dm.selector,
inputs: mergedInputs,
attrs: mergedAttrs,
outputs: mergedOutputs,
host: mergedHost,
queries: mergedQueries,
legacy: dm.legacy
};
if ( dm instanceof ComponentMetadata ) {
const componentSettings = StringMapWrapper.assign(
{},
directiveSettings as ComponentMetadata,
{
moduleId: dm.moduleId,
template: dm.template,
templateUrl: dm.templateUrl,
changeDetection: isPresent(dm.changeDetection) ? dm.changeDetection : ChangeDetectionStrategy.Default
}
);
return new ComponentMetadata( componentSettings );
} else {
return new DirectiveMetadata( directiveSettings );
}
}
} | the_stack |
import {UserAutoGenerateAttributes} from '../../../../__mocks__/user-auto-generate-attributes';
import {
Attribute,
AutoGenerateAttribute,
AUTO_GENERATE_ATTRIBUTE_STRATEGY,
Entity,
INDEX_TYPE,
Table,
} from '@typedorm/common';
import {Organisation} from '../../../../__mocks__/organisation';
import {User} from '../../../../__mocks__/user';
import {createTestConnection, resetTestConnection} from '@typedorm/testing';
import {EntityTransformer} from '../entity-transformer';
import {UserSparseIndexes} from '../../../../__mocks__/user-sparse-indexes';
import {table} from '@typedorm/core/__mocks__/table';
import {UserAttrAlias} from '@typedorm/core/__mocks__/user-with-attribute-alias';
import {CATEGORY, Photo} from '@typedorm/core/__mocks__/photo';
// Moment is only being used here to display the usage of @transform utility
// eslint-disable-next-line node/no-extraneous-import
import moment from 'moment';
import {UserCustomConstructor} from '@typedorm/core/__mocks__/user-custom-constructor';
jest.mock('uuid', () => ({
v4: () => 'c0ac5395-ba7c-41bf-bbc3-09a6087bcca2',
}));
jest.useFakeTimers('modern').setSystemTime(1622530750000);
import {UserWithDefaultValues} from '@typedorm/core/__mocks__/user-default-value';
let transformer: EntityTransformer;
beforeEach(() => {
const connection = createTestConnection({
entities: [
User,
Organisation,
UserAutoGenerateAttributes,
UserSparseIndexes,
UserAttrAlias,
Photo,
UserCustomConstructor,
UserWithDefaultValues,
],
});
transformer = new EntityTransformer(connection);
});
afterEach(() => {
resetTestConnection();
});
/**
* @group fromDynamoEntity
*/
test('transforms dynamo entity to entity model', () => {
const dynamoEntity = {
PK: 'USER#1',
SK: 'USER#1',
GSI1PK: 'USER#STATUS#active',
GSI1SK: 'USER#Me',
id: '1',
name: 'Me',
status: 'active',
};
const transformed = transformer.fromDynamoEntity(User, dynamoEntity);
expect(transformed).toEqual({
id: '1',
name: 'Me',
status: 'active',
});
});
/**
* Issue: #134
*/
test('transforms dynamo entity to entity model with custom constructor', () => {
const dynamoEntity = {
PK: 'USER#1',
SK: 'USER#1',
id: '1',
name: 'Me',
};
const transformed = transformer.fromDynamoEntity(
UserCustomConstructor,
dynamoEntity
);
expect(transformed).toEqual({
id: '1',
name: 'Me',
});
});
test('transforms dynamo entity with aliased attributes to entity model', () => {
const dynamoEntity = {
PK: 'USER#1',
SK: 'USER#1',
GSI1PK: 'USER#STATUS#active',
GSI1SK: 'USER#Me',
id: '1',
name: 'Me',
age: 1,
};
const transformed = transformer.fromDynamoEntity(
UserSparseIndexes,
dynamoEntity
);
expect(transformed).toEqual({
id: '1',
name: 'Me',
age: 1,
});
});
test('transforms inherited dynamo entity to entity model', () => {
const dynamoEntity = {
PK: 'CUS#1',
SK: 'CUS#user@example.com',
id: '1',
name: 'Me',
username: 'i-am-user',
password: 'password',
email: 'user@example.com',
loyaltyPoints: 97,
};
const transformed = transformer.fromDynamoEntity(User, dynamoEntity);
expect(transformed).toEqual({
id: '1',
name: 'Me',
email: 'user@example.com',
loyaltyPoints: 97,
password: 'password',
username: 'i-am-user',
});
});
test('excludes internal attributes from transformed object', () => {
const dynamoEntity = {
PK: 'CUS#1',
SK: 'CUS#user@example.com',
id: '1',
name: 'Me',
__en: 'user',
};
const transformed = transformer.fromDynamoEntity(User, dynamoEntity);
expect(transformed).toEqual({
id: '1',
name: 'Me',
});
});
test('excludes hidden props from returned response', () => {
@Entity({
name: 'user-priv',
table,
primaryKey: {
partitionKey: 'USER#{{id}}',
sortKey: 'USER#{{id}}',
},
})
class UserPriv {
@Attribute()
id: string;
@Attribute()
username: string;
@Attribute({
hidden: true,
})
password: string;
@AutoGenerateAttribute({
strategy: AUTO_GENERATE_ATTRIBUTE_STRATEGY.UUID4,
hidden: true,
})
createdAt: string;
}
transformer = new EntityTransformer(
createTestConnection({
entities: [UserPriv],
name: 'temp-hidden-props',
})
);
const dynamoEntity = {
PK: 'USER#1',
id: '1',
username: 'Me@21',
password: '12344',
createdAt: '13123123123',
__en: 'user-priv',
};
const transformed = transformer.fromDynamoEntity(UserPriv, dynamoEntity);
expect(transformed).toEqual({
id: '1',
username: 'Me@21',
});
});
test('transforms photo dynamo item to entity model instance ', () => {
const dynamoEntity = {
PK: 'PHOTO#PETS',
SK: 'PHOTO#1',
id: 1,
category: 'PETS',
name: 'my cute pet billy',
GSI1PK: 'PHOTO#c0ac5395-ba7c-41bf-bbc3-09a6087bcca2',
GSI1SK: 'PHOTO#kids-new',
createdAt: '2020-03-21T03:26:34.781Z',
};
const transformed = transformer.fromDynamoEntity(Photo, dynamoEntity);
expect(transformed).toMatchObject({
category: 'PETS',
createdAt: expect.any(moment),
id: 1,
name: 'my cute pet billy',
});
expect(transformed).toBeInstanceOf(Photo);
expect(transformed.createdDate()).toEqual('03-21-2020');
});
/**
* @group toDynamoEntity
*/
test('transforms simple model to dynamo entity', () => {
const user = new User();
user.id = '111';
user.name = 'Test User';
user.status = 'inactive';
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
GSI1PK: 'USER#STATUS#inactive',
GSI1SK: 'USER#Test User',
PK: 'USER#111',
SK: 'USER#111',
id: '111',
name: 'Test User',
status: 'inactive',
});
});
test('transforms photo entity to valid dynamo item ', () => {
const photo = new Photo(CATEGORY.KIDS, 'my baby');
const response = transformer.toDynamoEntity(photo);
expect(response).toEqual({
PK: 'PHOTO#kids-new',
SK: 'PHOTO#c0ac5395-ba7c-41bf-bbc3-09a6087bcca2',
GSI1PK: 'PHOTO#c0ac5395-ba7c-41bf-bbc3-09a6087bcca2',
GSI1SK: 'PHOTO#kids-new',
category: 'kids-new',
id: 'c0ac5395-ba7c-41bf-bbc3-09a6087bcca2',
updatedAt: '1622530750',
createdAt: '2021-06-01',
name: 'my baby',
});
});
test('transforms entity with attribute alias to dynamo entity', () => {
const user = new UserAttrAlias();
user.id = '111';
user.name = 'Test User';
user.status = 'inactive';
user.age = 10;
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
GSI1PK: 'inactive',
GSI1SK: 'USER#Test User',
PK: 'USER#111',
SK: 'USER#111',
LSI1SK: 10, // <-- aliased indexes are correctly persisting attribute types
age: 10,
id: '111',
name: 'Test User',
status: 'inactive',
});
});
test('transforms entity with attribute alias to dynamo entity', () => {
const user = new UserAttrAlias();
user.id = '111';
user.age = 10;
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
PK: 'USER#111',
SK: 'USER#111',
LSI1SK: 10, // <-- aliased indexes are correctly persisting attribute types
age: 10,
id: '111',
});
});
test('transforms entity with sparse index when variable referenced in sort key is missing a value', () => {
const user = new UserSparseIndexes();
user.id = '111';
user.status = 'active';
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
PK: 'USER_SPARSE_INDEXES#111',
SK: 'USER_SPARSE_INDEXES#111',
id: '111',
status: 'active',
});
});
test('transforms entity with sparse LSI index when variable referenced is missing a value', () => {
const user = new UserSparseIndexes();
user.id = '111';
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
PK: 'USER_SPARSE_INDEXES#111',
SK: 'USER_SPARSE_INDEXES#111',
id: '111',
});
});
/**
* Issue #37
*/
test('transforms simple model with auto generated values to dynamo entity', () => {
jest.useFakeTimers('modern').setSystemTime(new Date('2020-10-10'));
const user = new UserAutoGenerateAttributes();
user.id = '111';
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
GSI1PK: 'USER#UPDATED_AT#1602288000',
GSI1SK: 'USER#111',
PK: 'USER#111',
SK: 'USER#111',
id: '111',
updatedAt: 1602288000,
});
});
test('transforms complex model model to dynamo entity', () => {
resetTestConnection();
const table = new Table({
name: 'user-table',
partitionKey: 'PK',
sortKey: 'SK',
indexes: {
GSI1: {
partitionKey: 'GSI1PK',
sortKey: 'GSI1SK',
type: INDEX_TYPE.GSI,
},
GSI2: {
partitionKey: 'GSI2PK',
sortKey: 'GSI2SK',
type: INDEX_TYPE.GSI,
},
LSI1: {
sortKey: 'LSI1SK',
type: INDEX_TYPE.LSI,
},
},
});
@Entity({
name: 'User',
primaryKey: {
partitionKey: 'USER#{{id}}#NAME#{{name}}',
sortKey: 'USER#{{id}}',
},
indexes: {
GSI1: {
partitionKey: 'USER#{{id}}#AGE#{{age}}',
sortKey: 'USER#{{name}}',
type: INDEX_TYPE.GSI,
},
LSI1: {
sortKey: 'USER#{{id}}',
type: INDEX_TYPE.LSI,
},
},
table,
})
class ComplexUser {
@Attribute()
id: string;
@Attribute()
name: string;
@Attribute()
age: number;
}
const connection = createTestConnection({
entities: [ComplexUser],
});
transformer = new EntityTransformer(connection);
const user = new ComplexUser();
user.id = '111';
user.name = 'Test User';
user.age = 12;
const response = transformer.toDynamoEntity(user);
expect(response).toEqual({
id: '111',
GSI1PK: 'USER#111#AGE#12',
GSI1SK: 'USER#Test User',
LSI1SK: 'USER#111',
PK: 'USER#111#NAME#Test User',
SK: 'USER#111',
name: 'Test User',
age: 12,
});
});
/**
* Issue #135
*/
test('transforms put item requests with attributes containing default values', () => {
const user = new UserWithDefaultValues();
user.id = '1';
const putItem = transformer.toDynamoEntity(user);
expect(putItem).toEqual({
GSI1PK: 'USER#STATUS#active',
GSI1SK: 'USER#active',
PK: 'USER#1',
SK: 'USER#1',
id: '1',
status: 'active',
});
});
/**
* @group getAffectedIndexesForAttributes
*/
test('returns all affected indexes for static attributes', () => {
const affectedIndexes = transformer.getAffectedIndexesForAttributes(
User,
{
name: 'new updated name',
},
{name: 'static'}
);
expect(affectedIndexes).toEqual({
GSI1SK: 'USER#new updated name',
});
});
test('returns all affected indexes for dynamic update body', () => {
const affectedIndexes = transformer.getAffectedIndexesForAttributes<User>(
User,
{
age: {
DECREMENT_BY: 2,
},
},
{age: 'dynamic'}
);
expect(affectedIndexes).toEqual({});
});
test('returns all affected indexes for alias attributes', () => {
const affectedIndexes = transformer.getAffectedIndexesForAttributes(
UserAttrAlias,
{
age: 10,
status: 'inactive',
},
{age: 'static', status: 'static'}
);
expect(affectedIndexes).toEqual({
LSI1SK: 10, // <-- aliased indexes are correctly persisting attribute types
GSI1PK: 'inactive',
});
});
test('returns all affected indexes for complex attributes', () => {
const affectedIndexes = transformer.getAffectedIndexesForAttributes(
Organisation,
{
name: 'Updated name',
teamCount: 12,
active: false,
},
{
name: 'static',
teamCount: 'static',
active: 'static',
}
);
expect(affectedIndexes).toEqual({
GSI1SK: 'ORG#Updated name#ACTIVE#false',
GSI2SK: 'ORG#Updated name#TEAM_COUNT#12',
});
});
/**
* @group fromDynamoKeyToAttributes
*/
test('reverse transforms key schema to attributes', () => {
const attributes = transformer.fromDynamoKeyToAttributes(User, {
PK: 'USER#12',
SK: 'USER#12',
});
expect(attributes).toEqual({
id: '12',
});
});
test('safely fails to transform key for unknown entity ', () => {
const attributes = transformer.fromDynamoKeyToAttributes(User, {
PK: 'OTHERsUSER#12',
SK: 'OTHER_USER#12',
});
expect(attributes).toEqual({});
});
test('reverse transforms key schema to attributes with proper value types', () => {
resetTestConnection();
@Entity({
name: 'other-user',
primaryKey: {
partitionKey: 'USER#{{id}}#active#{{active}}',
sortKey: 'USER#{{id}}',
},
table,
})
class ComplexUser {
@Attribute()
id: number;
@Attribute()
name: string;
@Attribute()
age: number;
@Attribute()
active: boolean;
}
const connection = createTestConnection({
entities: [ComplexUser],
});
transformer = new EntityTransformer(connection);
const attributes = transformer.fromDynamoKeyToAttributes(ComplexUser, {
PK: 'USER#12#active#true',
SK: 'USER#12',
});
expect(attributes).toEqual({
id: 12,
active: true,
});
}); | the_stack |
import {WboxProps, WimageProps, WdateProps, WspacerProps, WstackProps, WtextProps} from '../types/widget'
import {getImage, hash} from './help'
import {URLSchemeFrom} from './constants'
type WidgetType = 'wbox' | 'wdate' | 'wimage' | 'wspacer' | 'wstack' | 'wtext'
type WidgetProps = WboxProps | WdateProps | WspacerProps | WstackProps | WtextProps | WimageProps
type Children<T extends Scriptable.Widget> = ((instance: T) => Promise<void>)[]
/**属性对应关系*/
type KeyMap<KEY extends null | undefined | string | symbol | number> = Record<NonNullable<KEY>, () => void>
class GenrateView {
public static listWidget: ListWidget
static setListWidget(listWidget: ListWidget): void {
this.listWidget = listWidget
}
// 根组件
static async wbox(props: WboxProps, ...children: Children<ListWidget>) {
const {background, spacing, href, updateDate, padding, onClick} = props
try {
// background
isDefined(background) && (await setBackground(this.listWidget, background))
// spacing
isDefined(spacing) && (this.listWidget.spacing = spacing)
// href
isDefined(href) && (this.listWidget.url = href)
// updateDate
isDefined(updateDate) && (this.listWidget.refreshAfterDate = updateDate)
// padding
isDefined(padding) && this.listWidget.setPadding(...padding)
// onClick
isDefined(onClick) && runOnClick(this.listWidget, onClick)
await addChildren(this.listWidget, children)
} catch (err) {
console.error(err)
}
return this.listWidget
}
// 容器组件
static wstack(props: WstackProps, ...children: Children<WidgetStack>) {
return async (
parentInstance: Scriptable.Widget & {
addStack(): WidgetStack
},
) => {
const widgetStack = parentInstance.addStack()
const {
background,
spacing,
padding,
width = 0,
height = 0,
borderRadius,
borderWidth,
borderColor,
href,
verticalAlign,
flexDirection,
onClick,
} = props
try {
// background
isDefined(background) && (await setBackground(widgetStack, background))
// spacing
isDefined(spacing) && (widgetStack.spacing = spacing)
// padding
isDefined(padding) && widgetStack.setPadding(...padding)
// borderRadius
isDefined(borderRadius) && (widgetStack.cornerRadius = borderRadius)
// borderWidth
isDefined(borderWidth) && (widgetStack.borderWidth = borderWidth)
// borderColor
isDefined(borderColor) && (widgetStack.borderColor = getColor(borderColor))
// href
isDefined(href) && (widgetStack.url = href)
// width、height
widgetStack.size = new Size(width, height)
// verticalAlign
const verticalAlignMap: KeyMap<WstackProps['verticalAlign']> = {
bottom: () => widgetStack.bottomAlignContent(),
center: () => widgetStack.centerAlignContent(),
top: () => widgetStack.topAlignContent(),
}
isDefined(verticalAlign) && verticalAlignMap[verticalAlign]()
// flexDirection
const flexDirectionMap: KeyMap<WstackProps['flexDirection']> = {
row: () => widgetStack.layoutHorizontally(),
column: () => widgetStack.layoutVertically(),
}
isDefined(flexDirection) && flexDirectionMap[flexDirection]()
// onClick
isDefined(onClick) && runOnClick(widgetStack, onClick)
} catch (err) {
console.error(err)
}
await addChildren(widgetStack, children)
}
}
// 图片组件
static wimage(props: WimageProps) {
return async (
parentInstance: Scriptable.Widget & {
addImage(image: Image): WidgetImage
},
) => {
const {
src,
href,
resizable,
width = 0,
height = 0,
opacity,
borderRadius,
borderWidth,
borderColor,
containerRelativeShape,
filter,
imageAlign,
mode,
onClick,
} = props
let _image: Image = src as Image
// src 为网络连接时
typeof src === 'string' && isUrl(src) && (_image = await getImage({url: src}))
// src 为 icon name 时
typeof src === 'string' && !isUrl(src) && (_image = SFSymbol.named(src).image)
const widgetImage = parentInstance.addImage(_image)
widgetImage.image = _image
try {
// href
isDefined(href) && (widgetImage.url = href)
// resizable
isDefined(resizable) && (widgetImage.resizable = resizable)
// width、height
widgetImage.imageSize = new Size(width, height)
// opacity
isDefined(opacity) && (widgetImage.imageOpacity = opacity)
// borderRadius
isDefined(borderRadius) && (widgetImage.cornerRadius = borderRadius)
// borderWidth
isDefined(borderWidth) && (widgetImage.borderWidth = borderWidth)
// borderColor
isDefined(borderColor) && (widgetImage.borderColor = getColor(borderColor))
// containerRelativeShape
isDefined(containerRelativeShape) && (widgetImage.containerRelativeShape = containerRelativeShape)
// filter
isDefined(filter) && (widgetImage.tintColor = getColor(filter))
// imageAlign
const imageAlignMap: KeyMap<WimageProps['imageAlign']> = {
left: () => widgetImage.leftAlignImage(),
center: () => widgetImage.centerAlignImage(),
right: () => widgetImage.rightAlignImage(),
}
isDefined(imageAlign) && imageAlignMap[imageAlign]()
// mode
const modeMap: KeyMap<WimageProps['mode']> = {
fit: () => widgetImage.applyFittingContentMode(),
fill: () => widgetImage.applyFillingContentMode(),
}
isDefined(mode) && modeMap[mode]()
// onClick
isDefined(onClick) && runOnClick(widgetImage, onClick)
} catch (err) {
console.error(err)
}
}
}
// 占位空格组件
static wspacer(props: WspacerProps) {
return async (
parentInstance: Scriptable.Widget & {
addSpacer(length?: number): WidgetSpacer
},
) => {
const widgetSpacer = parentInstance.addSpacer()
const {length} = props
try {
// length
isDefined(length) && (widgetSpacer.length = length)
} catch (err) {
console.error(err)
}
}
}
// 文字组件
static wtext(props: WtextProps, ...children: string[]) {
return async (
parentInstance: Scriptable.Widget & {
addText(text?: string): WidgetText
},
) => {
const widgetText = parentInstance.addText('')
const {
textColor,
font,
opacity,
maxLine,
scale,
shadowColor,
shadowRadius,
shadowOffset,
href,
textAlign,
onClick,
} = props
if (children && Array.isArray(children)) {
widgetText.text = children.join('')
}
try {
// textColor
isDefined(textColor) && (widgetText.textColor = getColor(textColor))
// font
isDefined(font) && (widgetText.font = typeof font === 'number' ? Font.systemFont(font) : font)
// opacity
isDefined(opacity) && (widgetText.textOpacity = opacity)
// maxLine
isDefined(maxLine) && (widgetText.lineLimit = maxLine)
// scale
isDefined(scale) && (widgetText.minimumScaleFactor = scale)
// shadowColor
isDefined(shadowColor) && (widgetText.shadowColor = getColor(shadowColor))
// shadowRadius
isDefined(shadowRadius) && (widgetText.shadowRadius = shadowRadius)
// shadowOffset
isDefined(shadowOffset) && (widgetText.shadowOffset = shadowOffset)
// href
isDefined(href) && (widgetText.url = href)
//textAlign
const textAlignMap: KeyMap<WtextProps['textAlign']> = {
left: () => widgetText.leftAlignText(),
center: () => widgetText.centerAlignText(),
right: () => widgetText.rightAlignText(),
}
isDefined(textAlign) && textAlignMap[textAlign]()
// onClick
isDefined(onClick) && runOnClick(widgetText, onClick)
} catch (err) {
console.error(err)
}
}
}
// 日期组件
static wdate(props: WdateProps) {
return async (
parentInstance: Scriptable.Widget & {
addDate(date: Date): WidgetDate
},
) => {
const widgetDate = parentInstance.addDate(new Date())
const {
date,
mode,
textColor,
font,
opacity,
maxLine,
scale,
shadowColor,
shadowRadius,
shadowOffset,
href,
textAlign,
onClick,
} = props
try {
// date
isDefined(date) && (widgetDate.date = date)
// textColor
isDefined(textColor) && (widgetDate.textColor = getColor(textColor))
// font
isDefined(font) && (widgetDate.font = typeof font === 'number' ? Font.systemFont(font) : font)
// opacity
isDefined(opacity) && (widgetDate.textOpacity = opacity)
// maxLine
isDefined(maxLine) && (widgetDate.lineLimit = maxLine)
// scale
isDefined(scale) && (widgetDate.minimumScaleFactor = scale)
// shadowColor
isDefined(shadowColor) && (widgetDate.shadowColor = getColor(shadowColor))
// shadowRadius
isDefined(shadowRadius) && (widgetDate.shadowRadius = shadowRadius)
// shadowOffset
isDefined(shadowOffset) && (widgetDate.shadowOffset = shadowOffset)
// href
isDefined(href) && (widgetDate.url = href)
// mode
const modeMap: KeyMap<WdateProps['mode']> = {
time: () => widgetDate.applyTimeStyle(),
date: () => widgetDate.applyDateStyle(),
relative: () => widgetDate.applyRelativeStyle(),
offset: () => widgetDate.applyOffsetStyle(),
timer: () => widgetDate.applyTimerStyle(),
}
isDefined(mode) && modeMap[mode]()
// textAlign
const textAlignMap: KeyMap<WdateProps['textAlign']> = {
left: () => widgetDate.leftAlignText(),
center: () => widgetDate.centerAlignText(),
right: () => widgetDate.rightAlignText(),
}
isDefined(textAlign) && textAlignMap[textAlign]()
// onClick
isDefined(onClick) && runOnClick(widgetDate, onClick)
} catch (err) {
console.error(err)
}
}
}
}
const listWidget = new ListWidget()
GenrateView.setListWidget(listWidget)
export function h(
type: WidgetType | (() => () => void),
props?: WidgetProps,
...children: Children<Scriptable.Widget> | string[]
): Promise<unknown> | unknown {
props = props || {}
// 由于 Fragment 的存在,children 可能为多维数组混合,先把它展平
const _children = flatteningArr(children as unknown[]) as typeof children
switch (type) {
case 'wbox':
return GenrateView.wbox(props as WboxProps, ...(_children as Children<Scriptable.Widget>))
break
case 'wdate':
return GenrateView.wdate(props as WdateProps)
break
case 'wimage':
return GenrateView.wimage(props as WimageProps)
break
case 'wspacer':
return GenrateView.wspacer(props as WspacerProps)
break
case 'wstack':
return GenrateView.wstack(props as WstackProps, ...(_children as Children<Scriptable.Widget>))
break
case 'wtext':
return GenrateView.wtext(props as WtextProps, ...(_children as string[]))
break
default:
// custom component
return type instanceof Function
? ((type as unknown) as (props: WidgetProps) => Promise<Scriptable.Widget>)({children: _children, ...props})
: null
break
}
}
export function Fragment({children}: {children: typeof h[]}): typeof h[] {
return children
}
/**
* 展平所有维度数组
* @param arr 数组
*/
function flatteningArr<T>(arr: T[]): T[] {
return [].concat(
...arr.map((item: T | T[]) => {
return (Array.isArray(item) ? flatteningArr(item) : item) as never[]
}),
) as T[]
}
/**
* 输出真正颜色(比如string转color)
* @param color
*/
function getColor(color: Color | string): Color {
return typeof color === 'string' ? new Color(color, 1) : color
}
/**
* 输出真正背景(比如string转color)
* @param bg 输入背景参数
*/
async function getBackground(bg: Color | Image | LinearGradient | string): Promise<Color | Image | LinearGradient> {
bg = (typeof bg === 'string' && !isUrl(bg)) || bg instanceof Color ? getColor(bg) : bg
if (typeof bg === 'string') {
bg = await getImage({url: bg})
}
return bg
}
/**
* 设置背景
* @param widget 实例
* @param bg 背景
*/
async function setBackground(
widget: Scriptable.Widget & {
backgroundColor: Color
backgroundImage: Image
backgroundGradient: LinearGradient
},
bg: Color | Image | LinearGradient | string,
): Promise<void> {
const _bg = await getBackground(bg)
if (_bg instanceof Color) {
widget.backgroundColor = _bg
}
if (_bg instanceof Image) {
widget.backgroundImage = _bg
}
if (_bg instanceof LinearGradient) {
widget.backgroundGradient = _bg
}
}
/**
* 添加子组件列表(把当前实例传下去)
* @param instance 当前实例
* @param children 子组件列表
*/
async function addChildren<T extends Scriptable.Widget>(instance: T, children: Children<T>): Promise<void> {
if (children && Array.isArray(children)) {
for (const child of children) {
child instanceof Function ? await child(instance) : ''
}
}
}
/**
* 如果某值不是 undefined、null、NaN 则返回 true
* @param value 值
*/
function isDefined<T>(value: T | undefined | null): value is T {
if (typeof value === 'number' && !isNaN(value)) {
return true
}
return value !== undefined && value !== null
}
/**
* 判断一个值是否为网络连接
* @param value 值
*/
function isUrl(value: string): boolean {
const reg = /^(http|https)\:\/\/[\w\W]+/
return reg.test(value)
}
/**
* 执行点击事件
* @param instance 当前实例
* @param onClick 点击事件
*/
function runOnClick<T extends Scriptable.Widget & {url: string}>(instance: T, onClick: () => unknown) {
const _eventId = hash(onClick.toString())
instance.url = `${URLScheme.forRunningScript()}?eventId=${encodeURIComponent(_eventId)}&from=${URLSchemeFrom.WIDGET}`
const {eventId, from} = args.queryParameters
if (eventId && eventId === _eventId && from === URLSchemeFrom.WIDGET) {
onClick()
}
} | the_stack |
import { NodeTags } from '../utils';
import { ParsedVisitor } from './parsed-visitor';
export type ParseSimpleType =
| ParseMethod // a function can be a type
| ParsePrimitiveType
| ParseReferenceType
| ParseValueType;
export type ParseType =
| ParseEmpty
| ParseSimpleType
| ParseUnionType;
export enum Primitives {
String = 'string',
Number = 'number',
Undefined = 'undefined',
Null = 'null',
Boolean = 'boolean',
Symbol = 'symbol',
}
/**
* @description
* Every Node that is Parsed extends from this basic class.
* It provides the node with a location to identify its position
*/
export class ParseNode {
/** Used by the visitors to have the reference of the parent nodes */
_parentNode: ParseNode;
_visited: boolean = false;
constructor(public location: ParseLocation) { }
visit(visitor: ParsedVisitor): any { return null; }
}
/**
* @description
* Empty class if node cannot be resolved
*/
export class ParseEmpty extends ParseNode {
constructor() {
super(null);
}
visit(visitor: ParsedVisitor): any { return null; }
}
/**
* @description
* The parse generic is being used as a placeholder during the transform process
* to be replaced later on with the real value.
*/
export class ParseGeneric extends ParseNode {
value: ParseNode;
type: ParseNode;
constructor(
location: ParseLocation,
public name: string,
public constraint?: ParseType,
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitGeneric(this);
}
}
/**
* @description
* The Position in the typescript source file of a node.
* Is used as unique identifier for the node.
*/
export class ParseLocation {
constructor(
public path: string,
public position: number,
) {}
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* P A R S E D T Y P E S
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
export class ParsePrimitiveType extends ParseNode {
constructor(
location: ParseLocation,
public type: Primitives,
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitPrimitiveType(this);
}
}
/**
* @description
* Parses a Union type `type x = 'a' | 'b'`
*/
export class ParseUnionType extends ParseNode {
constructor(
location: ParseLocation,
public types: ParseSimpleType[],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitUnionType(this);
}
}
/**
* @description
* Parses a typescript partial type `Partial<type>`
*/
export class ParsePartialType extends ParseUnionType {
constructor(
location: ParseLocation,
types: ParseSimpleType[],
) {
super(location, types);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitPartialType(this);
}
}
/**
* @description
* An intersection type combines multiple types into one.
* `method(): T & U {…}`
* @see https://www.typescriptlang.org/docs/handbook/advanced-types.html
*/
export class ParseIntersectionType extends ParseNode {
constructor(
location: ParseLocation,
public types: ParseSimpleType[],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitIntersectionType(this);
}
}
/**
* @description
* A parenthesized type combines multiple types to be applied for an array
* type as an example: `type a = (number | string)[]`
* So this array can hold numbers and strings
*/
export class ParseParenthesizedType extends ParseNode {
constructor(
location: ParseLocation,
public type: ParseSimpleType,
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitParenthesizedType(this);
}
}
/**
* @description
* A value type is every type that holds a real value (has to be a primitive type)
* For example `const a = 'myValue';` or `const b = 2;`.
* In these cases 'myValue' and 2 are value types.
*/
export class ParseValueType extends ParseNode {
constructor(
location: ParseLocation,
public value: string | boolean | number,
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitValueType(this);
}
}
/**
* @description
* A type that holds a reference to another (ParseInterface, ParseType)
* Can have `typeArguments` that are a kind of parameters for types.
* Can be used to pass data to a generic
*/
export class ParseReferenceType extends ParseNode {
constructor(
location: ParseLocation,
public name: string,
public typeArguments: ParseType[] = [],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitReferenceType(this);
}
}
/**
* @description
* Visits a array type like `string[]`
*/
export class ParseArrayType extends ParseNode {
constructor(
location: ParseLocation,
public type: ParseType,
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitArrayType(this);
}
}
/**
* @description
* A type parameter is passed like a generic `type a<T> = () => T`
* @param constraint The constraint can extend the generic type T
* like the following example `function f<T extends OtherType<I>>(): T`
*/
export class ParseTypeParameter extends ParseNode {
constructor(
location: ParseLocation,
public name: string,
public constraint?: ParseType,
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitTypeParameter(this);
}
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* P A R S E D N O D E S
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @description
* A type Literal is an object inside an interface in typescript
* for example: `interface a { b: string; c: { d: number }}`.
* In this case c would be a TypeLiteral
*/
export class ParseTypeLiteral extends ParseNode {
constructor(
location: ParseLocation,
public members: ParseProperty[] = [],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitTypeLiteral(this);
}
}
/**
* @description
* Visits a typescript Decorator
*/
export class ParseDecorator extends ParseNode {
constructor(
location: ParseLocation,
public name: string,
public args: ParseNode[] = [],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitDecorator(this);
}
}
/**
* @description
* Holds the information for a typescript expression more or less like
* a reference to the declaration with values for the parameters
*/
export class ParseExpression extends ParseReferenceType {
constructor(
location: ParseLocation,
name: string,
typeArguments: ParseType[] = [],
public args: ParseNode[] = [],
) {
super(location, name, typeArguments);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitExpression(this);
}
}
/**
* @description
* A parse object literal is an object with properties.
*/
export class ParseObjectLiteral extends ParseNode {
constructor(
location: ParseLocation,
public tags: NodeTags[],
public properties: ParseProperty[],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitObjectLiteral(this);
}
}
/**
* @description
* A parse array literal is an array with properties.
*/
export class ParseArrayLiteral extends ParseNode {
constructor(
location: ParseLocation,
public tags: NodeTags[],
public values: ParseSimpleType[],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitArrayLiteral(this);
}
}
/**
* @description
* A parse definition is every Root node in a SourceFile,
* a ParseResult consist out of ParseDefinitions
* Is only used for extending other classes!
*/
export class ParseDefinition extends ParseNode {
/**
* @param location location is the unique position in a file (consists out of filename and position)
* @param name name of the definition (Symbol Name)
* @param tags Array of jsDoc annotations like internal unrelated private or exported
*/
constructor(
location: ParseLocation,
public name: string,
public tags: NodeTags[],
) {
super(location);
}
visit(visitor: ParsedVisitor): null { return null; }
}
/**
* @description
* A parseProperty is used to hold the information of object, interface or class members
* it can be either a value or a function parameter.
*/
export class ParseProperty extends ParseDefinition {
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
public type: ParseType,
public value?: any,
public decorators?: ParseDecorator[],
public isOptional?: boolean,
) {
super(location, name, tags);
}
isFunction(): boolean {
return this.type instanceof ParseMethod;
}
isAngularInput(): boolean {
if (!this.decorators || !this.decorators.length) { return false; }
return !!this.decorators
.find((decorator: ParseDecorator) =>
decorator.name === 'Input');
}
visit(visitor: ParsedVisitor): any {
return visitor.visitProperty(this);
}
}
/**
* @description
* An index signature can be a member of a typescript interface.
```typescript
interface test {
[key: string]: any
}
```
*/
export class ParseIndexSignature extends ParseDefinition {
/**
* @param name index name (key)
* @param indexType the type of key
* @param type the type of the value
*/
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
public indexType: ParseType,
public type: ParseType,
) {
super(location, name, tags);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitIndexSignature(this);
}
}
/**
* @description
* A method signature can be a member of a typescript interface.
```typescript
interface test {
tick<T>(..args);
}
```
*/
export class ParseMethod extends ParseDefinition {
/**
* @param name index name (key)
* @param indexType the type of key
* @param type the type of the value
*/
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
public parameters: ParseProperty[],
public returnType: ParseType,
public typeParameters: ParseTypeParameter[] = [],
public decorators?: ParseDecorator[],
) {
super(location, name, tags);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitMethod(this);
}
}
/**
* @description
* A ParseDependency is an import or export statement.
* It is only used to build a dependency tree.
*/
export class ParseDependency extends ParseNode {
constructor(
location: ParseLocation,
public path: string,
public values: Set<string>,
) {
super(location);
}
visit(visitor: ParsedVisitor): null { return null; }
}
/**
* @description
* The Results are stored in this class it holds all dependency paths of a file
* and all parsed definitions. A Parse Result represents a parsed Typescript file.
*/
export class ParseResult extends ParseNode {
constructor(
location: ParseLocation,
public nodes: ParseDefinition[],
public dependencyPaths: ParseDependency[],
) {
super(location);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitResult(this);
}
}
/**
* @description
* The variable declaration that can store any value, it can be every
* `const`, `let`, `var` statement.
*/
export class ParseVariableDeclaration extends ParseDefinition {
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
public type: ParseType,
public value: ParseType,
) {
super(location, name, tags);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitVariableDeclaration(this);
}
}
/**
* @description
* A type alias declaration holds a type for a reference type
* `type myType<T> = () => T;`
*/
export class ParseTypeAliasDeclaration extends ParseProperty {
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
type: ParseType,
public typeParameters: ParseTypeParameter[] = [],
) {
super(location, name, tags, type);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitTypeAliasDeclaration(this);
}
}
/**
* @description
* Hold type information for objects or classes
*/
export class ParseInterfaceDeclaration extends ParseDefinition {
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
public members: (ParseProperty | ParseMethod | ParseIndexSignature)[] = [],
public typeParameters: ParseTypeParameter[] = [],
public extending: ParseReferenceType = undefined,
) {
super(location, name, tags);
}
visit(visitor: ParsedVisitor): any {
return visitor.visitInterfaceDeclaration(this);
}
}
/**
* @description
* Is a parsed node for a typescript `class a {}` often used
* to merge interfaces or heritage clauses
*/
export class ParseClassDeclaration extends ParseInterfaceDeclaration {
constructor(
location: ParseLocation,
name: string,
tags: NodeTags[],
members: (ParseProperty | ParseMethod)[] = [],
typeParameters: ParseTypeParameter[] = [],
extending: ParseReferenceType = undefined,
public implementing?: ParseReferenceType[],
public decorators?: ParseDecorator[],
) {
super(location, name, tags, members, typeParameters, extending);
}
isAngularComponent(): boolean {
if (!this.decorators || !this.decorators.length) { return false; }
return !!this.decorators
.find((decorator: ParseDecorator) =>
decorator.name === 'Component');
}
visit(visitor: ParsedVisitor): any {
return visitor.visitClassDeclaration(this);
}
} | the_stack |
import React from "react";
import styled from "styled-components";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { CodeStreamState } from "../store";
import { Dispatch } from "../store/common";
import Tooltip from "./Tooltip";
import { ComposeArea } from "./ReviewNav";
import { CSMe } from "@codestream/protocols/api";
import { openPanel, openModal } from "../store/context/actions";
import { WebviewPanels, WebviewModals } from "@codestream/protocols/webview";
import { isConnected } from "../store/providers/reducer";
import { setUserPreference } from "./actions";
import { Button } from "../src/components/Button";
import { HostApi } from "../webview-api";
import { OpenUrlRequestType } from "../ipc/host.protocol";
import { Tab, Tabs, Content } from "../src/components/Tabs";
import { Flow } from "./Flow";
import { CreateCodemarkIcons } from "./CreateCodemarkIcons";
import { PanelHeader } from "../src/components/PanelHeader";
import ScrollBox from "./ScrollBox";
import { isFeatureEnabled } from "../store/apiVersioning/reducer";
import { getSidebarLocation } from "../store/editorContext/reducer";
const Step = styled.div`
position: relative;
display: flex;
align-items: center;
cursor: pointer;
margin: 0 -10px;
padding: 10px 15px 10px 10px;
border-radius: 30px;
padding: 10px;
border-radius: 0;
border: 1px solid transparent;
&:hover {
// background: var(--app-background-color-hover);
border: 1px solid var(--base-border-color);
.icon {
top: -5px;
right: 0px;
position: absolute;
display: block !important;
transform: scale(0.7);
}
}
.icon {
display: none !important;
}
a {
display: block;
flex-shrink: 0;
margin-left: auto;
}
`;
const StepNumber = styled.div`
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
width: 30px;
height: 30px;
border-radius: 50%;
border-radius: 5px;
margin: 0 10px 0 0;
font-weight: bold;
background: var(--button-background-color);
color: var(--button-foreground-color);
`;
const StepNumberDone = styled(StepNumber)`
.vscode-dark& {
background: rgba(127, 127, 127, 0.4);
}
background: rgba(127, 127, 127, 0.2);
`;
const StepText = styled.div`
margin-right: 10px;
`;
const StepTitle = styled.span`
font-weight: bold;
color: var(--text-color-highlight);
`;
export const YouTubeImg = styled.img`
height: 22px;
cursor: pointer;
opacity: 0.8;
vertical-align: -2px;
&:hover {
opacity: 1;
text-shadow: 0 5px 10px rgba(0, 0, 0, 0.8);
}
`;
const StepSubtext = styled.span``;
const Status = styled.div`
margin: 20px 0;
`;
const StatusCount = styled.span`
font-size: larger;
color: var(--text-color-highlight);
`;
const Root = styled.div`
padding: 0 40px;
z-index: 0;
color: var(--text-color-subtle);
font-size: var(--font-size);
b,
h2 {
color: var(--text-color-highlight);
}
@media only screen and (max-width: 450px) {
padding: 0 30px;
}
@media only screen and (max-width: 350px) {
padding: 0 20px;
}
`;
const HR = styled.div`
width: 100%;
height: 1px;
border-bottom: 1px solid var(--base-border-color);
margin: 10px 0;
`;
const SpreadButtons = styled.div`
margin: 20px 0;
display: flex;
button:nth-child(2) {
margin-left: auto;
}
`;
export const STEPS = [
{
id: "addPhoto",
title: "Add a profile photo",
subtext: "so your teammates know who’s who.",
done: "Added profile photo",
pulse: "global-nav-more-label",
video: "https://youtu.be/-HBWfm9P96k",
modal: WebviewModals.ChangeAvatar,
isComplete: user => user.avatar
},
{
id: "createReview",
title: "Request Feedback",
subtext: "to get feedback on your work-in-progress, or final code review.",
done: "Requested Feedback",
pulse: "global-nav-plus-label",
video: "https://www.youtube.com/watch?v=2AyqT4z5Omc",
panel: WebviewPanels.NewReview,
isComplete: user => user.totalReviews > 0
},
{
id: "createCodemark",
title: "Comment on code",
subtext: "in the left margin, or select code in your editor and hit the plus button.",
done: "Commented on code",
pulse: "compose-gutter",
video: "https://youtu.be/RPaIIZgaFK8",
panel: WebviewPanels.NewComment,
isComplete: user => user.totalPosts > 0
},
{
id: "invite",
title: "Invite your teammates",
subtext: "and see what they are working on in real-time.",
done: "Invited teammates",
pulse: "global-nav-team-label",
video: "https://www.youtube.com/watch?v=h5KI3svlq-0",
modal: WebviewModals.Invite,
isComplete: user => user.numUsersInvited > 0
},
{
id: "viewPRs",
title: "View comments from PRs,",
subtext: "including merged PRs, and your current branch.",
done: "Connected to PR provider",
pulse: "pr-toggle",
video: "https://youtu.be/sM607iVWM3w",
panel: WebviewPanels.PRInfo,
isComplete: (_, state) =>
["github", "bitbucket", "gitlab"].some(name => isConnected(state, { name }))
},
{
id: "setUpIntegrations",
title: "Add integrations",
subtext: "with your code host, issue tracker, and messaging service.",
done: "Added integrations",
pulse: "global-nav-more-label",
video: "https://youtu.be/vPChygnwMAw",
panel: WebviewPanels.Integrations,
isComplete: user => {
const { providerInfo = {} } = user;
return Object.keys(providerInfo).length > 0;
}
}
];
interface GettingStartedProps {}
export function GettingStarted(props: GettingStartedProps) {
const dispatch = useDispatch<Dispatch>();
const derivedState = useSelector((state: CodeStreamState) => {
const user = state.users[state.session.userId!] as CSMe;
return {
todo: STEPS.filter(step => !step.isComplete(user, state)),
completed: STEPS.filter(step => step.isComplete(user, state)),
kickstartEnabled: false, //isFeatureEnabled(state, "kickstart")
sidebarLocation: getSidebarLocation(state)
};
}, shallowEqual);
const pulse = id => {
const element = document.getElementById(id);
if (element) element.classList.add("pulse");
};
const unPulse = id => {
const element = document.getElementById(id);
if (element) element.classList.remove("pulse");
};
const handleClick = (e, step) => {
// if they clicked on the youtube video link, don't open the panel
if (e && e.target && e.target.closest("a")) return;
// if they clicked
if (e && e.target && e.target.closest(".icon")) return;
unPulse(step.pulse);
if (step.panel) dispatch(openPanel(step.panel));
if (step.modal) dispatch(openModal(step.modal));
};
const [active, setActive] = React.useState("0");
const handleClickTab = e => {
const index = e.target.id;
if (index !== active) {
setActive(index);
const stepLabels = ["Getting Started", "The Basics", "Trunk Flow", "Branch Flow"];
HostApi.instance.track("Tour Tab Clicked", {
"Tour Step": stepLabels[index]
});
}
};
return (
<div className="panel full-height getting-started-panel">
{active === "0" && <CreateCodemarkIcons />}
<PanelHeader title={<> </>} />
<ScrollBox>
<div className="vscroll">
<Root>
<ComposeArea
side={derivedState.sidebarLocation === "right" ? "right" : "left"}
id="compose-gutter"
/>
{derivedState.kickstartEnabled ? (
<Tabs>
<Tab onClick={handleClickTab} active={active === "0"} id="0">
Getting Started
</Tab>
<Tab onClick={handleClickTab} active={active === "1"} id="1">
The Basics
</Tab>
<Tab onClick={handleClickTab} active={active === "2"} id="2">
Trunk Flow
</Tab>
<Tab onClick={handleClickTab} active={active === "3"} id="3">
Branch Flow
</Tab>
</Tabs>
) : (
<h2>Getting Started</h2>
)}
{active === "0" && (
<Content active>
<b>Let’s get you set up.</b> Follow the steps below to start coding more efficiently
with your team.
<Status>
<StatusCount>
{derivedState.completed.length} of {STEPS.length}
</StatusCount>{" "}
complete
</Status>
{derivedState.todo.map((step, index) => {
return (
<Step
key={step.id}
onMouseEnter={() => pulse(step.pulse)}
onMouseLeave={() => unPulse(step.pulse)}
onClick={e => handleClick(e, step)}
>
<StepNumber>{index + 1}</StepNumber>
<StepText>
<StepTitle>{step.title}</StepTitle>
<StepSubtext>{step.subtext}</StepSubtext>
</StepText>
<Tooltip
title="Watch the how-to video"
placement="bottomRight"
delay={1}
align={{ offset: [13, 0] }}
>
<a href={step.video}>
<YouTubeImg src="https://i.imgur.com/9IKqpzf.png" />
</a>
</Tooltip>
</Step>
);
})}
{derivedState.completed.length > 0 && <HR />}
{derivedState.completed.map(step => {
return (
<Step
key={step.id}
onMouseEnter={() => pulse(step.pulse)}
onMouseLeave={() => unPulse(step.pulse)}
onClick={e => handleClick(e, step)}
>
<StepNumberDone>
<b>{"\u2714"}</b>
</StepNumberDone>
<StepText>
<StepTitle>{step.done}</StepTitle>
</StepText>
<Tooltip title="Watch the how-to video" placement="bottomRight" delay={1}>
<a href={step.video}>
<YouTubeImg src="https://i.imgur.com/9IKqpzf.png" />
</a>
</Tooltip>
</Step>
);
})}
<HR />
<SpreadButtons>
<Button
variant="secondary"
size="compact"
onClick={() => {
dispatch(setUserPreference(["skipGettingStarted"], true));
dispatch(openPanel(WebviewPanels.Activity));
}}
>
Mark all as done
</Button>
<Button
variant="secondary"
size="compact"
onClick={() =>
HostApi.instance.send(OpenUrlRequestType, {
url: "https://www.codestream.com/video-library"
})
}
>
Video library
</Button>
</SpreadButtons>
</Content>
)}
{active === "1" && (
<Content active>
<Flow flow="adhoc" />
</Content>
)}
{active === "2" && (
<Content active>
<Flow flow="simplified" />
</Content>
)}
{active === "3" && (
<Content active>
<Flow flow="standard" />
</Content>
)}
</Root>
</div>
</ScrollBox>
</div>
);
} | the_stack |
import React from 'react'
import c from 'classnames'
import { debounce, omit, pick } from 'lodash-es'
import { getScrollParents } from '@floating-ui/dom'
import { ArrowUpOutlined, ArrowDownOutlined, DragOutlined, DeleteOutlined } from '@ant-design/icons'
import { css } from '../utils/emotion-css'
import usePersistFn from '@rcp/use.persistfn'
import { Button, Menu, Tooltip } from 'antd'
import { MometaHTMLElement, useProxyEvents } from './dom-api'
import { PreventFastClick } from '@rcp/c.preventfastop'
import MoreButton from './components/more-button'
import { useDrag } from 'react-dnd'
import { getSharedFromMain } from '../utils/get-from-main'
const { api } = getSharedFromMain()
function usePosition(dom: HTMLElement) {
const [data, setData] = React.useState({ isReady: false, rect: { width: 0, height: 0, x: 0, y: 0 } })
const [shouldHide, setShouldHide] = React.useState(false)
React.useEffect(() => {
if (!dom) {
return
}
const updatePos = () => {
const rect = dom.getBoundingClientRect()
setData({ rect, isReady: true })
}
updatePos()
const parents = getScrollParents(dom)
const reset = debounce(() => {
setShouldHide(false)
updatePos()
}, 500)
const debouncedUpdate: any = () => {
setShouldHide(true)
reset()
}
parents.forEach((par) => {
par.addEventListener('resize', debouncedUpdate)
par.addEventListener('scroll', debouncedUpdate)
})
return () => {
parents.forEach((par) => {
par.removeEventListener('resize', debouncedUpdate)
par.removeEventListener('scroll', debouncedUpdate)
})
}
}, [dom])
return { shouldHide, ...data }
}
type FloatingUiProps = JSX.IntrinsicElements['div'] & {
dom: MometaHTMLElement
leftTopElement?: React.ReactNode
rightTopElement?: React.ReactNode
rightBottomElement?: React.ReactNode
centerTopElement?: React.ReactNode
centerBottomElement?: React.ReactNode
}
export const FloatingUi = React.forwardRef<HTMLDivElement, FloatingUiProps>(function FloatingUi(
{
centerBottomElement,
centerTopElement,
rightTopElement,
rightBottomElement,
leftTopElement,
children,
dom,
...props
},
ref
) {
const { isReady, shouldHide, rect } = usePosition(dom)
const handlerKeys = React.useMemo(() => {
return Object.keys(props).filter((n) => /^on[A-Z]/.test(n))
}, [props])
const events = React.useMemo(() => pick(props, handlerKeys), [handlerKeys, props])
useProxyEvents(dom, events)
return (
!!isReady && (
<div
ref={ref}
style={{
position: 'absolute',
left: rect.x,
top: rect.y,
width: rect.width,
minHeight: rect.height,
display: shouldHide ? 'none' : ''
}}
{...omit(props, handlerKeys)}
>
{children}
{!!leftTopElement && (
<div
className={css`
display: flex;
transform: translateY(-100%);
position: absolute;
top: 0px;
left: -1px;
`}
>
{leftTopElement}
</div>
)}
{!!rightTopElement && (
<div
className={css`
display: flex;
transform: translateY(-100%);
position: absolute;
top: 0px;
right: -1px;
`}
>
{rightTopElement}
</div>
)}
{!!rightBottomElement && (
<div
className={css`
display: flex;
transform: translateY(100%);
position: absolute;
bottom: 0;
right: -1px;
`}
>
{rightBottomElement}
</div>
)}
{!!centerTopElement && (
<div
className={css`
display: flex;
transform: translate(-50%, -100%);
position: absolute;
top: 0px;
left: 50%;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
`}
>
{centerTopElement}
</div>
)}
{!!centerBottomElement && (
<div
className={css`
display: flex;
transform: translate(-50%, 100%);
position: absolute;
bottom: 0px;
left: 50%;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
`}
>
{centerBottomElement}
</div>
)}
</div>
)
)
})
type OveringFloatProps = FloatingUiProps & {
isSelected?: boolean
onSelect?: () => void
onDeselect?: () => void
isOverCurrent?: boolean
}
export const OveringFloat = React.forwardRef<HTMLDivElement, OveringFloatProps>(function OveringFloat(
{ isOverCurrent, isSelected, onDeselect, onSelect, dom, ...props },
ref
) {
React.useEffect(() => {
dom.__mometa.preventEvent = false
return () => {
if (dom?.__mometa) {
dom.__mometa.preventEvent = true
}
}
}, [dom])
const data = dom.__mometa?.getMometaData()
const [dataStr, drag, preview] = useDrag(
() => ({
type: 'dom',
item: dom,
end: (item, monitor) => {},
collect: (monitor) =>
JSON.stringify({
isDragging: monitor.isDragging()
})
}),
[dom]
)
const { isDragging } = React.useMemo(() => JSON.parse(dataStr), [dataStr])
const onClickFn = usePersistFn((evt) => {
// eslint-disable-next-line no-unused-expressions
onSelect?.()
})
const color = isSelected ? '#5185EC' : '#6F97E7'
const commonCss = css`
display: flex;
align-items: center;
color: #fff;
background-color: ${color};
height: 21px;
padding: 0 4px;
font-size: 12px;
pointer-events: auto;
border-radius: 3px 3px 0 0;
`
const btnCss = css`
display: inline-flex;
cursor: pointer;
margin-left: 2px;
margin-right: 2px;
width: 15px !important;
height: 17px !important;
line-height: 1 !important;
&::before {
background: transparent !important;
}
.anticon {
color: #fff !important;
}
`
const opHandler = usePersistFn(async (opType: string) => {
return api.handleViewOp(opType, dom)
})
const { rect } = usePosition(dom)
if (!dom || !data) {
return null
}
const commonOverCls = css`
min-height: 25px;
color: rgb(161, 160, 160);
font-style: italic;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(96, 125, 217, 0.3);
border: 1px dashed rgba(47, 84, 235, 0.8);
margin-left: -1px;
margin-right: -1px;
width: calc(100% + 2px);
`
const widthGte = true //rect.width >= rect.height
const widthSm = rect.width <= 120
const flagElem = (
<div ref={preview} className={c(commonCss)} title={data.text}>
{!!data.container && '*'}
{data.name || 'Unknown'}
</div>
)
const opElement = (
<>
{!!data.previousSibling && (
<Tooltip title={'上移'}>
{/*// @ts-ignore*/}
<PreventFastClick className={c(btnCss)} onClick={() => opHandler('up')}>
<Button type={'text'} size={'small'} icon={<ArrowUpOutlined />} />
</PreventFastClick>
</Tooltip>
)}
{!!data.nextSibling && (
<Tooltip title={'下移'}>
{/*// @ts-ignore*/}
<PreventFastClick className={c(btnCss)} onClick={() => opHandler('down')}>
<Button type={'text'} size={'small'} icon={<ArrowDownOutlined />} />
</PreventFastClick>
</Tooltip>
)}
<Tooltip title={'删除'}>
{/*// @ts-ignore*/}
<PreventFastClick className={c(btnCss)} onClick={() => opHandler('del')}>
<Button type={'text'} size={'small'} icon={<DeleteOutlined title={'删除'} />} />
</PreventFastClick>
</Tooltip>
</>
)
const dragElem = (
<Tooltip title={'按住并拖动来进行移动;暂时只允许同名文件内移动'}>
{/*// @ts-ignore*/}
<PreventFastClick className={c(btnCss)} onClick={() => opHandler('moving')}>
<Button ref={drag} type={'text'} size={'small'} icon={<DragOutlined />} title={''} />
</PreventFastClick>
</Tooltip>
)
const isSimple = rect.width < 230
const shouldShowOp = !isDragging && isSelected && !isOverCurrent
return (
<FloatingUi
ref={ref}
leftTopElement={!isDragging && flagElem}
rightBottomElement={
isSimple &&
shouldShowOp && (
<div
className={c(
commonCss,
css`
border-radius: 0 0 3px 3px;
`
)}
>
{dragElem}
<MoreButton
className={btnCss}
dom={dom}
menu={
<>
{!!data.previousSibling && <Menu.Item onClick={() => opHandler('up')}>上移</Menu.Item>}
{!!data.nextSibling && <Menu.Item onClick={() => opHandler('down')}>下移</Menu.Item>}
<Menu.Item danger onClick={() => opHandler('del')}>
删除
</Menu.Item>
</>
}
/>
</div>
)
}
rightTopElement={
!isSimple &&
shouldShowOp && (
<div className={c(commonCss)}>
{dragElem}
{opElement}
<MoreButton className={btnCss} dom={dom} />
</div>
)
}
dom={dom}
className={c(
css`
pointer-events: none; !important;
display: flex;
flex-direction: ${widthGte ? 'row' : 'column'};
`,
isDragging &&
css`
background-color: rgba(96, 125, 217, 0.3);
`,
!isOverCurrent && css`outline: ${isSelected ? '1px solid ' + color : '1px dashed ' + color}; !important;`
)}
onClick={onClickFn}
>
{!!isOverCurrent && (
<>
<div
data-pos={'up'}
className={c(
commonOverCls,
css`
background-color: rgba(95, 217, 129, 0.3);
flex: 2;
`
)}
>
{widthSm ? '' : '放置在上'}
</div>
{!data.selfClosed && (
<div
data-pos={'child'}
className={c(
commonOverCls,
css`
flex: 3;
`,
widthGte
? css`
border-left: none !important;
border-right: none !important;
`
: css`
border-top: none !important;
border-bottom: none !important;
`
)}
>
{widthSm ? '' : '放置在这'}
</div>
)}
<div
data-pos={'down'}
className={c(
commonOverCls,
css`
background-color: rgba(89, 214, 219, 0.3);
flex: 2;
`
)}
>
{widthSm ? '' : '放置在下'}
</div>
</>
)}
</FloatingUi>
)
}) | the_stack |
import { GraphQLResolveInfo } from 'graphql';
import { ApolloContext } from '../server/apolloContext';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]: Maybe<T[SubKey]> };
export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } &
{ [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
};
export type Project = {
__typename?: 'Project';
id?: Maybe<Scalars['Int']>;
title?: Maybe<Scalars['String']>;
createdAt?: Maybe<Scalars['String']>;
};
export type Query = {
__typename?: 'Query';
getAllPermissions: Array<Scalars['String']>;
projects?: Maybe<Array<Maybe<Project>>>;
user?: Maybe<User>;
users?: Maybe<Array<Maybe<User>>>;
};
export type UserInput = {
email: Scalars['String'];
name?: Maybe<Scalars['String']>;
password?: Maybe<Scalars['String']>;
};
export type AdminUserInput = {
id: Scalars['Int'];
email?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
permissions?: Maybe<Array<Scalars['String']>>;
};
export type CredentialsInput = {
email: Scalars['String'];
password?: Maybe<Scalars['String']>;
};
export type EmailInput = {
email: Scalars['String'];
};
export type NewPasswordInput = {
password: Scalars['String'];
token: Scalars['String'];
};
export enum AuthServices {
Google = 'GOOGLE',
}
export type SocialLoginInput = {
service: AuthServices;
token: Scalars['String'];
};
export type User = {
__typename?: 'User';
id?: Maybe<Scalars['Int']>;
email?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
permissions?: Maybe<Array<Maybe<Scalars['String']>>>;
};
export type AuthResult = {
__typename?: 'AuthResult';
success?: Maybe<Scalars['Boolean']>;
token?: Maybe<Scalars['String']>;
message?: Maybe<Scalars['String']>;
};
export type Mutation = {
__typename?: 'Mutation';
createUser?: Maybe<User>;
updateUser?: Maybe<User>;
register?: Maybe<AuthResult>;
login?: Maybe<AuthResult>;
forgotPassword?: Maybe<AuthResult>;
resetPassword?: Maybe<AuthResult>;
validateSocialLogin?: Maybe<AuthResult>;
};
export type MutationCreateUserArgs = {
user: UserInput;
};
export type MutationUpdateUserArgs = {
user: AdminUserInput;
};
export type MutationRegisterArgs = {
user: UserInput;
};
export type MutationLoginArgs = {
credentials: CredentialsInput;
};
export type MutationForgotPasswordArgs = {
credentials: EmailInput;
};
export type MutationResetPasswordArgs = {
credentials: NewPasswordInput;
};
export type MutationValidateSocialLoginArgs = {
credentials: SocialLoginInput;
};
export type WithIndex<TObject> = TObject & Record<string, any>;
export type ResolversObject<TObject> = WithIndex<TObject>;
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
selectionSet: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type StitchingResolver<TResult, TParent, TContext, TArgs> =
| LegacyStitchingResolver<TResult, TParent, TContext, TArgs>
| NewStitchingResolver<TResult, TParent, TContext, TArgs>;
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo,
) => Promise<TResult> | TResult;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo,
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo,
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> {
subscribe: SubscriptionSubscribeFn<
{ [key in TKey]: TResult },
TParent,
TContext,
TArgs
>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<
TResult,
TKey extends string,
TParent = {},
TContext = {},
TArgs = {}
> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo,
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (
obj: T,
context: TContext,
info: GraphQLResolveInfo,
) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo,
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = ResolversObject<{
Project: ResolverTypeWrapper<Project>;
Int: ResolverTypeWrapper<Scalars['Int']>;
String: ResolverTypeWrapper<Scalars['String']>;
Query: ResolverTypeWrapper<{}>;
UserInput: UserInput;
AdminUserInput: AdminUserInput;
CredentialsInput: CredentialsInput;
EmailInput: EmailInput;
NewPasswordInput: NewPasswordInput;
AuthServices: AuthServices;
SocialLoginInput: SocialLoginInput;
User: ResolverTypeWrapper<User>;
AuthResult: ResolverTypeWrapper<AuthResult>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']>;
Mutation: ResolverTypeWrapper<{}>;
}>;
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = ResolversObject<{
Project: Project;
Int: Scalars['Int'];
String: Scalars['String'];
Query: {};
UserInput: UserInput;
AdminUserInput: AdminUserInput;
CredentialsInput: CredentialsInput;
EmailInput: EmailInput;
NewPasswordInput: NewPasswordInput;
SocialLoginInput: SocialLoginInput;
User: User;
AuthResult: AuthResult;
Boolean: Scalars['Boolean'];
Mutation: {};
}>;
export type ProjectResolvers<
ContextType = ApolloContext,
ParentType extends ResolversParentTypes['Project'] = ResolversParentTypes['Project']
> = ResolversObject<{
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
title?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type QueryResolvers<
ContextType = ApolloContext,
ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']
> = ResolversObject<{
getAllPermissions?: Resolver<Array<ResolversTypes['String']>, ParentType, ContextType>;
projects?: Resolver<
Maybe<Array<Maybe<ResolversTypes['Project']>>>,
ParentType,
ContextType
>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
users?: Resolver<Maybe<Array<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
}>;
export type UserResolvers<
ContextType = ApolloContext,
ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']
> = ResolversObject<{
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
email?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
permissions?: Resolver<
Maybe<Array<Maybe<ResolversTypes['String']>>>,
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type AuthResultResolvers<
ContextType = ApolloContext,
ParentType extends ResolversParentTypes['AuthResult'] = ResolversParentTypes['AuthResult']
> = ResolversObject<{
success?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
token?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
message?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}>;
export type MutationResolvers<
ContextType = ApolloContext,
ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']
> = ResolversObject<{
createUser?: Resolver<
Maybe<ResolversTypes['User']>,
ParentType,
ContextType,
RequireFields<MutationCreateUserArgs, 'user'>
>;
updateUser?: Resolver<
Maybe<ResolversTypes['User']>,
ParentType,
ContextType,
RequireFields<MutationUpdateUserArgs, 'user'>
>;
register?: Resolver<
Maybe<ResolversTypes['AuthResult']>,
ParentType,
ContextType,
RequireFields<MutationRegisterArgs, 'user'>
>;
login?: Resolver<
Maybe<ResolversTypes['AuthResult']>,
ParentType,
ContextType,
RequireFields<MutationLoginArgs, 'credentials'>
>;
forgotPassword?: Resolver<
Maybe<ResolversTypes['AuthResult']>,
ParentType,
ContextType,
RequireFields<MutationForgotPasswordArgs, 'credentials'>
>;
resetPassword?: Resolver<
Maybe<ResolversTypes['AuthResult']>,
ParentType,
ContextType,
RequireFields<MutationResetPasswordArgs, 'credentials'>
>;
validateSocialLogin?: Resolver<
Maybe<ResolversTypes['AuthResult']>,
ParentType,
ContextType,
RequireFields<MutationValidateSocialLoginArgs, 'credentials'>
>;
}>;
export type Resolvers<ContextType = ApolloContext> = ResolversObject<{
Project?: ProjectResolvers<ContextType>;
Query?: QueryResolvers<ContextType>;
User?: UserResolvers<ContextType>;
AuthResult?: AuthResultResolvers<ContextType>;
Mutation?: MutationResolvers<ContextType>;
}>;
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = ApolloContext> = Resolvers<ContextType>; | the_stack |
import * as O from 'fp-ts/lib/Option'
import * as R from 'fp-ts/lib/Reader'
import * as ts from 'typescript'
import * as M from './model'
import { Lens } from 'monocle-ts'
import { tuple } from 'fp-ts/lib/function'
import * as S from 'fp-ts/lib/Semigroup'
import * as A from 'fp-ts/lib/Array'
import { head } from 'fp-ts/lib/NonEmptyArray'
import { pipe } from 'fp-ts/lib/pipeable'
/**
* @since 0.4.0
*/
export interface Options {
/** the name of the field used as tag */
tagName: string
/** the name prefix used for pattern matching functions */
foldName: string
/**
* the pattern matching handlers can be expressed as positional arguments
* or a single object literal `tag -> handler`
*/
handlersStyle: { type: 'positional' } | { type: 'record'; handlersName: string }
}
/**
* @since 0.4.0
*/
export const defaultOptions: Options = {
tagName: 'type',
foldName: 'fold',
handlersStyle: { type: 'positional' }
}
const getLens = Lens.fromProp<Options>()
/**
* @since 0.4.0
*/
export const lenses: { [K in keyof Options]: Lens<Options, Options[K]> } = {
tagName: getLens('tagName'),
foldName: getLens('foldName'),
handlersStyle: getLens('handlersStyle')
}
/**
* @since 0.4.0
*/
export interface AST<A> extends R.Reader<Options, A> {}
const getMemberName = (m: M.Member, position: number): string => {
return pipe(
m.name,
O.getOrElse(() => `value${position}`)
)
}
const getDomainParameterName = (type: M.Type): O.Option<string> => {
switch (type.kind) {
case 'Ref':
return O.some(getFirstLetterLowerCase(type.name))
case 'Tuple':
return O.some('tuple')
case 'Fun':
return O.some('f')
case 'Unit':
return O.none
}
}
const getTypeNode = (type: M.Type): ts.TypeNode => {
switch (type.kind) {
case 'Ref':
return ts.createTypeReferenceNode(type.name, type.parameters.map(p => getTypeNode(p)))
case 'Tuple':
return ts.createTupleTypeNode(type.types.map(getTypeNode))
case 'Fun':
return ts.createFunctionTypeNode(
undefined,
pipe(
getDomainParameterName(type.domain),
O.map(domainName => [getParameterDeclaration(domainName, getTypeNode(type.domain))]),
O.getOrElse<Array<ts.ParameterDeclaration>>(() => A.empty)
),
getTypeNode(type.codomain)
)
case 'Unit':
return ts.createTypeReferenceNode('undefined', A.empty)
}
}
const getTypeAliasDeclaration = (
name: string,
type: ts.TypeNode,
typeParameters?: Array<ts.TypeParameterDeclaration>
) => {
return ts.createTypeAliasDeclaration(
undefined,
[ts.createModifier(ts.SyntaxKind.ExportKeyword)],
name,
typeParameters,
type
)
}
const getDataTypeParameterDeclarations = (d: M.Data): Array<ts.TypeParameterDeclaration> => {
return d.parameterDeclarations.map(p =>
ts.createTypeParameterDeclaration(
p.name,
pipe(
p.constraint,
O.map(getTypeNode),
O.toUndefined
)
)
)
}
const getDataTypeReferenceWithNever = (d: M.Data): ts.TypeReferenceNode => {
return ts.createTypeReferenceNode(
d.name,
d.parameterDeclarations.map(p =>
pipe(
p.constraint,
O.map(c => getTypeNode(c)),
O.getOrElse<ts.TypeNode>(() => ts.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword))
)
)
)
}
const getDataTypeParameterReferences = (d: M.Data): Array<ts.TypeReferenceNode> => {
return d.parameterDeclarations.map(p => ts.createTypeReferenceNode(p.name, A.empty))
}
const getDataType = (d: M.Data): ts.TypeReferenceNode => {
return ts.createTypeReferenceNode(d.name, getDataTypeParameterReferences(d))
}
const getPropertySignature = (name: string, type: ts.TypeNode, isReadonly: boolean = true): ts.PropertySignature => {
return ts.createPropertySignature(
isReadonly ? [ts.createModifier(ts.SyntaxKind.ReadonlyKeyword)] : undefined,
name,
undefined,
type,
undefined
)
}
/**
* @since 0.4.0
*/
export function data(d: M.Data): AST<Array<ts.Node>> {
return e => {
const unionType = ts.createUnionTypeNode(
d.constructors.map(c => {
const members: Array<ts.TypeElement> = c.members.map((m, position) => {
return getPropertySignature(getMemberName(m, position), getTypeNode(m.type))
})
const tag: ts.TypeElement = getPropertySignature(e.tagName, ts.createLiteralTypeNode(ts.createLiteral(c.name)))
return ts.createTypeLiteralNode(M.isSum(d) ? [tag, ...members] : members)
})
)
return [getTypeAliasDeclaration(d.name, unionType, getDataTypeParameterDeclarations(d))]
}
}
const getFirstLetterLowerCase = (name: string): string => {
return name.substring(0, 1).toLocaleLowerCase() + name.substring(1)
}
const getFirstLetterUpperCase = (name: string): string => {
return name.substring(0, 1).toLocaleUpperCase() + name.substring(1)
}
const getConstantDeclaration = (
name: string,
initializer: ts.Expression,
type?: ts.TypeReferenceNode,
isExported: boolean = true
): ts.VariableStatement => {
return ts.createVariableStatement(
isExported ? [ts.createModifier(ts.SyntaxKind.ExportKeyword)] : A.empty,
ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], ts.NodeFlags.Const)
)
}
const getFunctionDeclaration = (
name: string,
typeParameters: Array<ts.TypeParameterDeclaration>,
parameters: Array<ts.ParameterDeclaration>,
type: ts.TypeNode,
body: ts.Block
) => {
return ts.createFunctionDeclaration(
undefined,
[ts.createModifier(ts.SyntaxKind.ExportKeyword)],
undefined,
name,
typeParameters,
parameters,
type,
body
)
}
const getParameterDeclaration = (name: string, type?: ts.TypeNode): ts.ParameterDeclaration => {
return ts.createParameter(undefined, undefined, undefined, name, undefined, type, undefined)
}
const getLiteralNullaryConstructor = (c: M.Constructor, d: M.Data): AST<ts.Node> => {
return e => {
const name = getFirstLetterLowerCase(c.name)
const initializer = ts.createObjectLiteral(
M.isSum(d) ? [ts.createPropertyAssignment(e.tagName, ts.createStringLiteral(c.name))] : []
)
return getConstantDeclaration(name, initializer, getDataTypeReferenceWithNever(d))
}
}
const getLiteralConstructor = (c: M.Constructor, d: M.Data): AST<ts.Node> => {
return e => {
const name = getFirstLetterLowerCase(c.name)
const typeParameters = getDataTypeParameterDeclarations(d)
const parameters = c.members.map((m, position) => {
const name = getMemberName(m, position)
const type = getTypeNode(m.type)
return getParameterDeclaration(name, type)
})
const properties = c.members.map((m, position) => {
const name = getMemberName(m, position)
return ts.createShorthandPropertyAssignment(name)
})
const body = ts.createBlock([
ts.createReturn(
ts.createObjectLiteral(
M.isSum(d)
? [ts.createPropertyAssignment(e.tagName, ts.createStringLiteral(c.name)), ...properties]
: properties
)
)
])
return getFunctionDeclaration(name, typeParameters, parameters, getDataType(d), body)
}
}
/**
* @since 0.4.0
*/
export function constructors(d: M.Data): AST<Array<ts.Node>> {
const constructors = d.constructors.map(c =>
A.foldLeft(() => getLiteralNullaryConstructor(c, d), () => getLiteralConstructor(c, d))(c.members)
)
return A.array.sequence(R.reader)(constructors)
}
const getFoldReturnTypeParameterName = (d: M.Data): string => {
const base = 'R'
let candidate = base
let counter = 0
while (d.parameterDeclarations.findIndex(({ name }) => candidate === name) !== -1) {
candidate = base + ++counter
}
return candidate
}
const getFoldHandlerName = (c: M.Constructor): string => {
return `on${c.name}`
}
const getFoldPositionalHandlers = (d: M.Data): Array<ts.ParameterDeclaration> => {
const returnTypeParameterName = getFoldReturnTypeParameterName(d)
return d.constructors.map(c => {
const type = ts.createFunctionTypeNode(
undefined,
c.members.map((m, position) => getParameterDeclaration(getMemberName(m, position), getTypeNode(m.type))),
ts.createTypeReferenceNode(returnTypeParameterName, A.empty)
)
return getParameterDeclaration(getFoldHandlerName(c), type)
})
}
const getFoldRecordHandlers = (d: M.Data, handlersName: string): Array<ts.ParameterDeclaration> => {
const returnTypeParameterName = getFoldReturnTypeParameterName(d)
const type = ts.createTypeLiteralNode(
d.constructors.map(c => {
const type = ts.createFunctionTypeNode(
undefined,
c.members.map((m, position) => getParameterDeclaration(getMemberName(m, position), getTypeNode(m.type))),
ts.createTypeReferenceNode(returnTypeParameterName, A.empty)
)
return getPropertySignature(getFoldHandlerName(c), type, false)
})
)
return [getParameterDeclaration(handlersName, type)]
}
const getFoldPositionalBody = (d: M.Data, matcheeName: string, tagName: string) => {
return ts.createBlock([
ts.createSwitch(
ts.createPropertyAccess(ts.createIdentifier(matcheeName), tagName),
ts.createCaseBlock(
d.constructors.map(c => {
const access = ts.createIdentifier(getFoldHandlerName(c))
return ts.createCaseClause(ts.createStringLiteral(c.name), [
ts.createReturn(
ts.createCall(
access,
A.empty,
c.members.map((m, position) => {
return ts.createPropertyAccess(ts.createIdentifier(matcheeName), getMemberName(m, position))
})
)
)
])
})
)
)
])
}
const getFoldRecordBody = (d: M.Data, matcheeName: string, tagName: string, handlersName: string) => {
return ts.createBlock([
ts.createSwitch(
ts.createPropertyAccess(ts.createIdentifier(matcheeName), tagName),
ts.createCaseBlock(
d.constructors.map(c => {
const access = ts.createPropertyAccess(ts.createIdentifier(handlersName), getFoldHandlerName(c))
return ts.createCaseClause(ts.createStringLiteral(c.name), [
ts.createReturn(
ts.createCall(
access,
A.empty,
c.members.map((m, position) => {
return ts.createPropertyAccess(ts.createIdentifier(matcheeName), getMemberName(m, position))
})
)
)
])
})
)
)
])
}
const getFold = (d: M.Data, name: string): AST<ts.FunctionDeclaration> => {
return e => {
const matcheeName = 'fa'
const tagName = e.tagName
const handlersStyle = e.handlersStyle
const returnTypeParameterName = getFoldReturnTypeParameterName(d)
const typeParameterDeclarations = [
...getDataTypeParameterDeclarations(d),
ts.createTypeParameterDeclaration(returnTypeParameterName)
]
const handlers =
handlersStyle.type === 'positional'
? getFoldPositionalHandlers(d)
: getFoldRecordHandlers(d, handlersStyle.handlersName)
const matchee = getParameterDeclaration(matcheeName, getDataType(d))
const returnType = ts.createFunctionTypeNode(
[],
[matchee],
ts.createTypeReferenceNode(returnTypeParameterName, A.empty)
)
const body = ts.createArrowFunction(
[],
[],
[getParameterDeclaration(matcheeName)],
undefined,
undefined,
handlersStyle.type === 'positional'
? getFoldPositionalBody(d, matcheeName, tagName)
: getFoldRecordBody(d, matcheeName, tagName, handlersStyle.handlersName)
)
return getFunctionDeclaration(
name,
typeParameterDeclarations,
handlers,
returnType,
ts.createBlock([ts.createReturn(body)])
)
}
}
/**
* @since 0.4.0
*/
export function fold(d: M.Data): AST<O.Option<ts.FunctionDeclaration>> {
if (!M.isSum(d)) {
return R.of(O.none)
} else {
return pipe(
R.ask<Options>(),
R.chain(e => getFold(d, e.foldName)),
R.map(O.some)
)
}
}
const getImportDeclaration = (namedImports: Array<string>, from: string): ts.ImportDeclaration => {
return ts.createImportDeclaration(
A.empty,
A.empty,
ts.createImportClause(
undefined,
ts.createNamedImports(namedImports.map(name => ts.createImportSpecifier(undefined, ts.createIdentifier(name))))
),
ts.createStringLiteral(from)
)
}
const getArrowFunction = (parameters: Array<string>, body: ts.ConciseBody) => {
return ts.createArrowFunction(
[],
A.empty,
parameters.map(p => getParameterDeclaration(p)),
undefined,
undefined,
body
)
}
/**
* @since 0.4.0
*/
export function prisms(d: M.Data): AST<Array<ts.Node>> {
return pipe(
R.ask<Options>(),
R.chain(e => {
if (!M.isSum(d)) {
return R.of(A.empty)
}
const dataType = getDataType(d)
const type = ts.createTypeReferenceNode('Prism', [dataType, dataType])
const getPrism = (name: string) => {
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier('Prism'), 'fromPredicate'), A.empty, [
getArrowFunction(
['s'],
getStrictEquals(ts.createPropertyAccess(ts.createIdentifier('s'), e.tagName), ts.createStringLiteral(name))
)
])
}
const monocleImport = getImportDeclaration(['Prism'], 'monocle-ts')
const typeParameters: Array<ts.TypeParameterDeclaration> = getDataTypeParameterDeclarations(d)
const constructors = d.constructors
if (M.isPolymorphic(d)) {
return R.of([
monocleImport,
...constructors.map<ts.Node>(c => {
const body = ts.createBlock([ts.createReturn(getPrism(c.name))])
return getFunctionDeclaration(`_${getFirstLetterLowerCase(c.name)}`, typeParameters, A.empty, type, body)
})
])
}
return R.of([
monocleImport,
...constructors.map(c => {
return getConstantDeclaration(`_${c.name}`, getPrism(c.name), type)
})
])
})
)
}
const semigroupBinaryExpression: S.Semigroup<ts.Expression> = {
concat: (x, y) => ts.createBinary(x, ts.SyntaxKind.AmpersandAmpersandToken, y)
}
const getStrictEquals = (left: ts.Expression, right: ts.Expression): ts.BinaryExpression => {
return ts.createBinary(left, ts.SyntaxKind.EqualsEqualsEqualsToken, right)
}
/**
* @since 0.4.0
*/
export function eq(d: M.Data): AST<Array<ts.Node>> {
const isSum = M.isSum(d)
if (!isSum && M.isNullary(head(d.constructors))) {
return R.of(A.empty)
}
const getMemberEqName = (c: M.Constructor, m: M.Member, position: number): string => {
let s = 'eq'
if (isSum) {
s += c.name
}
return s + getFirstLetterUpperCase(getMemberName(m, position))
}
const constructors = d.constructors
const eqsParameters = A.array.chain(constructors, c => {
return c.members
.map((m, position) => tuple(m, position))
.filter(([m]) => !M.isRecursiveMember(m, d))
.map(([m, position]) => {
const type = ts.createTypeReferenceNode('Eq', [getTypeNode(m.type)])
return getParameterDeclaration(getMemberEqName(c, m, position), type)
})
})
const getReturnValue = (c: M.Constructor): ts.Expression => {
return A.foldLeft(
() => ts.createTrue(),
() => {
const callExpressions = c.members.map((m, position) => {
const eqName = M.isRecursiveMember(m, d) ? 'S' : getMemberEqName(c, m, position)
const memberName = getMemberName(m, position)
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier(eqName), 'equals'), A.empty, [
ts.createPropertyAccess(ts.createIdentifier('x'), memberName),
ts.createPropertyAccess(ts.createIdentifier('y'), memberName)
])
})
return S.fold(semigroupBinaryExpression)(callExpressions[0], callExpressions.slice(1))
}
)(c.members)
}
return pipe(
R.ask<Options>(),
R.chain(e => {
const eqImport = getImportDeclaration(['Eq', 'fromEquals'], 'fp-ts/lib/Eq')
const ifs = [
...constructors.map(c => {
return ts.createIf(
semigroupBinaryExpression.concat(
getStrictEquals(ts.createPropertyAccess(ts.createIdentifier('x'), e.tagName), ts.createLiteral(c.name)),
getStrictEquals(ts.createPropertyAccess(ts.createIdentifier('y'), e.tagName), ts.createLiteral(c.name))
),
ts.createBlock([ts.createReturn(getReturnValue(c))])
)
}),
ts.createReturn(ts.createFalse())
]
const statements: Array<ts.Statement> = []
if (isSum) {
statements.push(...ifs)
} else {
statements.push(ts.createReturn(getReturnValue(head(d.constructors))))
}
const arrowFunction = getArrowFunction(['x', 'y'], ts.createBlock(statements))
const eq = ts.createCall(ts.createIdentifier('fromEquals'), A.empty, [arrowFunction])
const returnType = ts.createTypeReferenceNode('Eq', [getDataType(d)])
const body = M.isRecursive(d)
? [getConstantDeclaration('S', eq, returnType, false), ts.createReturn(ts.createIdentifier('S'))]
: [ts.createReturn(eq)]
const typeParameters: Array<ts.TypeParameterDeclaration> = getDataTypeParameterDeclarations(d)
return R.of([
eqImport,
getFunctionDeclaration('getEq', typeParameters, eqsParameters, returnType, ts.createBlock(body))
])
})
)
} | the_stack |
import { Component, OnInit, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { Location } from '@angular/common';
import { Project } from '../common/project';
import { Organization } from '../../organization/common/organization';
import { User } from '../../user/common/user';
import { JobTitle } from '../../job-title';
import { ProjectService } from '../common/project.service';
import { OrganizationService } from '../../organization/common/organization.service';
import { UserService } from '../../user/common/user.service';
import { AuthService } from '../../auth.service';
import { SkillService} from '../../skill/common/skill.service';
import { MaterializeAction } from 'angular2-materialize';
import { FormConstantsService } from '../../_services/form-constants.service';
declare const Materialize: any;
@Component({
selector: 'my-view-project',
providers: [AuthService],
templateUrl: 'project-view.component.html',
styleUrls: ['project-view.component.scss']
})
export class ProjectViewComponent implements OnInit {
organization: Organization;
project: Project;
projects: Project[];
user: User;
public jobTitlesArray: JobTitle[] = [];
numberOfProjects: number;
params: Params;
currentUserId: string;
// userProjectStatus: string;
auth: AuthService;
categoryName: string;
globalActions = new EventEmitter<string|MaterializeAction>();
modalActions = new EventEmitter<string|MaterializeAction>();
displayShare = true;
displayApply = false;
displayBookmark = false;
displayEdit = false;
displayReopen = false;
displayClose = false;
displayApplicants = false;
displayApplicationForm = false;
userProfileIncomplete = false;
projectStatusApplied = false;
projectStatusBookmarked = false;
projectStatusAccepted = false;
projectStatusDeclined = false;
prevPage: string;
projectId;
constructor(private projectService: ProjectService,
private organizationService: OrganizationService,
private userService: UserService,
private skillService: SkillService,
public constantsService: FormConstantsService,
private route: ActivatedRoute,
private router: Router,
public authService: AuthService,
private location: Location) {
}
ngOnInit(): void {
this.auth = this.authService;
this.currentUserId = this.authService.getCurrentUserId();
this.route.params.subscribe(params => {
const id = params['projectId'];
this.projectId = id;
this.prevPage = localStorage.getItem('prevPage');
localStorage.setItem('prevPage', '');
this.projectService.getProject(id)
.subscribe(
res => {
this.project = res;
this.getSkills(id);
this.displayButtons();
this.getOrganization(res.organizationId);
this.getProjects(res.organizationId);
},
error => console.log(error)
);
this.userService.getAllJobTitles()
.subscribe(
res => {
this.jobTitlesArray = res;
}, error => console.log(error)
);
});
}
pad(str: string, padValue: string, max: number): string {
max += str.length;
return (max - str.length > 0 ? padValue.repeat(max - str.length) + str : str);
}
// Skills for this project
getSkills(projectId): void {
this.skillService.getSkillsByProject(projectId)
.subscribe(
result => {
this.project.skills = result;
}
);
}
// Projects for this organization
getProjects(organizationId): void {
this.projectService.getProjectByOrg(organizationId, 'A')
.subscribe(
resProjects => {
this.projects = resProjects.json();
this.projects.forEach((e: Project) => {
this.skillService.getSkillsByProject(e.id).subscribe(
response => {
e.skills = response;
});
});
},
errorProjects => console.log(errorProjects)
);
}
// Organization for this project
getOrganization(organizationId): void {
this.organizationService.getOrganization(organizationId)
.subscribe(
resi => {
this.organization = resi;
// Validation rules should force websiteUrl to start with http but add check just in case
if (this.organization.websiteUrl && this.organization.websiteUrl.indexOf('http') !== 0) {
this.organization.websiteUrl = `http://${this.organization.websiteUrl}`;
}
if (this.organization.description != null && this.organization.description.length > 100) {
this.organization.description = this.organization.description.slice(0, 100) + '...';
}
this.setCategoryName();
}
);
}
displayButtons(): void {
if (!this.authService.authenticated()) {
this.displayApply = true;
this.displayBookmark = true;
} else if (this.authService.authenticated()) {
if (this.authService.isVolunteer()) {
this.displayApply = true;
this.displayBookmark = true;
// if user applied or bookmarked this project, disable the apply/bookmark button
const projectsIDs = this.projectService.getUserProjectStatusFromLocalStorage();
if (projectsIDs != null) {
if (projectsIDs.appliedProjectsIDs != null
&& projectsIDs.appliedProjectsIDs.split(',').includes(this.projectId)) {
this.projectStatusApplied = true;
} else {
this.projectStatusApplied = false;
}
if (projectsIDs.bookmarkedProjectsIDs != null
&& projectsIDs.bookmarkedProjectsIDs.split(',').includes(this.projectId)) {
this.projectStatusBookmarked = true;
} else {
this.projectStatusBookmarked = false;
}
if (projectsIDs.acceptedProjectsIDs != null
&& projectsIDs.acceptedProjectsIDs.split(',').includes(this.projectId)) {
this.projectStatusAccepted = true;
} else {
this.projectStatusAccepted = false;
}
if (projectsIDs.declinedProjectsIDs != null
&& projectsIDs.declinedProjectsIDs.split(',').includes(this.projectId)) {
this.projectStatusDeclined = true;
} else {
this.projectStatusDeclined = false;
}
}
// If user profile hasn't complete, user can't apply
this.userService.getUser(Number(this.currentUserId)).subscribe(
res => {
this.user = res;
if (!this.user.userName) {
this.userProfileIncomplete = true;
}
},
error => console.log(error)
);
} else if (this.authService.isOrganization()) {
this.organizationService.getUserOrganization(Number(this.authService.getCurrentUserId())).subscribe(
res => {
let organization: Organization;
organization = res[0];
if ((organization !== undefined) && (organization.id === Number(this.project.organizationId))) {
this.displayEdit = true;
this.displayClose = true;
this.displayApplicants = true;
this.displayReopen = false;
}
if (this.project.status === 'C') {
this.displayClose = false;
this.displayShare = false;
this.displayEdit = false;
this.displayReopen = true;
}
},
error => console.log(error)
);
} else if (this.authService.isAdmin()) {
this.displayEdit = true;
this.displayClose = true;
this.displayApplicants = true;
this.displayReopen = false;
if (this.project.status === 'C') {
this.displayClose = false;
this.displayShare = false;
this.displayEdit = false;
this.displayReopen = true;
}
}
}
}
toggleApplicationForm(): void {
if (this.authService.authenticated() && this.currentUserId !== null && this.currentUserId !== '0') {
if (this.displayApplicationForm === false) {
this.displayApplicationForm = true;
} else {
this.displayApplicationForm = false;
}
} else {
localStorage.setItem('redirectAfterLogin', this.router.url);
this.authService.login();
}
}
// refer application component
onApplicationCreated(applicationCreated: boolean): void {
if (applicationCreated) {
this.projectStatusApplied = true;
this.toggleApplicationForm();
const projectsIDs = this.projectService.getUserProjectStatusFromLocalStorage();
localStorage.setItem('appliedProjectsIDs', (projectsIDs.appliedProjectsIDs + ',' + this.project.id));
this.globalActions.emit({action: 'toast', params: ['You have applied for the project', 4000]});
} else {
this.globalActions.emit({action: 'toast', params: ['Error in application', 4000]});
this.projectStatusApplied = false;
}
}
// refer application component
onApplicationAccepted(applicationAccepted: boolean): void {
if (applicationAccepted) {
const projectsIDs = this.projectService.getUserProjectStatusFromLocalStorage();
localStorage.setItem('acceptedProjectsIDs', (projectsIDs.acceptedProjectsIDs + ',' + this.project.id));
this.globalActions.emit({action: 'toast', params: ['You have accepted the applicant', 4000]});
} else {
this.globalActions.emit({action: 'toast', params: ['Error in accepting the applicant', 4000]});
}
}
// refer application component
onApplicationDeclined(applicationDeclined: boolean): void {
if (applicationDeclined) {
const projectsIDs = this.projectService.getUserProjectStatusFromLocalStorage();
localStorage.setItem('declinedProjectsIDs', (projectsIDs.declinedProjectsIDs + ',' + this.project.id));
this.globalActions.emit({action: 'toast', params: ['You have declined the applicant', 4000]});
} else {
this.globalActions.emit({action: 'toast', params: ['Error in declining the applicant', 4000]});
}
}
// refer application component
isBadgeGiven(badgeGiven: boolean): void {
if (badgeGiven) {
this.globalActions.emit({action: 'toast', params: ['You have given out a badge to the volunteer.', 4000]});
} else {
this.globalActions.emit({action: 'toast', params: ['Error in giving a badge to the volunteer', 4000]});
}
}
createBookmark(): void {
if (this.authService.authenticated() && this.currentUserId !== null && this.currentUserId !== '0') {
this.projectService.createBookmark(this.project.id, this.currentUserId)
.subscribe(res => {
const projectsIDs = this.projectService.getUserProjectStatusFromLocalStorage();
localStorage.setItem('bookmarkedProjectsIDs', (projectsIDs.bookmarkedProjectsIDs + ',' + this.project.id));
this.projectStatusBookmarked = true;
this.globalActions.emit({action: 'toast', params: ['You have bookmarked the project', 4000]});
}, (error) => {
this.globalActions.emit({action: 'toast', params: ['Error creating bookmark', 4000]});
});
} else {
localStorage.setItem('redirectAfterLogin', this.router.url);
this.authService.login();
}
}
edit(): void {
this.router.navigate(['project/edit', this.project.id]);
}
reOpen(): void {
this.project.status = 'A';
this.projectService
.update(this.project)
.subscribe(res => {
this.router.navigate(['/project/view/' + this.project.id]);
Materialize.toast('The project is reopened', 4000);
this.displayEdit = true;
this.displayClose = true;
this.displayApplicants = true;
this.displayReopen = false;
}, error => console.log(error));
}
goBack(): void {
localStorage.setItem('prevPage', 'ProjectList');
this.location.back();
}
onClose(): void {
this.projectService
.delete(this.project.id)
.subscribe(
response => {
this.router.navigate(['/project/view', this.project.id]);
Materialize.toast('The project is closed', 4000);
this.project.status = 'C';
this.displayClose = false;
this.displayShare = false;
this.displayEdit = false;
this.displayReopen = true;
// this.router.navigate(['/project/view', this.project.id]);
},
error => {
Materialize.toast('Error closing the project', 4000);
console.log(error);
}
);
}
redirectToMySettings(): void {
this.router.navigate(['user/edit', this.currentUserId]);
}
openModal(project) {
this.modalActions.emit({action: 'modal', params: ['open']});
}
closeModal() {
this.modalActions.emit({action: 'modal', params: ['close']});
}
setCategoryName(): void {
if (this.organization.category === 'N') {
this.categoryName = 'Nonprofit';
} else if (this.organization.category === 'O') {
this.categoryName = 'Open Source';
} else if (this.organization.category === 'S') {
this.categoryName = 'Social Enterprise';
} else if (this.organization.category === 'U') {
this.categoryName = 'Startup';
}
}
} | the_stack |
import _ from "lodash";
import { createDeferred } from "joynr/joynr/util/UtilInternal";
import * as util from "util";
import Enumeration from "../generated-javascript/joynr/interlanguagetest/Enumeration";
import * as EnumerationWithoutDefinedValues from "../generated-javascript/joynr/interlanguagetest/EnumerationWithoutDefinedValues";
import StructWithStringArray from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection1/StructWithStringArray";
import BaseStruct2 from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/BaseStruct";
import BaseStructWithoutElements from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/BaseStructWithoutElements";
import ExtendedBaseStruct from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedBaseStruct";
import ExtendedInterfaceEnumerationInTypeCollection from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedInterfaceEnumerationInTypeCollection";
import ExtendedStructOfPrimitives from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedStructOfPrimitives";
import ExtendedTypeCollectionEnumerationInTypeCollection from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedTypeCollectionEnumerationInTypeCollection";
import StructOfPrimitives from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/StructOfPrimitives";
import ExtendedExtendedEnumeration = require("../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedExtendedEnumeration");
import ExtendedExtendedBaseStruct = require("../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedExtendedBaseStruct");
import JoynrRuntimeException = require("joynr/joynr/exceptions/JoynrRuntimeException");
export { createDeferred };
const log = require("test-base").logging.log;
const useRestrictedUnsignedRange = true;
const FillMap = {
stringArrayElement: ["Hello", "World"],
baseStructString: "Hiya",
enumElement: Enumeration.ENUM_0_VALUE_3,
enumWithoutDefinedValuesElement: EnumerationWithoutDefinedValues.ENUM_0_VALUE_1
};
const structWithStringArray = new StructWithStringArray(createSettings(["stringArrayElement"]));
export const Constants = {
StringArray: FillMap.stringArrayElement,
ByteArray: [1, 127],
DoubleArray: [1.1, 2.2, 3.3],
UInt64Array: [1, 127],
ExtendedInterfaceEnumInTypeCollectionArray: [
ExtendedInterfaceEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_INTERFACE,
ExtendedInterfaceEnumerationInTypeCollection.ENUM_I1_VALUE_3
],
ExtendedExtendedEnumerationArray: [
ExtendedExtendedEnumeration.ENUM_2_VALUE_EXTENSION_EXTENDED,
ExtendedExtendedEnumeration.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION
],
StructWithStringArray: structWithStringArray,
StructWithStringArrayArray: [structWithStringArray, structWithStringArray],
BaseStructWithoutElements: new BaseStructWithoutElements(),
BaseStruct: new BaseStruct2(createSettings(["baseStructString"])),
ExtendedBaseStruct: new ExtendedBaseStruct(createSettings(["baseStructString", "enumElement"])),
ExtendedExtendedBaseStruct: new ExtendedExtendedBaseStruct(
createSettings(["baseStructString", "enumElement", "enumWithoutDefinedValuesElement"])
)
};
type Keys = keyof typeof Constants;
export function create<T extends Keys>(key: T): typeof Constants[T] {
return _.cloneDeep(Constants[key]);
}
/**
* checks equality against preset objects specified by the key
* @param key of preset object to compare against
* @param value to compare
*/
export function check(key: Keys, value: any): boolean {
const equal = _.isEqual(Constants[key], value);
if (!equal) {
log(`expected ${util.inspect(Constants[key])} to Equal ${util.inspect(value)}`);
}
return equal;
}
/**
* checks equality ignoring the object type by checking stringified values
* @param key type of object to compare against
* @param value to compare
*/
export function checkObject(key: Keys, value: any): boolean {
const equal = JSON.stringify(Constants[key]) === JSON.stringify(value);
if (!equal) {
log(`expected ${util.inspect(Constants[key])} to Equal ${util.inspect(value)}`);
}
return equal;
}
export function fill(struct: Record<string, any>, key: keyof typeof FillMap): void {
if (!FillMap[key]) {
throw new Error("fill can't be called with this key");
}
struct[key] = FillMap[key];
}
export function createSettings(keys: (keyof typeof FillMap)[]): any {
const base: Record<string, any> = {};
keys.forEach(key => fill(base, key));
return base;
}
/* StructOfPrimitives*/
export function fillStructOfPrimitives(structOfPrimitives: StructOfPrimitives): StructOfPrimitives {
structOfPrimitives.booleanElement = true;
structOfPrimitives.doubleElement = 1.1;
structOfPrimitives.floatElement = 1.1;
structOfPrimitives.int8MinElement = -128;
structOfPrimitives.int8MaxElement = 127;
structOfPrimitives.int16MinElement = -32768;
structOfPrimitives.int16MaxElement = 32767;
structOfPrimitives.int32MinElement = -2147483648;
structOfPrimitives.int32MaxElement = 2147483647;
// The original 64-bit maximum values for Java and C++
// exceed the safe integer range of Javascript, hence
// we have to use reduced values.
// The original C++ values are
//structOfPrimitives.int64MinElement = -9223372036854775808;
//structOfPrimitives.int64MaxElement = 9223372036854775807;
structOfPrimitives.int64MinElement = -9007199254740991;
structOfPrimitives.int64MaxElement = 9007199254740991;
structOfPrimitives.constString = "Hiya";
structOfPrimitives.uInt8MinElement = 0;
if (useRestrictedUnsignedRange) {
structOfPrimitives.uInt8MaxElement = 127;
} else {
structOfPrimitives.uInt8MaxElement = 255;
}
structOfPrimitives.uInt16MinElement = 0;
if (useRestrictedUnsignedRange) {
structOfPrimitives.uInt16MaxElement = 32767;
} else {
structOfPrimitives.uInt16MaxElement = 65535;
}
structOfPrimitives.uInt32MinElement = 0;
if (useRestrictedUnsignedRange) {
structOfPrimitives.uInt32MaxElement = 2147483647;
} else {
structOfPrimitives.uInt32MaxElement = 4294967295;
}
structOfPrimitives.uInt64MinElement = 0;
// The original 64-bit maximum values for Java and C++
// exceeds the safe integer range of Javascript, hence
// we have to use reduced values.
// TODO: should be 18446744073709551615 (original C++)
// But the value would translate to
// 18437736874454810625 in C++
structOfPrimitives.uInt64MaxElement = 9007199254740991;
structOfPrimitives.booleanArray = [];
structOfPrimitives.booleanArray.push(true);
structOfPrimitives.booleanArray.push(false);
structOfPrimitives.doubleArray = [];
structOfPrimitives.doubleArray.push(1.1);
structOfPrimitives.doubleArray.push(2.2);
structOfPrimitives.floatArray = [];
structOfPrimitives.floatArray.push(1.1);
structOfPrimitives.floatArray.push(2.2);
structOfPrimitives.int8Array = [];
structOfPrimitives.int8Array.push(1);
structOfPrimitives.int8Array.push(2);
structOfPrimitives.int16Array = [];
structOfPrimitives.int16Array.push(1);
structOfPrimitives.int16Array.push(2);
structOfPrimitives.int32Array = [];
structOfPrimitives.int32Array.push(1);
structOfPrimitives.int32Array.push(2);
structOfPrimitives.int64Array = [];
structOfPrimitives.int64Array.push(1);
structOfPrimitives.int64Array.push(2);
structOfPrimitives.stringArray = [];
structOfPrimitives.stringArray.push("Hello");
structOfPrimitives.stringArray.push("World");
structOfPrimitives.uInt8Array = [];
structOfPrimitives.uInt8Array.push(1);
structOfPrimitives.uInt8Array.push(2);
structOfPrimitives.uInt16Array = [];
structOfPrimitives.uInt16Array.push(1);
structOfPrimitives.uInt16Array.push(2);
structOfPrimitives.uInt32Array = [];
structOfPrimitives.uInt32Array.push(1);
structOfPrimitives.uInt32Array.push(2);
structOfPrimitives.uInt64Array = [];
structOfPrimitives.uInt64Array.push(1);
structOfPrimitives.uInt64Array.push(2);
if (!checkStructOfPrimitives(structOfPrimitives)) {
throw new JoynrRuntimeException({
detailMessage: "Internal error in fillExtendedExtendedBaseStruct"
});
}
return structOfPrimitives;
}
export function checkStructOfPrimitives(structOfPrimitives: any): boolean {
if (!structOfPrimitives) {
log("checkStructOfPrimitives: not set");
return false;
}
if (structOfPrimitives.booleanElement !== true) {
log("checkStructOfPrimitives: invalid content of booleanElement");
return false;
}
if (!cmpDouble(structOfPrimitives.doubleElement, 1.1)) {
log("checkStructOfPrimitives: invalid content of doubleElement");
return false;
}
if (!cmpFloat(structOfPrimitives.floatElement, 1.1)) {
log("checkStructOfPrimitives: invalid content of floatElement");
return false;
}
if (structOfPrimitives.int8MinElement !== -128) {
log("checkStructOfPrimitives: invalid content of int8MinElement");
return false;
}
if (structOfPrimitives.int8MaxElement !== 127) {
log("checkStructOfPrimitives: invalid content of int8MaxElement");
return false;
}
if (structOfPrimitives.int16MinElement !== -32768) {
log("checkStructOfPrimitives: invalid content of int16MinElement");
return false;
}
if (structOfPrimitives.int16MaxElement !== 32767) {
log("checkStructOfPrimitives: invalid content of int16MaxElement");
return false;
}
if (structOfPrimitives.int32MinElement !== -2147483648) {
log("checkStructOfPrimitives: invalid content of int32MinElement");
return false;
}
if (structOfPrimitives.int32MaxElement !== 2147483647) {
log("checkStructOfPrimitives: invalid content of int32MaxElement");
return false;
}
//
// Use reduced value range for int64, since it must stay within
// Javascript maximum safe integer range.
//
// Original Java and C++ limits would require the code below.
// However, the values the get rounded up and will not match expectations
// on Java or C++ side.
//
//if (structOfPrimitives.int64MinElement !== -9223372036854775808) {
// log("checkStructOfPrimitives: invalid content of int64MinElement");
// return false;
//}
//if (structOfPrimitives.int64MaxElement !== 9223372036854775807) {
// log("checkStructOfPrimitives: invalid content of int64MaxElement");
// return false;
//}
if (structOfPrimitives.int64MinElement !== -9007199254740991) {
log("checkStructOfPrimitives: invalid content of int64MinElement");
return false;
}
if (structOfPrimitives.int64MaxElement !== 9007199254740991) {
log("checkStructOfPrimitives: invalid content of int64MaxElement");
return false;
}
if (structOfPrimitives.constString !== "Hiya") {
log("checkStructOfPrimitives: invalid content of constString");
return false;
}
if (structOfPrimitives.uInt8MinElement !== 0) {
log("checkStructOfPrimitives: invalid content of uInt8MinElement");
return false;
}
if (useRestrictedUnsignedRange) {
if (structOfPrimitives.uInt8MaxElement !== 127) {
log("checkStructOfPrimitives: invalid content of uInt8MaxElement");
return false;
}
} else if (structOfPrimitives.uInt8MaxElement !== 255) {
log("checkStructOfPrimitives: invalid content of uInt8MaxElement");
return false;
}
if (structOfPrimitives.uInt16MinElement !== 0) {
log("checkStructOfPrimitives: invalid content of uInt16MinElement");
return false;
}
if (useRestrictedUnsignedRange) {
if (structOfPrimitives.uInt16MaxElement !== 32767) {
log("checkStructOfPrimitives: invalid content of uInt16MaxElement");
return false;
}
} else if (structOfPrimitives.uInt16MaxElement !== 65535) {
log("checkStructOfPrimitives: invalid content of uInt16MaxElement");
return false;
}
if (structOfPrimitives.uInt32MinElement !== 0) {
log("checkStructOfPrimitives: invalid content of uInt32MinElement");
return false;
}
if (useRestrictedUnsignedRange) {
if (structOfPrimitives.uInt32MaxElement !== 2147483647) {
log("checkStructOfPrimitives: invalid content of uInt32MaxElement");
return false;
}
} else if (structOfPrimitives.uInt32MaxElement !== 4294967295) {
log("checkStructOfPrimitives: invalid content of uInt32MaxElement");
return false;
}
if (structOfPrimitives.uInt64MinElement !== 0) {
log("checkStructOfPrimitives: invalid content of uInt64MinElement");
return false;
}
// If there were no limitations, the check would make sense with
// structOfPrimitives.uInt64MaxElement !== 18446744073709551615
if (structOfPrimitives.uInt64MaxElement !== 9007199254740991) {
log("checkStructOfPrimitives: invalid content of uInt64MaxElement");
return false;
}
if (!structOfPrimitives.booleanArray) {
log("checkStructOfPrimitives: booleanArray not set");
return false;
}
if (structOfPrimitives.booleanArray.length !== 2) {
log("checkStructOfPrimitives: booleanArray has invalid length");
return false;
}
if (structOfPrimitives.booleanArray[0] !== true) {
log("checkStructOfPrimitives: booleanArray has invalid content");
return false;
}
if (structOfPrimitives.booleanArray[1] !== false) {
log("checkStructOfPrimitives: booleanArray has invalid content");
return false;
}
if (!structOfPrimitives.doubleArray) {
log("checkStructOfPrimitives: doubleArray not set");
return false;
}
if (structOfPrimitives.doubleArray.length !== 2) {
log("checkStructOfPrimitives: doubleArray has invalid length");
return false;
}
if (!cmpDouble(structOfPrimitives.doubleArray[0], 1.1)) {
log("checkStructOfPrimitives: doubleArray has invalid content");
return false;
}
if (!cmpDouble(structOfPrimitives.doubleArray[1], 2.2)) {
log("checkStructOfPrimitives: doubleArray has invalid content");
return false;
}
if (!structOfPrimitives.floatArray) {
log("checkStructOfPrimitives: floatArray not set");
return false;
}
if (structOfPrimitives.floatArray.length !== 2) {
log("checkStructOfPrimitives: floatArray has invalid length");
return false;
}
if (!cmpFloat(structOfPrimitives.floatArray[0], 1.1)) {
log("checkStructOfPrimitives: floatArray has invalid content");
return false;
}
if (!cmpFloat(structOfPrimitives.floatArray[1], 2.2)) {
log("checkStructOfPrimitives: floatArray has invalid content");
return false;
}
if (!structOfPrimitives.int8Array) {
log("checkStructOfPrimitives: int8Array not set");
return false;
}
if (structOfPrimitives.int8Array.length !== 2) {
log("checkStructOfPrimitives: int8Array has invalid length");
return false;
}
if (structOfPrimitives.int8Array[0] !== 1) {
log("checkStructOfPrimitives: int8Array has invalid content");
return false;
}
if (structOfPrimitives.int8Array[1] !== 2) {
log("checkStructOfPrimitives: int8Array has invalid content");
return false;
}
if (!structOfPrimitives.int16Array) {
log("checkStructOfPrimitives: int16Array not set");
return false;
}
if (structOfPrimitives.int16Array.length !== 2) {
log("checkStructOfPrimitives: int16Array has invalid length");
return false;
}
if (structOfPrimitives.int16Array[0] !== 1) {
log("checkStructOfPrimitives: int16Array has invalid content");
return false;
}
if (structOfPrimitives.int16Array[1] !== 2) {
log("checkStructOfPrimitives: int16Array has invalid content");
return false;
}
if (!structOfPrimitives.int32Array) {
log("checkStructOfPrimitives: int32Array not set");
return false;
}
if (structOfPrimitives.int32Array.length !== 2) {
log("checkStructOfPrimitives: int32Array has invalid length");
return false;
}
if (structOfPrimitives.int32Array[0] !== 1) {
log("checkStructOfPrimitives: int32Array has invalid content");
return false;
}
if (structOfPrimitives.int32Array[1] !== 2) {
log("checkStructOfPrimitives: int32Array has invalid content");
return false;
}
if (!structOfPrimitives.int64Array) {
log("checkStructOfPrimitives: int64Array not set");
return false;
}
if (structOfPrimitives.int64Array.length !== 2) {
log("checkStructOfPrimitives: int64Array has invalid length");
return false;
}
if (structOfPrimitives.int64Array[0] !== 1) {
log("checkStructOfPrimitives: int64Array has invalid content");
return false;
}
if (structOfPrimitives.int64Array[1] !== 2) {
log("checkStructOfPrimitives: int64Array has invalid content");
return false;
}
if (!structOfPrimitives.stringArray) {
log("checkStructOfPrimitives: stringArray not set");
return false;
}
if (structOfPrimitives.stringArray.length !== 2) {
log("checkStructOfPrimitives: stringArray has invalid length");
return false;
}
if (structOfPrimitives.stringArray[0] !== "Hello") {
log("checkStructOfPrimitives: stringArray has invalid content");
return false;
}
if (structOfPrimitives.stringArray[1] !== "World") {
log("checkStructOfPrimitives: stringArray has invalid content");
return false;
}
if (!structOfPrimitives.uInt8Array) {
log("checkStructOfPrimitives: uInt8Array not set");
return false;
}
if (structOfPrimitives.uInt8Array.length !== 2) {
log("checkStructOfPrimitives: uInt8Array has invalid length");
return false;
}
if (structOfPrimitives.uInt8Array[0] !== 1) {
log("checkStructOfPrimitives: uInt8Array has invalid content");
return false;
}
if (structOfPrimitives.uInt8Array[1] !== 2) {
log("checkStructOfPrimitives: uInt8Array has invalid content");
return false;
}
if (!structOfPrimitives.uInt16Array) {
log("checkStructOfPrimitives: uInt16Array not set");
return false;
}
if (structOfPrimitives.uInt16Array.length !== 2) {
log("checkStructOfPrimitives: uInt16Array has invalid length");
return false;
}
if (structOfPrimitives.uInt16Array[0] !== 1) {
log("checkStructOfPrimitives: uInt16Array has invalid content");
return false;
}
if (structOfPrimitives.uInt16Array[1] !== 2) {
log("checkStructOfPrimitives: uInt16Array has invalid content");
return false;
}
if (!structOfPrimitives.uInt32Array) {
log("checkStructOfPrimitives: uInt32Array not set");
return false;
}
if (structOfPrimitives.uInt32Array.length !== 2) {
log("checkStructOfPrimitives: uInt32Array has invalid length");
return false;
}
if (structOfPrimitives.uInt32Array[0] !== 1) {
log("checkStructOfPrimitives: uInt32Array has invalid content");
return false;
}
if (structOfPrimitives.uInt32Array[1] !== 2) {
log("checkStructOfPrimitives: uInt32Array has invalid content");
return false;
}
if (!structOfPrimitives.uInt64Array) {
log("checkStructOfPrimitives: uInt64Array not set");
return false;
}
if (structOfPrimitives.uInt64Array.length !== 2) {
log("checkStructOfPrimitives: uInt64Array has invalid length");
return false;
}
if (structOfPrimitives.uInt64Array[0] !== 1) {
log("checkStructOfPrimitives: uInt64Array has invalid content");
return false;
}
if (structOfPrimitives.uInt64Array[1] !== 2) {
log("checkStructOfPrimitives: uInt64Array has invalid content");
return false;
}
return true;
}
export function createStructOfPrimitives(): StructOfPrimitives {
// @ts-ignore
let structOfPrimitives = new StructOfPrimitives();
structOfPrimitives = fillStructOfPrimitives(structOfPrimitives);
return structOfPrimitives;
}
/* ExtendedStructOfPrimitives*/
export function fillExtendedStructOfPrimitives(
extendedStructOfPrimitives: ExtendedStructOfPrimitives
): ExtendedStructOfPrimitives {
extendedStructOfPrimitives.extendedStructElement = create("ExtendedBaseStruct");
fillStructOfPrimitives(extendedStructOfPrimitives);
if (!checkExtendedStructOfPrimitives(extendedStructOfPrimitives)) {
throw new JoynrRuntimeException({
detailMessage: "Internal error in checkExtendedStructOfPrimitives"
});
}
return extendedStructOfPrimitives;
}
export function createExtendedStructOfPrimitives(): ExtendedStructOfPrimitives {
// @ts-ignore
const extendedStructOfPrimitives = new ExtendedStructOfPrimitives();
extendedStructOfPrimitives.extendedEnumElement =
ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION;
fillExtendedStructOfPrimitives(extendedStructOfPrimitives);
if (!checkExtendedStructOfPrimitives(extendedStructOfPrimitives)) {
throw new JoynrRuntimeException({ detailMessage: "Internal error in checkExtendedStructOfPrimitives" });
}
return extendedStructOfPrimitives;
}
export function checkExtendedStructOfPrimitives(extendedStructOfPrimitives: ExtendedStructOfPrimitives): boolean {
if (!extendedStructOfPrimitives) {
log("checkExtendedStructOfPrimitives: extendedStructOfPrimitives not set");
return false;
}
if (
extendedStructOfPrimitives.extendedEnumElement !==
ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION
) {
log("checkExtendedStructOfPrimitives: extendedEnumElement has invalid content");
return false;
}
if (!check("ExtendedBaseStruct", extendedStructOfPrimitives.extendedStructElement)) {
log("checkExtendedStructOfPrimitives: extendedBaseStruct has invalid content");
return false;
}
if (!checkStructOfPrimitives(extendedStructOfPrimitives)) {
log("checkExtendedStructOfPrimitives: structOfPrimitives has invalid content");
return false;
}
return true;
}
export function cmpFloat(a: number, b: number): boolean {
return Math.abs(a - b) < 0.001;
}
export function cmpDouble(a: number, b: number): boolean {
return Math.abs(a - b) < 0.001;
}
export function cmpByteBuffers(a: number[], b: number[]): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
} | the_stack |
import EventEmitter from 'eventemitter3';
import Log from '../Utils/Logger';
import SpeedSampler from './SpeedChecker';
import BaseLoader from './BaseLoader';
import { RuntimeException } from '../Utils/Exception';
import UserConfig from '../Interfaces/UserConfig';
import RangeSeekHandler from './RangeSeekHandler';
import SeekRange from '../Interfaces/SeekRange';
// import Headers from '../Interfaces/Headers';
import LoaderStatus from './LoaderStatus';
import MediaConfig from '../Interfaces/MediaConfig';
import LoaderErrors from './LoaderErrors';
class RangeLoader extends BaseLoader {
Tag: string
/**
* use range request to seek
*/
private seekHandler: RangeSeekHandler
/**
* 初始化配置
*/
private userConfig: UserConfig
_needStash: boolean
/**
* 块数据的大小
*/
private _currentChunkSizeKB: number
/**
* 当前标准速度
*/
private _currentSpeedNormalized: number
/**
* 下载速度为0的次数
*/
private _zeroSpeedChunkCount: number
/**
* xhr
*/
_xhr: XMLHttpRequest | null
private _speedSampler: SpeedSampler
/**
* 是否阻止请求
*/
private _requestAbort: boolean
private _waitForTotalLength: boolean
/**
* 是否收到整个数据
*/
private _totalLengthReceived: boolean
/**
* 当前请求url
*/
private _currentRequestURL: string | null
private _currentRedirectedURL: string | null
/**
* 当前range
*/
_currentRequestRange: SeekRange | null
/**
* 数据的长度
*/
private _contentLength: number | null
/**
* 接受数据长度
*/
private _receivedLength: number
/**
* 最新下载进度, 字节
*/
private _lastTimeLoaded: number
/**
* chunk list
*/
private _chunkSizeKBList: number[]
/**
* 文件总长度
*/
private _totalLength: number | null
private _range: SeekRange | null
private mediaConfig: MediaConfig | null
eventEmitter: EventEmitter = new EventEmitter()
/**
* 是否支持xhr
*/
static isSupported() {
try {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com', true);
xhr.responseType = 'arraybuffer';
return xhr.responseType === 'arraybuffer';
} catch (e) {
Log.warn('RangeLoader', e.message);
return false;
}
}
constructor(seekHandler: RangeSeekHandler, userConfig: UserConfig) {
super('xhr-range-laoder', 'flv');
this.Tag = 'RangerLoader';
this.seekHandler = seekHandler;
this.userConfig = userConfig;
this._needStash = false;
this._chunkSizeKBList = [
128,
256,
384,
512,
768,
1024,
1536,
2048,
3072,
4096,
5120,
6144,
7168,
8192
];
this._currentChunkSizeKB = 384;
this._currentSpeedNormalized = 0;
this._zeroSpeedChunkCount = 0;
this._xhr = null;
this._speedSampler = new SpeedSampler();
this._requestAbort = false;
this._waitForTotalLength = false;
this._totalLengthReceived = false;
this._currentRequestURL = null;
this._currentRedirectedURL = null;
this._currentRequestRange = null;
this._totalLength = null;
this._contentLength = null;
this._receivedLength = 0;
this._lastTimeLoaded = 0;
this._range = null;
this.mediaConfig = null;
}
destory(): void {
if(this.isWorking()) {
this.abort();
}
if(this._xhr) {
this._xhr.onreadystatechange = null;
this._xhr.onprogress = null;
this._xhr.onload = null;
this._xhr.onerror = null;
this._xhr = null;
}
super.destroy();
}
get currentSpeed(): number {
return this._speedSampler.lastSecondKBps;
}
startLoad(mediaConfig: MediaConfig, seekRange: SeekRange): void {
this.mediaConfig = mediaConfig;
this._range = seekRange;
this._status = LoaderStatus.kConnecting;
let useRefTotalLength = false;
if(this.mediaConfig.fileSize !== undefined && this.mediaConfig.fileSize !== 0) {
useRefTotalLength = true;
this._totalLength = this.mediaConfig.fileSize;
}
if(!this._totalLengthReceived && !useRefTotalLength) {
this._waitForTotalLength = true;
this._internalOpen(this.mediaConfig, { from: 0, to: -1 });
} else {
this._openSubRange();
}
}
/**
* 请求子range
*/
_openSubRange(): void {
if(!this._range) {
return;
}
const chunkSize = this._currentChunkSizeKB * 1024;
const from = this._range.from + this._receivedLength;
let to = from + chunkSize;
if(this._contentLength != null) {
if(to - this._range.from >= this._contentLength) {
to = this._range.from + this._contentLength - 1;
}
}
this._currentRequestRange = { from, to };
this._internalOpen(this.mediaConfig, this._currentRequestRange);
}
/**
* 请求数据
*/
_internalOpen(mediaConfig: MediaConfig | null, seekRange: SeekRange): void {
if(!mediaConfig || !this.mediaConfig) {
return;
}
this._lastTimeLoaded = 0;
let sourceURL = mediaConfig.url;
if(this.userConfig.reuseRedirectedURL) {
if(this._currentRedirectedURL) {
sourceURL = this._currentRedirectedURL;
} else if(mediaConfig.redirectedURL !== undefined) {
sourceURL = mediaConfig.redirectedURL;
}
}
const seekConfig = this.seekHandler.getConfig(sourceURL, seekRange);
this._currentRequestURL = seekConfig.url;
this._xhr = new XMLHttpRequest();
const xhr = this._xhr;
xhr.open('GET', seekConfig.url, true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = this._onReadyStateChange.bind(this);
xhr.onprogress = this._onProgress.bind(this);
xhr.onload = this._onLoad.bind(this);
xhr.onerror = this._onXhrError.bind(this);
if(mediaConfig.withCredentials) {
xhr.withCredentials = true;
}
if(typeof seekConfig.headers === 'object') {
const { headers } = seekConfig;
Object.keys(headers).forEach((key) => {
xhr.setRequestHeader(key, headers[key]);
});
}
// add additional headers
if(typeof this.userConfig.headers === 'object') {
const { headers } = this.userConfig;
Object.keys(headers).forEach((key) => {
xhr.setRequestHeader(key, headers[key]);
});
}
xhr.send();
}
abort(): void {
this._requestAbort = true;
this._internalAbort();
this._status = LoaderStatus.kComplete;
}
_onReadyStateChange(e: Event): void {
const xhr = <XMLHttpRequest>e.target;
if(xhr.readyState === 2) {
if(xhr.responseURL !== undefined) {
const redirectedURL: string = this.seekHandler.removeURLParameters(xhr.responseURL);
if(
xhr.responseURL !== this._currentRequestURL
&& redirectedURL !== this._currentRedirectedURL
) {
this._currentRedirectedURL = redirectedURL;
if(this._onURLRedirect) {
this._onURLRedirect(redirectedURL);
}
}
}
if(xhr.status >= 200 && xhr.status <= 299) {
if(this._waitForTotalLength) {
return;
}
this._status = LoaderStatus.kBuffering;
} else {
this._status = LoaderStatus.kError;
if(this._onError) {
this._onError(LoaderErrors.HTTP_STATUS_CODE_INVALID, {
code: xhr.status,
reason: xhr.statusText
});
} else {
throw new RuntimeException(
`RangeLoader: http code invalid, ${xhr.status} ${xhr.statusText}`
);
}
}
}
}
_onProgress(e: ProgressEvent): void {
if(this._status === LoaderStatus.kError) {
return;
}
// 判断 _range null。
if(!this._range) {
return;
}
if(this._contentLength === null) {
let openNextRange: boolean = false;
if(this._waitForTotalLength) {
this._waitForTotalLength = false;
this._totalLengthReceived = true;
openNextRange = true;
const { total } = e;
this._internalAbort();
if(total != null && total !== 0) {
this._totalLength = total;
}
}
if(this._range.to === -1) {
this._contentLength = <number> this._totalLength - this._range.from;
} else {
this._contentLength = this._range.to - this._range.from + 1;
}
if(openNextRange) {
this._openSubRange();
return;
}
if(this._onContentLengthKnown) {
this._onContentLengthKnown(this._contentLength);
}
}
const delta: number = e.loaded - this._lastTimeLoaded;
this._lastTimeLoaded = e.loaded;
this._speedSampler.addBytes(delta);
}
_onLoad(e: Event): void {
if(!this._range || !e.target) {
return;
}
if(this._status === LoaderStatus.kError) {
return;
}
if(this._waitForTotalLength) {
this._waitForTotalLength = false;
return;
}
this._lastTimeLoaded = 0;
let KBps: number = this._speedSampler.lastSecondKBps;
if(KBps === 0) {
this._zeroSpeedChunkCount++;
if(this._zeroSpeedChunkCount >= 3) {
KBps = this._speedSampler.currentKBps;
}
}
if(KBps !== 0) {
const normalized: number = this._normalizeSpeed(KBps);
if(this._currentSpeedNormalized !== normalized) {
this._currentSpeedNormalized = normalized;
this._currentChunkSizeKB = normalized;
}
}
const chunk = (e.target as XMLHttpRequest).response;
const byteStart: number = this._range.from + this._receivedLength;
this._receivedLength += chunk.byteLength;
let reportComplete = false;
if(this._contentLength !== null && this._receivedLength < this._contentLength) {
this._openSubRange();
} else {
reportComplete = true;
}
if(this._onDataArrival) {
this._onDataArrival(chunk, byteStart, this._receivedLength);
}
if(reportComplete) {
this._status = LoaderStatus.kComplete;
if(this._onComplete) {
this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
}
}
}
_onXhrError(e: ProgressEvent): void {
this._status = LoaderStatus.kError;
let type: number | string = 0;
let info: null | { code: number; reason: string };
if(
this._contentLength
&& this._receivedLength > 0
&& this._receivedLength < this._contentLength
) {
type = LoaderErrors.EARLY_EOF;
info = {
code: -1,
reason: 'RangeLoder meet Early-Eof'
};
} else {
type = LoaderErrors.EXCEPTION;
info = { code: -1, reason: `${e.constructor.name} ${e.type}` };
}
if(this._onError) {
this._onError(type, info);
} else {
throw new RuntimeException(info.reason);
}
}
_normalizeSpeed(input: number): number {
const list = this._chunkSizeKBList;
const last: number = list.length - 1;
let mid: number = 0;
let lbound: number = 0;
let ubound = last;
if(input < list[0]) {
return list[0];
}
while(lbound <= ubound) {
mid = lbound + Math.floor((ubound - lbound) / 2);
if(mid === last || (input >= list[mid] && input < list[mid + 1])) {
return list[mid];
} if(list[mid] < input) {
lbound = mid + 1;
} else {
ubound = mid - 1;
}
}
return list[0];
}
_internalAbort(): void {
if(this._xhr) {
this._xhr.onreadystatechange = null;
this._xhr.onprogress = null;
this._xhr.onload = null;
this._xhr.onerror = null;
this._xhr.abort();
this._xhr = null;
}
}
on(eventName: string, callback: EventEmitter.ListenerFn): void {
this.eventEmitter.on(eventName, callback);
}
once(eventName: string, callback: EventEmitter.ListenerFn): void {
this.eventEmitter.once(eventName, callback);
}
off(eventName: string, callback?: EventEmitter.ListenerFn): void {
this.eventEmitter.off(eventName, callback);
}
}
export default RangeLoader; | the_stack |
import React from 'react';
import {
Drawer,
Checkbox,
Button,
Tooltip,
Spin,
Select,
Tag,
Empty,
} from 'antd';
import './index.less';
import { connect } from 'react-redux';
import BrowserView, { removeViews } from 'react-electron-browser-view';
import {
HighlightOutlined,
FieldTimeOutlined,
EnterOutlined,
FileAddOutlined,
ReloadOutlined,
} from '@ant-design/icons';
import rangy from 'rangy';
import { GraphDrawerProps } from './interface';
import 'rangy/lib/rangy-highlighter';
import 'rangy/lib/rangy-classapplier';
import 'rangy/lib/rangy-serializer';
import 'rangy/lib/rangy-selectionsaverestore.js';
const { Option } = Select;
const mapStateToProps = (state) => ({
layout: state.layout,
selectedDoc: state.document.selectedDoc,
});
const mapDispatchToProps = (dispatch) => {
return {
// dispatching plain actions
handleClose: () =>
dispatch({
type: 'TOGGLE_DRAWER',
payload: { visible: false, type: '', width: null },
}),
selectDoc: (payload) => dispatch({ type: 'SELECT_DOCUMENT', payload }),
resetSelectedDoc: () => dispatch({ type: 'RESET_SELECTED_DOC' }),
};
};
const tagColors = [
'green',
'blue',
'orange',
'cyan',
'magenta',
'geekblue',
'purple',
'gold',
'red',
'volcano',
];
class SelectedDocument extends React.Component {
state = {
tags: [],
tagInputValue: '',
loading: false,
};
webview = null;
componentDidMount(): void {
this.getTags();
}
async getTags() {
const res = await fetch('http://localhost:3000/tags');
const tagsData = await res.json();
const tags = [];
tagsData.rows.forEach((tag) => {
tags.push(tag.doc);
});
console.log('tags', tags);
this.setState(
{
tags,
},
() => {
this.setState({
loading: false,
});
}
);
}
chooseColor() {
const { tags } = this.state;
const colors = [];
tags.forEach((tag) => {
colors.push(tag.color);
});
for (const tagColor of tagColors) {
if (!colors.includes(tagColor)) {
console.log('_chooseColor', tagColor);
return tagColor;
}
}
return tagColors[Math.floor(Math.random() * (tagColors.length - 1))];
}
addTag() {
const { tagInputValue, tags } = this.state;
const color = this.chooseColor();
const tag = {
color,
label: tagInputValue,
};
this.addTagToDoc(tagInputValue, color);
let exist = false;
tags.forEach((tag) => {
if (tag.label === tagInputValue) {
exist = true;
}
});
if (!exist) {
this.setState(
{
tags: [...tags, tag],
},
() => {
this.updateDb('http://localhost:3000/tags', tag);
}
);
}
}
addTagToDoc(label, color) {
const { selectedDoc } = this.props;
const newSelectedDoc = { ...selectedDoc };
if (!newSelectedDoc.tags) {
newSelectedDoc.tags = [];
}
const tag = {
color,
label,
};
let exist = false;
newSelectedDoc.tags.forEach((tag) => {
if (tag.label === label) {
exist = true;
}
});
if (!exist) {
newSelectedDoc.tags.push(tag);
this.setState(
{
selectedDoc: newSelectedDoc,
},
() => {
newSelectedDoc.updatedTime = new Date().getTime();
this.updateDb(
`http://localhost:3000/documents/${newSelectedDoc._id}`,
newSelectedDoc
);
}
);
}
}
removeTagFromDoc(label) {
const { selectedDoc } = this.props;
const newSelectedDoc = { ...selectedDoc };
const findIndex = newSelectedDoc.tags.findIndex((tag, index) => {
if (tag.label === label) {
return true;
}
});
if (findIndex > -1) {
newSelectedDoc.tags.splice(findIndex, 1);
}
this.setState(
{
selectedDoc: newSelectedDoc,
},
() => {
newSelectedDoc.updatedTime = new Date().getTime();
this.updateDb(
`http://localhost:3000/documents/${newSelectedDoc._id}`,
newSelectedDoc
);
}
);
}
async updateDb(endpoint, body, method = 'POST') {
await fetch(endpoint, {
method, // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
}
render() {
const { layout, selectedDoc, resetSelectedDoc } = this.props;
const { tags, tagInputValue, loading } = this.state;
const { width } = layout.drawer;
let readerWidth = '50%';
if (width) {
readerWidth = window.innerWidth - width - 48;
}
return (
<div>
{Object.keys(selectedDoc).length !== 0 ? (
<div style={{ display: 'flex' }}>
<div
style={{
flex: 1,
borderRight: '1px solid #EFEFEF',
padding: 8,
maxWidth: 250,
}}
>
<div style={{ marginBottom: 32 }}>
<div style={{ fontWeight: 600 }}>My Tags</div>
<div
style={{
display: 'flex',
margin: '16px 0',
flexWrap: 'wrap',
}}
>
{selectedDoc.tags.map((tag) => {
return (
<div key={`${tag.label}_${tag.color}`}>
<Tag
style={{ margin: 4 }}
closable
onClose={() => {
this.removeTagFromDoc(tag.label);
}}
color={tag.color}
>
{tag.label}
</Tag>
{/* <div style={{width: '100%', padding: 8, fontSize: 12}}>{highlight.selectedText}</div> */}
</div>
);
})}
</div>
<Select
notFoundContent={
<div className="select-option">
<div>
<span style={{ fontSize: 12, marginRight: 8 }}>
Create
</span>
<Tag>{tagInputValue}</Tag>
</div>
<EnterOutlined />
</div>
}
size="small"
showSearch
placeholder="Type..."
// defaultOpen={true}
style={{ width: 220 }}
// className={contentStyles['tag-input']}
value={tagInputValue}
onChange={(value) => {
this.addTagToDoc(value.split('_')[0], value.split('_')[1]);
}}
onClick={(e) => {
e.stopPropagation();
}}
onSearch={(val) => {
this.setState({ tagInputValue: val });
}}
// onBlur={() => {this.handleEditInputConfirm(result.id)}}
// onInputKeyDown={(e) => console.log(e)}
onKeyDown={(e) => {
if (e.keyCode === 13) {
this.addTag();
}
}}
>
{tags.length > 0 ? (
<span style={{ fontSize: 10 }}>
Choose an existing option or create one
</span>
) : (
<span style={{ fontSize: 10 }}>
Start typing to create a new tag
</span>
)}
{tags.map((tag, index) => {
return (
<Option
key={`unique_tag_selection_${index}`}
value={`${tag.label}_${tag.color}`}
>
<div className="select-option">
<Tag color={tag.color}>{tag.label}</Tag>
<div className="select-option-enter">
<EnterOutlined />
</div>
</div>
</Option>
);
})}
</Select>
</div>
<div style={{ fontWeight: 600 }}>My Highlights</div>
{selectedDoc.highlights.map((highlight) => {
return (
<div
style={{ display: 'flex', margin: '12px 0px' }}
key={highlight.id}
>
<div style={{ width: 4 }} className={highlight.className} />
<div style={{ width: '100%', padding: 8, fontSize: 12 }}>
{highlight.selectedText}
</div>
</div>
);
})}
<div style={{ fontWeight: 600 }}>My Notes</div>
</div>
{/* <div */}
{/* style={{padding: 16, background: '#f4ecd8', flex: 2}} */}
{/* id={'reader'} */}
{/* dangerouslySetInnerHTML={{ __html: selectedDoc.content }} */}
{/* /> */}
<BrowserView
ref={(webview) => {
this.webview = webview;
}}
onDomReady={() => {
// rangy.init()
// let highlighter = rangy.createHighlighter()
// let classApplierModule = rangy.modules.ClassApplier
//
// const highlightPurple = rangy.createClassApplier('inline-tool-bar--highlight-purple')
// const highlightBlue = rangy.createClassApplier('inline-tool-bar--highlight-blue')
// const highlightGreen = rangy.createClassApplier('inline-tool-bar--highlight-green')
// const highlightOrange = rangy.createClassApplier('inline-tool-bar--highlight-orange')
// const highlightRed = rangy.createClassApplier('inline-tool-bar--highlight-red')
//
// highlighter.addClassApplier(highlightPurple)
// highlighter.addClassApplier(highlightBlue)
// highlighter.addClassApplier(highlightGreen)
// highlighter.addClassApplier(highlightOrange)
// highlighter.addClassApplier(highlightRed)
//
// { selectedDoc.highlights.map((highlight => {
// console.log('deserialize')
// highlighter.deserialize(highlight.serializedHighlight)
// })) }
}}
style={{ flex: 2, height: window.innerHeight }}
src={selectedDoc.url}
/>
</div>
) : (
<div style={{ marginTop: 50 }}>
<Empty
description={'<- Select an item in your inbox to preview.'}
/>
</div>
)}
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SelectedDocument); | the_stack |
import { Container, Utils as KernelUtils } from "@packages/core-kernel";
import { NetworkStateStatus } from "@packages/core-p2p/src/enums";
import { NetworkState } from "@packages/core-p2p/src/network-state";
import { Peer } from "@packages/core-p2p/src/peer";
import { PeerVerificationResult } from "@packages/core-p2p/src/peer-verifier";
import { Blocks, Crypto, Utils } from "@packages/crypto";
describe("NetworkState", () => {
// @ts-ignore
const lastBlock = {
data: {
id: "17882607875259085966",
version: 0,
timestamp: 46583330,
height: 8,
reward: Utils.BigNumber.make("0"),
previousBlock: "17184958558311101492",
numberOfTransactions: 0,
totalAmount: Utils.BigNumber.make("0"),
totalFee: Utils.BigNumber.make("0"),
payloadLength: 0,
payloadHash: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
generatorPublicKey: "026c598170201caf0357f202ff14f365a3b09322071e347873869f58d776bfc565",
blockSignature:
"3045022100e7385c6ea42bd950f7f6ab8c8619cf2f66a41d8f8f185b0bc99af032cb25f30d02200b6210176a6cedfdcbe483167fd91c21d740e0e4011d24d679c601fdd46b0de9",
},
transactions: [],
} as Blocks.Block;
const blockchainService = { getLastBlock: () => lastBlock };
const appGet = {
[Container.Identifiers.BlockchainService]: blockchainService,
};
const configuration = { getOptional: () => 2 }; // minimumNetworkReach
const app = {
get: (key) => appGet[key],
getTagged: () => configuration,
};
const networkMonitor = {
app,
isColdStart: jest.fn(),
completeColdStart: jest.fn(),
} as any;
let peers = [];
const peerStorage = { getPeers: () => peers } as any;
beforeEach(() => {
jest.resetAllMocks();
});
describe("analyze", () => {
describe("when this is a cold start", () => {
it("should call completeColdStart() and return ColdStart status", async () => {
networkMonitor.isColdStart = jest.fn().mockReturnValueOnce(true);
const networkState = await NetworkState.analyze(networkMonitor, peerStorage);
expect(networkState.status).toBe(NetworkStateStatus.ColdStart);
expect(networkMonitor.completeColdStart).toBeCalledTimes(1);
});
});
describe("when process.env.CORE_ENV='test'", () => {
it("should return Test status", async () => {
process.env.CORE_ENV = "test";
const networkState = await NetworkState.analyze(networkMonitor, peerStorage);
expect(networkState.status).toBe(NetworkStateStatus.Test);
delete process.env.CORE_ENV;
});
});
describe("when peers are below minimum network reach", () => {
it("should return BelowMinimumPeers status", async () => {
const networkState = await NetworkState.analyze(networkMonitor, peerStorage);
expect(networkState.status).toBe(NetworkStateStatus.BelowMinimumPeers);
});
});
describe("when returning quorum details", () => {
it("should return accurate quorum values peersNoQuorum peersQuorum peersForked", async () => {
const blockTimeLookup = await KernelUtils.forgingInfoCalculator.getBlockTimeLookup(
// @ts-ignore - app exists but isn't on the interface for now
networkMonitor.app,
lastBlock.data.height,
);
const currentSlot = Crypto.Slots.getSlotNumber(blockTimeLookup);
const peer1 = new Peer("181.168.65.65", 4000);
peer1.state = {
header: { height: 9, id: "12112607875259085966" },
height: 9,
forgingAllowed: true,
currentSlot: currentSlot + 1,
}; // overheight
const peer2 = new Peer("182.168.65.65", 4000);
peer2.state = { header: {}, height: 8, forgingAllowed: true, currentSlot: currentSlot }; // same height
const peer3 = new Peer("183.168.65.65", 4000);
peer3.state = { header: {}, height: 8, forgingAllowed: true, currentSlot: currentSlot }; // same height
const peer4 = new Peer("184.168.65.65", 4000);
peer4.state = { header: {}, height: 6, forgingAllowed: false, currentSlot: currentSlot - 2 }; // below height
peer4.verificationResult = new PeerVerificationResult(8, 6, 4); // forked
const peer5 = new Peer("185.168.65.65", 4000);
peer5.state = { header: {}, height: 6, forgingAllowed: false, currentSlot: currentSlot - 2 }; // below height, not forked
peers = [peer1, peer2, peer3, peer4, peer5];
const networkState = await NetworkState.analyze(networkMonitor, peerStorage);
expect(networkState.getQuorum()).toBe(3 / 5); // 2 same-height + 1 below-height but not forked
expect(networkState.getOverHeightBlockHeaders()).toEqual([peer1.state.header]);
});
});
});
describe("parse", () => {
describe("when data or data.status is undefined", () => {
it.each([[undefined], [{}]])("should return NetworkStateStatus.Unknown", (data) => {
expect(NetworkState.parse(data)).toEqual(new NetworkState(NetworkStateStatus.Unknown));
});
});
it.each([
[NetworkStateStatus.Default, 5, "7aaf2d2dc30fdbe8808b010714fd429f893535f5a90aa2abdb0ca62aa7d35130"],
[NetworkStateStatus.ColdStart, 144, "416d6ac21f279d9b79dde1fe59c6084628779a3a3cb5b4ea11fa4bf10295143b"],
[
NetworkStateStatus.BelowMinimumPeers,
2,
"1d582b5c84d5b72da8a25ca2bd95ccef1534c58823a01e0f698786a6fd0be4e6",
],
[NetworkStateStatus.Test, 533, "10024d739768a68b43a6e4124718129e1fe07b0461630b3f275b7640d298c3b7"],
[NetworkStateStatus.Unknown, 5333, "d76512050d858417f71da1f84ca4896a78057c14ea1ecebf70830c7cc87cd49a"],
])("should return the NetworkState corresponding to the data provided", (status, nodeHeight, lastBlockId) => {
const data = {
status,
nodeHeight,
lastBlockId,
quorumDetails: {
peersQuorum: 31,
peersNoQuorum: 3,
peersOverHeight: 0,
peersOverHeightBlockHeaders: {},
peersForked: 0,
peersDifferentSlot: 0,
peersForgingNotAllowed: 1,
},
};
const parsed = NetworkState.parse(data);
for (const key of ["status", "nodeHeight", "lastBlockId"]) {
expect(data[key]).toEqual(parsed[key]);
}
});
});
describe("getNodeHeight", () => {
it("should return node height", () => {
const data = {
status: NetworkStateStatus.Test,
nodeHeight: 31,
lastBlockId: "10024d739768a68b43a6e4124718129e1fe07b0461630b3f275b7640d298c3b7",
quorumDetails: {
peersQuorum: 31,
peersNoQuorum: 7,
peersOverHeight: 0,
peersOverHeightBlockHeaders: {},
peersForked: 0,
peersDifferentSlot: 0,
peersForgingNotAllowed: 1,
},
};
const networkState = NetworkState.parse(data);
expect(networkState.getNodeHeight()).toBe(31);
});
});
describe("getLastBlockId", () => {
it("should return lats block id", () => {
const data = {
status: NetworkStateStatus.Test,
nodeHeight: 31,
lastBlockId: "10024d739768a68b43a6e4124718129e1fe07b0461630b3f275b7640d298c3b7",
quorumDetails: {
peersQuorum: 31,
peersNoQuorum: 7,
peersOverHeight: 0,
peersOverHeightBlockHeaders: {},
peersForked: 0,
peersDifferentSlot: 0,
peersForgingNotAllowed: 1,
},
};
const networkState = NetworkState.parse(data);
expect(networkState.getLastBlockId()).toBe(
"10024d739768a68b43a6e4124718129e1fe07b0461630b3f275b7640d298c3b7",
);
});
});
describe("getQuorum", () => {
it("should return 1 when NetworkStateStatus.Test", () => {
const data = {
status: NetworkStateStatus.Test,
nodeHeight: 31,
lastBlockId: "10024d739768a68b43a6e4124718129e1fe07b0461630b3f275b7640d298c3b7",
quorumDetails: {
peersQuorum: 31,
peersNoQuorum: 7,
peersOverHeight: 0,
peersOverHeightBlockHeaders: {},
peersForked: 0,
peersDifferentSlot: 0,
peersForgingNotAllowed: 1,
},
};
const parsed = NetworkState.parse(data);
expect(parsed.getQuorum()).toBe(1);
});
});
describe("toJson", () => {
it("should return 1 when NetworkStateStatus.Test", () => {
const data = {
status: NetworkStateStatus.Default,
nodeHeight: 31,
lastBlockId: "10024d739768a68b43a6e4124718129e1fe07b0461630b3f275b7640d298c3b7",
quorumDetails: {
peersQuorum: 30,
peersNoQuorum: 10,
peersOverHeight: 0,
peersOverHeightBlockHeaders: {},
peersForked: 0,
peersDifferentSlot: 0,
peersForgingNotAllowed: 1,
},
};
const expectedJson = { ...data, quorum: 0.75 }; // 30 / (10+30)
delete expectedJson.status;
const parsed = NetworkState.parse(data);
expect(JSON.parse(parsed.toJson())).toEqual(expectedJson);
});
});
}); | the_stack |
import { Op, OpInfo, AuxType, SymEffect } from "../ir/op"
import { UInt64 } from "../int64"
import {
t_bool,
t_f32,
t_f64,
t_i16,
t_i32,
t_i64,
t_mem,
t_nil,
t_u16,
t_u32,
t_u64,
t_u8,
t_uintptr
} from "../ast"
const u64_ffff = new UInt64(65535,0),
u64_50000ffff = new UInt64(65535,5),
u64_10000ffff = new UInt64(65535,1),
u64_ffffffff = new UInt64(-1,0);
export const opnameMaxLen = 14;
export const ops = {
// generic
Invalid: 0,
Unknown: 1,
Phi: 2,
Copy: 3,
Arg: 4,
VarDef: 5,
InitMem: 6,
CallArg: 7,
NilCheck: 8,
InlMark: 9,
Call: 10,
TailCall: 11,
ConstBool: 12,
ConstI8: 13,
ConstI16: 14,
ConstI32: 15,
ConstI64: 16,
ConstF32: 17,
ConstF64: 18,
ConstStr: 19,
SP: 20,
SB: 21,
Load: 22,
Store: 23,
Move: 24,
Zero: 25,
OffPtr: 26,
StoreReg: 27,
LoadReg: 28,
AddI8: 29,
AddI16: 30,
AddI32: 31,
AddI64: 32,
AddF32: 33,
AddF64: 34,
SubI8: 35,
SubI16: 36,
SubI32: 37,
SubI64: 38,
SubF32: 39,
SubF64: 40,
MulI8: 41,
MulI16: 42,
MulI32: 43,
MulI64: 44,
MulF32: 45,
MulF64: 46,
DivS8: 47,
DivU8: 48,
DivS16: 49,
DivU16: 50,
DivS32: 51,
DivU32: 52,
DivS64: 53,
DivU64: 54,
DivF32: 55,
DivF64: 56,
RemS8: 57,
RemU8: 58,
RemS16: 59,
RemU16: 60,
RemS32: 61,
RemU32: 62,
RemI64: 63,
RemU64: 64,
AndI8: 65,
AndI16: 66,
AndI32: 67,
AndI64: 68,
OrI8: 69,
OrI16: 70,
OrI32: 71,
OrI64: 72,
XorI8: 73,
XorI16: 74,
XorI32: 75,
XorI64: 76,
ShLI8x8: 77,
ShLI8x16: 78,
ShLI8x32: 79,
ShLI8x64: 80,
ShLI16x8: 81,
ShLI16x16: 82,
ShLI16x32: 83,
ShLI16x64: 84,
ShLI32x8: 85,
ShLI32x16: 86,
ShLI32x32: 87,
ShLI32x64: 88,
ShLI64x8: 89,
ShLI64x16: 90,
ShLI64x32: 91,
ShLI64x64: 92,
ShRS8x8: 93,
ShRS8x16: 94,
ShRS8x32: 95,
ShRS8x64: 96,
ShRS16x8: 97,
ShRS16x16: 98,
ShRS16x32: 99,
ShRS16x64: 100,
ShRS32x8: 101,
ShRS32x16: 102,
ShRS32x32: 103,
ShRS32x64: 104,
ShRS64x8: 105,
ShRS64x16: 106,
ShRS64x32: 107,
ShRS64x64: 108,
ShRU8x8: 109,
ShRU8x16: 110,
ShRU8x32: 111,
ShRU8x64: 112,
ShRU16x8: 113,
ShRU16x16: 114,
ShRU16x32: 115,
ShRU16x64: 116,
ShRU32x8: 117,
ShRU32x16: 118,
ShRU32x32: 119,
ShRU32x64: 120,
ShRU64x8: 121,
ShRU64x16: 122,
ShRU64x32: 123,
ShRU64x64: 124,
EqI8: 125,
EqI16: 126,
EqI32: 127,
EqI64: 128,
EqF32: 129,
EqF64: 130,
NeqI8: 131,
NeqI16: 132,
NeqI32: 133,
NeqI64: 134,
NeqF32: 135,
NeqF64: 136,
LessS8: 137,
LessU8: 138,
LessS16: 139,
LessU16: 140,
LessS32: 141,
LessU32: 142,
LessS64: 143,
LessU64: 144,
LessF32: 145,
LessF64: 146,
LeqS8: 147,
LeqU8: 148,
LeqS16: 149,
LeqU16: 150,
LeqS32: 151,
LeqU32: 152,
LeqS64: 153,
LeqU64: 154,
LeqF32: 155,
LeqF64: 156,
GreaterS8: 157,
GreaterU8: 158,
GreaterS16: 159,
GreaterU16: 160,
GreaterS32: 161,
GreaterU32: 162,
GreaterS64: 163,
GreaterU64: 164,
GreaterF32: 165,
GreaterF64: 166,
GeqS8: 167,
GeqU8: 168,
GeqS16: 169,
GeqU16: 170,
GeqS32: 171,
GeqU32: 172,
GeqS64: 173,
GeqU64: 174,
GeqF32: 175,
GeqF64: 176,
Not: 177,
MinF32: 178,
MinF64: 179,
MaxF32: 180,
MaxF64: 181,
NegI8: 182,
NegI16: 183,
NegI32: 184,
NegI64: 185,
NegF32: 186,
NegF64: 187,
CtzI8: 188,
CtzI16: 189,
CtzI32: 190,
CtzI64: 191,
CtzI8NonZero: 192,
CtzI16NonZero: 193,
CtzI32NonZero: 194,
CtzI64NonZero: 195,
BitLen8: 196,
BitLen16: 197,
BitLen32: 198,
BitLen64: 199,
PopCountI8: 200,
PopCountI16: 201,
PopCountI32: 202,
PopCountI64: 203,
SqrtF32: 204,
SqrtF64: 205,
FloorF32: 206,
FloorF64: 207,
CeilF32: 208,
CeilF64: 209,
TruncF32: 210,
TruncF64: 211,
RoundF32: 212,
RoundF64: 213,
RoundToEvenF32: 214,
RoundToEvenF64: 215,
AbsF32: 216,
AbsF64: 217,
CopysignF32: 218,
CopysignF64: 219,
SignExtI8to16: 220,
SignExtI8to32: 221,
SignExtI8to64: 222,
SignExtI16to32: 223,
SignExtI16to64: 224,
SignExtI32to64: 225,
ZeroExtI8to16: 226,
ZeroExtI8to32: 227,
ZeroExtI8to64: 228,
ZeroExtI16to32: 229,
ZeroExtI16to64: 230,
ZeroExtI32to64: 231,
TruncI8toBool: 232,
TruncI16toBool: 233,
TruncI32toBool: 234,
TruncI64toBool: 235,
TruncF32toBool: 236,
TruncF64toBool: 237,
TruncI16to8: 238,
TruncI32to8: 239,
TruncI32to16: 240,
TruncI64to8: 241,
TruncI64to16: 242,
TruncI64to32: 243,
ConvI32toF32: 244,
ConvI32toF64: 245,
ConvI64toF32: 246,
ConvI64toF64: 247,
ConvF32toI32: 248,
ConvF32toI64: 249,
ConvF64toI32: 250,
ConvF64toI64: 251,
ConvF32toF64: 252,
ConvF64toF32: 253,
ConvU32toF32: 254,
ConvU32toF64: 255,
ConvF32toU32: 256,
ConvF64toU32: 257,
ConvU64toF32: 258,
ConvU64toF64: 259,
ConvF32toU64: 260,
ConvF64toU64: 261,
AtomicLoad32: 262,
AtomicLoad64: 263,
AtomicLoadPtr: 264,
AtomicStore32: 265,
AtomicStore64: 266,
AtomicStorePtr: 267,
AtomicSwap32: 268,
AtomicSwap64: 269,
AtomicAdd32: 270,
AtomicAdd64: 271,
AtomicCAS32: 272,
AtomicCAS64: 273,
AtomicAnd8: 274,
AtomicOr8: 275,
// covm
CovmMOV32const: 276,
CovmLoad8: 277,
CovmLoad16: 278,
CovmLoad32: 279,
CovmLoad64: 280,
CovmStore8: 281,
CovmStore16: 282,
CovmStore32: 283,
CovmStore64: 284,
CovmADD32: 285,
CovmADD32const: 286,
CovmADD64: 287,
CovmMUL32: 288,
CovmCALL: 289,
CovmLowNilCheck: 290,
CovmZeroLarge: 291,
// END
OpcodeMax: 292,
};
export const opinfo :OpInfo[] = [
// generic
{ name: 'Invalid',
argLen: 0,
generic: true,
},
{ name: 'Unknown',
argLen: 0,
generic: true,
},
{ name: 'Phi',
argLen: -1,
generic: true,
zeroWidth: true,
},
{ name: 'Copy',
argLen: 1,
generic: true,
},
{ name: 'Arg',
argLen: 0,
aux: AuxType.SymOff,
generic: true,
symEffect: 1,
zeroWidth: true,
},
{ name: 'VarDef',
argLen: 1,
aux: AuxType.Sym,
generic: true,
symEffect: 0,
type: t_mem,
zeroWidth: true,
},
{ name: 'InitMem',
argLen: 0,
generic: true,
type: t_mem,
zeroWidth: true,
},
{ name: 'CallArg',
argLen: 1,
generic: true,
zeroWidth: true,
},
{ name: 'NilCheck',
argLen: 2,
faultOnNilArg0: true,
generic: true,
nilCheck: true,
type: t_nil,
},
{ name: 'InlMark',
argLen: 1,
aux: AuxType.Int32,
generic: true,
type: t_nil,
},
{ name: 'Call',
argLen: 1,
aux: AuxType.SymOff,
call: true,
generic: true,
type: t_mem,
},
{ name: 'TailCall',
argLen: 1,
aux: AuxType.SymOff,
call: true,
generic: true,
type: t_mem,
},
{ name: 'ConstBool',
argLen: 0,
aux: AuxType.Bool,
constant: true,
generic: true,
},
{ name: 'ConstI8',
argLen: 0,
aux: AuxType.Int8,
constant: true,
generic: true,
},
{ name: 'ConstI16',
argLen: 0,
aux: AuxType.Int16,
constant: true,
generic: true,
},
{ name: 'ConstI32',
argLen: 0,
aux: AuxType.Int32,
constant: true,
generic: true,
},
{ name: 'ConstI64',
argLen: 0,
aux: AuxType.Int64,
constant: true,
generic: true,
},
{ name: 'ConstF32',
argLen: 0,
aux: AuxType.Int32,
constant: true,
generic: true,
},
{ name: 'ConstF64',
argLen: 0,
aux: AuxType.Int64,
constant: true,
generic: true,
},
{ name: 'ConstStr',
argLen: 0,
aux: AuxType.String,
generic: true,
},
{ name: 'SP',
argLen: 0,
generic: true,
zeroWidth: true,
},
{ name: 'SB',
argLen: 0,
generic: true,
type: t_uintptr,
zeroWidth: true,
},
{ name: 'Load',
argLen: 2,
generic: true,
},
{ name: 'Store',
argLen: 3,
aux: AuxType.Type,
generic: true,
type: t_mem,
},
{ name: 'Move',
argLen: 3,
generic: true,
type: t_mem,
},
{ name: 'Zero',
argLen: 2,
generic: true,
type: t_mem,
},
{ name: 'OffPtr',
argLen: 1,
aux: AuxType.Int64,
generic: true,
type: t_mem,
},
{ name: 'StoreReg',
argLen: 1,
generic: true,
},
{ name: 'LoadReg',
argLen: 1,
generic: true,
},
{ name: 'AddI8',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AddI16',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AddI32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AddI64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AddF32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AddF64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'SubI8',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'SubI16',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'SubI32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'SubI64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'SubF32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'SubF64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'MulI8',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'MulI16',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'MulI32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'MulI64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'MulF32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'MulF64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'DivS8',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivU8',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivS16',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivU16',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivS32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivU32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivS64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivU64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivF32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'DivF64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemS8',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemU8',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemS16',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemU16',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemS32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemU32',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemI64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'RemU64',
argLen: 2,
generic: true,
resultInArg0: true,
},
{ name: 'AndI8',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AndI16',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AndI32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'AndI64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'OrI8',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'OrI16',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'OrI32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'OrI64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'XorI8',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'XorI16',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'XorI32',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'XorI64',
argLen: 2,
commutative: true,
generic: true,
resultInArg0: true,
},
{ name: 'ShLI8x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI8x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI8x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI8x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI16x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI16x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI16x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI16x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI32x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI32x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI32x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI32x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI64x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI64x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI64x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShLI64x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS8x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS8x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS8x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS8x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS16x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS16x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS16x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS16x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS32x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS32x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS32x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS32x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS64x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS64x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS64x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRS64x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU8x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU8x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU8x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU8x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU16x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU16x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU16x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU16x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU32x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU32x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU32x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU32x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU64x8',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU64x16',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU64x32',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'ShRU64x64',
argLen: 2,
aux: AuxType.Bool,
generic: true,
},
{ name: 'EqI8',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'EqI16',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'EqI32',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'EqI64',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'EqF32',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'EqF64',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'NeqI8',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'NeqI16',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'NeqI32',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'NeqI64',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'NeqF32',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'NeqF64',
argLen: 2,
commutative: true,
generic: true,
type: t_bool,
},
{ name: 'LessS8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessU8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessS16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessU16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessS32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessU32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessS64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessU64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessF32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LessF64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqS8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqU8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqS16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqU16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqS32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqU32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqS64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqU64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqF32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'LeqF64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterS8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterU8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterS16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterU16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterS32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterU32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterS64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterU64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterF32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GreaterF64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqS8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqU8',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqS16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqU16',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqS32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqU32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqS64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqU64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqF32',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'GeqF64',
argLen: 2,
generic: true,
type: t_bool,
},
{ name: 'Not',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'MinF32',
argLen: 2,
generic: true,
},
{ name: 'MinF64',
argLen: 2,
generic: true,
},
{ name: 'MaxF32',
argLen: 2,
generic: true,
},
{ name: 'MaxF64',
argLen: 2,
generic: true,
},
{ name: 'NegI8',
argLen: 1,
generic: true,
},
{ name: 'NegI16',
argLen: 1,
generic: true,
},
{ name: 'NegI32',
argLen: 1,
generic: true,
},
{ name: 'NegI64',
argLen: 1,
generic: true,
},
{ name: 'NegF32',
argLen: 1,
generic: true,
},
{ name: 'NegF64',
argLen: 1,
generic: true,
},
{ name: 'CtzI8',
argLen: 1,
generic: true,
},
{ name: 'CtzI16',
argLen: 1,
generic: true,
},
{ name: 'CtzI32',
argLen: 1,
generic: true,
},
{ name: 'CtzI64',
argLen: 1,
generic: true,
},
{ name: 'CtzI8NonZero',
argLen: 1,
generic: true,
},
{ name: 'CtzI16NonZero',
argLen: 1,
generic: true,
},
{ name: 'CtzI32NonZero',
argLen: 1,
generic: true,
},
{ name: 'CtzI64NonZero',
argLen: 1,
generic: true,
},
{ name: 'BitLen8',
argLen: 1,
generic: true,
},
{ name: 'BitLen16',
argLen: 1,
generic: true,
},
{ name: 'BitLen32',
argLen: 1,
generic: true,
},
{ name: 'BitLen64',
argLen: 1,
generic: true,
},
{ name: 'PopCountI8',
argLen: 1,
generic: true,
},
{ name: 'PopCountI16',
argLen: 1,
generic: true,
},
{ name: 'PopCountI32',
argLen: 1,
generic: true,
},
{ name: 'PopCountI64',
argLen: 1,
generic: true,
},
{ name: 'SqrtF32',
argLen: 1,
generic: true,
},
{ name: 'SqrtF64',
argLen: 1,
generic: true,
},
{ name: 'FloorF32',
argLen: 1,
generic: true,
},
{ name: 'FloorF64',
argLen: 1,
generic: true,
},
{ name: 'CeilF32',
argLen: 1,
generic: true,
},
{ name: 'CeilF64',
argLen: 1,
generic: true,
},
{ name: 'TruncF32',
argLen: 1,
generic: true,
},
{ name: 'TruncF64',
argLen: 1,
generic: true,
},
{ name: 'RoundF32',
argLen: 1,
generic: true,
},
{ name: 'RoundF64',
argLen: 1,
generic: true,
},
{ name: 'RoundToEvenF32',
argLen: 1,
generic: true,
},
{ name: 'RoundToEvenF64',
argLen: 1,
generic: true,
},
{ name: 'AbsF32',
argLen: 1,
generic: true,
},
{ name: 'AbsF64',
argLen: 1,
generic: true,
},
{ name: 'CopysignF32',
argLen: 2,
generic: true,
},
{ name: 'CopysignF64',
argLen: 2,
generic: true,
},
{ name: 'SignExtI8to16',
argLen: 1,
generic: true,
type: t_i16,
},
{ name: 'SignExtI8to32',
argLen: 1,
generic: true,
type: t_i32,
},
{ name: 'SignExtI8to64',
argLen: 1,
generic: true,
type: t_i64,
},
{ name: 'SignExtI16to32',
argLen: 1,
generic: true,
type: t_i32,
},
{ name: 'SignExtI16to64',
argLen: 1,
generic: true,
type: t_i64,
},
{ name: 'SignExtI32to64',
argLen: 1,
generic: true,
type: t_i64,
},
{ name: 'ZeroExtI8to16',
argLen: 1,
generic: true,
type: t_u16,
},
{ name: 'ZeroExtI8to32',
argLen: 1,
generic: true,
type: t_u32,
},
{ name: 'ZeroExtI8to64',
argLen: 1,
generic: true,
type: t_u64,
},
{ name: 'ZeroExtI16to32',
argLen: 1,
generic: true,
type: t_u32,
},
{ name: 'ZeroExtI16to64',
argLen: 1,
generic: true,
type: t_u64,
},
{ name: 'ZeroExtI32to64',
argLen: 1,
generic: true,
type: t_u64,
},
{ name: 'TruncI8toBool',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'TruncI16toBool',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'TruncI32toBool',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'TruncI64toBool',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'TruncF32toBool',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'TruncF64toBool',
argLen: 1,
generic: true,
type: t_bool,
},
{ name: 'TruncI16to8',
argLen: 1,
generic: true,
},
{ name: 'TruncI32to8',
argLen: 1,
generic: true,
},
{ name: 'TruncI32to16',
argLen: 1,
generic: true,
},
{ name: 'TruncI64to8',
argLen: 1,
generic: true,
},
{ name: 'TruncI64to16',
argLen: 1,
generic: true,
},
{ name: 'TruncI64to32',
argLen: 1,
generic: true,
},
{ name: 'ConvI32toF32',
argLen: 1,
generic: true,
type: t_f32,
},
{ name: 'ConvI32toF64',
argLen: 1,
generic: true,
type: t_f64,
},
{ name: 'ConvI64toF32',
argLen: 1,
generic: true,
type: t_f32,
},
{ name: 'ConvI64toF64',
argLen: 1,
generic: true,
type: t_f64,
},
{ name: 'ConvF32toI32',
argLen: 1,
generic: true,
type: t_i32,
},
{ name: 'ConvF32toI64',
argLen: 1,
generic: true,
type: t_i64,
},
{ name: 'ConvF64toI32',
argLen: 1,
generic: true,
type: t_i32,
},
{ name: 'ConvF64toI64',
argLen: 1,
generic: true,
type: t_i64,
},
{ name: 'ConvF32toF64',
argLen: 1,
generic: true,
type: t_f64,
},
{ name: 'ConvF64toF32',
argLen: 1,
generic: true,
type: t_f32,
},
{ name: 'ConvU32toF32',
argLen: 1,
generic: true,
type: t_f32,
},
{ name: 'ConvU32toF64',
argLen: 1,
generic: true,
type: t_f64,
},
{ name: 'ConvF32toU32',
argLen: 1,
generic: true,
type: t_u32,
},
{ name: 'ConvF64toU32',
argLen: 1,
generic: true,
type: t_u32,
},
{ name: 'ConvU64toF32',
argLen: 1,
generic: true,
type: t_f32,
},
{ name: 'ConvU64toF64',
argLen: 1,
generic: true,
type: t_f64,
},
{ name: 'ConvF32toU64',
argLen: 1,
generic: true,
type: t_u64,
},
{ name: 'ConvF64toU64',
argLen: 1,
generic: true,
type: t_u64,
},
{ name: 'AtomicLoad32',
argLen: 2,
generic: true,
},
{ name: 'AtomicLoad64',
argLen: 2,
generic: true,
},
{ name: 'AtomicLoadPtr',
argLen: 2,
generic: true,
},
{ name: 'AtomicStore32',
argLen: 3,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicStore64',
argLen: 3,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicStorePtr',
argLen: 3,
generic: true,
hasSideEffects: true,
type: t_mem,
},
{ name: 'AtomicSwap32',
argLen: 3,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicSwap64',
argLen: 3,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicAdd32',
argLen: 3,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicAdd64',
argLen: 3,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicCAS32',
argLen: 4,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicCAS64',
argLen: 4,
generic: true,
hasSideEffects: true,
},
{ name: 'AtomicAnd8',
argLen: 3,
generic: true,
hasSideEffects: true,
type: t_uintptr,
},
{ name: 'AtomicOr8',
argLen: 3,
generic: true,
hasSideEffects: true,
type: t_uintptr,
},
// covm
{ name: 'MOV32const',
argLen: 0,
aux: AuxType.Int32,
reg: {
inputs: [],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
rematerializeable: true,
type: t_u32,
},
{ name: 'Load8',
argLen: 2,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
symEffect: 1,
type: t_u8,
},
{ name: 'Load16',
argLen: 2,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
symEffect: 1,
type: t_u16,
},
{ name: 'Load32',
argLen: 2,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
symEffect: 1,
type: t_u32,
},
{ name: 'Load64',
argLen: 2,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
symEffect: 1,
type: t_u64,
},
{ name: 'Store8',
argLen: 3,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [],
clobbers: UInt64.ZERO
},
symEffect: 2,
type: t_mem,
},
{ name: 'Store16',
argLen: 3,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [],
clobbers: UInt64.ZERO
},
symEffect: 2,
type: t_mem,
},
{ name: 'Store32',
argLen: 3,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [],
clobbers: UInt64.ZERO
},
symEffect: 2,
type: t_mem,
},
{ name: 'Store64',
argLen: 3,
aux: AuxType.SymOff,
faultOnNilArg0: true,
reg: {
inputs: [
{idx:0,regs:u64_50000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [],
clobbers: UInt64.ZERO
},
symEffect: 2,
type: t_mem,
},
{ name: 'ADD32',
argLen: 2,
commutative: true,
reg: {
inputs: [
{idx:0,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
type: t_u32,
},
{ name: 'ADD32const',
argLen: 1,
aux: AuxType.Int32,
commutative: true,
reg: {
inputs: [
{idx:0,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
type: t_u32,
},
{ name: 'ADD64',
argLen: 2,
commutative: true,
reg: {
inputs: [
{idx:0,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
type: t_u64,
},
{ name: 'MUL32',
argLen: 2,
commutative: true,
reg: {
inputs: [
{idx:0,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/},
{idx:1,regs:u64_10000ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 }*/}
],
outputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
clobbers: UInt64.ZERO
},
type: t_u32,
},
{ name: 'CALL',
argLen: 1,
aux: AuxType.SymOff,
call: true,
clobberFlags: true,
reg: {
inputs: [],
outputs: [],
clobbers: u64_ffffffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 }*/
},
type: t_mem,
},
{ name: 'LowNilCheck',
argLen: 2,
faultOnNilArg0: true,
nilCheck: true,
reg: {
inputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
outputs: [],
clobbers: UInt64.ZERO
},
type: t_nil,
},
{ name: 'ZeroLarge',
argLen: 2,
aux: AuxType.Int64,
reg: {
inputs: [
{idx:0,regs:u64_ffff /*RegSet { r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 }*/}
],
outputs: [],
clobbers: UInt64.ZERO
},
},
]; // ops
// fmtop returns a printable representation of an operator
//
export function fmtop(op :Op) :string {
let info = opinfo[op]
assert(info, `unknown op #${op}`)
return info.name
} | the_stack |
import { log } from '../util/logging';
import { ITicks, INeonTransferChunk, INeonNotification } from '../util/progress';
import {
RustDltIndexerChannel,
RustDltStatsChannel,
RustExportFileChannel,
RustDltSocketChannel,
RustDltPcapChannel,
RustDltPcapConverterChannel
} from '../native';
import { NativeComputationManager } from '../native_computation_manager';
import { CancelablePromise } from '../util/promise';
import {
IDLTFilters,
IDLTOptions,
IIndexDltParams,
DltFilterConf,
DltLogLevel,
LevelDistribution,
StatisticInfo,
IFibexConfig
} from '../../../../common/interfaces/interface.dlt';
import { IFileSaveParams } from '../../../../common/interfaces';
import { ChunkHandler, NotificationHandler, ProgressEventHandler } from './common';
export {
IDLTFilters,
IDLTOptions,
IIndexDltParams,
DltFilterConf,
DltLogLevel,
LevelDistribution,
StatisticInfo,
IFibexConfig
};
export interface IDltSocketParams {
filterConfig: DltFilterConf;
fibex: IFibexConfig;
tag: string;
out: string;
stdout: boolean;
statusUpdates: boolean;
}
export interface ISocketConfig {
multicast_addr: IMulticastInfo[];
bind_addr: string;
port: string;
udp_connection_info?: {
multicast_addr: IMulticastInfo[];
},
target: 'Tcp' | 'Udp',
}
/// Multicast config information.
/// `multiaddr` address must be a valid multicast address
/// `interface` is the address of the local interface with which the
/// system should join the
/// multicast group. If it's equal to `INADDR_ANY` then an appropriate
/// interface is chosen by the system.
export interface IMulticastInfo {
multiaddr: string;
interface?: string;
}
export interface IIndexDltOptions {}
export interface IIndexDltOptionsChecked {}
export type TDltStatsEvents = 'config' | 'progress' | 'notification';
export type TDltStatsEventConfig = (event: StatisticInfo) => void;
export type TDltStatsEventObject = TDltStatsEventConfig | ProgressEventHandler | NotificationHandler;
export function dltStatsAsync(
dltFile: string,
options?: IIndexDltOptions
): CancelablePromise<void, void, TDltStatsEvents, TDltStatsEventObject> {
return new CancelablePromise<
void,
void,
TDltStatsEvents,
TDltStatsEventObject
>((resolve, reject, cancel, refCancelCB, self) => {
try {
// Get defaults options
const opt = getDefaultIndexDltProcessingOptions(options);
const channel = new RustDltStatsChannel(dltFile);
const emitter = new NativeComputationManager<StatisticInfo>(channel);
let total: number = 1;
// Add cancel callback
refCancelCB(() => {
// Cancelation is started, but not canceled
log(`Get command "break" operation. Starting breaking.`);
emitter.requestShutdown();
});
emitter.onItem((chunk: StatisticInfo) => {
self.emit('config', chunk);
});
emitter.onProgress((ticks: ITicks) => {
total = ticks.total;
self.emit('progress', ticks);
});
emitter.onStopped(() => {
cancel();
});
emitter.onNotification((notification: INeonNotification) => {
log('dltStats: we got a notification: ' + JSON.stringify(notification));
self.emit('notification', notification);
});
emitter.onFinished(() => {
resolve();
});
} catch (err) {
if (!(err instanceof Error)) {
log(`operation is stopped. Error isn't valid:`);
log(err);
err = new Error(`operation is stopped. Error isn't valid.`);
} else {
log(`operation is stopped due error: ${err.message}`);
}
// Operation is rejected
reject(err);
}
});
}
export type TDltFileAsyncEvents = 'progress' | 'notification';
export type TDltFileAsyncEventObject = ProgressEventHandler;
export function exportDltFile(
source: string,
sourceType: 'session' | 'file',
targetFile: string,
params: IFileSaveParams
): CancelablePromise<void, void, TDltFileAsyncEvents, TDltFileAsyncEventObject> {
return new CancelablePromise<
void,
void,
TDltFileAsyncEvents,
TDltFileAsyncEventObject
>((resolve, reject, cancel, refCancelCB, self) => {
try {
log(`exportDltFile using file-save-parmams: ${params}`);
// Add cancel callback
refCancelCB(() => {
// Cancelation is started, but not canceled
log(`export dlt file command "break" operation`);
emitter.requestShutdown();
});
// Create channel
const channel = new RustExportFileChannel(source, sourceType, targetFile, params, false);
// Create emitter
const emitter: NativeComputationManager<ITicks> = new NativeComputationManager(channel);
let chunks: number = 0;
// Add listenters
emitter.onItem((ticks: ITicks) => {
self.emit('progress', ticks);
});
emitter.onStopped(() => {
log(`we got a stopped event while saving dlt file (${sourceType}) with source ${source}`);
cancel();
});
emitter.onNotification((notification: INeonNotification) => {
self.emit('notification', notification);
});
emitter.onFinished(() => {
log('we got a finished event after ' + chunks + ' chunks');
resolve();
});
// Handle finale of promise
self.finally(() => {
log('processing dlt export is finished');
});
} catch (err) {
if (!(err instanceof Error)) {
log(`operation is stopped. Error isn't valid:`);
log(err);
err = new Error(`operation is stopped. Error isn't valid.`);
} else {
log(`operation is stopped due error: ${err.message}`);
}
// Operation is rejected
reject(err);
}
});
}
export type TIndexDltAsyncEvents = 'chunk' | 'progress' | 'notification';
export type TIndexDltAsyncEventObject = ChunkHandler | ProgressEventHandler | NotificationHandler;
export function indexDltAsync(
params: IIndexDltParams,
options?: IIndexDltOptions
): CancelablePromise<void, void, TIndexDltAsyncEvents, TIndexDltAsyncEventObject> {
return new CancelablePromise<
void,
void,
TIndexDltAsyncEvents,
TIndexDltAsyncEventObject
>((resolve, reject, cancel, refCancelCB, self) => {
try {
log(`using fibex: ${params.fibex}`);
// Get defaults options
const opt = getDefaultIndexDltProcessingOptions(options);
// Add cancel callback
refCancelCB(() => {
// Cancelation is started, but not canceled
log(`Get command "break" operation. Starting breaking.`);
emitter.requestShutdown();
});
// Create channel
const channel = new RustDltIndexerChannel(
params.dltFile,
params.tag,
params.out,
params.append,
params.chunk_size,
params.filterConfig,
params.fibex
);
// Create emitter
const emitter: NativeComputationManager<INeonTransferChunk> = new NativeComputationManager(channel);
let chunks: number = 0;
// Add listenters
emitter.onItem((c: INeonTransferChunk) => {
self.emit('chunk', {
bytesStart: c.b[0],
bytesEnd: c.b[1],
rowsStart: c.r[0],
rowsEnd: c.r[1]
});
chunks += 1;
});
emitter.onProgress((ticks: ITicks) => {
self.emit('progress', ticks);
});
emitter.onStopped(() => {
log('we got a stopped event after ' + chunks + ' chunks');
cancel();
});
emitter.onNotification((notification: INeonNotification) => {
self.emit('notification', notification);
});
emitter.onFinished(() => {
log('we got a finished event after ' + chunks + ' chunks');
resolve();
});
// Handle finale of promise
self.finally(() => {
log('processing dlt indexing is finished');
});
} catch (err) {
if (!(err instanceof Error)) {
log(`operation is stopped. Error isn't valid:`);
log(err);
err = new Error(`operation is stopped. Error isn't valid.`);
} else {
log(`operation is stopped due error: ${err.message}`);
}
// Operation is rejected
reject(err);
}
});
}
export type TDLTSocketEvents = 'chunk' | 'progress' | 'notification' | 'connect';
export type TDLTSocketEventConnect = () => void;
export type TDLTSocketEventObject = ChunkHandler | TDLTSocketEventConnect | ProgressEventHandler | NotificationHandler;
export function indexPcapDlt(
params: IIndexDltParams
): CancelablePromise<void, void, TIndexDltAsyncEvents, TIndexDltAsyncEventObject> {
log('indexPcapDlt');
return new CancelablePromise<
void,
void,
TIndexDltAsyncEvents,
TIndexDltAsyncEventObject
>((resolve, reject, cancel, refCancelCB, self) => {
log(`indexPcapDlt: params: ${JSON.stringify(params)}`);
try {
// Add cancel callback
refCancelCB(() => {
// Cancelation is started, but not canceled
log(`Get command "break" operation. Requesting shutdown.`);
emitter.requestShutdown();
});
// Create channel
const channel = new RustDltPcapChannel(
params.dltFile,
params.tag,
params.out,
params.chunk_size,
params.filterConfig,
params.append,
params.fibex
);
log('created channel');
// Create emitter
const emitter: NativeComputationManager<INeonTransferChunk> = new NativeComputationManager(channel);
log('created emitter');
let chunks: number = 0;
// Add listenters
emitter.onItem((c: INeonTransferChunk) => {
log('received pcap item: ' + JSON.stringify(c));
self.emit('chunk', {
bytesStart: c.b[0],
bytesEnd: c.b[1],
rowsStart: c.r[0],
rowsEnd: c.r[1]
});
chunks += 1;
});
emitter.onProgress((ticks: ITicks) => {
self.emit('progress', ticks);
});
emitter.onStopped(() => {
log('pcap: we got a stopped event after ' + chunks + ' chunks');
cancel();
});
emitter.onNotification((notification: INeonNotification) => {
self.emit('notification', notification);
});
emitter.onFinished(() => {
log('pcap: we got a finished event after ' + chunks + ' chunks');
resolve();
});
// Handle finale of promise
self.finally(() => {
log('processing dlt pcap is finished');
});
} catch (err) {
if (!(err instanceof Error)) {
log(`pcap operation is stopped. Error isn't valid:`);
log(err);
err = new Error(`pcap operation is stopped. Error isn't valid.`);
} else {
log(`pcap: operation is stopped due error: ${err.message}`);
}
// Operation is rejected
reject(err);
}
});
}
export function dltOverSocket(
sessionId: String,
params: IDltSocketParams,
socketConfig: ISocketConfig
): CancelablePromise<void, void, TDLTSocketEvents, TDLTSocketEventObject> {
return new CancelablePromise<
void,
void,
TDLTSocketEvents,
TDLTSocketEventObject
>((resolve, reject, cancel, refCancelCB, self) => {
log(`dltOverSocket: params: ${JSON.stringify(params)}`);
try {
socketConfig.udp_connection_info = socketConfig.target === 'Udp' ? {
multicast_addr: socketConfig.multicast_addr,
} : undefined;
log(`dltOverSocket: using sock-conf: ${JSON.stringify(socketConfig)}`);
// Add cancel callback
refCancelCB(() => {
// Cancelation is started, but not canceled
log(`Get command "break" operation. Starting breaking.`);
emitter.requestShutdown();
});
// Create channel
const channel = new RustDltSocketChannel(
sessionId,
socketConfig,
params.tag,
params.out,
params.filterConfig,
params.fibex
);
// Create emitter
const emitter: NativeComputationManager<INeonTransferChunk> = new NativeComputationManager(channel);
let chunks: number = 0;
// Add listenters
emitter.onItem((c: INeonTransferChunk) => {
log('received over socket: ' + JSON.stringify(c));
if (c.b[0] === 0 && c.b[1] === 0) {
self.emit('connect');
} else {
self.emit('chunk', {
bytesStart: c.b[0],
bytesEnd: c.b[1],
rowsStart: c.r[0],
rowsEnd: c.r[1]
});
chunks += 1;
}
});
emitter.onProgress((ticks: ITicks) => {
self.emit('progress', ticks);
});
emitter.onStopped(() => {
log('we got a stopped event after ' + chunks + ' chunks');
cancel();
});
emitter.onNotification((notification: INeonNotification) => {
self.emit('notification', notification);
});
emitter.onFinished(() => {
log('we got a finished event after ' + chunks + ' chunks');
resolve();
});
// Handle finale of promise
self.finally(() => {
log('processing dlt indexing is finished');
});
} catch (err) {
if (!(err instanceof Error)) {
log(`operation is stopped. Error isn't valid:`);
log(err);
err = new Error(`operation is stopped. Error isn't valid.`);
} else {
log(`operation is stopped due error: ${err.message}`);
}
// Operation is rejected
reject(err);
}
});
}
function getDefaultIndexDltProcessingOptions(options: IIndexDltOptions | undefined): IIndexDltOptionsChecked {
if (typeof options !== 'object' || options === null) {
options = {};
}
return options as IIndexDltOptionsChecked;
}
export type TPcap2DltEvents = 'progress' | 'notification';
export type TPcap2DltsEventObject = ProgressEventHandler | NotificationHandler;
export function pcap2dlt(
pcapFilePath: String,
outFilePath: String
): CancelablePromise<void, void, TPcap2DltEvents, TPcap2DltsEventObject> {
return new CancelablePromise<
void,
void,
TPcap2DltEvents,
TPcap2DltsEventObject
>((resolve, reject, cancel, refCancelCB, self) => {
try {
// Create channel
const channel = new RustDltPcapConverterChannel(pcapFilePath, outFilePath);
// Create emitter
const emitter: NativeComputationManager<void> = new NativeComputationManager(channel);
let chunks: number = 0;
// Add cancel callback
refCancelCB(() => {
emitter.requestShutdown();
});
// Add listenters
emitter.onProgress((ticks: ITicks) => {
self.emit('progress', ticks);
});
emitter.onStopped(() => {
log('Stopped event after ' + chunks + ' chunks');
cancel();
});
emitter.onNotification((notification: INeonNotification) => {
self.emit('notification', notification);
});
emitter.onFinished(() => {
log('Finished event after ' + chunks + ' chunks');
resolve();
});
// Handle finale of promise
self.finally(() => {
log('Operation pcap2dlt is finished');
});
} catch (err) {
if (!(err instanceof Error)) {
log(`Operation stopped. Error isn't valid:`);
log(err);
err = new Error(`Operation stopped. Error isn't valid.`);
} else {
log(`Operation stopped due error: ${err.message}`);
}
// Operation is rejected
reject(err);
}
});
} | the_stack |
import { CommonModule } from '@angular/common';
import {
Component, QueryList, Input, Output, EventEmitter, ContentChild, Directive,
NgModule, TemplateRef, OnInit, AfterViewInit, ContentChildren, OnDestroy, HostBinding, ElementRef, Optional, Inject
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { growVerIn, growVerOut } from '../animations/grow';
import { IgxCheckboxModule } from '../checkbox/checkbox.component';
import { DisplayDensityBase, DisplayDensityToken, IDisplayDensityOptions } from '../core/displayDensity';
import { IgxExpansionPanelModule } from '../expansion-panel/public_api';
import { ToggleAnimationSettings } from '../expansion-panel/toggle-animation-component';
import { IgxIconModule } from '../icon/public_api';
import { IgxInputGroupModule } from '../input-group/public_api';
import { IgxProgressBarModule } from '../progressbar/progressbar.component';
import {
IGX_TREE_COMPONENT, IgxTreeSelectionType, IgxTree, ITreeNodeToggledEventArgs,
ITreeNodeTogglingEventArgs, ITreeNodeSelectionEvent, IgxTreeNode, IgxTreeSearchResolver
} from './common';
import { IgxTreeNavigationService } from './tree-navigation.service';
import { IgxTreeNodeComponent, IgxTreeNodeLinkDirective } from './tree-node/tree-node.component';
import { IgxTreeSelectionService } from './tree-selection.service';
import { IgxTreeService } from './tree.service';
/**
* @hidden @internal
* Used for templating the select marker of the tree
*/
@Directive({
selector: '[igxTreeSelectMarker]'
})
export class IgxTreeSelectMarkerDirective {
}
/**
* @hidden @internal
* Used for templating the expand indicator of the tree
*/
@Directive({
selector: '[igxTreeExpandIndicator]'
})
export class IgxTreeExpandIndicatorDirective {
}
@Component({
selector: 'igx-tree',
templateUrl: 'tree.component.html',
providers: [
IgxTreeService,
IgxTreeSelectionService,
IgxTreeNavigationService,
{ provide: IGX_TREE_COMPONENT, useExisting: IgxTreeComponent },
]
})
export class IgxTreeComponent extends DisplayDensityBase implements IgxTree, OnInit, AfterViewInit, OnDestroy {
@HostBinding('class.igx-tree')
public cssClass = 'igx-tree';
/**
* Gets/Sets tree selection mode
*
* @remarks
* By default the tree selection mode is 'None'
* @param selectionMode: IgxTreeSelectionType
*/
@Input()
public get selection() {
return this._selection;
}
public set selection(selectionMode: IgxTreeSelectionType) {
this._selection = selectionMode;
this.selectionService.clearNodesSelection();
}
/** Get/Set how the tree should handle branch expansion.
* If set to `true`, only a single branch can be expanded at a time, collapsing all others
*
* ```html
* <igx-tree [singleBranchExpand]="true">
* ...
* </igx-tree>
* ```
*
* ```typescript
* const tree: IgxTree = this.tree;
* this.tree.singleBranchExpand = false;
* ```
*/
@Input()
public singleBranchExpand = false;
/** Get/Set the animation settings that branches should use when expanding/collpasing.
*
* ```html
* <igx-tree [animationSettings]="customAnimationSettings">
* </igx-tree>
* ```
*
* ```typescript
* const animationSettings: ToggleAnimationSettings = {
* openAnimation: growVerIn,
* closeAnimation: growVerOut
* };
*
* this.tree.animationSettings = animationSettings;
* ```
*/
@Input()
public animationSettings: ToggleAnimationSettings = {
openAnimation: growVerIn,
closeAnimation: growVerOut
};
/** Emitted when the node selection is changed through interaction
*
* ```html
* <igx-tree (nodeSelection)="handleNodeSelection($event)">
* </igx-tree>
* ```
*
*```typescript
* public handleNodeSelection(event: ITreeNodeSelectionEvent) {
* const newSelection: IgxTreeNode<any>[] = event.newSelection;
* const added: IgxTreeNode<any>[] = event.added;
* console.log("New selection will be: ", newSelection);
* console.log("Added nodes: ", event.added);
* }
*```
*/
@Output()
public nodeSelection = new EventEmitter<ITreeNodeSelectionEvent>();
/** Emitted when a node is expanding, before it finishes
*
* ```html
* <igx-tree (nodeExpanding)="handleNodeExpanding($event)">
* </igx-tree>
* ```
*
*```typescript
* public handleNodeExpanding(event: ITreeNodeTogglingEventArgs) {
* const expandedNode: IgxTreeNode<any> = event.node;
* if (expandedNode.disabled) {
* event.cancel = true;
* }
* }
*```
*/
@Output()
public nodeExpanding = new EventEmitter<ITreeNodeTogglingEventArgs>();
/** Emitted when a node is expanded, after it finishes
*
* ```html
* <igx-tree (nodeExpanded)="handleNodeExpanded($event)">
* </igx-tree>
* ```
*
*```typescript
* public handleNodeExpanded(event: ITreeNodeToggledEventArgs) {
* const expandedNode: IgxTreeNode<any> = event.node;
* console.log("Node is expanded: ", expandedNode.data);
* }
*```
*/
@Output()
public nodeExpanded = new EventEmitter<ITreeNodeToggledEventArgs>();
/** Emitted when a node is collapsing, before it finishes
*
* ```html
* <igx-tree (nodeCollapsing)="handleNodeCollapsing($event)">
* </igx-tree>
* ```
*
*```typescript
* public handleNodeCollapsing(event: ITreeNodeTogglingEventArgs) {
* const collapsedNode: IgxTreeNode<any> = event.node;
* if (collapsedNode.alwaysOpen) {
* event.cancel = true;
* }
* }
*```
*/
@Output()
public nodeCollapsing = new EventEmitter<ITreeNodeTogglingEventArgs>();
/** Emitted when a node is collapsed, after it finishes
*
* @example
* ```html
* <igx-tree (nodeCollapsed)="handleNodeCollapsed($event)">
* </igx-tree>
* ```
* ```typescript
* public handleNodeCollapsed(event: ITreeNodeToggledEventArgs) {
* const collapsedNode: IgxTreeNode<any> = event.node;
* console.log("Node is collapsed: ", collapsedNode.data);
* }
* ```
*/
@Output()
public nodeCollapsed = new EventEmitter<ITreeNodeToggledEventArgs>();
/**
* Emitted when the active node is changed.
*
* @example
* ```
* <igx-tree (activeNodeChanged)="activeNodeChanged($event)"></igx-tree>
* ```
*/
@Output()
public activeNodeChanged = new EventEmitter<IgxTreeNode<any>>();
/**
* A custom template to be used for the expand indicator of nodes
* ```html
* <igx-tree>
* <ng-template igxTreeExpandIndicator let-expanded>
* <igx-icon>{{ expanded ? "close_fullscreen": "open_in_full"}}</igx-icon>
* </ng-template>
* </igx-tree>
* ```
*/
@ContentChild(IgxTreeExpandIndicatorDirective, { read: TemplateRef })
public expandIndicator: TemplateRef<any>;
/** @hidden @internal */
@ContentChildren(IgxTreeNodeComponent, { descendants: true })
public nodes: QueryList<IgxTreeNodeComponent<any>>;
/** @hidden @internal */
public disabledChange = new EventEmitter<IgxTreeNode<any>>();
/**
* Returns all **root level** nodes
*
* ```typescript
* const tree: IgxTree = this.tree;
* const rootNodes: IgxTreeNodeComponent<any>[] = tree.rootNodes;
* ```
*/
public get rootNodes(): IgxTreeNodeComponent<any>[] {
return this.nodes?.filter(node => node.level === 0);
}
/**
* Emitted when the active node is set through API
*
* @hidden @internal
*/
public activeNodeBindingChange = new EventEmitter<IgxTreeNode<any>>();
/** @hidden @internal */
public forceSelect = [];
private _selection: IgxTreeSelectionType = IgxTreeSelectionType.None;
private destroy$ = new Subject<void>();
private unsubChildren$ = new Subject<void>();
constructor(
private navService: IgxTreeNavigationService,
private selectionService: IgxTreeSelectionService,
private treeService: IgxTreeService,
private element: ElementRef<HTMLElement>,
@Optional() @Inject(DisplayDensityToken) protected _displayDensityOptions?: IDisplayDensityOptions) {
super(_displayDensityOptions);
this.selectionService.register(this);
this.treeService.register(this);
this.navService.register(this);
}
/** @hidden @internal */
public get nativeElement() {
return this.element.nativeElement;
}
/**
* Expands all of the passed nodes.
* If no nodes are passed, expands ALL nodes
*
* @param nodes nodes to be expanded
*
* ```typescript
* const targetNodes: IgxTreeNode<any> = this.tree.findNodes(true, (_data: any, node: IgxTreeNode<any>) => node.data.expandable);
* tree.expandAll(nodes);
* ```
*/
public expandAll(nodes?: IgxTreeNode<any>[]) {
nodes = nodes || this.nodes.toArray();
nodes.forEach(e => e.expanded = true);
}
/**
* Collapses all of the passed nodes.
* If no nodes are passed, collapses ALL nodes
*
* @param nodes nodes to be collapsed
*
* ```typescript
* const targetNodes: IgxTreeNode<any> = this.tree.findNodes(true, (_data: any, node: IgxTreeNode<any>) => node.data.collapsible);
* tree.collapseAll(nodes);
* ```
*/
public collapseAll(nodes?: IgxTreeNode<any>[]) {
nodes = nodes || this.nodes.toArray();
nodes.forEach(e => e.expanded = false);
}
/**
* Deselect all nodes if the nodes collection is empty. Otherwise, deselect the nodes in the nodes collection.
*
* @example
* ```typescript
* const arr = [
* this.tree.nodes.toArray()[0],
* this.tree.nodes.toArray()[1]
* ];
* this.tree.deselectAll(arr);
* ```
* @param nodes: IgxTreeNodeComponent<any>[]
*/
public deselectAll(nodes?: IgxTreeNodeComponent<any>[]) {
this.selectionService.deselectNodesWithNoEvent(nodes);
}
/**
* Returns all of the nodes that match the passed searchTerm.
* Accepts a custom comparer function for evaluating the search term against the nodes.
*
* @remark
* Default search compares the passed `searchTerm` against the node's `data` Input.
* When using `findNodes` w/o a `comparer`, make sure all nodes have `data` passed.
*
* @param searchTerm The data of the searched node
* @param comparer A custom comparer function that evaluates the passed `searchTerm` against all nodes.
* @returns Array of nodes that match the search. `null` if no nodes are found.
*
* ```html
* <igx-tree>
* <igx-tree-node *ngFor="let node of data" [data]="node">
* {{ node.label }}
* </igx-tree-node>
* </igx-tree>
* ```
*
* ```typescript
* public data: DataEntry[] = FETCHED_DATA;
* ...
* const matchedNodes: IgxTreeNode<DataEntry>[] = this.tree.findNodes<DataEntry>(searchTerm: data[5]);
* ```
*
* Using a custom comparer
* ```typescript
* public data: DataEntry[] = FETCHED_DATA;
* ...
* const comparer: IgxTreeSearchResolver = (data: any, node: IgxTreeNode<DataEntry>) {
* return node.data.index % 2 === 0;
* }
* const evenIndexNodes: IgxTreeNode<DataEntry>[] = this.tree.findNodes<DataEntry>(null, comparer);
* ```
*/
public findNodes(searchTerm: any, comparer?: IgxTreeSearchResolver): IgxTreeNodeComponent<any>[] | null {
const compareFunc = comparer || this._comparer;
const results = this.nodes.filter(node => compareFunc(searchTerm, node));
return results?.length === 0 ? null : results;
}
/** @hidden @internal */
public handleKeydown(event: KeyboardEvent) {
this.navService.handleKeydown(event);
}
/** @hidden @internal */
public ngOnInit() {
super.ngOnInit();
this.disabledChange.pipe(takeUntil(this.destroy$)).subscribe((e) => {
this.navService.update_disabled_cache(e);
});
this.activeNodeBindingChange.pipe(takeUntil(this.destroy$)).subscribe((node) => {
this.expandToNode(this.navService.activeNode);
this.scrollNodeIntoView(node?.header?.nativeElement);
});
this.onDensityChanged.pipe(takeUntil(this.destroy$)).subscribe(() => {
requestAnimationFrame(() => {
this.scrollNodeIntoView(this.navService.activeNode?.header.nativeElement);
});
});
this.subToCollapsing();
}
/** @hidden @internal */
public ngAfterViewInit() {
this.nodes.changes.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.subToChanges();
});
this.scrollNodeIntoView(this.navService.activeNode?.header?.nativeElement);
this.subToChanges();
}
/** @hidden @internal */
public ngOnDestroy() {
this.unsubChildren$.next();
this.unsubChildren$.complete();
this.destroy$.next();
this.destroy$.complete();
}
private expandToNode(node: IgxTreeNode<any>) {
if (node && node.parentNode) {
node.path.forEach(n => {
if (n !== node && !n.expanded) {
n.expanded = true;
}
});
}
}
private subToCollapsing() {
this.nodeCollapsing.pipe(takeUntil(this.destroy$)).subscribe(event => {
if (event.cancel) {
return;
}
this.navService.update_visible_cache(event.node, false);
});
this.nodeExpanding.pipe(takeUntil(this.destroy$)).subscribe(event => {
if (event.cancel) {
return;
}
this.navService.update_visible_cache(event.node, true);
});
}
private subToChanges() {
this.unsubChildren$.next();
const toBeSelected = [...this.forceSelect];
requestAnimationFrame(() => {
this.selectionService.selectNodesWithNoEvent(toBeSelected);
});
this.forceSelect = [];
this.nodes.forEach(node => {
node.expandedChange.pipe(takeUntil(this.unsubChildren$)).subscribe(nodeState => {
this.navService.update_visible_cache(node, nodeState);
});
node.closeAnimationDone.pipe(takeUntil(this.unsubChildren$)).subscribe(() => {
const targetElement = this.navService.focusedNode?.header.nativeElement;
this.scrollNodeIntoView(targetElement);
});
node.openAnimationDone.pipe(takeUntil(this.unsubChildren$)).subscribe(() => {
const targetElement = this.navService.focusedNode?.header.nativeElement;
this.scrollNodeIntoView(targetElement);
});
});
this.navService.init_invisible_cache();
}
private scrollNodeIntoView(el: HTMLElement) {
if (!el) {
return;
}
const nodeRect = el.getBoundingClientRect();
const treeRect = this.nativeElement.getBoundingClientRect();
const topOffset = treeRect.top > nodeRect.top ? nodeRect.top - treeRect.top : 0;
const bottomOffset = treeRect.bottom < nodeRect.bottom ? nodeRect.bottom - treeRect.bottom : 0;
const shouldScroll = !!topOffset || !!bottomOffset;
if (shouldScroll && this.nativeElement.scrollHeight > this.nativeElement.clientHeight) {
// this.nativeElement.scrollTop = nodeRect.y - treeRect.y - nodeRect.height;
this.nativeElement.scrollTop =
this.nativeElement.scrollTop + bottomOffset + topOffset + (topOffset ? -1 : +1) * nodeRect.height;
}
}
private _comparer = <T>(data: T, node: IgxTreeNodeComponent<T>) => node.data === data;
}
/**
* @hidden
*
* NgModule defining the components and directives needed for `igx-tree`
*/
@NgModule({
declarations: [
IgxTreeSelectMarkerDirective,
IgxTreeExpandIndicatorDirective,
IgxTreeNodeLinkDirective,
IgxTreeComponent,
IgxTreeNodeComponent
],
imports: [
CommonModule,
FormsModule,
IgxIconModule,
IgxInputGroupModule,
IgxCheckboxModule,
IgxProgressBarModule
],
exports: [
IgxTreeSelectMarkerDirective,
IgxTreeExpandIndicatorDirective,
IgxTreeNodeLinkDirective,
IgxTreeComponent,
IgxTreeNodeComponent,
IgxIconModule,
IgxInputGroupModule,
IgxCheckboxModule,
IgxExpansionPanelModule
]
})
export class IgxTreeModule {
} | the_stack |
import {
languages as Languages, Disposable, TextDocument, ProviderResult, Range as VRange, Position as VPosition, TextEdit as VTextEdit, FormattingOptions as VFormattingOptions,
DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider, workspace as Workspace, OnTypeFormattingEditProvider
} from 'vscode';
import {
ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, DocumentHighlightRegistrationOptions, DocumentFormattingOptions, DocumentFormattingRequest, TextDocumentRegistrationOptions, DocumentFormattingParams, DocumentRangeFormattingRegistrationOptions, DocumentRangeFormattingOptions, DocumentRangeFormattingRequest, DocumentRangeFormattingParams, DocumentOnTypeFormattingOptions, DocumentOnTypeFormattingRegistrationOptions, DocumentOnTypeFormattingRequest, DocumentOnTypeFormattingParams} from 'vscode-languageserver-protocol';
import * as UUID from './utils/uuid';
import type * as c2p from './codeConverter';
import { TextDocumentLanguageFeature, FeatureClient, ensure } from './features';
namespace FileFormattingOptions {
export function fromConfiguration(document: TextDocument): c2p.FileFormattingOptions {
const filesConfig = Workspace.getConfiguration('files', document);
return {
trimTrailingWhitespace: filesConfig.get('trimTrailingWhitespace'),
trimFinalNewlines: filesConfig.get('trimFinalNewlines'),
insertFinalNewline: filesConfig.get('insertFinalNewline'),
};
}
}
export interface ProvideDocumentFormattingEditsSignature {
(this: void, document: TextDocument, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideDocumentRangeFormattingEditsSignature {
(this: void, document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideOnTypeFormattingEditsSignature {
(this: void, document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface FormattingMiddleware {
provideDocumentFormattingEdits?: (this: void, document: TextDocument, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideDocumentRangeFormattingEdits?: (this: void, document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentRangeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideOnTypeFormattingEdits?: (this: void, document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken, next: ProvideOnTypeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
}
export class DocumentFormattingFeature extends TextDocumentLanguageFeature<boolean | DocumentFormattingOptions, DocumentHighlightRegistrationOptions, DocumentFormattingEditProvider, FormattingMiddleware> {
constructor(client: FeatureClient<FormattingMiddleware>) {
super(client, DocumentFormattingRequest.type);
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
ensure(ensure(capabilities, 'textDocument')!, 'formatting')!.dynamicRegistration = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider);
if (!options) {
return;
}
this.register({ id: UUID.generateUuid(), registerOptions: options });
}
protected registerLanguageProvider(options: TextDocumentRegistrationOptions): [Disposable, DocumentFormattingEditProvider] {
const selector = options.documentSelector!;
const provider: DocumentFormattingEditProvider = {
provideDocumentFormattingEdits: (document, options, token) => {
const client = this._client;
const provideDocumentFormattingEdits: ProvideDocumentFormattingEditsSignature = (document, options, token) => {
const params: DocumentFormattingParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))
};
return client.sendRequest(DocumentFormattingRequest.type, params, token).then((result) => {
if (token.isCancellationRequested) {
return null;
}
return client.protocol2CodeConverter.asTextEdits(result, token);
}, (error) => {
return client.handleFailedRequest(DocumentFormattingRequest.type, token, error, null);
});
};
const middleware = client.middleware;
return middleware.provideDocumentFormattingEdits
? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits)
: provideDocumentFormattingEdits(document, options, token);
}
};
return [Languages.registerDocumentFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
}
}
export class DocumentRangeFormattingFeature extends TextDocumentLanguageFeature<boolean | DocumentRangeFormattingOptions, DocumentRangeFormattingRegistrationOptions, DocumentRangeFormattingEditProvider, FormattingMiddleware> {
constructor(client: FeatureClient<FormattingMiddleware>) {
super(client, DocumentRangeFormattingRequest.type);
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
ensure(ensure(capabilities, 'textDocument')!, 'rangeFormatting')!.dynamicRegistration = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider);
if (!options) {
return;
}
this.register({ id: UUID.generateUuid(), registerOptions: options });
}
protected registerLanguageProvider(options: TextDocumentRegistrationOptions): [Disposable, DocumentRangeFormattingEditProvider] {
const selector = options.documentSelector!;
const provider: DocumentRangeFormattingEditProvider = {
provideDocumentRangeFormattingEdits: (document, range, options, token) => {
const client = this._client;
const provideDocumentRangeFormattingEdits: ProvideDocumentRangeFormattingEditsSignature = (document, range, options, token) => {
const params: DocumentRangeFormattingParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range),
options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))
};
return client.sendRequest(DocumentRangeFormattingRequest.type, params, token).then((result) => {
if (token.isCancellationRequested) {
return null;
}
return client.protocol2CodeConverter.asTextEdits(result, token);
}, (error) => {
return client.handleFailedRequest(DocumentRangeFormattingRequest.type, token, error, null);
});
};
const middleware = client.middleware;
return middleware.provideDocumentRangeFormattingEdits
? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits)
: provideDocumentRangeFormattingEdits(document, range, options, token);
}
};
return [Languages.registerDocumentRangeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
}
}
export class DocumentOnTypeFormattingFeature extends TextDocumentLanguageFeature<DocumentOnTypeFormattingOptions, DocumentOnTypeFormattingRegistrationOptions, OnTypeFormattingEditProvider, FormattingMiddleware> {
constructor(client: FeatureClient<FormattingMiddleware>) {
super(client, DocumentOnTypeFormattingRequest.type);
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
ensure(ensure(capabilities, 'textDocument')!, 'onTypeFormatting')!.dynamicRegistration = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider);
if (!options) {
return;
}
this.register({ id: UUID.generateUuid(), registerOptions: options });
}
protected registerLanguageProvider(options: DocumentOnTypeFormattingRegistrationOptions): [Disposable, OnTypeFormattingEditProvider] {
const selector = options.documentSelector!;
const provider: OnTypeFormattingEditProvider = {
provideOnTypeFormattingEdits: (document, position, ch, options, token) => {
const client = this._client;
const provideOnTypeFormattingEdits: ProvideOnTypeFormattingEditsSignature = (document, position, ch, options, token) => {
let params: DocumentOnTypeFormattingParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: client.code2ProtocolConverter.asPosition(position),
ch: ch,
options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))
};
return client.sendRequest(DocumentOnTypeFormattingRequest.type, params, token).then((result) => {
if (token.isCancellationRequested) {
return null;
}
return client.protocol2CodeConverter.asTextEdits(result, token);
}, (error) => {
return client.handleFailedRequest(DocumentOnTypeFormattingRequest.type, token, error, null);
});
};
const middleware = client.middleware;
return middleware.provideOnTypeFormattingEdits
? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits)
: provideOnTypeFormattingEdits(document, position, ch, options, token);
}
};
const moreTriggerCharacter = options.moreTriggerCharacter || [];
return [Languages.registerOnTypeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider];
}
} | the_stack |
import { DebugElement } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, flushMicrotasks, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { of, throwError } from 'rxjs';
import {
createDummies,
dispatchMouseEvent,
expectDom,
fastTestSetup,
getVisibleErrorAt,
typeInElement,
} from '../../../../test/helpers';
import { MockDialog } from '../../../../test/mocks/browser';
import { VcsAccountDummy } from '../../../core/dummies';
import { VcsRepositoryNotExistsError } from '../../../core/vcs';
import { GitService, SharedModule } from '../../shared';
import { Dialog } from '../../ui/dialog';
import { MenuItem } from '../../ui/menu';
import { UiModule } from '../../ui/ui.module';
import { VCS_ACCOUNT_DATABASE, VcsAccountDatabase, VcsAccountDatabaseProvider } from '../vcs-account-database';
import { GithubAccountsDialogComponent } from '../vcs-remote';
import { VcsService } from '../vcs.service';
import { VcsSettingsComponent } from './vcs-settings.component';
import Spy = jasmine.Spy;
describe('browser.vcs.vcsSettings.VcsSettingsComponent', () => {
let component: VcsSettingsComponent;
let fixture: ComponentFixture<VcsSettingsComponent>;
let mockDialog: MockDialog;
let accountDB: VcsAccountDatabase;
let vcs: VcsService;
let git: GitService;
const accountDummy = new VcsAccountDummy();
function ignoreAccountsGetting(): void {
component['loadAccounts'] = jasmine.createSpy('private method');
}
function ignoreFetchAccountGetting(): void {
component['getFetchAccountAndPatchFormValueIfExists'] =
jasmine.createSpy('getFetchAccountAndPatchFormValueIfExists private method');
}
function ignoreRemoteUrlGetting(): void {
component['getRemoteUrlAndPatchFormValueIfExists'] =
jasmine.createSpy('getRemoteUrlAndPatchFormValueIfExists private method');
}
const getAccountSelectEl = (): HTMLElement =>
fixture.debugElement.query(By.css('#vcs-remote-setting-github-account-select')).nativeElement;
const getRemoteUrlFormFieldDe = (): DebugElement =>
fixture.debugElement.query(By.css('#vcs-remote-setting-url-form-field'));
const getRemoteUrlInputEl = (): HTMLInputElement =>
fixture.debugElement.query(By.css('#vcs-remote-setting-url-input')).nativeElement as HTMLInputElement;
const getSaveRemoteButtonEl = (): HTMLButtonElement =>
fixture.debugElement.query(By.css('.VcsSettings__saveRemoteButton')).nativeElement as HTMLButtonElement;
const getSaveRemoteResultMessageEl = (): HTMLElement =>
fixture.debugElement.query(By.css('.VcsSettings__saveRemoteResultMessage')).nativeElement as HTMLElement;
fastTestSetup();
beforeAll(async () => {
mockDialog = new MockDialog();
vcs = jasmine.createSpyObj('vcs', [
'setRemoveProvider',
'isRemoteRepositoryUrlValid',
'findRemoteRepository',
'setRemoteRepository',
'getRepositoryFetchAccount',
'getRemoteRepositoryUrl',
]);
(vcs.setRemoveProvider as Spy).and.returnValue(vcs);
await TestBed
.configureTestingModule({
imports: [
UiModule,
SharedModule,
],
providers: [
VcsAccountDatabaseProvider,
{ provide: VcsService, useValue: vcs },
],
declarations: [
VcsSettingsComponent,
],
})
.overrideComponent(VcsSettingsComponent, {
set: {
providers: [{ provide: Dialog, useValue: mockDialog }],
},
})
.compileComponents();
});
beforeEach(() => {
accountDB = TestBed.get(VCS_ACCOUNT_DATABASE);
git = TestBed.get(GitService);
fixture = TestBed.createComponent(VcsSettingsComponent);
component = fixture.componentInstance;
});
afterEach(async () => {
await accountDB.accounts.clear();
});
describe('remote setting', () => {
it('should get all accounts from account database on ngOnInit.', fakeAsync(() => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
const accounts = createDummies(accountDummy, 10);
spyOn(accountDB, 'getAllAccounts').and.returnValue(Promise.resolve(accounts));
// Expect to fetch accounts.
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(component.accountMenuItems).toEqual(accounts.map(account => ({
id: account.email,
label: `${account.name} <${account.email}>`,
} as MenuItem)));
}));
// FIXME LATER
xit('should open github accounts dialog when click \'add account\' button. After dialog '
+ 'closed, should reload all accounts from account database.', fakeAsync(() => {
const prevAccounts = createDummies(accountDummy, 5);
spyOn(accountDB, 'getAllAccounts').and.returnValue(Promise.resolve(prevAccounts));
fixture.detectChanges();
flushMicrotasks();
fixture.detectChanges();
expect(component.accountMenuItems).toEqual(prevAccounts.map(account => ({
id: account.email,
label: `${account.name} <${account.email}>`,
} as MenuItem)));
// First, we should open menu...
const menuTriggerEl = getAccountSelectEl();
dispatchMouseEvent(menuTriggerEl, 'mousedown');
menuTriggerEl.click();
tick();
fixture.detectChanges();
// Click add account button
const addAccountButtonEl = document.querySelector('#add-github-account-button') as HTMLButtonElement;
console.log(addAccountButtonEl);
addAccountButtonEl.click();
tick(500);
fixture.detectChanges();
const githubAccountsDialogRef = mockDialog.getByComponent<GithubAccountsDialogComponent>(
GithubAccountsDialogComponent,
);
expect(githubAccountsDialogRef).toBeDefined();
const nextAccounts = [...prevAccounts, ...createDummies(accountDummy, 5)];
(accountDB.getAllAccounts as jasmine.Spy).and.returnValue(Promise.resolve(nextAccounts));
githubAccountsDialogRef.close();
flushMicrotasks();
fixture.detectChanges();
expect(component.accountMenuItems).toEqual(nextAccounts.map(account => ({
id: account.email,
label: `${account.name} <${account.email}>`,
} as MenuItem)));
}));
it('should save remote button is disabled if github account is not selected.', () => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
(vcs.isRemoteRepositoryUrlValid as Spy).and.returnValue(true);
// Github Account: invalid, Remote URL: valid
typeInElement('https://github.com/seokju-na/geeks-diary', getRemoteUrlInputEl());
component.remoteSettingForm.get('githubAccount').patchValue(null);
fixture.detectChanges();
expectDom(getSaveRemoteButtonEl()).toBeDisabled();
});
it('should save remote button is disabled if remote url is not input.', () => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
// Github Account: valid, Remote URL: invalid
component.remoteSettingForm.get('githubAccount').patchValue(accountDummy.create());
typeInElement('', getRemoteUrlInputEl());
fixture.detectChanges();
expectDom(getSaveRemoteButtonEl()).toBeDisabled();
});
it('should save remote button is disabled if remote url is not valid.', () => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
(vcs.isRemoteRepositoryUrlValid as Spy).and.returnValue(false);
// Github Account: valid, Remote URL: invalid
component.remoteSettingForm.get('githubAccount').patchValue(accountDummy.create());
typeInElement('not_valid_url', getRemoteUrlInputEl());
fixture.detectChanges();
expectDom(getSaveRemoteButtonEl()).toBeDisabled();
});
it('should save remote button is not disabled if github account is selected and '
+ 'remote url is valid.', () => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
(vcs.isRemoteRepositoryUrlValid as Spy).and.returnValue(true);
component.remoteSettingForm.get('githubAccount').patchValue(accountDummy.create());
typeInElement('https://github.com/seokju-na/geeks-diary', getRemoteUrlInputEl());
fixture.detectChanges();
expectDom(getSaveRemoteButtonEl()).not.toBeDisabled();
});
it('should show repository not exists error if repository not exists in remote provider '
+ 'when submit remote setting form.', fakeAsync(() => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
const fetchAccount = accountDummy.create();
const remoteUrl = 'https://github.com/seokju-na/geeks-diary.git';
component.remoteSettingForm.patchValue({
githubAccount: fetchAccount,
remoteUrl,
});
fixture.detectChanges();
(vcs.findRemoteRepository as Spy).and.returnValue(throwError(new VcsRepositoryNotExistsError()));
getSaveRemoteButtonEl().click();
flush();
fixture.detectChanges();
expect(vcs.findRemoteRepository).toHaveBeenCalledWith(remoteUrl, fetchAccount.authentication);
expect(getVisibleErrorAt(getRemoteUrlFormFieldDe()).errorName).toEqual('repositoryNotExists');
}));
it('should show success message if set remote repository success when submit '
+ 'remote settings form.', fakeAsync(() => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
const fetchAccount = accountDummy.create();
const remoteUrl = 'https://github.com/seokju-na/geeks-diary.git';
component.remoteSettingForm.patchValue({
githubAccount: fetchAccount,
remoteUrl,
});
fixture.detectChanges();
(vcs.findRemoteRepository as Spy).and.returnValue(of(null));
(vcs.setRemoteRepository as Spy).and.returnValue(of(null));
getSaveRemoteButtonEl().click();
flush();
fixture.detectChanges();
expect(vcs.setRemoteRepository).toHaveBeenCalledWith(fetchAccount, remoteUrl);
expectDom(getSaveRemoteResultMessageEl())
.toContainClasses('VcsSettings__saveRemoteResultMessage--success');
expectDom(getSaveRemoteResultMessageEl())
.toContainText(component.saveRemoteResultMessage);
}));
it('should show fail message if set remote repository fail when submit '
+ 'remote setting form', fakeAsync(() => {
ignoreFetchAccountGetting();
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
fixture.detectChanges();
const fetchAccount = accountDummy.create();
const remoteUrl = 'https://github.com/seokju-na/geeks-diary.git';
component.remoteSettingForm.patchValue({
githubAccount: fetchAccount,
remoteUrl,
});
fixture.detectChanges();
(vcs.findRemoteRepository as Spy).and.returnValue(of(null));
(vcs.setRemoteRepository as Spy).and.returnValue(throwError(new Error('Some Error')));
getSaveRemoteButtonEl().click();
flush();
fixture.detectChanges();
expect(vcs.setRemoteRepository).toHaveBeenCalledWith(fetchAccount, remoteUrl);
expectDom(getSaveRemoteResultMessageEl())
.toContainClasses('VcsSettings__saveRemoteResultMessage--fail');
expectDom(getSaveRemoteResultMessageEl())
.toContainText(component.saveRemoteResultMessage);
}));
it('should set github account if fetch repository account is exists on ngOnInit.', () => {
ignoreRemoteUrlGetting();
ignoreAccountsGetting();
const fetchAccount = accountDummy.create();
(vcs.getRepositoryFetchAccount as Spy).and.returnValue(of(fetchAccount));
fixture.detectChanges();
expect(component.remoteSettingForm.get('githubAccount').value).toEqual(fetchAccount);
});
it('should set remote url if remote url is exists on ngOnInit.', () => {
ignoreFetchAccountGetting();
ignoreAccountsGetting();
const remoteUrl = 'https://github.com/seokju-na/geeks-diary.git';
(vcs.getRemoteRepositoryUrl as Spy).and.returnValue(of(remoteUrl));
fixture.detectChanges();
expect(component.remoteSettingForm.get('remoteUrl').value).toEqual(remoteUrl);
});
});
}); | the_stack |
/////////////////////////////
/// ECMAScript APIs
/////////////////////////////
declare var NaN: number;
declare var Infinity: number;
/**
* Evaluates JavaScript code and executes it.
* @param x A String value that contains valid JavaScript code.
*/
declare function eval(x: string): any;
/**
* Converts a string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
declare function parseInt(s: string, radix?: number): number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
declare function parseFloat(string: string): number;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).
* @param number A numeric value.
*/
declare function isNaN(number: number): boolean;
/**
* Determines whether a supplied number is finite.
* @param number Any numeric value.
*/
declare function isFinite(number: number): boolean;
/**
* Gets the unencoded version of an encoded Uniform Resource Identifier (URI).
* @param encodedURI A value representing an encoded URI.
*/
declare function decodeURI(encodedURI: string): string;
/**
* Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).
* @param encodedURIComponent A value representing an encoded URI component.
*/
declare function decodeURIComponent(encodedURIComponent: string): string;
/**
* Encodes a text string as a valid Uniform Resource Identifier (URI)
* @param uri A value representing an encoded URI.
*/
declare function encodeURI(uri: string): string;
/**
* Encodes a text string as a valid component of a Uniform Resource Identifier (URI).
* @param uriComponent A value representing an encoded URI component.
*/
declare function encodeURIComponent(uriComponent: string | number | boolean): string;
/**
* Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.
* @param string A string value
*/
declare function escape(string: string): string;
/**
* Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.
* @param string A string value
*/
declare function unescape(string: string): string;
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): symbol;
}
declare type PropertyKey = string | number | symbol;
interface PropertyDescriptor {
configurable?: boolean;
enumerable?: boolean;
value?: any;
writable?: boolean;
get?(): any;
set?(v: any): void;
}
interface PropertyDescriptorMap {
[s: string]: PropertyDescriptor;
}
interface Object {
/** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */
constructor: Function;
/** Returns a string representation of an object. */
toString(): string;
/** Returns a date converted to a string using the current locale. */
toLocaleString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean;
/**
* Determines whether an object exists in another object's prototype chain.
* @param v Another object whose prototype chain is to be checked.
*/
isPrototypeOf(v: Object): boolean;
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
new(value?: any): Object;
(): any;
(value: any): any;
/** A reference to the prototype for a class of objects. */
readonly prototype: Object;
/**
* Returns the prototype of an object.
* @param o The object that references the prototype.
*/
getPrototypeOf(o: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined;
/**
* Returns the names of the own properties of an object. The own properties of an object are those that are defined directly
* on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.
* @param o Object that contains the own properties.
*/
getOwnPropertyNames(o: any): string[];
/**
* Creates an object that has the specified prototype or that has null prototype.
* @param o Object to use as a prototype. May be null.
*/
create(o: object | null): any;
/**
* Creates an object that has the specified prototype, and that optionally contains specified properties.
* @param o Object to use as a prototype. May be null
* @param properties JavaScript object that contains one or more property descriptors.
*/
create(o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor property.
*/
defineProperty(o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>): any;
/**
* Adds one or more properties to an object, and/or modifies attributes of existing properties.
* @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.
* @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.
*/
defineProperties(o: any, properties: PropertyDescriptorMap & ThisType<any>): any;
/**
* Prevents the modification of attributes of existing properties, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
seal<T>(o: T): T;
/**
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(a: T[]): readonly T[];
/**
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T extends Function>(f: T): T;
/**
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(o: T): Readonly<T>;
/**
* Prevents the addition of new properties to an object.
* @param o Object to make non-extensible.
*/
preventExtensions<T>(o: T): T;
/**
* Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.
* @param o Object to test.
*/
isSealed(o: any): boolean;
/**
* Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.
* @param o Object to test.
*/
isFrozen(o: any): boolean;
/**
* Returns a value that indicates whether new properties can be added to an object.
* @param o Object to test.
*/
isExtensible(o: any): boolean;
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
keys(o: object): string[];
}
/**
* Provides functionality common to all JavaScript objects.
*/
declare var Object: ObjectConstructor;
/**
* Creates a new function.
*/
interface Function {
/**
* Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(this: Function, thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(this: Function, thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
// Non-standard extensions
arguments: any;
caller: Function;
}
interface FunctionConstructor {
/**
* Creates a new function.
* @param args A list of arguments the function accepts.
*/
new(...args: string[]): Function;
(...args: string[]): Function;
readonly prototype: Function;
}
declare var Function: FunctionConstructor;
/**
* Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
*/
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
/**
* Removes the 'this' parameter from a function type.
*/
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;
interface CallableFunction extends Function {
/**
* Calls the function with the specified object as the this value and the elements of specified array as the arguments.
* @param thisArg The object to be used as the this object.
* @param args An array of argument values to be passed to the function.
*/
apply<T, R>(this: (this: T) => R, thisArg: T): R;
apply<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T, args: A): R;
/**
* Calls the function with the specified object as the this value and the specified rest arguments as the arguments.
* @param thisArg The object to be used as the this object.
* @param args Argument values to be passed to the function.
*/
call<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R;
/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg The object to be used as the this object.
* @param args Arguments to bind to the parameters of the function.
*/
bind<T>(this: T, thisArg: ThisParameterType<T>): OmitThisParameter<T>;
bind<T, A0, A extends any[], R>(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R;
bind<T, A0, A1, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R;
bind<T, A0, A1, A2, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R;
bind<T, A0, A1, A2, A3, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R;
bind<T, AX, R>(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R;
}
interface NewableFunction extends Function {
/**
* Calls the function with the specified object as the this value and the elements of specified array as the arguments.
* @param thisArg The object to be used as the this object.
* @param args An array of argument values to be passed to the function.
*/
apply<T>(this: new () => T, thisArg: T): void;
apply<T, A extends any[]>(this: new (...args: A) => T, thisArg: T, args: A): void;
/**
* Calls the function with the specified object as the this value and the specified rest arguments as the arguments.
* @param thisArg The object to be used as the this object.
* @param args Argument values to be passed to the function.
*/
call<T, A extends any[]>(this: new (...args: A) => T, thisArg: T, ...args: A): void;
/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg The object to be used as the this object.
* @param args Arguments to bind to the parameters of the function.
*/
bind<T>(this: T, thisArg: any): T;
bind<A0, A extends any[], R>(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R;
bind<A0, A1, A extends any[], R>(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R;
bind<A0, A1, A2, A extends any[], R>(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R;
bind<A0, A1, A2, A3, A extends any[], R>(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R;
bind<AX, R>(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R;
}
interface IArguments {
[index: number]: any;
length: number;
callee: Function;
}
interface String {
/** Returns a string representation of a string. */
toString(): string;
/**
* Returns the character at the specified index.
* @param pos The zero-based index of the desired character.
*/
charAt(pos: number): string;
/**
* Returns the Unicode value of the character at the specified location.
* @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.
*/
charCodeAt(index: number): number;
/**
* Returns a string that contains the concatenation of two or more strings.
* @param strings The strings to append to the end of the string.
*/
concat(...strings: string[]): string;
/**
* Returns the position of the first occurrence of a substring.
* @param searchString The substring to search for in the string
* @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.
*/
indexOf(searchString: string, position?: number): number;
/**
* Returns the last occurrence of a substring in the string.
* @param searchString The substring to search for.
* @param position The index at which to begin searching. If omitted, the search begins at the end of the string.
*/
lastIndexOf(searchString: string, position?: number): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
*/
localeCompare(that: string): number;
/**
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
match(regexp: string | RegExp): RegExpMatchArray | null;
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A string to search for.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: string | RegExp, replaceValue: string): string;
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A string to search for.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param regexp The regular expression pattern and applicable flags.
*/
search(regexp: string | RegExp): number;
/**
* Returns a section of a string.
* @param start The index to the beginning of the specified portion of stringObj.
* @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.
* If this value is not specified, the substring continues to the end of stringObj.
*/
slice(start?: number, end?: number): string;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(separator: string | RegExp, limit?: number): string[];
/**
* Returns the substring at the specified location within a String object.
* @param start The zero-based index number indicating the beginning of the substring.
* @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.
* If end is omitted, the characters from start through the end of the original string are returned.
*/
substring(start: number, end?: number): string;
/** Converts all the alphabetic characters in a string to lowercase. */
toLowerCase(): string;
/** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */
toLocaleLowerCase(locales?: string | string[]): string;
/** Converts all the alphabetic characters in a string to uppercase. */
toUpperCase(): string;
/** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */
toLocaleUpperCase(locales?: string | string[]): string;
/** Removes the leading and trailing white space and line terminator characters from a string. */
trim(): string;
/** Returns the length of a String object. */
readonly length: number;
// IE extensions
/**
* Gets a substring beginning at the specified location and having the specified length.
* @param from The starting position of the desired substring. The index of the first character in the string is zero.
* @param length The number of characters to include in the returned substring.
*/
substr(from: number, length?: number): string;
/** Returns the primitive value of the specified object. */
valueOf(): string;
readonly [index: number]: string;
}
interface StringConstructor {
new(value?: any): String;
(value?: any): string;
readonly prototype: String;
fromCharCode(...codes: number[]): string;
}
/**
* Allows manipulation and formatting of text strings and determination and location of substrings within strings.
*/
declare var String: StringConstructor;
interface Boolean {
/** Returns the primitive value of the specified object. */
valueOf(): boolean;
}
interface BooleanConstructor {
new(value?: any): Boolean;
<T>(value?: T): boolean;
readonly prototype: Boolean;
}
declare var Boolean: BooleanConstructor;
interface Number {
/**
* Returns a string representation of an object.
* @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.
*/
toString(radix?: number): string;
/**
* Returns a string representing a number in fixed-point notation.
* @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
*/
toFixed(fractionDigits?: number): string;
/**
* Returns a string containing a number represented in exponential notation.
* @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
*/
toExponential(fractionDigits?: number): string;
/**
* Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.
* @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.
*/
toPrecision(precision?: number): string;
/** Returns the primitive value of the specified object. */
valueOf(): number;
}
interface NumberConstructor {
new(value?: any): Number;
(value?: any): number;
readonly prototype: Number;
/** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */
readonly MAX_VALUE: number;
/** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */
readonly MIN_VALUE: number;
/**
* A value that is not a number.
* In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.
*/
readonly NaN: number;
/**
* A value that is less than the largest negative number that can be represented in JavaScript.
* JavaScript displays NEGATIVE_INFINITY values as -infinity.
*/
readonly NEGATIVE_INFINITY: number;
/**
* A value greater than the largest number that can be represented in JavaScript.
* JavaScript displays POSITIVE_INFINITY values as infinity.
*/
readonly POSITIVE_INFINITY: number;
}
/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */
declare var Number: NumberConstructor;
interface TemplateStringsArray extends ReadonlyArray<string> {
readonly raw: readonly string[];
}
/**
* The type of `import.meta`.
*
* If you need to declare that a given property exists on `import.meta`,
* this type may be augmented via interface merging.
*/
interface ImportMeta {
}
interface Math {
/** The mathematical constant e. This is Euler's number, the base of natural logarithms. */
readonly E: number;
/** The natural logarithm of 10. */
readonly LN10: number;
/** The natural logarithm of 2. */
readonly LN2: number;
/** The base-2 logarithm of e. */
readonly LOG2E: number;
/** The base-10 logarithm of e. */
readonly LOG10E: number;
/** Pi. This is the ratio of the circumference of a circle to its diameter. */
readonly PI: number;
/** The square root of 0.5, or, equivalently, one divided by the square root of 2. */
readonly SQRT1_2: number;
/** The square root of 2. */
readonly SQRT2: number;
/**
* Returns the absolute value of a number (the value without regard to whether it is positive or negative).
* For example, the absolute value of -5 is the same as the absolute value of 5.
* @param x A numeric expression for which the absolute value is needed.
*/
abs(x: number): number;
/**
* Returns the arc cosine (or inverse cosine) of a number.
* @param x A numeric expression.
*/
acos(x: number): number;
/**
* Returns the arcsine of a number.
* @param x A numeric expression.
*/
asin(x: number): number;
/**
* Returns the arctangent of a number.
* @param x A numeric expression for which the arctangent is needed.
*/
atan(x: number): number;
/**
* Returns the angle (in radians) from the X axis to a point.
* @param y A numeric expression representing the cartesian y-coordinate.
* @param x A numeric expression representing the cartesian x-coordinate.
*/
atan2(y: number, x: number): number;
/**
* Returns the smallest integer greater than or equal to its numeric argument.
* @param x A numeric expression.
*/
ceil(x: number): number;
/**
* Returns the cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cos(x: number): number;
/**
* Returns e (the base of natural logarithms) raised to a power.
* @param x A numeric expression representing the power of e.
*/
exp(x: number): number;
/**
* Returns the greatest integer less than or equal to its numeric argument.
* @param x A numeric expression.
*/
floor(x: number): number;
/**
* Returns the natural logarithm (base e) of a number.
* @param x A numeric expression.
*/
log(x: number): number;
/**
* Returns the larger of a set of supplied numeric expressions.
* @param values Numeric expressions to be evaluated.
*/
max(...values: number[]): number;
/**
* Returns the smaller of a set of supplied numeric expressions.
* @param values Numeric expressions to be evaluated.
*/
min(...values: number[]): number;
/**
* Returns the value of a base expression taken to a specified power.
* @param x The base value of the expression.
* @param y The exponent value of the expression.
*/
pow(x: number, y: number): number;
/** Returns a pseudorandom number between 0 and 1. */
random(): number;
/**
* Returns a supplied numeric expression rounded to the nearest integer.
* @param x The value to be rounded to the nearest integer.
*/
round(x: number): number;
/**
* Returns the sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sin(x: number): number;
/**
* Returns the square root of a number.
* @param x A numeric expression.
*/
sqrt(x: number): number;
/**
* Returns the tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tan(x: number): number;
}
/** An intrinsic object that provides basic mathematics functionality and constants. */
declare var Math: Math;
/** Enables basic storage and retrieval of dates and times. */
interface Date {
/** Returns a string representation of a date. The format of the string depends on the locale. */
toString(): string;
/** Returns a date as a string value. */
toDateString(): string;
/** Returns a time as a string value. */
toTimeString(): string;
/** Returns a value as a string value appropriate to the host environment's current locale. */
toLocaleString(): string;
/** Returns a date as a string value appropriate to the host environment's current locale. */
toLocaleDateString(): string;
/** Returns a time as a string value appropriate to the host environment's current locale. */
toLocaleTimeString(): string;
/** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
valueOf(): number;
/** Gets the time value in milliseconds. */
getTime(): number;
/** Gets the year, using local time. */
getFullYear(): number;
/** Gets the year using Universal Coordinated Time (UTC). */
getUTCFullYear(): number;
/** Gets the month, using local time. */
getMonth(): number;
/** Gets the month of a Date object using Universal Coordinated Time (UTC). */
getUTCMonth(): number;
/** Gets the day-of-the-month, using local time. */
getDate(): number;
/** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
getUTCDate(): number;
/** Gets the day of the week, using local time. */
getDay(): number;
/** Gets the day of the week using Universal Coordinated Time (UTC). */
getUTCDay(): number;
/** Gets the hours in a date, using local time. */
getHours(): number;
/** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
getUTCHours(): number;
/** Gets the minutes of a Date object, using local time. */
getMinutes(): number;
/** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
getUTCMinutes(): number;
/** Gets the seconds of a Date object, using local time. */
getSeconds(): number;
/** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
getUTCSeconds(): number;
/** Gets the milliseconds of a Date, using local time. */
getMilliseconds(): number;
/** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
getUTCMilliseconds(): number;
/** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
getTimezoneOffset(): number;
/**
* Sets the date and time value in the Date object.
* @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
*/
setTime(time: number): number;
/**
* Sets the milliseconds value in the Date object using local time.
* @param ms A numeric value equal to the millisecond value.
*/
setMilliseconds(ms: number): number;
/**
* Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
* @param ms A numeric value equal to the millisecond value.
*/
setUTCMilliseconds(ms: number): number;
/**
* Sets the seconds value in the Date object using local time.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setSeconds(sec: number, ms?: number): number;
/**
* Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCSeconds(sec: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using local time.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the hour value in the Date object using local time.
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the hours value in the Date object using Universal Coordinated Time (UTC).
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the numeric day-of-the-month value of the Date object using local time.
* @param date A numeric value equal to the day of the month.
*/
setDate(date: number): number;
/**
* Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
* @param date A numeric value equal to the day of the month.
*/
setUTCDate(date: number): number;
/**
* Sets the month value in the Date object using local time.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
*/
setMonth(month: number, date?: number): number;
/**
* Sets the month value in the Date object using Universal Coordinated Time (UTC).
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
*/
setUTCMonth(month: number, date?: number): number;
/**
* Sets the year of the Date object using local time.
* @param year A numeric value for the year.
* @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
* @param date A numeric value equal for the day of the month.
*/
setFullYear(year: number, month?: number, date?: number): number;
/**
* Sets the year value in the Date object using Universal Coordinated Time (UTC).
* @param year A numeric value equal to the year.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
* @param date A numeric value equal to the day of the month.
*/
setUTCFullYear(year: number, month?: number, date?: number): number;
/** Returns a date converted to a string using Universal Coordinated Time (UTC). */
toUTCString(): string;
/** Returns a date as a string value in ISO format. */
toISOString(): string;
/** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
toJSON(key?: any): string;
}
interface DateConstructor {
new(): Date;
new(value: number | string): Date;
new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;
(): string;
readonly prototype: Date;
/**
* Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.
* @param s A date string
*/
parse(s: string): number;
/**
* Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.
* @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.
* @param month The month as a number between 0 and 11 (January to December).
* @param date The date as a number between 1 and 31.
* @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.
* @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.
* @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.
* @param ms A number from 0 to 999 that specifies the milliseconds.
*/
UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
now(): number;
}
declare var Date: DateConstructor;
interface RegExpMatchArray extends Array<string> {
index?: number;
input?: string;
}
interface RegExpExecArray extends Array<string> {
index: number;
input: string;
}
interface RegExp {
/**
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/
exec(string: string): RegExpExecArray | null;
/**
* Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
* @param string String on which to perform the search.
*/
test(string: string): boolean;
/** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */
readonly source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
readonly global: boolean;
/** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */
readonly ignoreCase: boolean;
/** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */
readonly multiline: boolean;
lastIndex: number;
// Non-standard extensions
compile(): this;
}
interface RegExpConstructor {
new(pattern: RegExp | string): RegExp;
new(pattern: string, flags?: string): RegExp;
(pattern: RegExp | string): RegExp;
(pattern: string, flags?: string): RegExp;
readonly prototype: RegExp;
// Non-standard extensions
$1: string;
$2: string;
$3: string;
$4: string;
$5: string;
$6: string;
$7: string;
$8: string;
$9: string;
lastMatch: string;
}
declare var RegExp: RegExpConstructor;
interface Error {
name: string;
message: string;
stack?: string;
}
interface ErrorConstructor {
new(message?: string): Error;
(message?: string): Error;
readonly prototype: Error;
}
declare var Error: ErrorConstructor;
interface EvalError extends Error {
}
interface EvalErrorConstructor extends ErrorConstructor {
new(message?: string): EvalError;
(message?: string): EvalError;
readonly prototype: EvalError;
}
declare var EvalError: EvalErrorConstructor;
interface RangeError extends Error {
}
interface RangeErrorConstructor extends ErrorConstructor {
new(message?: string): RangeError;
(message?: string): RangeError;
readonly prototype: RangeError;
}
declare var RangeError: RangeErrorConstructor;
interface ReferenceError extends Error {
}
interface ReferenceErrorConstructor extends ErrorConstructor {
new(message?: string): ReferenceError;
(message?: string): ReferenceError;
readonly prototype: ReferenceError;
}
declare var ReferenceError: ReferenceErrorConstructor;
interface SyntaxError extends Error {
}
interface SyntaxErrorConstructor extends ErrorConstructor {
new(message?: string): SyntaxError;
(message?: string): SyntaxError;
readonly prototype: SyntaxError;
}
declare var SyntaxError: SyntaxErrorConstructor;
interface TypeError extends Error {
}
interface TypeErrorConstructor extends ErrorConstructor {
new(message?: string): TypeError;
(message?: string): TypeError;
readonly prototype: TypeError;
}
declare var TypeError: TypeErrorConstructor;
interface URIError extends Error {
}
interface URIErrorConstructor extends ErrorConstructor {
new(message?: string): URIError;
(message?: string): URIError;
readonly prototype: URIError;
}
declare var URIError: URIErrorConstructor;
interface JSON {
/**
* Converts a JavaScript Object Notation (JSON) string into an object.
* @param text A valid JSON string.
* @param reviver A function that transforms the results. This function is called for each member of the object.
* If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
*/
declare var JSON: JSON;
/////////////////////////////
/// ECMAScript Array API (specially handled by compiler)
/////////////////////////////
interface ReadonlyArray<T> {
/**
* Gets the length of the array. This is a number one higher than the highest element defined in an array.
*/
readonly length: number;
/**
* Returns a string representation of an array.
*/
toString(): string;
/**
* Returns a string representation of an array. The elements are converted to string using their toLocalString methods.
*/
toLocaleString(): string;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: ConcatArray<T>[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T | ConcatArray<T>)[]): T[];
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): T[];
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
*/
indexOf(searchElement: T, fromIndex?: number): number;
/**
* Returns the index of the last occurrence of a specified value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
*/
lastIndexOf(searchElement: T, fromIndex?: number): number;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter<S extends T>(callbackfn: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T;
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T;
reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T;
/**
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U;
readonly [n: number]: T;
}
interface ConcatArray<T> {
readonly length: number;
readonly [n: number]: T;
join(separator?: string): string;
slice(start?: number, end?: number): T[];
}
interface Array<T> {
/**
* Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
*/
length: number;
/**
* Returns a string representation of an array.
*/
toString(): string;
/**
* Returns a string representation of an array. The elements are converted to string using their toLocalString methods.
*/
toLocaleString(): string;
/**
* Removes the last element from an array and returns it.
*/
pop(): T | undefined;
/**
* Appends new elements to an array, and returns the new length of the array.
* @param items New elements of the Array.
*/
push(...items: T[]): number;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: ConcatArray<T>[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T | ConcatArray<T>)[]): T[];
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Reverses the elements in an Array.
*/
reverse(): T[];
/**
* Removes the first element from an array and returns it.
*/
shift(): T | undefined;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): T[];
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: T, b: T) => number): this;
/**
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
*/
splice(start: number, deleteCount?: number): T[];
/**
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @param items Elements to insert into the array in place of the deleted elements.
*/
splice(start: number, deleteCount: number, ...items: T[]): T[];
/**
* Inserts new elements at the start of an array.
* @param items Elements to insert at the start of the Array.
*/
unshift(...items: T[]): number;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
*/
indexOf(searchElement: T, fromIndex?: number): number;
/**
* Returns the index of the last occurrence of a specified value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
*/
lastIndexOf(searchElement: T, fromIndex?: number): number;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
/**
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
[n: number]: T;
}
interface ArrayConstructor {
new(arrayLength?: number): any[];
new <T>(arrayLength: number): T[];
new <T>(...items: T[]): T[];
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
isArray(arg: any): arg is any[];
readonly prototype: any[];
}
declare var Array: ArrayConstructor;
interface TypedPropertyDescriptor<T> {
enumerable?: boolean;
configurable?: boolean;
writable?: boolean;
value?: T;
get?: () => T;
set?: (value: T) => void;
}
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
}
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
interface ArrayLike<T> {
readonly length: number;
readonly [n: number]: T;
}
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T required
*/
type Required<T> = {
[P in keyof T]-?: T[P];
};
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T, pick a set of properties whose keys are in the union K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
/**
* Exclude from T those types that are assignable to U
*/
type Exclude<T, U> = T extends U ? never : T;
/**
* Extract from T those types that are assignable to U
*/
type Extract<T, U> = T extends U ? T : never;
/**
* Construct a type with the properties of T except for those in type K.
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
/**
* Obtain the parameters of a function type in a tuple
*/
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
/**
* Obtain the parameters of a constructor function type in a tuple
*/
type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;
/**
* Obtain the return type of a function type
*/
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
/**
* Obtain the return type of a constructor function type
*/
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
/**
* Marker for contextual 'this' type
*/
interface ThisType<T> { }
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
/**
* Read-only. The length of the ArrayBuffer (in bytes).
*/
readonly byteLength: number;
/**
* Returns a section of an ArrayBuffer.
*/
slice(begin: number, end?: number): ArrayBuffer;
}
/**
* Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.
*/
interface ArrayBufferTypes {
ArrayBuffer: ArrayBuffer;
}
type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];
interface ArrayBufferConstructor {
readonly prototype: ArrayBuffer;
new(byteLength: number): ArrayBuffer;
isView(arg: any): arg is ArrayBufferView;
}
declare var ArrayBuffer: ArrayBufferConstructor;
interface ArrayBufferView {
/**
* The ArrayBuffer instance referenced by the array.
*/
buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
byteLength: number;
/**
* The offset in bytes of the array.
*/
byteOffset: number;
}
interface DataView {
readonly buffer: ArrayBuffer;
readonly byteLength: number;
readonly byteOffset: number;
/**
* Gets the Float32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat32(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Float64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat64(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Int8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt8(byteOffset: number): number;
/**
* Gets the Int16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt16(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Int32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt32(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Uint8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint8(byteOffset: number): number;
/**
* Gets the Uint16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint16(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Uint32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint32(byteOffset: number, littleEndian?: boolean): number;
/**
* Stores an Float32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Float64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Int8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setInt8(byteOffset: number, value: number): void;
/**
* Stores an Int16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Int32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Uint8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setUint8(byteOffset: number, value: number): void;
/**
* Stores an Uint16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Uint32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;
}
interface DataViewConstructor {
new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;
}
declare var DataView: DataViewConstructor;
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Int8Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Int8Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Int8Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Int8ArrayConstructor {
readonly prototype: Int8Array;
new(length: number): Int8Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int8Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array;
}
declare var Int8Array: Int8ArrayConstructor;
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Uint8Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Uint8Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Uint8Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Uint8ArrayConstructor {
readonly prototype: Uint8Array;
new(length: number): Uint8Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint8Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array;
}
declare var Uint8Array: Uint8ArrayConstructor;
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Uint8ClampedArray;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Uint8ClampedArray;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Uint8ClampedArray;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Uint8ClampedArrayConstructor {
readonly prototype: Uint8ClampedArray;
new(length: number): Uint8ClampedArray;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint8ClampedArray;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
declare var Uint8ClampedArray: Uint8ClampedArrayConstructor;
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Int16Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Int16Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Int16Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Int16ArrayConstructor {
readonly prototype: Int16Array;
new(length: number): Int16Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int16Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array;
}
declare var Int16Array: Int16ArrayConstructor;
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Uint16Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Uint16Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Uint16Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Uint16ArrayConstructor {
readonly prototype: Uint16Array;
new(length: number): Uint16Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint16Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array;
}
declare var Uint16Array: Uint16ArrayConstructor;
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Int32Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Int32Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Int32Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Int32ArrayConstructor {
readonly prototype: Int32Array;
new(length: number): Int32Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int32Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array;
}
declare var Int32Array: Int32ArrayConstructor;
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Uint32Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Uint32Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Uint32Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Uint32ArrayConstructor {
readonly prototype: Uint32Array;
new(length: number): Uint32Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint32Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array;
}
declare var Uint32Array: Uint32ArrayConstructor;
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Float32Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Float32Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Float32Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Float32ArrayConstructor {
readonly prototype: Float32Array;
new(length: number): Float32Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Float32Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array;
}
declare var Float32Array: Float32ArrayConstructor;
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Float64Array;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Float64Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls
* the callbackfn function for each element in the array until the callbackfn returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Float64Array;
toString(): string;
[index: number]: number;
}
interface Float64ArrayConstructor {
readonly prototype: Float64Array;
new(length: number): Float64Array;
new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Float64Array;
new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array;
}
declare var Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare namespace Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new(locales?: string | string[], options?: CollatorOptions): Collator;
(locales?: string | string[], options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];
};
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat;
(locales?: string | string[], options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];
};
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];
};
}
interface String {
/**
* Determines whether two strings are equivalent in the current or specified locale.
* @param that String to compare to target string
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
} | the_stack |
declare module "crypto" {
import * as stream from "stream";
interface Certificate {
exportChallenge(spkac: BinaryLike): Buffer;
exportPublicKey(spkac: BinaryLike): Buffer;
verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
}
const Certificate: {
new(): Certificate;
(): Certificate;
};
namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants
const OPENSSL_VERSION_NUMBER: number;
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
const SSL_OP_ALL: number;
/** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
/** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
/** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */
const SSL_OP_CISCO_ANYCONNECT: number;
/** Instructs OpenSSL to turn on cookie exchange. */
const SSL_OP_COOKIE_EXCHANGE: number;
/** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
/** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
/** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */
const SSL_OP_EPHEMERAL_RSA: number;
/** Allows initial connection to servers that do not support RI. */
const SSL_OP_LEGACY_SERVER_CONNECT: number;
const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
const SSL_OP_MICROSOFT_SESS_ID_BUG: number;
/** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */
const SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
const SSL_OP_NETSCAPE_CA_DN_BUG: number;
const SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
/** Instructs OpenSSL to disable support for SSL/TLS compression. */
const SSL_OP_NO_COMPRESSION: number;
const SSL_OP_NO_QUERY_MTU: number;
/** Instructs OpenSSL to always start a new session when performing renegotiation. */
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
const SSL_OP_NO_SSLv2: number;
const SSL_OP_NO_SSLv3: number;
const SSL_OP_NO_TICKET: number;
const SSL_OP_NO_TLSv1: number;
const SSL_OP_NO_TLSv1_1: number;
const SSL_OP_NO_TLSv1_2: number;
const SSL_OP_PKCS1_CHECK_1: number;
const SSL_OP_PKCS1_CHECK_2: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */
const SSL_OP_SINGLE_DH_USE: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */
const SSL_OP_SINGLE_ECDH_USE: number;
const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
const SSL_OP_TLS_BLOCK_PADDING_BUG: number;
const SSL_OP_TLS_D5_BUG: number;
/** Instructs OpenSSL to disable version rollback attack detection. */
const SSL_OP_TLS_ROLLBACK_BUG: number;
const ENGINE_METHOD_RSA: number;
const ENGINE_METHOD_DSA: number;
const ENGINE_METHOD_DH: number;
const ENGINE_METHOD_RAND: number;
const ENGINE_METHOD_EC: number;
const ENGINE_METHOD_CIPHERS: number;
const ENGINE_METHOD_DIGESTS: number;
const ENGINE_METHOD_PKEY_METHS: number;
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
const ENGINE_METHOD_ALL: number;
const ENGINE_METHOD_NONE: number;
const DH_CHECK_P_NOT_SAFE_PRIME: number;
const DH_CHECK_P_NOT_PRIME: number;
const DH_UNABLE_TO_CHECK_GENERATOR: number;
const DH_NOT_SUITABLE_GENERATOR: number;
const ALPN_ENABLED: number;
const RSA_PKCS1_PADDING: number;
const RSA_SSLV23_PADDING: number;
const RSA_NO_PADDING: number;
const RSA_PKCS1_OAEP_PADDING: number;
const RSA_X931_PADDING: number;
const RSA_PKCS1_PSS_PADDING: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
const RSA_PSS_SALTLEN_DIGEST: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
const RSA_PSS_SALTLEN_MAX_SIGN: number;
/** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
const RSA_PSS_SALTLEN_AUTO: number;
const POINT_CONVERSION_COMPRESSED: number;
const POINT_CONVERSION_UNCOMPRESSED: number;
const POINT_CONVERSION_HYBRID: number;
/** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
const defaultCoreCipherList: string;
/** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
const defaultCipherList: string;
}
interface HashOptions extends stream.TransformOptions {
/**
* For XOF hash functions such as `shake256`, the
* outputLength option can be used to specify the desired output length in bytes.
*/
outputLength?: number;
}
/** @deprecated since v10.0.0 */
const fips: boolean;
function createHash(algorithm: string, options?: HashOptions): Hash;
function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac;
type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1";
type HexBase64Latin1Encoding = "latin1" | "hex" | "base64";
type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary";
type HexBase64BinaryEncoding = "binary" | "base64" | "hex";
type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid";
class Hash extends stream.Transform {
private constructor();
copy(): Hash;
update(data: BinaryLike): Hash;
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash;
digest(): Buffer;
digest(encoding: HexBase64Latin1Encoding): string;
}
class Hmac extends stream.Transform {
private constructor();
update(data: BinaryLike): Hmac;
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac;
digest(): Buffer;
digest(encoding: HexBase64Latin1Encoding): string;
}
type KeyObjectType = 'secret' | 'public' | 'private';
interface KeyExportOptions<T extends KeyFormat> {
type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1';
format: T;
cipher?: string;
passphrase?: string | Buffer;
}
class KeyObject {
private constructor();
asymmetricKeyType?: KeyType;
/**
* For asymmetric keys, this property represents the size of the embedded key in
* bytes. This property is `undefined` for symmetric keys.
*/
asymmetricKeySize?: number;
export(options: KeyExportOptions<'pem'>): string | Buffer;
export(options?: KeyExportOptions<'der'>): Buffer;
symmetricKeySize?: number;
type: KeyObjectType;
}
type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305';
type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm';
type BinaryLike = string | NodeJS.ArrayBufferView;
type CipherKey = BinaryLike | KeyObject;
interface CipherCCMOptions extends stream.TransformOptions {
authTagLength: number;
}
interface CipherGCMOptions extends stream.TransformOptions {
authTagLength?: number;
}
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher;
function createCipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options: CipherCCMOptions
): CipherCCM;
function createCipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options?: CipherGCMOptions
): CipherGCM;
function createCipheriv(
algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions
): Cipher;
class Cipher extends stream.Transform {
private constructor();
update(data: BinaryLike): Buffer;
update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer;
update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string;
update(data: string, input_encoding: Utf8AsciiBinaryEncoding | undefined, output_encoding: HexBase64BinaryEncoding): string;
final(): Buffer;
final(output_encoding: BufferEncoding): string;
setAutoPadding(auto_padding?: boolean): this;
// getAuthTag(): Buffer;
// setAAD(buffer: Buffer): this; // docs only say buffer
}
interface CipherCCM extends Cipher {
setAAD(buffer: Buffer, options: { plaintextLength: number }): this;
getAuthTag(): Buffer;
}
interface CipherGCM extends Cipher {
setAAD(buffer: Buffer, options?: { plaintextLength: number }): this;
getAuthTag(): Buffer;
}
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher;
function createDecipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options: CipherCCMOptions,
): DecipherCCM;
function createDecipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options?: CipherGCMOptions,
): DecipherGCM;
function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher;
class Decipher extends stream.Transform {
private constructor();
update(data: NodeJS.ArrayBufferView): Buffer;
update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer;
update(data: NodeJS.ArrayBufferView, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string;
update(data: string, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string;
final(): Buffer;
final(output_encoding: BufferEncoding): string;
setAutoPadding(auto_padding?: boolean): this;
// setAuthTag(tag: NodeJS.ArrayBufferView): this;
// setAAD(buffer: NodeJS.ArrayBufferView): this;
}
interface DecipherCCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this;
}
interface DecipherGCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this;
}
interface PrivateKeyInput {
key: string | Buffer;
format?: KeyFormat;
type?: 'pkcs1' | 'pkcs8' | 'sec1';
passphrase?: string | Buffer;
}
interface PublicKeyInput {
key: string | Buffer;
format?: KeyFormat;
type?: 'pkcs1' | 'spki';
}
function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject;
function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject;
function createSecretKey(key: Buffer): KeyObject;
function createSign(algorithm: string, options?: stream.WritableOptions): Signer;
interface SigningOptions {
/**
* @See crypto.constants.RSA_PKCS1_PADDING
*/
padding?: number;
saltLength?: number;
}
interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {
}
type KeyLike = string | Buffer | KeyObject;
class Signer extends stream.Writable {
private constructor();
update(data: BinaryLike): Signer;
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer;
sign(private_key: SignPrivateKeyInput | KeyLike): Buffer;
sign(private_key: SignPrivateKeyInput | KeyLike, output_format: HexBase64Latin1Encoding): string;
}
function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
class Verify extends stream.Writable {
private constructor();
update(data: BinaryLike): Verify;
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify;
verify(object: object | KeyLike, signature: NodeJS.ArrayBufferView): boolean;
verify(object: object | KeyLike, signature: string, signature_format?: HexBase64Latin1Encoding): boolean;
// https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format
// The signature field accepts a TypedArray type, but it is only available starting ES2017
}
function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman;
function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman;
class DiffieHellman {
private constructor();
generateKeys(): Buffer;
generateKeys(encoding: HexBase64Latin1Encoding): string;
computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer;
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer;
computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: HexBase64Latin1Encoding): string;
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string;
getPrime(): Buffer;
getPrime(encoding: HexBase64Latin1Encoding): string;
getGenerator(): Buffer;
getGenerator(encoding: HexBase64Latin1Encoding): string;
getPublicKey(): Buffer;
getPublicKey(encoding: HexBase64Latin1Encoding): string;
getPrivateKey(): Buffer;
getPrivateKey(encoding: HexBase64Latin1Encoding): string;
setPublicKey(public_key: NodeJS.ArrayBufferView): void;
setPublicKey(public_key: string, encoding: BufferEncoding): void;
setPrivateKey(private_key: NodeJS.ArrayBufferView): void;
setPrivateKey(private_key: string, encoding: BufferEncoding): void;
verifyError: number;
}
function getDiffieHellman(group_name: string): DiffieHellman;
function pbkdf2(
password: BinaryLike,
salt: BinaryLike,
iterations: number,
keylen: number,
digest: string,
callback: (err: Error | null, derivedKey: Buffer) => any,
): void;
function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer;
function randomBytes(size: number): Buffer;
function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function pseudoRandomBytes(size: number): Buffer;
function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function randomFillSync<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, callback: (err: Error | null, buf: T) => void): void;
function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void;
function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void;
interface ScryptOptions {
N?: number;
r?: number;
p?: number;
maxmem?: number;
}
function scrypt(
password: BinaryLike,
salt: BinaryLike,
keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
function scrypt(
password: BinaryLike,
salt: BinaryLike,
keylen: number,
options: ScryptOptions,
callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
interface RsaPublicKey {
key: KeyLike;
padding?: number;
}
interface RsaPrivateKey {
key: KeyLike;
passphrase?: string;
/**
* @default 'sha1'
*/
oaepHash?: string;
oaepLabel?: NodeJS.TypedArray;
padding?: number;
}
function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function getCiphers(): string[];
function getCurves(): string[];
function getHashes(): string[];
class ECDH {
private constructor();
static convertKey(
key: BinaryLike,
curve: string,
inputEncoding?: HexBase64Latin1Encoding,
outputEncoding?: "latin1" | "hex" | "base64",
format?: "uncompressed" | "compressed" | "hybrid",
): Buffer | string;
generateKeys(): Buffer;
generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string;
computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer;
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer;
computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: HexBase64Latin1Encoding): string;
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string;
getPrivateKey(): Buffer;
getPrivateKey(encoding: HexBase64Latin1Encoding): string;
getPublicKey(): Buffer;
getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string;
setPrivateKey(private_key: NodeJS.ArrayBufferView): void;
setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void;
}
function createECDH(curve_name: string): ECDH;
function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean;
/** @deprecated since v10.0.0 */
const DEFAULT_ENCODING: BufferEncoding;
type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519';
type KeyFormat = 'pem' | 'der';
interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
format: T;
cipher?: string;
passphrase?: string;
}
interface KeyPairKeyObjectResult {
publicKey: KeyObject;
privateKey: KeyObject;
}
interface ED25519KeyPairKeyObjectOptions {
/**
* No options.
*/
}
interface ECKeyPairKeyObjectOptions {
/**
* Name of the curve to use.
*/
namedCurve: string;
}
interface RSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* @default 0x10001
*/
publicExponent?: number;
}
interface DSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
}
interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* @default 0x10001
*/
publicExponent?: number;
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs1' | 'pkcs8';
};
}
interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Name of the curve to use.
*/
namedCurve: string;
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'sec1' | 'pkcs8';
};
}
interface ED25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'sec1' | 'pkcs8';
};
}
interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
publicKey: T1;
privateKey: T2;
}
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
namespace generateKeyPair {
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
function __promisify__(type: "ed25519", options: ED25519KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
}
/**
* Calculates and returns the signature for `data` using the given private key and
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
* dependent upon the key type (especially Ed25519 and Ed448).
*
* If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
* passed to [`crypto.createPrivateKey()`][].
*/
function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignPrivateKeyInput): Buffer;
interface VerifyKeyWithOptions extends KeyObject, SigningOptions {
}
/**
* Calculates and returns the signature for `data` using the given private key and
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
* dependent upon the key type (especially Ed25519 and Ed448).
*
* If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
* passed to [`crypto.createPublicKey()`][].
*/
function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyWithOptions, signature: NodeJS.ArrayBufferView): boolean;
} | the_stack |
import React, { useState, useRef, useEffect, KeyboardEvent } from 'react'
import {
today,
addDays,
subMonths,
addMonths,
startOfMonth,
startOfWeek,
isSameDay,
isSameMonth,
isDateWithinMinAndMax,
subYears,
keepDateBetweenMinAndMax,
addYears,
listToTable,
setMonth,
setYear,
min,
max,
subDays,
subWeeks,
addWeeks,
endOfWeek,
handleTabKey,
} from './utils'
const CalendarModes = {
DATE_PICKER: 'DATE_PICKER',
MONTH_PICKER: 'MONTH_PICKER',
YEAR_PICKER: 'YEAR_PICKER',
} as const
type CalendarMode = typeof CalendarModes[keyof typeof CalendarModes]
import { Day } from './Day'
import { MonthPicker } from './MonthPicker'
import { YearPicker } from './YearPicker'
import { FocusMode } from './DatePicker'
import { DatePickerLocalization, EN_US } from './i18n'
export const Calendar = ({
date,
selectedDate,
handleSelectDate,
minDate,
maxDate,
rangeDate,
setStatuses,
focusMode,
i18n = EN_US,
}: {
date?: Date
selectedDate?: Date
handleSelectDate: (value: string) => void
minDate: Date
maxDate?: Date
rangeDate?: Date
setStatuses: (statuses: string[]) => void
focusMode: FocusMode
i18n?: DatePickerLocalization
}): React.ReactElement => {
const prevYearEl = useRef<HTMLButtonElement>(null)
const prevMonthEl = useRef<HTMLButtonElement>(null)
const nextMonthEl = useRef<HTMLButtonElement>(null)
const nextYearEl = useRef<HTMLButtonElement>(null)
const selectMonthEl = useRef<HTMLButtonElement>(null)
const selectYearEl = useRef<HTMLButtonElement>(null)
const focusedDayEl = useRef<HTMLButtonElement>(null)
const datePickerEl = useRef<HTMLDivElement>(null)
const [dateToDisplay, setDateToDisplay] = useState(date || today())
const [mode, setMode] = useState<CalendarMode>(CalendarModes.DATE_PICKER)
const [nextToFocus, setNextToFocus] = useState<
[HTMLButtonElement | null, HTMLDivElement | null]
>([null, null])
let calendarWasHidden = true
const handleSelectMonth = (monthIndex: number): void => {
let newDate = setMonth(dateToDisplay, monthIndex)
newDate = keepDateBetweenMinAndMax(newDate, minDate, maxDate)
setDateToDisplay(newDate)
setMode(CalendarModes.DATE_PICKER)
}
const handleSelectYear = (year: number): void => {
let newDate = setYear(dateToDisplay, year)
newDate = keepDateBetweenMinAndMax(newDate, minDate, maxDate)
setDateToDisplay(newDate)
setMode(CalendarModes.DATE_PICKER)
}
const focusedDate = addDays(dateToDisplay, 0)
const focusedMonth = dateToDisplay.getMonth()
const focusedYear = dateToDisplay.getFullYear()
const monthLabel = i18n.months[parseInt(`${focusedMonth}`)]
const dayOfWeekShortLabels = i18n.daysOfWeekShort
const dayOfWeekLabels = i18n.daysOfWeek
const backOneYear = i18n.backOneYear
const backOneMonth = i18n.backOneMonth
const clickToSelectMonth = `${monthLabel}. ${i18n.clickToSelectMonth}`
const clickToSelectYear = `${focusedYear}. ${i18n.clickToSelectYear}`
const forwardOneMonth = i18n.forwardOneMonth
const forwardOneYear = i18n.forwardOneYear
useEffect(() => {
calendarWasHidden = false
}, [])
useEffect(() => {
// Update displayed date when input changes (only if viewing date picker - otherwise an effect loop will occur)
if (date && mode === CalendarModes.DATE_PICKER) {
setDateToDisplay(date)
}
}, [date])
useEffect(() => {
if (focusMode !== FocusMode.Input) {
const [focusEl, fallbackFocusEl] = nextToFocus
if (focusEl && fallbackFocusEl) {
if (focusEl.disabled) {
fallbackFocusEl.focus()
} else {
focusEl.focus()
}
setNextToFocus([null, null])
} else {
// Focus on new date when it changes
const focusedDateEl =
datePickerEl.current &&
datePickerEl.current.querySelector<HTMLElement>(
'.usa-date-picker__calendar__date--focused'
)
if (focusedDateEl) {
focusedDateEl.focus()
}
}
}
if (calendarWasHidden) {
const newStatuses = [`${monthLabel} ${focusedYear}`]
if (selectedDate && isSameDay(focusedDate, selectedDate)) {
const selectedDateText = i18n.selectedDate
newStatuses.unshift(selectedDateText)
}
setStatuses(newStatuses)
}
}, [dateToDisplay])
if (mode === CalendarModes.MONTH_PICKER) {
return (
<MonthPicker
date={dateToDisplay}
minDate={minDate}
maxDate={maxDate}
handleSelectMonth={handleSelectMonth}
i18n={i18n}
/>
)
} else if (mode === CalendarModes.YEAR_PICKER) {
return (
<YearPicker
date={dateToDisplay}
minDate={minDate}
maxDate={maxDate}
handleSelectYear={handleSelectYear}
setStatuses={setStatuses}
/>
)
}
const prevMonth = subMonths(dateToDisplay, 1)
const nextMonth = addMonths(dateToDisplay, 1)
const firstOfMonth = startOfMonth(dateToDisplay)
const prevButtonsDisabled = isSameMonth(dateToDisplay, minDate)
const nextButtonsDisabled = maxDate && isSameMonth(dateToDisplay, maxDate)
const rangeConclusionDate = selectedDate || dateToDisplay
const rangeStartDate = rangeDate && min(rangeConclusionDate, rangeDate)
const rangeEndDate = rangeDate && max(rangeConclusionDate, rangeDate)
const withinRangeStartDate = rangeStartDate && addDays(rangeStartDate, 1)
const withinRangeEndDate = rangeEndDate && subDays(rangeEndDate, 1)
const handleDatePickerTab = (event: KeyboardEvent): void => {
handleTabKey(event, [
prevYearEl?.current,
prevMonthEl?.current,
selectMonthEl?.current,
selectYearEl?.current,
nextMonthEl?.current,
nextYearEl?.current,
focusedDayEl?.current,
])
}
const handleKeyDownFromDay = (event: KeyboardEvent): void => {
let newDisplayDate
switch (event.key) {
case 'ArrowUp':
case 'Up':
newDisplayDate = subWeeks(dateToDisplay, 1)
break
case 'ArrowDown':
case 'Down':
newDisplayDate = addWeeks(dateToDisplay, 1)
break
case 'ArrowLeft':
case 'Left':
newDisplayDate = subDays(dateToDisplay, 1)
break
case 'ArrowRight':
case 'Right':
newDisplayDate = addDays(dateToDisplay, 1)
break
case 'Home':
newDisplayDate = startOfWeek(dateToDisplay)
break
case 'End':
newDisplayDate = endOfWeek(dateToDisplay)
break
case 'PageDown':
if (event.shiftKey) {
newDisplayDate = addYears(dateToDisplay, 1)
} else {
newDisplayDate = addMonths(dateToDisplay, 1)
}
break
case 'PageUp':
if (event.shiftKey) {
newDisplayDate = subYears(dateToDisplay, 1)
} else {
newDisplayDate = subMonths(dateToDisplay, 1)
}
break
default:
return
}
if (newDisplayDate !== undefined) {
const cappedDate = keepDateBetweenMinAndMax(
newDisplayDate,
minDate,
maxDate
)
if (!isSameDay(dateToDisplay, cappedDate)) {
setDateToDisplay(newDisplayDate)
}
}
event.preventDefault()
}
const handleMouseMoveFromDay = (hoverDate: Date): void => {
if (hoverDate === dateToDisplay) return
setDateToDisplay(hoverDate)
}
const handlePreviousYearClick = (): void => {
let newDate = subYears(dateToDisplay, 1)
newDate = keepDateBetweenMinAndMax(newDate, minDate, maxDate)
setDateToDisplay(newDate)
setNextToFocus([prevYearEl.current, datePickerEl.current])
}
const handlePreviousMonthClick = (): void => {
let newDate = subMonths(dateToDisplay, 1)
newDate = keepDateBetweenMinAndMax(newDate, minDate, maxDate)
setDateToDisplay(newDate)
setNextToFocus([prevMonthEl.current, datePickerEl.current])
}
const handleNextMonthClick = (): void => {
let newDate = addMonths(dateToDisplay, 1)
newDate = keepDateBetweenMinAndMax(newDate, minDate, maxDate)
setDateToDisplay(newDate)
setNextToFocus([nextMonthEl.current, datePickerEl.current])
}
const handleNextYearClick = (): void => {
let newDate = addYears(dateToDisplay, 1)
newDate = keepDateBetweenMinAndMax(newDate, minDate, maxDate)
setDateToDisplay(newDate)
setNextToFocus([nextYearEl.current, datePickerEl.current])
}
const handleToggleMonthSelection = (): void => {
setMode(CalendarModes.MONTH_PICKER)
const selectAMonth = i18n.selectAMonth
setStatuses([selectAMonth])
}
const handleToggleYearSelection = (): void => {
setMode(CalendarModes.YEAR_PICKER)
}
const days = []
let dateIterator = startOfWeek(firstOfMonth)
while (
days.length < 28 ||
dateIterator.getMonth() === focusedMonth ||
days.length % 7 !== 0
) {
const isFocused = isSameDay(dateIterator, focusedDate)
days.push(
<Day
date={dateIterator}
onClick={handleSelectDate}
onKeyDown={handleKeyDownFromDay}
onMouseMove={handleMouseMoveFromDay}
ref={isFocused ? focusedDayEl : null}
isDisabled={!isDateWithinMinAndMax(dateIterator, minDate, maxDate)}
isSelected={selectedDate && isSameDay(dateIterator, selectedDate)}
isFocused={isFocused}
isPrevMonth={isSameMonth(dateIterator, prevMonth)}
isFocusedMonth={isSameMonth(dateIterator, focusedDate)}
isNextMonth={isSameMonth(dateIterator, nextMonth)}
isToday={isSameDay(dateIterator, today())}
isRangeDate={rangeDate && isSameDay(dateIterator, rangeDate)}
isRangeStart={rangeStartDate && isSameDay(dateIterator, rangeStartDate)}
isRangeEnd={rangeEndDate && isSameDay(dateIterator, rangeEndDate)}
isWithinRange={
withinRangeStartDate &&
withinRangeEndDate &&
isDateWithinMinAndMax(
dateIterator,
withinRangeStartDate,
withinRangeEndDate
)
}
i18n={i18n}
/>
)
dateIterator = addDays(dateIterator, 1)
}
return (
// Ignoring error: "Static HTML elements with event handlers require a role."
// Ignoring because this element does not have a role in the USWDS implementation (https://github.com/uswds/uswds/blob/develop/src/js/components/date-picker.js#L1042)
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
tabIndex={-1}
className="usa-date-picker__calendar__date-picker"
data-testid="calendar-date-picker"
ref={datePickerEl}
onKeyDown={handleDatePickerTab}>
<div className="usa-date-picker__calendar__row">
<div className="usa-date-picker__calendar__cell usa-date-picker__calendar__cell--center-items">
<button
type="button"
data-testid="previous-year"
onClick={handlePreviousYearClick}
ref={prevYearEl}
className="usa-date-picker__calendar__previous-year"
aria-label={backOneYear}
disabled={prevButtonsDisabled}>
</button>
</div>
<div className="usa-date-picker__calendar__cell usa-date-picker__calendar__cell--center-items">
<button
type="button"
data-testid="previous-month"
onClick={handlePreviousMonthClick}
ref={prevMonthEl}
className="usa-date-picker__calendar__previous-month"
aria-label={backOneMonth}
disabled={prevButtonsDisabled}>
</button>
</div>
<div className="usa-date-picker__calendar__cell usa-date-picker__calendar__month-label">
<button
type="button"
data-testid="select-month"
onClick={handleToggleMonthSelection}
ref={selectMonthEl}
className="usa-date-picker__calendar__month-selection"
aria-label={clickToSelectMonth}>
{monthLabel}
</button>
<button
type="button"
data-testid="select-year"
onClick={handleToggleYearSelection}
ref={selectYearEl}
className="usa-date-picker__calendar__year-selection"
aria-label={clickToSelectYear}>
{focusedYear}
</button>
</div>
<div className="usa-date-picker__calendar__cell usa-date-picker__calendar__cell--center-items">
<button
type="button"
data-testid="next-month"
onClick={handleNextMonthClick}
ref={nextMonthEl}
className="usa-date-picker__calendar__next-month"
aria-label={forwardOneMonth}
disabled={nextButtonsDisabled}>
</button>
</div>
<div className="usa-date-picker__calendar__cell usa-date-picker__calendar__cell--center-items">
<button
type="button"
data-testid="next-year"
onClick={handleNextYearClick}
ref={nextYearEl}
className="usa-date-picker__calendar__next-year"
aria-label={forwardOneYear}
disabled={nextButtonsDisabled}>
</button>
</div>
</div>
<table className="usa-date-picker__calendar__table" role="presentation">
<thead>
<tr>
{dayOfWeekShortLabels.map((d, i) => (
<th
className="usa-date-picker__calendar__day-of-week"
scope="col"
aria-label={dayOfWeekLabels[parseInt(`${i}`)]}
key={`day-of-week-${d}-${i}`}>
{d}
</th>
))}
</tr>
</thead>
<tbody>{listToTable(days, 7)}</tbody>
</table>
</div>
)
}
Calendar.displayName = 'Calendar' | the_stack |
// Some lines of code are from Elyra Code Snippet.
/*
* Copyright 2018-2020 IBM Corporation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions a* limitations under the License.
*/
import { CodeEditor, IEditorServices } from '@jupyterlab/codeeditor';
import {
ReactWidget,
showDialog,
Dialog,
WidgetTracker,
} from '@jupyterlab/apputils';
import { Button } from '@jupyterlab/ui-components';
import { Message } from '@lumino/messaging';
import React from 'react';
import { CodeSnippetService } from './CodeSnippetService';
import { CodeSnippetWidget } from './CodeSnippetWidget';
import { SUPPORTED_LANGUAGES } from './CodeSnippetLanguages';
import { CodeSnippetEditorTags } from './CodeSnippetEditorTags';
import { showMessage } from './CodeSnippetMessage';
import { validateInputs, saveOverWriteFile } from './CodeSnippetUtilities';
/**
* CSS style classes
*/
const CODE_SNIPPET_EDITOR = 'jp-codeSnippet-editor';
const CODE_SNIPPET_EDITOR_TITLE = 'jp-codeSnippet-editor-title';
const CODE_SNIPPET_EDITOR_METADATA = 'jp-codeSnippet-editor-metadata';
const CODE_SNIPPET_EDITOR_INPUT_ACTIVE = 'jp-codeSnippet-editor-active';
const CODE_SNIPPET_EDITOR_NAME_INPUT = 'jp-codeSnippet-editor-name';
const CODE_SNIPPET_EDITOR_LABEL = 'jp-codeSnippet-editor-label';
const CODE_SNIPPET_EDITOR_DESC_INPUT = 'jp-codeSnippet-editor-description';
const CODE_SNIPPET_EDITOR_LANG_INPUT = 'jp-codeSnippet-editor-language';
const CODE_SNIPPET_EDITOR_MIRROR = 'jp-codeSnippetInput-editor';
const CODE_SNIPPET_EDITOR_INPUTAREA = 'jp-codeSnippetInputArea';
const CODE_SNIPPET_EDITOR_INPUTAREA_MIRROR = 'jp-codeSnippetInputArea-editor';
const EDITOR_DIRTY_CLASS = 'jp-mod-dirty';
export interface ICodeSnippetEditorMetadata {
name: string;
description: string;
language: string;
code: string[];
id: number;
selectedTags: string[];
allSnippetTags: string[];
allLangTags: string[];
fromScratch: boolean;
}
export class CodeSnippetEditor extends ReactWidget {
editorServices: IEditorServices;
private editor: CodeEditor.IEditor;
private saved: boolean;
private oldCodeSnippetName: string;
private _codeSnippetEditorMetaData: ICodeSnippetEditorMetadata;
private _hasRefreshedSinceAttach: boolean;
contentsService: CodeSnippetService;
codeSnippetWidget: CodeSnippetWidget;
tracker: WidgetTracker;
constructor(
editorServices: IEditorServices,
tracker: WidgetTracker,
codeSnippetWidget: CodeSnippetWidget,
args: ICodeSnippetEditorMetadata
) {
super();
this.addClass(CODE_SNIPPET_EDITOR);
this.contentsService = CodeSnippetService.getCodeSnippetService();
this.editorServices = editorServices;
this.tracker = tracker;
this._codeSnippetEditorMetaData = args;
this.oldCodeSnippetName = args.name;
this.saved = true;
this._hasRefreshedSinceAttach = false;
this.codeSnippetWidget = codeSnippetWidget;
this.renderCodeInput = this.renderCodeInput.bind(this);
this.handleInputFieldChange = this.handleInputFieldChange.bind(this);
this.activateCodeMirror = this.activateCodeMirror.bind(this);
this.saveChange = this.saveChange.bind(this);
this.updateSnippet = this.updateSnippet.bind(this);
this.handleChangeOnTag = this.handleChangeOnTag.bind(this);
}
get codeSnippetEditorMetadata(): ICodeSnippetEditorMetadata {
return this._codeSnippetEditorMetaData;
}
private deactivateEditor(
event: React.MouseEvent<HTMLDivElement, MouseEvent>
): void {
let target = event.target as HTMLElement;
while (target && target.parentElement) {
if (
target.classList.contains(CODE_SNIPPET_EDITOR_MIRROR) ||
target.classList.contains(CODE_SNIPPET_EDITOR_NAME_INPUT) ||
target.classList.contains(CODE_SNIPPET_EDITOR_DESC_INPUT)
) {
break;
}
target = target.parentElement;
}
const nameInput = document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_NAME_INPUT}`
);
const descriptionInput = document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_DESC_INPUT}`
);
const editor = document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} #code-${this._codeSnippetEditorMetaData.id}`
);
if (target.classList.contains(CODE_SNIPPET_EDITOR_NAME_INPUT)) {
this.deactivateDescriptionField(descriptionInput);
this.deactivateCodeMirror(editor);
} else if (target.classList.contains(CODE_SNIPPET_EDITOR_DESC_INPUT)) {
this.deactivateNameField(nameInput);
this.deactivateCodeMirror(editor);
} else if (target.classList.contains(CODE_SNIPPET_EDITOR_MIRROR)) {
this.deactivateNameField(nameInput);
this.deactivateDescriptionField(descriptionInput);
} else {
this.deactivateNameField(nameInput);
this.deactivateDescriptionField(descriptionInput);
this.deactivateCodeMirror(editor);
}
}
private deactivateNameField(nameInput: Element): void {
if (nameInput.classList.contains(CODE_SNIPPET_EDITOR_INPUT_ACTIVE)) {
nameInput.classList.remove(CODE_SNIPPET_EDITOR_INPUT_ACTIVE);
}
}
private deactivateDescriptionField(descriptionInput: Element): void {
if (descriptionInput.classList.contains(CODE_SNIPPET_EDITOR_INPUT_ACTIVE)) {
descriptionInput.classList.remove(CODE_SNIPPET_EDITOR_INPUT_ACTIVE);
}
}
private activeFieldState(
event: React.MouseEvent<HTMLInputElement, MouseEvent>
): void {
const target = event.target as HTMLElement;
if (!target.classList.contains(CODE_SNIPPET_EDITOR_INPUT_ACTIVE)) {
target.classList.add(CODE_SNIPPET_EDITOR_INPUT_ACTIVE);
}
}
onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
if (
!this.editor &&
document.getElementById('code-' + this._codeSnippetEditorMetaData.id)
) {
const editorFactory = this.editorServices.factoryService.newInlineEditor;
const getMimeTypeByLanguage =
this.editorServices.mimeTypeService.getMimeTypeByLanguage;
this.editor = editorFactory({
host: document.getElementById(
'code-' + this._codeSnippetEditorMetaData.id
),
model: new CodeEditor.Model({
value: this._codeSnippetEditorMetaData.code.join('\n'),
mimeType: getMimeTypeByLanguage({
name: this._codeSnippetEditorMetaData.language,
codemirror_mode: this._codeSnippetEditorMetaData.language,
}),
}),
});
this.editor.model.value.changed.connect((args: any) => {
this._codeSnippetEditorMetaData.code = args.text.split('\n');
if (!this.title.className.includes(EDITOR_DIRTY_CLASS)) {
this.title.className += ` ${EDITOR_DIRTY_CLASS}`;
}
this.saved = false;
});
}
if (this.isVisible) {
this._hasRefreshedSinceAttach = true;
this.editor.refresh();
}
}
onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this._hasRefreshedSinceAttach = false;
if (this.isVisible) {
this.update();
}
window.addEventListener('beforeunload', (e) => {
if (!this.saved) {
e.preventDefault();
e.returnValue = '';
}
});
}
onAfterShow(msg: Message): void {
if (!this._hasRefreshedSinceAttach) {
this.update();
}
}
/**
* Initial focus on the editor when it gets activated!
* @param msg
*/
onActivateRequest(msg: Message): void {
this.editor.focus();
}
onCloseRequest(msg: Message): void {
if (!this.saved) {
showDialog({
title: 'Close without saving?',
body: (
<p>
{' '}
{`"${this._codeSnippetEditorMetaData.name}" has unsaved changes, close without saving?`}{' '}
</p>
),
buttons: [
Dialog.cancelButton(),
Dialog.warnButton({ label: 'Discard' }),
Dialog.okButton({ label: 'Save' }),
],
}).then((response: any): void => {
if (response.button.accept) {
if (response.button.label === 'Discard') {
this.dispose();
super.onCloseRequest(msg);
} else if (response.button.label === 'Save') {
const name = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_NAME_INPUT}`
) as HTMLInputElement
).value;
const description = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_DESC_INPUT}`
) as HTMLInputElement
).value;
const language = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_LANG_INPUT}`
) as HTMLSelectElement
).value;
const validity = validateInputs(name, description, language);
if (validity) {
this.updateSnippet().then((value) => {
if (value) {
this.dispose();
super.onCloseRequest(msg);
}
});
}
}
}
});
} else {
this.dispose();
super.onCloseRequest(msg);
}
}
/**
* Visualize the editor more look like an editor
* @param event
*/
activateCodeMirror(
event: React.MouseEvent<HTMLDivElement, MouseEvent>
): void {
let target = event.target as HTMLElement;
while (target && target.parentElement) {
if (target.classList.contains(CODE_SNIPPET_EDITOR_MIRROR)) {
break;
}
target = target.parentElement;
}
const editor = document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} #code-${this._codeSnippetEditorMetaData.id}`
);
if (target.classList.contains(CODE_SNIPPET_EDITOR_MIRROR)) {
if (!editor.classList.contains('active')) {
editor.classList.add('active');
}
}
}
deactivateCodeMirror(editor: Element): void {
if (editor.classList.contains('active')) {
editor.classList.remove('active');
}
}
handleInputFieldChange(event: React.ChangeEvent<HTMLInputElement>): void {
if (!this.title.className.includes(EDITOR_DIRTY_CLASS)) {
this.title.className += ` ${EDITOR_DIRTY_CLASS}`;
}
const target = event.target as HTMLElement;
if (!target.classList.contains('FieldChanged')) {
target.classList.add('FieldChanged');
}
this.saved = false;
}
saveChange(event: React.MouseEvent<HTMLElement, MouseEvent>): void {
const name = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_NAME_INPUT}`
) as HTMLInputElement
).value;
const description = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_DESC_INPUT}`
) as HTMLInputElement
).value;
const language = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_LANG_INPUT}`
) as HTMLSelectElement
).value;
const validity = validateInputs(name, description, language);
if (validity) {
this.updateSnippet();
}
}
async updateSnippet(): Promise<boolean> {
const name = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_NAME_INPUT}`
) as HTMLInputElement
).value;
const description = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_DESC_INPUT}`
) as HTMLInputElement
).value;
const language = (
document.querySelector(
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_LANG_INPUT}`
) as HTMLSelectElement
).value;
this._codeSnippetEditorMetaData.name = name;
this._codeSnippetEditorMetaData.description = description;
this._codeSnippetEditorMetaData.language = language;
const newName = this._codeSnippetEditorMetaData.name;
const oldName = this.oldCodeSnippetName;
const newSnippet = {
name: this._codeSnippetEditorMetaData.name,
description: this._codeSnippetEditorMetaData.description,
language: this._codeSnippetEditorMetaData.language,
code: this._codeSnippetEditorMetaData.code,
id: this._codeSnippetEditorMetaData.id,
tags: this._codeSnippetEditorMetaData.selectedTags,
};
const isDuplicatName = this.contentsService.duplicateNameExists(newName);
// set new name as an old name
this.oldCodeSnippetName = this._codeSnippetEditorMetaData.name;
// add new snippet
if (this._codeSnippetEditorMetaData.fromScratch) {
if (isDuplicatName) {
const oldSnippet = this.contentsService.getSnippet(newName)[0];
await saveOverWriteFile(this.contentsService, oldSnippet, newSnippet);
} else {
this.contentsService.addSnippet(newSnippet).then((res: boolean) => {
if (!res) {
console.log('Error in adding snippet');
return false;
}
});
showMessage('confirm');
}
}
// modify existing snippet
else {
if (newName !== oldName) {
if (isDuplicatName) {
// overwrite
const oldSnippet = this.contentsService.getSnippet(newName)[0];
await saveOverWriteFile(
this.contentsService,
oldSnippet,
newSnippet
).then((res: boolean) => {
if (res) {
// get the id of snippet you are editting
const removedSnippet =
this.contentsService.getSnippet(oldName)[0];
// delete the one you are editing
this.contentsService.deleteSnippet(removedSnippet.id);
} else {
return false;
}
});
}
}
this.contentsService
.modifyExistingSnippet(oldName, newSnippet)
.then((res: boolean) => {
if (!res) {
console.log('Error in modifying snippet');
return false;
}
});
}
this.saved = true;
// remove the dirty state
this.title.className = this.title.className.replace(
` ${EDITOR_DIRTY_CLASS}`,
''
);
// change label
this.title.label =
'[' +
this._codeSnippetEditorMetaData.language +
'] ' +
this._codeSnippetEditorMetaData.name;
if (!this._codeSnippetEditorMetaData.fromScratch) {
// update tracker
this.tracker.save(this);
}
// update the display in code snippet explorer
this.codeSnippetWidget.updateCodeSnippetWidget();
// close editor if it's from scratch
if (this._codeSnippetEditorMetaData.fromScratch) {
this.dispose();
}
return true;
}
handleChangeOnTag(selectedTags: string[], allTags: string[]): void {
if (!this.title.className.includes(EDITOR_DIRTY_CLASS)) {
this.title.className += ` ${EDITOR_DIRTY_CLASS}`;
}
this._codeSnippetEditorMetaData.selectedTags = selectedTags;
this._codeSnippetEditorMetaData.allSnippetTags = allTags;
this.saved = false;
}
handleOnBlur(event: React.FocusEvent<HTMLInputElement>): void {
const target = event.target as HTMLElement;
if (!target.classList.contains('touched')) {
target.classList.add('touched');
}
}
/**
* TODO: clean CSS style class - "Use constant"
*/
renderCodeInput(): React.ReactElement {
return (
<section
className={CODE_SNIPPET_EDITOR_INPUTAREA_MIRROR}
onMouseDown={this.activateCodeMirror}
>
<div
className={CODE_SNIPPET_EDITOR_MIRROR}
id={'code-' + this._codeSnippetEditorMetaData.id.toString()}
></div>
</section>
);
}
renderLanguages(): React.ReactElement {
SUPPORTED_LANGUAGES.sort();
return (
<div>
<input
className={CODE_SNIPPET_EDITOR_LANG_INPUT}
list="languages"
name="language"
defaultValue={this._codeSnippetEditorMetaData.language}
onChange={this.handleInputFieldChange}
required
/>
<datalist id="languages">
{SUPPORTED_LANGUAGES.map((lang) => this.renderLanguageOptions(lang))}
</datalist>
</div>
);
}
renderLanguageOptions(option: string): JSX.Element {
return <option key={option} value={option} />;
}
render(): React.ReactElement {
const fromScratch = this._codeSnippetEditorMetaData.fromScratch;
return (
<div
className={CODE_SNIPPET_EDITOR_INPUTAREA}
onMouseDown={(
event: React.MouseEvent<HTMLDivElement, MouseEvent>
): void => {
this.deactivateEditor(event);
}}
>
<span className={CODE_SNIPPET_EDITOR_TITLE}>
{fromScratch ? 'New Code Snippet' : 'Edit Code Snippet'}
</span>
<section className={CODE_SNIPPET_EDITOR_METADATA}>
<label className={CODE_SNIPPET_EDITOR_LABEL}>Name (required)</label>
<input
className={CODE_SNIPPET_EDITOR_NAME_INPUT}
defaultValue={this._codeSnippetEditorMetaData.name}
placeholder={'Ex. starter code'}
type="text"
required
onMouseDown={(
event: React.MouseEvent<HTMLInputElement, MouseEvent>
): void => this.activeFieldState(event)}
onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
this.handleInputFieldChange(event);
}}
onBlur={this.handleOnBlur}
></input>
<label className={CODE_SNIPPET_EDITOR_LABEL}>
Description (optional)
</label>
<input
className={CODE_SNIPPET_EDITOR_DESC_INPUT}
defaultValue={this._codeSnippetEditorMetaData.description}
placeholder={'Description'}
type="text"
onMouseDown={(
event: React.MouseEvent<HTMLInputElement, MouseEvent>
): void => this.activeFieldState(event)}
onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
this.handleInputFieldChange(event);
}}
onBlur={this.handleOnBlur}
></input>
<label className={CODE_SNIPPET_EDITOR_LABEL}>
Language (required)
</label>
{this.renderLanguages()}
<label className={CODE_SNIPPET_EDITOR_LABEL}>Tags</label>
<CodeSnippetEditorTags
selectedTags={this.codeSnippetEditorMetadata.selectedTags}
snippetTags={this.codeSnippetEditorMetadata.allSnippetTags}
langTags={this.codeSnippetEditorMetadata.allLangTags}
handleChange={this.handleChangeOnTag}
/>
</section>
<span className={CODE_SNIPPET_EDITOR_LABEL}>Code</span>
{this.renderCodeInput()}
<Button className="saveBtn" onClick={this.saveChange}>
{fromScratch ? 'Create & Close' : 'Save'}
</Button>
</div>
);
}
} | the_stack |
import {
createLoggingContext,
createRequestContext,
delay,
jsonifyError,
RequestContext,
RequestContextWithTransactionId,
safeJsonStringify,
} from "@connext/nxtp-utils";
import { BigNumber, providers } from "ethers";
import { getContext } from "../../router";
import {
ActiveTransaction,
CrosschainTransactionStatus,
FulfillPayload,
PreparePayload,
Tracker,
attemptedTransfer,
completedTransfer,
successfulAuction,
senderFailedCancel,
receiverFailedPrepare,
senderFailedFulfill,
receiverExpired,
senderExpired,
receiverFailedCancel,
senderPrepared,
receiverPrepared,
receiverFulfilled,
senderFulfilled,
senderCancelled,
receiverCancelled,
ActiveTransactionsTracker,
} from "../../lib/entities";
import { getOperations } from "../../lib/operations";
import { ContractReaderNotAvailableForChain } from "../../lib/errors";
import { incrementFees } from "../../lib/helpers";
import { getAssetName, incrementTotalTransferredVolume } from "../../lib/helpers/metrics";
import { getFeesInSendingAsset } from "../../lib/helpers/shared";
const LOOP_INTERVAL = 30_000;
export const getLoopInterval = () => LOOP_INTERVAL;
export const handlingTracker: Map<string, Tracker> = new Map();
export let activeTransactionsTracker: ActiveTransactionsTracker[] = [];
export const bindContractReader = async () => {
const { contractReader, logger, config } = getContext();
setInterval(async () => {
const { requestContext, methodContext } = createLoggingContext("bindContractReader");
let transactions: ActiveTransaction<any>[] = [];
try {
transactions = await contractReader.getActiveTransactions();
if (transactions.length > 0) {
activeTransactionsTracker = transactions.map((v) => {
return {
status: v.status,
transactionsId: v.crosschainTx.invariant.transactionId,
sendingChainId: v.crosschainTx.invariant.sendingChainId,
receivingChainId: v.crosschainTx.invariant.receivingChainId,
};
});
logger.info("active transactions tracker", requestContext, methodContext, {
activeTransactionsLength: transactions.length,
activeTransactionsTracker: activeTransactionsTracker,
});
logger.info("handling tracker", requestContext, methodContext, {
handlingTrackerLength: handlingTracker.size,
handlingTracker: [...handlingTracker],
});
}
} catch (err: any) {
logger.error("Error getting active txs, waiting for next loop", requestContext, methodContext, jsonifyError(err));
return;
}
// handle the case for `ReceiverFulfilled` -- in this case, the transaction will *not*
// be re-processed from the loop because the next logical status is `SenderFulfilled`,
// which is not recognized as an "active transaction". instead, the transaction
// should be removed from the tracker completely to avoid a memory leak
Object.entries(config.chainConfig).forEach(async ([chainId]) => {
const records = await contractReader.getSyncRecords(Number(chainId));
const highestSyncedBlock = Math.max(...records.map((r) => r.syncedBlock));
handlingTracker.forEach((value, key) => {
if (
value.chainId === Number(chainId) &&
value.block > 0 &&
value.block <= highestSyncedBlock &&
value.status === "ReceiverFulfilled"
) {
logger.debug("Deleting tracker record", requestContext, methodContext, {
transactionId: key,
chainId: chainId,
blockNumber: value.block,
syncedBlock: highestSyncedBlock,
});
handlingTracker.delete(key);
}
});
});
await handleActiveTransactions(transactions);
}, getLoopInterval());
};
export const handleActiveTransactions = async (
transactions: ActiveTransaction<any>[],
_requestContext?: RequestContext,
) => {
const { logger } = getContext();
for (const transaction of transactions) {
const { requestContext, methodContext } = createLoggingContext(
handleActiveTransactions.name,
typeof _requestContext === "object"
? { ..._requestContext, transactionId: transaction.crosschainTx.invariant.transactionId }
: undefined,
transaction.crosschainTx.invariant.transactionId,
);
// chainId where onChain interaction will happen
let chainId: number;
if (
transaction.status === CrosschainTransactionStatus.SenderPrepared ||
transaction.status === CrosschainTransactionStatus.SenderExpired
) {
chainId = transaction.crosschainTx.invariant.receivingChainId;
} else {
chainId = transaction.crosschainTx.invariant.sendingChainId;
}
// check if transactionId is already handled for respective chainId
if (
handlingTracker.has(transaction.crosschainTx.invariant.transactionId) &&
(transaction.status === handlingTracker.get(transaction.crosschainTx.invariant.transactionId)?.status ||
handlingTracker.get(transaction.crosschainTx.invariant.transactionId)?.status === "Processing")
) {
logger.debug("Already handling transaction", requestContext, methodContext, { status: transaction.status });
continue;
}
handlingTracker.set(transaction.crosschainTx.invariant.transactionId, {
status: "Processing",
chainId,
block: -1,
});
handleSingle(transaction, requestContext)
.then((result) => {
logger.debug("Handle Single Result", requestContext, methodContext, { transactionResult: result });
if (result && result.blockNumber) {
handlingTracker.set(transaction.crosschainTx.invariant.transactionId, {
status: transaction.status,
chainId,
block: result.blockNumber,
});
} else {
handlingTracker.delete(transaction.crosschainTx.invariant.transactionId);
}
})
.catch((err) => {
logger.debug("Handle Single Errors", requestContext, methodContext, { error: jsonifyError(err) });
handlingTracker.delete(transaction.crosschainTx.invariant.transactionId);
});
await delay(750); // delay here to not flood the provider
}
};
export const handleSingle = async (
transaction: ActiveTransaction<any>,
_requestContext: RequestContextWithTransactionId,
): Promise<providers.TransactionReceipt | undefined> => {
const { requestContext, methodContext } = createLoggingContext(
handleSingle.name,
_requestContext,
transaction.crosschainTx.invariant.transactionId,
);
const { logger, txService, config, cache } = getContext();
const { prepare, cancel, fulfill } = getOperations();
let receipt: providers.TransactionReceipt | undefined;
if (transaction.status === CrosschainTransactionStatus.SenderPrepared) {
const _transaction = transaction as ActiveTransaction<"SenderPrepared">;
const chainConfig = config.chainConfig[_transaction.crosschainTx.invariant.sendingChainId];
if (!chainConfig) {
// this should not happen, this should get checked before this point
throw new ContractReaderNotAvailableForChain(_transaction.crosschainTx.invariant.sendingChainId, {
methodContext,
requestContext,
});
}
if (!_transaction.payload.hashes.sending) {
logger.warn("No sending hashes with SenderPrepared status", requestContext, methodContext, {
hashes: _transaction.payload.hashes,
});
return;
}
const senderPrepareReceipt = await txService.getTransactionReceipt(
_transaction.crosschainTx.invariant.sendingChainId,
_transaction.payload.hashes.sending.prepareHash,
);
if ((senderPrepareReceipt?.confirmations ?? 0) < chainConfig.confirmations) {
logger.info("Waiting for safe confirmations", requestContext, methodContext, {
txConfirmations: senderPrepareReceipt?.confirmations ?? 0,
configuredConfirmations: chainConfig.confirmations,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
txHash: _transaction.payload.hashes.sending.prepareHash,
});
return;
}
const preparePayload: PreparePayload = _transaction.payload;
try {
logger.info("Preparing receiver", requestContext, methodContext);
// We need to confirm in the cache that this bid was accepted by the user and we are
// going through with our commitment to prepare on the receiving chain. The bid may expire in
// the time it takes to send the prepare transaction, but doing so ensures the cache extends
// the outstanding liquidity reservation for that time.
// See the `finally` block below for the `removeBid` operation that releases the outstanding liquidity.
const didConfirm = cache.auctions.confirmBid(
_transaction.crosschainTx.invariant.receivingChainId,
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.transactionId,
);
if (!didConfirm) {
logger.warn("Unable to confirm bid to extend liquidity reservation", requestContext, methodContext, {
didConfirm,
receivingChainId: _transaction.crosschainTx.invariant.receivingChainId,
receivingAssetId: _transaction.crosschainTx.invariant.receivingAssetId,
transactionId: _transaction.crosschainTx.invariant.transactionId,
receivingAmount: _transaction.crosschainTx.receiving?.amount,
});
}
receipt = await prepare(
_transaction.crosschainTx.invariant,
{
senderExpiry: _transaction.crosschainTx.sending.expiry,
senderAmount: _transaction.crosschainTx.sending.amount,
bidSignature: preparePayload.bidSignature,
encodedBid: preparePayload.encodedBid,
encryptedCallData: preparePayload.encryptedCallData,
},
requestContext,
);
// if successfully prepared, was successful auction, sender/receiver prepare
const sendingAssetName = getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
);
const receivingAssetName = getAssetName(
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
);
successfulAuction.inc(
{
sendingAssetId: _transaction.crosschainTx.invariant.sendingAssetId,
receivingAssetId: _transaction.crosschainTx.invariant.receivingAssetId,
sendingChainId: _transaction.crosschainTx.invariant.sendingChainId,
receivingChainId: _transaction.crosschainTx.invariant.receivingChainId,
sendingAssetName,
receivingAssetName,
},
1,
);
senderPrepared.inc({
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
});
receiverPrepared.inc({
assetId: _transaction.crosschainTx.invariant.receivingAssetId,
chainId: _transaction.crosschainTx.invariant.receivingChainId,
assetName: receivingAssetName,
});
logger.info("Prepared receiver", requestContext, methodContext, { txHash: receipt?.transactionHash });
attemptedTransfer.inc({
sendingAssetId: _transaction.crosschainTx.invariant.sendingAssetId,
receivingAssetId: _transaction.crosschainTx.invariant.receivingAssetId,
sendingChainId: _transaction.crosschainTx.invariant.sendingChainId,
receivingChainId: _transaction.crosschainTx.invariant.receivingChainId,
sendingAssetName,
receivingAssetName,
});
} catch (err: any) {
const sendingAssetName = getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
);
const receivingAssetName = getAssetName(
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
);
receiverFailedPrepare.inc({
assetId: _transaction.crosschainTx.invariant.receivingAssetId,
chainId: _transaction.crosschainTx.invariant.receivingChainId,
assetName: receivingAssetName,
});
const json = jsonifyError(err);
if (safeJsonStringify(json).includes("#P:015")) {
logger.warn("Receiver transaction already prepared", requestContext, methodContext, { error: json });
return;
} else {
logger.error("Error preparing receiver", requestContext, methodContext, json, {
chainId: transaction.crosschainTx.invariant.receivingChainId,
});
}
if (err.cancellable === true) {
logger.warn("Cancellable validation error, cancelling", requestContext, methodContext);
try {
const cancelRes = await cancel(
transaction.crosschainTx.invariant,
{
amount: transaction.crosschainTx.sending.amount,
expiry: transaction.crosschainTx.sending.expiry,
preparedBlockNumber: transaction.crosschainTx.sending.preparedBlockNumber,
preparedTransactionHash: transaction.payload.hashes.sending.prepareHash,
side: "sender",
},
requestContext,
);
senderCancelled.inc({
assetId: transaction.crosschainTx.invariant.sendingAssetId,
chainId: transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
});
logger.info("Cancelled transaction", requestContext, methodContext, { txHash: cancelRes?.transactionHash });
// if successfully cancelled, was successful auction
successfulAuction.inc(
{
sendingAssetId: _transaction.crosschainTx.invariant.sendingAssetId,
receivingAssetId: _transaction.crosschainTx.invariant.receivingAssetId,
sendingChainId: _transaction.crosschainTx.invariant.sendingChainId,
receivingChainId: _transaction.crosschainTx.invariant.receivingChainId,
sendingAssetName,
receivingAssetName: receivingAssetName,
},
1,
);
} catch (cancelErr: any) {
senderFailedCancel.inc({
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
),
});
const cancelJson = jsonifyError(cancelErr);
if (safeJsonStringify(jsonifyError(cancelErr)).includes("#C:019")) {
logger.warn("Already cancelled", requestContext, methodContext, {
transaction: _transaction.crosschainTx.invariant.transactionId,
error: cancelJson,
});
} else {
logger.error("Error cancelling sender", requestContext, methodContext, cancelJson, {
chainId: transaction.crosschainTx.invariant.sendingChainId,
});
}
}
}
} finally {
// Regardless of whether the prepare executed successfully, we can free up the outstanding liquidity.
// If it was successful, the liquidity will go from being outstanding, to being locked up for the transaction,
// and current balance will reflect that.
cache.auctions.removeBid(
_transaction.crosschainTx.invariant.receivingChainId,
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.transactionId,
);
}
} else if (transaction.status === CrosschainTransactionStatus.ReceiverFulfilled) {
const _transaction = transaction as ActiveTransaction<"ReceiverFulfilled">;
const chainConfig = config.chainConfig[_transaction.crosschainTx.invariant.receivingChainId];
if (!chainConfig) {
// this should not happen, this should get checked before this point
throw new ContractReaderNotAvailableForChain(_transaction.crosschainTx.invariant.receivingChainId, {});
}
if (!_transaction.payload.hashes?.receiving || !_transaction.payload.hashes?.receiving.fulfillHash) {
logger.warn("No receiving hashes with ReceiverFulfilled status", requestContext, methodContext, {
hashes: _transaction.payload.hashes,
});
return;
}
const receiverFulfillReceipt = await txService.getTransactionReceipt(
_transaction.crosschainTx.invariant.receivingChainId,
_transaction.payload.hashes.receiving.fulfillHash,
);
if ((receiverFulfillReceipt?.confirmations ?? 0) < chainConfig.confirmations) {
logger.info("Waiting for safe confirmations", requestContext, methodContext, {
chainId: _transaction.crosschainTx.invariant.receivingChainId,
txHash: _transaction.payload.hashes.receiving.fulfillHash,
txConfirmations: receiverFulfillReceipt?.confirmations ?? 0,
configuredConfirmations: chainConfig.confirmations,
});
return;
}
const fulfillPayload: FulfillPayload = _transaction.payload;
try {
logger.info("Fulfilling sender", requestContext, methodContext);
receipt = await fulfill(
_transaction.crosschainTx.invariant,
{
amount: _transaction.crosschainTx.sending.amount,
expiry: _transaction.crosschainTx.sending.expiry,
preparedBlockNumber: _transaction.crosschainTx.sending.preparedBlockNumber,
signature: fulfillPayload.signature,
callData: fulfillPayload.callData,
relayerFee: fulfillPayload.relayerFee,
},
requestContext,
);
logger.info("Fulfilled sender", requestContext, methodContext, { txHash: receipt?.transactionHash });
const sendingAssetName = getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
);
const receivingAssetName = getAssetName(
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
);
completedTransfer.inc({
sendingAssetId: _transaction.crosschainTx.invariant.sendingAssetId,
receivingAssetId: _transaction.crosschainTx.invariant.receivingAssetId,
sendingChainId: _transaction.crosschainTx.invariant.sendingChainId,
receivingChainId: _transaction.crosschainTx.invariant.receivingChainId,
sendingAssetName,
receivingAssetName,
});
receiverFulfilled.inc(
{
assetId: _transaction.crosschainTx.invariant.receivingAssetId,
chainId: _transaction.crosschainTx.invariant.receivingChainId,
assetName: receivingAssetName,
},
1,
);
senderFulfilled.inc(
{
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
},
1,
);
// Update total transferred volume (denominated in receiving asset)
incrementTotalTransferredVolume(
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
_transaction.crosschainTx.receiving!.amount,
requestContext,
);
// wrap in promise so it isnt awaited
const incrementFeesPromise = async () => {
// Get the fees in sending asset
// NOTE: may not be exact same rate depending on oracle returns
const fees = await getFeesInSendingAsset(
BigNumber.from(_transaction.crosschainTx.receiving!.amount),
BigNumber.from(_transaction.crosschainTx.sending.amount),
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
);
logger.info("Got fees in sending asset", requestContext, methodContext, {
receivedAmount: _transaction.crosschainTx.receiving!.amount,
sentAmount: _transaction.crosschainTx.sending.amount,
sendingAssetId: _transaction.crosschainTx.invariant.sendingAssetId,
sendingChainId: _transaction.crosschainTx.invariant.sendingChainId,
receivingAssetId: _transaction.crosschainTx.invariant.receivingAssetId,
receivingChainId: _transaction.crosschainTx.invariant.receivingChainId,
fees,
});
// Add difference between sending and receiving amount
await incrementFees(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
BigNumber.from(fees),
requestContext,
);
};
incrementFeesPromise();
} catch (err: any) {
senderFailedFulfill.inc({
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
),
});
const jsonErr = jsonifyError(err);
if (safeJsonStringify(jsonErr).includes("#F:019")) {
logger.warn("Sender already fulfilled", requestContext, methodContext, { error: jsonErr });
} else {
logger.error("Error fulfilling sender", requestContext, methodContext, jsonErr, {
chainId: transaction.crosschainTx.invariant.sendingChainId,
});
}
}
} else if (transaction.status === CrosschainTransactionStatus.ReceiverExpired) {
const requestContext = createRequestContext(
"ContractReader => ReceiverExpired",
transaction.crosschainTx.invariant.transactionId,
);
const _transaction = transaction as ActiveTransaction<"ReceiverExpired">;
if (!_transaction.payload.hashes?.receiving) {
logger.warn("No receiving hashes with ReceiverExpired status", requestContext, methodContext, {
hashes: _transaction.payload.hashes,
});
return;
}
try {
logger.info("Cancelling expired receiver", requestContext, methodContext);
receipt = await cancel(
_transaction.crosschainTx.invariant,
{
amount: _transaction.crosschainTx.receiving!.amount,
expiry: _transaction.crosschainTx.receiving!.expiry,
preparedBlockNumber: _transaction.crosschainTx.receiving!.preparedBlockNumber,
preparedTransactionHash: _transaction.payload.hashes.receiving.prepareHash,
side: "receiver",
},
requestContext,
);
logger.info("Cancelled receiver", requestContext, methodContext, {
txHash: receipt?.transactionHash,
});
const receivingAssetName = getAssetName(
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
);
receiverCancelled.inc({
assetId: _transaction.crosschainTx.invariant.receivingAssetId,
chainId: _transaction.crosschainTx.invariant.receivingChainId,
assetName: receivingAssetName,
});
receiverExpired.inc({
assetId: _transaction.crosschainTx.invariant.receivingAssetId,
chainId: _transaction.crosschainTx.invariant.receivingChainId,
assetName: receivingAssetName,
});
} catch (err: any) {
receiverFailedCancel.inc({
assetId: _transaction.crosschainTx.invariant.receivingAssetId,
chainId: _transaction.crosschainTx.invariant.receivingChainId,
assetName: getAssetName(
_transaction.crosschainTx.invariant.receivingAssetId,
_transaction.crosschainTx.invariant.receivingChainId,
),
});
const errJson = jsonifyError(err);
if (safeJsonStringify(errJson).includes("#C:019")) {
logger.warn("Already cancelled", requestContext, methodContext, { error: errJson });
} else {
logger.error("Error cancelling receiver", requestContext, methodContext, errJson, {
chainId: transaction.crosschainTx.invariant.receivingChainId,
});
}
}
} else if (transaction.status === CrosschainTransactionStatus.SenderExpired) {
const requestContext = createRequestContext(
"ContractReader => SenderExpired",
transaction.crosschainTx.invariant.transactionId,
);
const _transaction = transaction as ActiveTransaction<"SenderExpired">;
if (!_transaction.payload.hashes.sending) {
logger.warn("No sending hashes with SenderExpired status", requestContext, methodContext, {
hashes: _transaction.payload.hashes,
});
return;
}
try {
logger.info("Cancelling expired sender", requestContext, methodContext);
receipt = await cancel(
_transaction.crosschainTx.invariant,
{
amount: _transaction.crosschainTx.sending.amount,
expiry: _transaction.crosschainTx.sending.expiry,
preparedBlockNumber: _transaction.crosschainTx.sending.preparedBlockNumber,
preparedTransactionHash: _transaction.payload.hashes.sending.prepareHash,
side: "sender",
},
requestContext,
);
logger.info("Cancelled sender", requestContext, methodContext, { txHash: receipt?.transactionHash });
const sendingAssetName = getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
);
senderCancelled.inc({
assetId: transaction.crosschainTx.invariant.sendingAssetId,
chainId: transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
});
senderExpired.inc({
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
});
} catch (err: any) {
const errJson = jsonifyError(err);
if (safeJsonStringify(errJson).includes("#C:019")) {
logger.warn("Already cancelled", requestContext, methodContext, { error: errJson });
} else {
logger.error("Error cancelling sender", requestContext, methodContext, errJson, {
chainId: transaction.crosschainTx.invariant.sendingChainId,
});
}
}
// If sender is cancelled, receiver should already be expired. If we do
// not cancel here that is *ok* because it would have been caught earlier
// when we cancel the receiving chain side (via enforcement)
} else if (transaction.status === CrosschainTransactionStatus.ReceiverCancelled) {
const _transaction = transaction as ActiveTransaction<"ReceiverCancelled">;
// if receiver is cancelled, cancel the sender as well
const requestContext = createRequestContext(
"ContractReader => ReceiverCancelled",
transaction.crosschainTx.invariant.transactionId,
);
if (!_transaction.payload.hashes.sending) {
logger.warn("No sending hashes with ReceiverCancelled status", requestContext, methodContext, {
hashes: _transaction.payload.hashes,
});
return;
}
try {
logger.info("Cancelling sender after receiver cancelled", requestContext, methodContext);
receipt = await cancel(
_transaction.crosschainTx.invariant,
{
amount: _transaction.crosschainTx.sending.amount,
expiry: _transaction.crosschainTx.sending.expiry,
preparedBlockNumber: _transaction.crosschainTx.sending.preparedBlockNumber,
preparedTransactionHash: _transaction.payload.hashes.sending.prepareHash,
side: "sender",
},
requestContext,
);
logger.info("Cancelled sender", requestContext, methodContext, { txHash: receipt?.transactionHash });
const sendingAssetName = getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
);
senderCancelled.inc({
assetId: transaction.crosschainTx.invariant.sendingAssetId,
chainId: transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
});
} catch (err: any) {
senderFailedCancel.inc({
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
),
});
const errJson = jsonifyError(err);
if (safeJsonStringify(errJson).includes("#C:019")) {
logger.warn("Already cancelled", requestContext, methodContext, { error: errJson });
} else {
logger.error("Error cancelling sender", requestContext, methodContext, errJson, {
chainId: transaction.crosschainTx.invariant.sendingChainId,
});
}
}
} else if (transaction.status === CrosschainTransactionStatus.ReceiverNotConfigured) {
const _transaction = transaction as ActiveTransaction<"ReceiverNotConfigured">;
// if receiver is not configured, cancel the sender
const requestContext = createRequestContext(
"ContractReader => ReceiverNotConfigured",
transaction.crosschainTx.invariant.transactionId,
);
if (!_transaction.payload.hashes.sending) {
logger.warn("No sending hashes with ReceiverNotConfigured status", requestContext, methodContext, {
hashes: _transaction.payload.hashes,
});
return;
}
try {
logger.info("Cancelling sender because receiver is not configured", requestContext, methodContext);
receipt = await cancel(
_transaction.crosschainTx.invariant,
{
amount: _transaction.crosschainTx.sending.amount,
expiry: _transaction.crosschainTx.sending.expiry,
preparedBlockNumber: _transaction.crosschainTx.sending.preparedBlockNumber,
preparedTransactionHash: _transaction.payload.hashes.sending.prepareHash,
side: "sender",
},
requestContext,
);
logger.info("Cancelled sender", requestContext, methodContext, { txHash: receipt?.transactionHash });
const sendingAssetName = getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
);
senderCancelled.inc({
assetId: transaction.crosschainTx.invariant.sendingAssetId,
chainId: transaction.crosschainTx.invariant.sendingChainId,
assetName: sendingAssetName,
});
} catch (err: any) {
senderFailedCancel.inc({
assetId: _transaction.crosschainTx.invariant.sendingAssetId,
chainId: _transaction.crosschainTx.invariant.sendingChainId,
assetName: getAssetName(
_transaction.crosschainTx.invariant.sendingAssetId,
_transaction.crosschainTx.invariant.sendingChainId,
),
});
const errJson = jsonifyError(err);
if (safeJsonStringify(errJson).includes("#C:019")) {
logger.warn("Already cancelled", requestContext, methodContext, { error: errJson });
} else {
logger.error("Error cancelling sender", requestContext, methodContext, errJson, {
chainId: transaction.crosschainTx.invariant.sendingChainId,
});
}
}
}
return receipt;
}; | the_stack |
export class PositionStats {
AB: number = 0;
AD: number = 0;
A2: number = 0;
constructor(public scale: number) {}
addVariable(v: Variable): void {
var ai = this.scale / v.scale;
var bi = v.offset / v.scale;
var wi = v.weight;
this.AB += wi * ai * bi;
this.AD += wi * ai * v.desiredPosition;
this.A2 += wi * ai * ai;
}
getPosn(): number {
return (this.AD - this.AB) / this.A2;
}
}
export class Constraint {
lm: number;
active: boolean = false;
unsatisfiable: boolean = false;
constructor(public left: Variable, public right: Variable, public gap: number, public equality: boolean = false) {
this.left = left;
this.right = right;
this.gap = gap;
this.equality = equality;
}
slack(): number {
return this.unsatisfiable ? Number.MAX_VALUE
: this.right.scale * this.right.position() - this.gap
- this.left.scale * this.left.position();
}
}
export class Variable {
offset: number = 0;
block: Block;
cIn: Constraint[];
cOut: Constraint[];
constructor(public desiredPosition: number, public weight: number = 1, public scale: number = 1) {}
dfdv(): number {
return 2.0 * this.weight * (this.position() - this.desiredPosition);
}
position(): number {
return (this.block.ps.scale * this.block.posn + this.offset) / this.scale;
}
// visit neighbours by active constraints within the same block
visitNeighbours(prev: Variable, f: (c: Constraint, next: Variable) => void ): void {
var ff = (c, next) => c.active && prev !== next && f(c, next);
this.cOut.forEach(c=> ff(c, c.right));
this.cIn.forEach(c=> ff(c, c.left));
}
}
export class Block {
vars: Variable[] = [];
posn: number;
ps: PositionStats;
blockInd: number;
constructor(v: Variable) {
v.offset = 0;
this.ps = new PositionStats(v.scale);
this.addVariable(v);
}
private addVariable(v: Variable): void {
v.block = this;
this.vars.push(v);
this.ps.addVariable(v);
this.posn = this.ps.getPosn();
}
// move the block where it needs to be to minimize cost
updateWeightedPosition(): void {
this.ps.AB = this.ps.AD = this.ps.A2 = 0;
for (var i = 0, n = this.vars.length; i < n; ++i)
this.ps.addVariable(this.vars[i]);
this.posn = this.ps.getPosn();
}
private compute_lm(v: Variable, u: Variable, postAction: (c: Constraint)=>void): number {
var dfdv = v.dfdv();
v.visitNeighbours(u, (c, next) => {
var _dfdv = this.compute_lm(next, v, postAction);
if (next === c.right) {
dfdv += _dfdv * c.left.scale;
c.lm = _dfdv;
} else {
dfdv += _dfdv * c.right.scale;
c.lm = -_dfdv;
}
postAction(c);
});
return dfdv / v.scale;
}
private populateSplitBlock(v: Variable, prev: Variable): void {
v.visitNeighbours(prev, (c, next) => {
next.offset = v.offset + (next === c.right ? c.gap : -c.gap);
this.addVariable(next);
this.populateSplitBlock(next, v);
});
}
// traverse the active constraint tree applying visit to each active constraint
traverse(visit: (c: Constraint) => any, acc: any[], v: Variable = this.vars[0], prev: Variable=null) {
v.visitNeighbours(prev, (c, next) => {
acc.push(visit(c));
this.traverse(visit, acc, next, v);
});
}
// calculate lagrangian multipliers on constraints and
// find the active constraint in this block with the smallest lagrangian.
// if the lagrangian is negative, then the constraint is a split candidate.
findMinLM(): Constraint {
var m: Constraint = null;
this.compute_lm(this.vars[0], null, c=> {
if (!c.equality && (m === null || c.lm < m.lm)) m = c;
});
return m;
}
private findMinLMBetween(lv: Variable, rv: Variable): Constraint {
this.compute_lm(lv, null, () => {});
var m = null;
this.findPath(lv, null, rv, (c, next)=> {
if (!c.equality && c.right === next && (m === null || c.lm < m.lm)) m = c;
});
return m;
}
private findPath(v: Variable, prev: Variable, to: Variable, visit: (c: Constraint, next:Variable)=>void): boolean {
var endFound = false;
v.visitNeighbours(prev, (c, next) => {
if (!endFound && (next === to || this.findPath(next, v, to, visit)))
{
endFound = true;
visit(c, next);
}
});
return endFound;
}
// Search active constraint tree from u to see if there is a directed path to v.
// Returns true if path is found.
isActiveDirectedPathBetween(u: Variable, v: Variable) : boolean {
if (u === v) return true;
var i = u.cOut.length;
while(i--) {
var c = u.cOut[i];
if (c.active && this.isActiveDirectedPathBetween(c.right, v))
return true;
}
return false;
}
// split the block into two by deactivating the specified constraint
static split(c: Constraint): Block[]{
/* DEBUG
console.log("split on " + c);
console.assert(c.active, "attempt to split on inactive constraint");
DEBUG */
c.active = false;
return [Block.createSplitBlock(c.left), Block.createSplitBlock(c.right)];
}
private static createSplitBlock(startVar: Variable): Block {
var b = new Block(startVar);
b.populateSplitBlock(startVar, null);
return b;
}
// find a split point somewhere between the specified variables
splitBetween(vl: Variable, vr: Variable): { constraint: Constraint; lb: Block; rb: Block } {
/* DEBUG
console.assert(vl.block === this);
console.assert(vr.block === this);
DEBUG */
var c = this.findMinLMBetween(vl, vr);
if (c !== null) {
var bs = Block.split(c);
return { constraint: c, lb: bs[0], rb: bs[1] };
}
// couldn't find a split point - for example the active path is all equality constraints
return null;
}
mergeAcross(b: Block, c: Constraint, dist: number): void {
c.active = true;
for (var i = 0, n = b.vars.length; i < n; ++i) {
var v = b.vars[i];
v.offset += dist;
this.addVariable(v);
}
this.posn = this.ps.getPosn();
}
cost(): number {
var sum = 0, i = this.vars.length;
while (i--) {
var v = this.vars[i],
d = v.position() - v.desiredPosition;
sum += d * d * v.weight;
}
return sum;
}
/* DEBUG
toString(): string {
var cs = [];
this.traverse(c=> c.toString() + "\n", cs)
return "b"+this.blockInd + "@" + this.posn + ": vars=" + this.vars.map(v=> v.toString()+":"+v.offset) + ";\n cons=\n" + cs;
}
DEBUG */
}
export class Blocks {
private list: Block[];
constructor(public vs: Variable[]) {
var n = vs.length;
this.list = new Array(n);
while (n--) {
var b = new Block(vs[n]);
this.list[n] = b;
b.blockInd = n;
}
}
cost(): number {
var sum = 0, i = this.list.length;
while (i--) sum += this.list[i].cost();
return sum;
}
insert(b: Block) {
/* DEBUG
console.assert(!this.contains(b), "blocks error: tried to reinsert block " + b.blockInd)
DEBUG */
b.blockInd = this.list.length;
this.list.push(b);
/* DEBUG
console.log("insert block: " + b.blockInd);
this.contains(b);
DEBUG */
}
remove(b: Block) {
/* DEBUG
console.log("remove block: " + b.blockInd);
console.assert(this.contains(b));
DEBUG */
var last = this.list.length - 1;
var swapBlock = this.list[last];
this.list.length = last;
if (b !== swapBlock) {
this.list[b.blockInd] = swapBlock;
swapBlock.blockInd = b.blockInd;
/* DEBUG
console.assert(this.contains(swapBlock));
DEBUG */
}
}
// merge the blocks on either side of the specified constraint, by copying the smaller block into the larger
// and deleting the smaller.
merge(c: Constraint): void {
var l = c.left.block, r = c.right.block;
/* DEBUG
console.assert(l!==r, "attempt to merge within the same block");
DEBUG */
var dist = c.right.offset - c.left.offset - c.gap;
if (l.vars.length < r.vars.length) {
r.mergeAcross(l, c, dist);
this.remove(l);
} else {
l.mergeAcross(r, c, -dist);
this.remove(r);
}
/* DEBUG
console.assert(Math.abs(c.slack()) < 1e-6, "Error: Constraint should be at equality after merge!");
console.log("merged on " + c);
DEBUG */
}
forEach(f: (b: Block, i: number) => void ) {
this.list.forEach(f);
}
// useful, for example, after variable desired positions change.
updateBlockPositions(): void {
this.list.forEach(b=> b.updateWeightedPosition());
}
// split each block across its constraint with the minimum lagrangian
split(inactive: Constraint[]): void {
this.updateBlockPositions();
this.list.forEach(b=> {
var v = b.findMinLM();
if (v !== null && v.lm < Solver.LAGRANGIAN_TOLERANCE) {
b = v.left.block;
Block.split(v).forEach(nb=>this.insert(nb));
this.remove(b);
inactive.push(v);
/* DEBUG
console.assert(this.contains(v.left.block));
console.assert(this.contains(v.right.block));
DEBUG */
}
});
}
/* DEBUG
// checks b is in the block, and does a sanity check over list index integrity
contains(b: Block): boolean {
var result = false;
this.list.forEach((bb, i) => {
if (bb.blockInd !== i) {
console.error("blocks error, blockInd " + b.blockInd + " found at " + i);
return false;
}
result = result || b === bb;
});
return result;
}
toString(): string {
return this.list.toString();
}
DEBUG */
}
export class Solver {
bs: Blocks;
inactive: Constraint[];
static LAGRANGIAN_TOLERANCE = -1e-4;
static ZERO_UPPERBOUND = -1e-10;
constructor(public vs: Variable[], public cs: Constraint[]) {
this.vs = vs;
vs.forEach(v => {
v.cIn = [], v.cOut = [];
/* DEBUG
v.toString = () => "v" + vs.indexOf(v);
DEBUG */
});
this.cs = cs;
cs.forEach(c => {
c.left.cOut.push(c);
c.right.cIn.push(c);
/* DEBUG
c.toString = () => c.left + "+" + c.gap + "<=" + c.right + " slack=" + c.slack() + " active=" + c.active;
DEBUG */
});
this.inactive = cs.map(c=> { c.active = false; return c; });
this.bs = null;
}
cost(): number {
return this.bs.cost();
}
// set starting positions without changing desired positions.
// Note: it throws away any previous block structure.
setStartingPositions(ps: number[]): void {
this.inactive = this.cs.map(c=> { c.active = false; return c; });
this.bs = new Blocks(this.vs);
this.bs.forEach((b, i) => b.posn = ps[i]);
}
setDesiredPositions(ps: number[]): void {
this.vs.forEach((v, i) => v.desiredPosition = ps[i]);
}
/* DEBUG
private getId(v: Variable): number {
return this.vs.indexOf(v);
}
// sanity check of the index integrity of the inactive list
checkInactive(): void {
var inactiveCount = 0;
this.cs.forEach(c=> {
var i = this.inactive.indexOf(c);
console.assert(!c.active && i >= 0 || c.active && i < 0, "constraint should be in the inactive list if it is not active: " + c);
if (i >= 0) {
inactiveCount++;
} else {
console.assert(c.active, "inactive constraint not found in inactive list: " + c);
}
});
console.assert(inactiveCount === this.inactive.length, inactiveCount + " inactive constraints found, " + this.inactive.length + "in inactive list");
}
// after every call to satisfy the following should check should pass
checkSatisfied(): void {
this.cs.forEach(c=>console.assert(c.slack() >= vpsc.Solver.ZERO_UPPERBOUND, "Error: Unsatisfied constraint! "+c));
}
DEBUG */
private mostViolated(): Constraint {
var minSlack = Number.MAX_VALUE,
v: Constraint = null,
l = this.inactive,
n = l.length,
deletePoint = n;
for (var i = 0; i < n; ++i) {
var c = l[i];
if (c.unsatisfiable) continue;
var slack = c.slack();
if (c.equality || slack < minSlack) {
minSlack = slack;
v = c;
deletePoint = i;
if (c.equality) break;
}
}
if (deletePoint !== n &&
(minSlack < Solver.ZERO_UPPERBOUND && !v.active || v.equality))
{
l[deletePoint] = l[n - 1];
l.length = n - 1;
}
return v;
}
// satisfy constraints by building block structure over violated constraints
// and moving the blocks to their desired positions
satisfy(): void {
if (this.bs == null) {
this.bs = new Blocks(this.vs);
}
/* DEBUG
console.log("satisfy: " + this.bs);
DEBUG */
this.bs.split(this.inactive);
var v: Constraint = null;
while ((v = this.mostViolated()) && (v.equality || v.slack() < Solver.ZERO_UPPERBOUND && !v.active)) {
var lb = v.left.block, rb = v.right.block;
/* DEBUG
console.log("most violated is: " + v);
this.bs.contains(lb);
this.bs.contains(rb);
DEBUG */
if (lb !== rb) {
this.bs.merge(v);
} else {
if (lb.isActiveDirectedPathBetween(v.right, v.left)) {
// cycle found!
v.unsatisfiable = true;
continue;
}
// constraint is within block, need to split first
var split = lb.splitBetween(v.left, v.right);
if (split !== null) {
this.bs.insert(split.lb);
this.bs.insert(split.rb);
this.bs.remove(lb);
this.inactive.push(split.constraint);
} else {
/* DEBUG
console.log("unsatisfiable constraint found");
DEBUG */
v.unsatisfiable = true;
continue;
}
if (v.slack() >= 0) {
/* DEBUG
console.log("violated constraint indirectly satisfied: " + v);
DEBUG */
// v was satisfied by the above split!
this.inactive.push(v);
} else {
/* DEBUG
console.log("merge after split:");
DEBUG */
this.bs.merge(v);
}
}
/* DEBUG
this.bs.contains(v.left.block);
this.bs.contains(v.right.block);
this.checkInactive();
DEBUG */
}
/* DEBUG
this.checkSatisfied();
DEBUG */
}
// repeatedly build and split block structure until we converge to an optimal solution
solve(): number {
this.satisfy();
var lastcost = Number.MAX_VALUE, cost = this.bs.cost();
while (Math.abs(lastcost - cost) > 0.0001) {
this.satisfy();
lastcost = cost;
cost = this.bs.cost();
}
return cost;
}
}
/**
* Remove overlap between spans while keeping their centers as close as possible to the specified desiredCenters.
* Lower and upper bounds will be respected if the spans physically fit between them
* (otherwise they'll be moved and their new position returned).
* If no upper/lower bound is specified then the bounds of the moved spans will be returned.
* returns a new center for each span.
*/
export function removeOverlapInOneDimension(spans: { size: number, desiredCenter: number }[], lowerBound?: number, upperBound?: number)
: { newCenters: number[], lowerBound: number, upperBound: number }
{
const vs: Variable[] = spans.map(s => new Variable(s.desiredCenter));
const cs: Constraint[] = [];
const n = spans.length;
for (var i = 0; i < n - 1; i++) {
const left = spans[i], right = spans[i + 1];
cs.push(new Constraint(vs[i], vs[i + 1], (left.size + right.size) / 2));
}
const leftMost = vs[0],
rightMost = vs[n - 1],
leftMostSize = spans[0].size / 2,
rightMostSize = spans[n - 1].size / 2;
let vLower: Variable = null, vUpper: Variable = null;
if (lowerBound) {
vLower = new Variable(lowerBound, leftMost.weight * 1000);
vs.push(vLower);
cs.push(new Constraint(vLower, leftMost, leftMostSize));
}
if (upperBound) {
vUpper = new Variable(upperBound, rightMost.weight * 1000);
vs.push(vUpper);
cs.push(new Constraint(rightMost, vUpper, rightMostSize));
}
var solver = new Solver(vs, cs);
solver.solve();
return {
newCenters: vs.slice(0, spans.length).map(v => v.position()),
lowerBound: vLower ? vLower.position() : leftMost.position() - leftMostSize,
upperBound: vUpper ? vUpper.position() : rightMost.position() + rightMostSize
};
} | the_stack |
import React from 'react';
import { MutableRefObject } from 'react';
import {
TypeComputedProps,
TypeComputedColumn,
TypeSingleSortInfo,
} from '../../types';
import { IS_IE, IS_MS_BROWSER } from '../../../detect-ua';
import { getCellHeader } from '../../../Layout/ColumnLayout/HeaderLayout/Header';
import Menu from '../../../packages/Menu';
import renderGridMenu from '../../../renderGridMenu';
const COLUMN_MENU_ALIGN_POSITIONS = [
'tl-bl',
'tr-br',
'tl-tr',
'tr-tl',
'br-tr',
'bl-tl',
'br-tl',
'bl-tr',
'lc-tr',
'rc-tl',
];
const COLUMN_MENU_ALIGN_POSITIONS_RTL = [
'tr-br',
'tl-bl',
'tr-tl',
'tl-tr',
'br-tr',
'bl-tl',
'br-tl',
'bl-tr',
'lc-tr',
'rc-tl',
];
const notEmpty = (x: any): boolean => !!x;
const getTopComputedProps = (
computedProps: TypeComputedProps
): TypeComputedProps => {
while (computedProps.initialProps.parentComputedProps) {
computedProps = computedProps.initialProps.parentComputedProps;
}
return computedProps;
};
const getAlignTo = (selection: any, menuTools: any[], index: number) => {
const filteredTools = menuTools.filter(
(_, i) => i !== Object.keys(selection).length
);
const length = filteredTools.length;
let alignTo;
if (index > length) {
alignTo = filteredTools[length - 1];
} else if (index <= length) {
alignTo = filteredTools[index - 1];
}
if (!alignTo) {
alignTo = filteredTools[0];
}
return alignTo;
};
export default (
computedProps: TypeComputedProps,
computedPropsRef: MutableRefObject<TypeComputedProps | null>
) => {
const cellProps = computedProps.columnContextMenuProps;
if (!cellProps) {
return null;
}
const groupBy = computedProps.computedGroupBy;
let visibleCountWithColumnMenu = 0;
const visibleMap = computedProps.initialProps.columns.reduce((acc, col) => {
const column = computedProps.getColumnBy((col.name || col.id)!);
if (column && computedProps.isColumnVisible(column)) {
const value = (column.id || column.name)!;
acc[value] = column.id || column.name;
if (column.showColumnMenuTool !== false) {
visibleCountWithColumnMenu++;
}
}
return acc;
}, {} as { [key: string]: any });
const onSelectionChange = (selection: any) => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
if (IS_IE) {
computedProps.preventIEMenuCloseRef.current = true;
setTimeout(() => {
computedProps.preventIEMenuCloseRef.current = false;
}, 100);
}
computedProps.initialProps.columns.forEach(col => {
const computedCol = computedProps.getColumnBy(col) as TypeComputedColumn;
if (computedCol) {
const visible = computedCol.id in selection;
computedProps.setColumnVisible(col, visible);
}
});
if (computedProps.updateMenuPositionOnColumnsChange) {
const menuTools = Array.prototype.slice.call(
computedProps.domRef.current.querySelectorAll(
'.InovuaReactDataGrid__column-header__menu-tool'
)
);
const mainMenu = computedProps.domRef.current.querySelector(
'.InovuaReactDataGrid > .inovua-react-toolkit-menu'
);
const cellInstance = computedProps.columnContextMenuInstanceProps;
const columnIndex = cellInstance.props.computedVisibleIndex;
const alignTo = getAlignTo(selection, menuTools, columnIndex);
if (alignTo) {
computedProps.updateMainMenuPosition(alignTo);
if (mainMenu) {
(mainMenu as any).style.transition = 'transform 200ms';
setTimeout(() => {
(mainMenu as any).style.transition = '';
}, 200);
}
}
}
};
const currentColumn = computedProps.getColumnBy(
cellProps.id
) as TypeComputedColumn;
const colSortInfo = currentColumn.computedSortInfo as TypeSingleSortInfo;
const lockLimit =
!cellProps.computedLocked && computedProps.unlockedColumns.length <= 1;
const isAutoLock =
cellProps.autoLock &&
computedProps.lockedStartColumns &&
!!computedProps.lockedStartColumns.filter(c => !c.autoLock).length;
let showColumnMenuLockOptions =
cellProps.showColumnMenuLockOptions !== undefined
? cellProps.showColumnMenuLockOptions
: computedProps.initialProps.showColumnMenuLockOptions;
if (cellProps.lockable === false) {
showColumnMenuLockOptions = false;
}
const showColumnMenuGroupOptions =
cellProps.showColumnMenuGroupOptions !== undefined
? cellProps.showColumnMenuGroupOptions
: computedProps.initialProps.showColumnMenuGroupOptions;
const showColumnMenuFilterOptions =
cellProps.showColumnMenuFilterOptions !== undefined
? cellProps.showColumnMenuFilterOptions
: computedProps.initialProps.showColumnMenuFilterOptions;
const showColumnMenuSortOptions =
cellProps.showColumnMenuSortOptions !== undefined
? cellProps.showColumnMenuSortOptions
: computedProps.initialProps.showColumnMenuSortOptions;
let columnsItem: any = {
label: computedProps.i18n('columns'),
itemId: 'columns',
menuProps: {
dismissOnClick: false,
},
items: computedProps
.getColumnsInOrder()
.filter(c => c.showInContextMenu !== false)
.map((c: TypeComputedColumn) => {
const value = c.id || c.name || '';
return {
label: getCellHeader(c, c, null, {
currentColumn,
}),
itemId: `column-${c.id}`,
value,
disabled:
c.hideable === false ||
(visibleCountWithColumnMenu === 1 && visibleMap[value]),
name: value,
};
}),
};
if (computedProps.computedPivot) {
columnsItem = null;
}
let items = [
showColumnMenuSortOptions === false
? null
: {
label: computedProps.i18n('sortAsc'),
itemId: 'sortAsc',
disabled:
!cellProps.computedSortable ||
(colSortInfo && colSortInfo.dir === 1),
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setColumnSortInfo(cellProps.id, 1);
computedProps.hideColumnContextMenu();
},
},
showColumnMenuSortOptions === false
? null
: {
label: computedProps.i18n('sortDesc'),
itemId: 'sortDesc',
disabled:
!cellProps.computedSortable ||
(colSortInfo && colSortInfo.dir === -1),
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setColumnSortInfo(cellProps.id, -1);
computedProps.hideColumnContextMenu();
},
},
(computedProps.initialProps.allowUnsort ||
computedProps.computedIsMultiSort) &&
showColumnMenuSortOptions !== false
? {
label: computedProps.i18n('unsort'),
itemId: 'unsort',
disabled: !colSortInfo,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.unsortColumn(cellProps.id);
computedProps.hideColumnContextMenu();
},
}
: null,
showColumnMenuGroupOptions === false ? null : '-',
showColumnMenuGroupOptions === false
? null
: {
label: computedProps.i18n('group'),
itemId: 'group',
disabled:
!groupBy ||
groupBy.indexOf(cellProps.id) !== -1 ||
currentColumn.groupBy === false,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.addGroupByColumn(cellProps.id);
computedProps.hideColumnContextMenu();
},
},
showColumnMenuGroupOptions === false
? null
: {
label: computedProps.i18n('ungroup'),
itemId: 'ungroup',
disabled:
!groupBy ||
groupBy.indexOf(cellProps.id) === -1 ||
currentColumn.groupBy === false,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.removeGroupByColumn(cellProps.id);
computedProps.hideColumnContextMenu();
},
},
showColumnMenuLockOptions === false ? null : '-',
showColumnMenuLockOptions === false
? null
: {
label: computedProps.i18n('lockStart'),
itemId: 'lockStart',
disabled: cellProps.computedLocked === 'start' || lockLimit,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setColumnLocked(cellProps.id, 'start');
computedProps.hideColumnContextMenu();
},
},
showColumnMenuLockOptions === false
? null
: {
label: computedProps.i18n('lockEnd'),
itemId: 'lockEnd',
disabled:
cellProps.computedLocked === 'end' || lockLimit || isAutoLock,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setColumnLocked(cellProps.id, 'end');
computedProps.hideColumnContextMenu();
},
},
showColumnMenuLockOptions === false
? null
: {
label: computedProps.i18n('unlock'),
itemId: 'unlock',
disabled: !cellProps.computedLocked || isAutoLock,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setColumnLocked(cellProps.id, false);
computedProps.hideColumnContextMenu();
},
},
columnsItem ? '-' : null,
columnsItem,
].filter(notEmpty);
if (items[0] === '-') {
items = items.slice(1);
}
if (
computedProps.initialProps.enableFiltering !== false &&
showColumnMenuFilterOptions !== false
) {
const isFilterable = computedProps.computedFilterable;
const showFilteringMenuItems = computedProps.shouldShowFilteringMenuItems
? computedProps.shouldShowFilteringMenuItems()
: false;
if (showFilteringMenuItems) {
items.push('-');
items.push({
label: computedProps.i18n('showFilteringRow', 'Show Filtering Row'),
itemId: 'showFilteringRow',
disabled: isFilterable,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setEnableFiltering(true);
computedProps.hideColumnContextMenu();
},
});
items.push({
label: computedProps.i18n('hideFilteringRow', 'Hide Filtering Row'),
itemId: 'hideFilteringRow',
disabled: !isFilterable,
onClick: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.setEnableFiltering(false);
computedProps.hideColumnContextMenu();
},
});
}
}
items.forEach(item => {
const onClick = item.onClick;
if (onClick && IS_MS_BROWSER) {
item.onClick = () => {
// in order to avoid the browser
// triggering weird text selection
// when you open the menu a second time
// after clicking an item beforehand
requestAnimationFrame(onClick);
};
}
});
let constrainToComputedProps = getTopComputedProps(computedProps);
// const constrainTo = constrainToComputedProps.columnContextMenuInfoRef.current.getMenuConstrainTo();
const constrainTo = true;
const menuProps = {
updatePositionOnScroll: computedProps.updateMenuPositionOnScroll,
maxHeight: constrainToComputedProps.initialProps
.columnContextMenuConstrainTo
? null
: constrainTo === true
? null
: computedProps.getMenuAvailableHeight(),
nativeScroll: !IS_MS_BROWSER,
autoFocus: true,
enableSelection: true,
defaultSelected: visibleMap,
onDismiss: () => {
const { current: computedProps } = computedPropsRef;
if (!computedProps) {
return;
}
computedProps.hideColumnContextMenu();
},
onSelectionChange,
style: {
zIndex: 110000,
position:
computedProps.initialProps.columnContextMenuPosition || 'absolute',
},
items,
theme: computedProps.theme,
constrainTo,
alignPositions:
computedProps.initialProps.columnContextMenuAlignPositions ||
computedProps.rtl
? COLUMN_MENU_ALIGN_POSITIONS_RTL
: COLUMN_MENU_ALIGN_POSITIONS,
alignTo: computedProps.columnContextMenuInfoRef.current.menuAlignTo,
};
let result;
if (computedProps.initialProps.renderColumnContextMenu) {
result = computedProps.initialProps.renderColumnContextMenu(menuProps, {
cellProps,
grid: computedProps.publicAPI,
computedProps,
computedPropsRef,
});
}
if (result === undefined) {
result = <Menu {...menuProps} />;
}
if (computedProps.initialProps.renderGridMenu) {
return computedProps.initialProps.renderGridMenu(result, computedProps);
}
return renderGridMenu(result, computedProps);
}; | the_stack |
import { ApiResponse, FileWrapper, RequestOptions } from '../core';
import {
AcceptDisputeResponse,
acceptDisputeResponseSchema,
} from '../models/acceptDisputeResponse';
import {
CreateDisputeEvidenceFileRequest,
createDisputeEvidenceFileRequestSchema,
} from '../models/createDisputeEvidenceFileRequest';
import {
CreateDisputeEvidenceFileResponse,
createDisputeEvidenceFileResponseSchema,
} from '../models/createDisputeEvidenceFileResponse';
import {
CreateDisputeEvidenceTextRequest,
createDisputeEvidenceTextRequestSchema,
} from '../models/createDisputeEvidenceTextRequest';
import {
CreateDisputeEvidenceTextResponse,
createDisputeEvidenceTextResponseSchema,
} from '../models/createDisputeEvidenceTextResponse';
import {
DeleteDisputeEvidenceResponse,
deleteDisputeEvidenceResponseSchema,
} from '../models/deleteDisputeEvidenceResponse';
import {
ListDisputeEvidenceResponse,
listDisputeEvidenceResponseSchema,
} from '../models/listDisputeEvidenceResponse';
import {
ListDisputesResponse,
listDisputesResponseSchema,
} from '../models/listDisputesResponse';
import {
RetrieveDisputeEvidenceResponse,
retrieveDisputeEvidenceResponseSchema,
} from '../models/retrieveDisputeEvidenceResponse';
import {
RetrieveDisputeResponse,
retrieveDisputeResponseSchema,
} from '../models/retrieveDisputeResponse';
import {
SubmitEvidenceResponse,
submitEvidenceResponseSchema,
} from '../models/submitEvidenceResponse';
import { optional, string } from '../schema';
import { BaseApi } from './baseApi';
export class DisputesApi extends BaseApi {
/**
* Returns a list of disputes associated with a particular account.
*
* @param cursor A pagination cursor returned by a previous call to this endpoint. Provide this
* cursor to retrieve the next set of results for the original query. For more
* information, see [Pagination](https://developer.squareup.
* com/docs/basics/api101/pagination).
* @param states The dispute states to filter the result. If not specified, the endpoint returns all
* open disputes (the dispute status is not `INQUIRY_CLOSED`, `WON`, or `LOST`).
* @param locationId The ID of the location for which to return a list of disputes. If not specified, the
* endpoint returns all open disputes (the dispute status is not `INQUIRY_CLOSED`, `WON`,
* or `LOST`) associated with all locations.
* @return Response from the API call
*/
async listDisputes(
cursor?: string,
states?: string,
locationId?: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<ListDisputesResponse>> {
const req = this.createRequest('GET', '/v2/disputes');
const mapped = req.prepareArgs({
cursor: [cursor, optional(string())],
states: [states, optional(string())],
locationId: [locationId, optional(string())],
});
req.query('cursor', mapped.cursor);
req.query('states', mapped.states);
req.query('location_id', mapped.locationId);
return req.callAsJson(listDisputesResponseSchema, requestOptions);
}
/**
* Returns details about a specific dispute.
*
* @param disputeId The ID of the dispute you want more details about.
* @return Response from the API call
*/
async retrieveDispute(
disputeId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<RetrieveDisputeResponse>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({ disputeId: [disputeId, string()] });
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}`;
return req.callAsJson(retrieveDisputeResponseSchema, requestOptions);
}
/**
* Accepts the loss on a dispute. Square returns the disputed amount to the cardholder and
* updates the dispute state to ACCEPTED.
*
* Square debits the disputed amount from the seller’s Square account. If the Square account
* does not have sufficient funds, Square debits the associated bank account.
*
* @param disputeId The ID of the dispute you want to accept.
* @return Response from the API call
*/
async acceptDispute(
disputeId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<AcceptDisputeResponse>> {
const req = this.createRequest('POST');
const mapped = req.prepareArgs({ disputeId: [disputeId, string()] });
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/accept`;
return req.callAsJson(acceptDisputeResponseSchema, requestOptions);
}
/**
* Returns a list of evidence associated with a dispute.
*
* @param disputeId The ID of the dispute.
* @param cursor A pagination cursor returned by a previous call to this endpoint. Provide this cursor
* to retrieve the next set of results for the original query. For more information, see
* [Pagination](https://developer.squareup.com/docs/basics/api101/pagination).
* @return Response from the API call
*/
async listDisputeEvidence(
disputeId: string,
cursor?: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<ListDisputeEvidenceResponse>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
disputeId: [disputeId, string()],
cursor: [cursor, optional(string())],
});
req.query('cursor', mapped.cursor);
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/evidence`;
return req.callAsJson(listDisputeEvidenceResponseSchema, requestOptions);
}
/**
* Uploads a file to use as evidence in a dispute challenge. The endpoint accepts HTTP
* multipart/form-data file uploads in HEIC, HEIF, JPEG, PDF, PNG, and TIFF formats.
*
* @param disputeId The ID of the dispute you want to upload evidence
* for.
* @param request Defines the parameters for a
* `CreateDisputeEvidenceFile` request.
* @param imageFile
* @return Response from the API call
*/
async createDisputeEvidenceFile(
disputeId: string,
request?: CreateDisputeEvidenceFileRequest,
imageFile?: FileWrapper,
requestOptions?: RequestOptions
): Promise<ApiResponse<CreateDisputeEvidenceFileResponse>> {
const req = this.createRequest('POST');
const mapped = req.prepareArgs({
disputeId: [disputeId, string()],
request: [request, optional(createDisputeEvidenceFileRequestSchema)],
});
req.formData({
request: JSON.stringify(mapped.request),
image_file: imageFile,
});
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/evidence-files`;
return req.callAsJson(
createDisputeEvidenceFileResponseSchema,
requestOptions
);
}
/**
* Uploads text to use as evidence for a dispute challenge.
*
* @param disputeId The ID of the dispute you want to upload evidence
* for.
* @param body An object containing the fields to POST for the
* request. See the corresponding object definition for
* field details.
* @return Response from the API call
*/
async createDisputeEvidenceText(
disputeId: string,
body: CreateDisputeEvidenceTextRequest,
requestOptions?: RequestOptions
): Promise<ApiResponse<CreateDisputeEvidenceTextResponse>> {
const req = this.createRequest('POST');
const mapped = req.prepareArgs({
disputeId: [disputeId, string()],
body: [body, createDisputeEvidenceTextRequestSchema],
});
req.json(mapped.body);
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/evidence-text`;
return req.callAsJson(
createDisputeEvidenceTextResponseSchema,
requestOptions
);
}
/**
* Removes specified evidence from a dispute.
*
* Square does not send the bank any evidence that is removed. Also, you cannot remove evidence after
* submitting it to the bank using [SubmitEvidence]($e/Disputes/SubmitEvidence).
*
* @param disputeId The ID of the dispute you want to remove evidence from.
* @param evidenceId The ID of the evidence you want to remove.
* @return Response from the API call
*/
async deleteDisputeEvidence(
disputeId: string,
evidenceId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<DeleteDisputeEvidenceResponse>> {
const req = this.createRequest('DELETE');
const mapped = req.prepareArgs({
disputeId: [disputeId, string()],
evidenceId: [evidenceId, string()],
});
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/evidence/${mapped.evidenceId}`;
return req.callAsJson(deleteDisputeEvidenceResponseSchema, requestOptions);
}
/**
* Returns the evidence metadata specified by the evidence ID in the request URL path
*
* You must maintain a copy of the evidence you upload if you want to reference it later. You cannot
* download the evidence after you upload it.
*
* @param disputeId The ID of the dispute that you want to retrieve evidence from.
* @param evidenceId The ID of the evidence to retrieve.
* @return Response from the API call
*/
async retrieveDisputeEvidence(
disputeId: string,
evidenceId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<RetrieveDisputeEvidenceResponse>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
disputeId: [disputeId, string()],
evidenceId: [evidenceId, string()],
});
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/evidence/${mapped.evidenceId}`;
return req.callAsJson(
retrieveDisputeEvidenceResponseSchema,
requestOptions
);
}
/**
* Submits evidence to the cardholder's bank.
*
* Before submitting evidence, Square compiles all available evidence. This includes evidence uploaded
* using the [CreateDisputeEvidenceFile]($e/Disputes/CreateDisputeEvidenceFile) and
* [CreateDisputeEvidenceText]($e/Disputes/CreateDisputeEvidenceText) endpoints and
* evidence automatically provided by Square, when available.
*
* @param disputeId The ID of the dispute that you want to submit evidence for.
* @return Response from the API call
*/
async submitEvidence(
disputeId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<SubmitEvidenceResponse>> {
const req = this.createRequest('POST');
const mapped = req.prepareArgs({ disputeId: [disputeId, string()] });
req.appendTemplatePath`/v2/disputes/${mapped.disputeId}/submit-evidence`;
return req.callAsJson(submitEvidenceResponseSchema, requestOptions);
}
} | the_stack |
* @fileoverview A SpriteMesh is a THREE.js Mesh that handles the creation and
* properties of a collection of Sprites.
*
* Because a SpriteMesh is meant to be rendered using a THREE.js WebGLRenderer
* and has a custom SpriteMaterial, the details of this implementation are very
* vertex-centric. The downside of this is that data ends up being repeated, but
* the upside is that the material's vertex shader can perform many steps in
* parallel on the GPU.
*
* Animation is implemented in the vertex shader of the SpriteMaterial through
* attributes specified in the mesh's BufferGeometry. The geometry's position
* attribute contains vertex positions at the end of a time range, and the
* basePosition attribute contains the vertex positions at the beginning
* of the time range. This way, any other logic that looks at geometry positions
* (like ray casting) will do so using the end-of-animation positions.
*/
import {SpriteAtlas, SpriteImageData} from './sprite-atlas';
import {SpriteMaterial} from './sprite-material';
export {SpriteImageData};
declare var THREE: any;
/**
* The Sprite class acts as an object-oriented interface for interacting with
* the underlying properties managed by the SpriteMesh.
*
* In order to perform animation in the shaders of the SpriteMaterial, each
* Sprite has two states: the current state, and the starting (base) state.
* During rendering, each property of the Sprite is interpolated between these
* states using an easing function according to the current time.
*
* For example, say a sprite is moving from position (0, 0, 0) to position
* (1, 1, 1) from time 0 to time 10. At time 5, the sprite's effective position
* will be half way between the starting base position and the current position
* at (.5, .5, .5).
*
* Although you can directly manipulate both the base and current states of a
* sprite, it's best to use the rebase() method, which will interpolate
* attribute properties according to the SpriteMaterial's easing.
*
* Say you wanted to take a brand new Sprite and move it over the next 500 ms
* from x=0 to x=900. In that case, here's what you'd want to do:
*
* // Take note of the current time and create the sprite.
* const now = Date.now();
* const sprite = spriteMesh.createSprite();
*
* // Initalize property to interpolate and specify timestamp.
* sprite.x = 0;
* sprite.timestamp = now;
*
* // Rebase the sprite based on the current time.
* sprite.rebase(now);
*
* // Overwrite the property to interpolate and update the timestamp.
* sprite.x = 900;
* sprite.timestamp = now + 500;
*
* When the SpriteMaterial's shaders are invoked to draw the sprite at any time
* during the next 500 ms, its x position will be interpolated between 0 and
* 900. After that, it'll just be 900.
*
* The benefit to this approach is that we can interrupt the animation mid-way
* through and specify a new current value. For example, say we suddenly want
* to put the sprite back at x=0 (over the next 500 ms). Here are the commands
* to make it so:
*
* // Take note of the current time and rebase the sprite.
* const now = Date.now();
* sprite.rebase(now);
*
* // Overwrite the property to interpolate and update the timestamp.
* sprite.x = 0;
* sprite.timestamp = now + 500;
*
* This works no matter how much time has passed---whether the animation is
* ongoing or not.
*
* Also note that since each sprite has its own pair of starting and current
* timestamps, each sprite can independently animate over a different period of
* time if desired. By staggering the timestamps slightly from one sprite to the
* next, you can produce a wave effect, rather than having them all move in
* unison (if desired).
*/
export class Sprite {
/**
* The SpriteMesh to which this Sprite is attached.
*/
private _spriteMesh: SpriteMesh;
/**
* The index of this sprite in its SpriteMesh.
*/
private _spriteIndex: number;
/**
* A Sprite is bound to a particular SpriteMesh at a particular index.
*/
constructor(spriteMesh: SpriteMesh, spriteIndex: number) {
this._spriteMesh = spriteMesh;
this._spriteIndex = spriteIndex;
}
public get spriteMesh(): SpriteMesh {
return this._spriteMesh;
}
public get spriteIndex(): number {
return this._spriteIndex;
}
public get x(): number {
return this._spriteMesh.getX(this._spriteIndex);
}
public set x(x: number) {
this._spriteMesh.setX(this._spriteIndex, x);
}
public get y(): number {
return this._spriteMesh.getY(this._spriteIndex);
}
public set y(y: number) {
this._spriteMesh.setY(this._spriteIndex, y);
}
public get z(): number {
return this._spriteMesh.getZ(this._spriteIndex);
}
public set z(z: number) {
this._spriteMesh.setZ(this._spriteIndex, z);
}
public get r(): number {
return this._spriteMesh.getR(this._spriteIndex);
}
public set r(r: number) {
this._spriteMesh.setR(this._spriteIndex, r);
}
public get g(): number {
return this._spriteMesh.getG(this._spriteIndex);
}
public set g(g: number) {
this._spriteMesh.setG(this._spriteIndex, g);
}
public get b(): number {
return this._spriteMesh.getB(this._spriteIndex);
}
public set b(b: number) {
this._spriteMesh.setB(this._spriteIndex, b);
}
public get a(): number {
return this._spriteMesh.getA(this._spriteIndex);
}
public set a(a: number) {
this._spriteMesh.setA(this._spriteIndex, a);
}
public get opacity(): number {
return this._spriteMesh.getOpacity(this._spriteIndex);
}
public set opacity(opacity: number) {
this._spriteMesh.setOpacity(this._spriteIndex, opacity);
}
public get timestamp(): number {
return this._spriteMesh.getTimestamp(this._spriteIndex);
}
public set timestamp(timestamp: number) {
this._spriteMesh.setTimestamp(this._spriteIndex, timestamp);
}
public get baseX(): number {
return this._spriteMesh.getBaseX(this._spriteIndex);
}
public set baseX(baseX: number) {
this._spriteMesh.setBaseX(this._spriteIndex, baseX);
}
public get baseY(): number {
return this._spriteMesh.getBaseY(this._spriteIndex);
}
public set baseY(baseY: number) {
this._spriteMesh.setBaseY(this._spriteIndex, baseY);
}
public get baseZ(): number {
return this._spriteMesh.getBaseZ(this._spriteIndex);
}
public set baseZ(baseZ: number) {
this._spriteMesh.setBaseZ(this._spriteIndex, baseZ);
}
public get baseR(): number {
return this._spriteMesh.getBaseR(this._spriteIndex);
}
public set baseR(baseR: number) {
this._spriteMesh.setBaseR(this._spriteIndex, baseR);
}
public get baseG(): number {
return this._spriteMesh.getBaseG(this._spriteIndex);
}
public set baseG(baseG: number) {
this._spriteMesh.setBaseG(this._spriteIndex, baseG);
}
public get baseB(): number {
return this._spriteMesh.getBaseB(this._spriteIndex);
}
public set baseB(baseB: number) {
this._spriteMesh.setBaseB(this._spriteIndex, baseB);
}
public get baseA(): number {
return this._spriteMesh.getBaseA(this._spriteIndex);
}
public set baseA(baseA: number) {
this._spriteMesh.setBaseA(this._spriteIndex, baseA);
}
public get baseOpacity(): number {
return this._spriteMesh.getBaseOpacity(this._spriteIndex);
}
public set baseOpacity(baseOpacity: number) {
this._spriteMesh.setBaseOpacity(this._spriteIndex, baseOpacity);
}
public get baseTimestamp(): number {
return this._spriteMesh.getBaseTimestamp(this._spriteIndex);
}
public set baseTimestamp(baseTimestamp: number) {
this._spriteMesh.setBaseTimestamp(this._spriteIndex, baseTimestamp);
}
public get textureIndex(): number {
return this._spriteMesh.getTextureIndex(this._spriteIndex);
}
public set textureIndex(textureIndex: number) {
this._spriteMesh.setTextureIndex(this._spriteIndex, textureIndex);
}
public get baseTextureIndex(): number {
return this._spriteMesh.getBaseTextureIndex(this._spriteIndex);
}
public set baseTextureIndex(baseTextureIndex: number) {
this._spriteMesh.setBaseTextureIndex(this._spriteIndex, baseTextureIndex);
}
public get textureTimestamp(): number {
return this._spriteMesh.getTextureTimestamp(this._spriteIndex);
}
public set textureTimestamp(textureTimestamp: number) {
this._spriteMesh.setTextureTimestamp(this._spriteIndex, textureTimestamp);
}
public get baseTextureTimestamp(): number {
return this._spriteMesh.getBaseTextureTimestamp(this._spriteIndex);
}
public set baseTextureTimestamp(baseTextureTimestamp: number) {
this._spriteMesh.setBaseTextureTimestamp(
this._spriteIndex, baseTextureTimestamp);
}
/**
* Rebase the current position and opacity into the base position and
* opacity at the timestamp specified. If no timestamp is specified, then the
* SpriteMesh's current time is used.
*/
rebase(timestamp?: number) {
this._spriteMesh.rebase(this._spriteIndex, timestamp);
}
/**
* Asynchronously set this Sprite's image data and invoke the callback when
* finished. Typically the callback will update the texture index and
* texture timestamps to begin smooth animated tweening.
*/
setSpriteImageData(imageData: SpriteImageData, callback?: () => any) {
this._spriteMesh.setSpriteImageData(this._spriteIndex, imageData, callback);
}
/**
* Swap between the default and sprite textures over the duration indicated.
*/
switchTextures(startTimestamp: number, endTimestamp: number) {
this._spriteMesh.switchTextures(
this._spriteIndex, startTimestamp, endTimestamp);
}
}
/**
* Constants representing the offset values within the various data arrays of
* the SpriteMesh's underlying geometry.
* @see SpriteMesh:positionData.
*/
const VERTICES_PER_SPRITE = 4;
const AV = 0, BV = 1, CV = 2, DV = 3;
const POSITIONS_PER_SPRITE = 12;
const AX = 0, AY = 1, AZ = 2;
const BX = 3, BY = 4, BZ = 5;
const CX = 6, CY = 7, CZ = 8;
const DX = 9, DY = 10, DZ = 11;
const COLORS_PER_SPRITE = 16;
const AR = 0, AG = 1, AB = 2, AA = 3;
const BR = 4, BG = 5, BB = 6, BA = 7;
const CR = 8, CG = 9, CB = 10, CA = 11;
const DR = 12, DG = 13, DB = 14, DA = 15;
const FACE_INDICES_PER_SPRITE = 6;
/**
* Constants indicating which texture to use for each sprite.
*/
export const DEFAULT_TEXTURE_INDEX = 0;
export const SPRITE_TEXTURE_INDEX = 1;
export class SpriteMesh extends THREE.Mesh {
// SETTINGS.
/**
* The number of sprites this SpriteMesh is capable of representing. Must
* be set when the object is created and is treated as immutable thereafter.
*/
capacity: number;
/**
* Width of a sprite image in pixels. Defaults to 32px.
*/
imageWidth: number;
/**
* Height of a sprite image in pixels. Defaults to 32px.
*/
imageHeight: number;
/**
* Width of a sprite in world coordinates. Defaults to the aspect ratio of
* imageWidth and imageHeight. Should be set prior to creating Sprites.
*/
spriteWidth: number;
/**
* Height of a sprite in world coordinates. Defaults to 1. Should be set prior
* to creating Sprites.
*/
spriteHeight: number;
// READ-ONLY PROPERTIES.
/**
* The next unused index for creating sprites.
*/
nextIndex: number;
/**
* Positions of the sprite vertices. Each sprite consists of four vertices
* (A, B, C and D) connected by two triangular faces (ABC and ACD). Each
* vertex has three positions (X, Y and Z), so the length of the positionData
* array is 4 vertices * 3 positions = 12 total positions per sprite.
*
* The face indices are stored separately in faceIndexData. Each sprite has
* two triangular faces: ABC and ACD. 2 faces * 3 indices = 6 indices per
* sprite.
*
* D C
* +-----------+
* | / | Positions:
* | / | [ AX AY AZ BX BY BZ CX CY CZ DX DY DZ ]
* | / |
* | / | Face Indicies:
* | / | [ AV BV CV AV CV DV ]
* +-----------+
* A B
*
* The position data is dynamic, allowing sprite positions to change. However
* the face index data is static since the offset indicies into the positions
* data are known in advance.
*/
positionData: Float32Array;
/**
* THREE.js BufferAttribute for the positionData.
*/
positionAttribute: THREE.BufferAttribute;
/**
* Base positions for the sprite vertices. Has the same dimensionality and
* semantics as positionData. This attribute is used by the SpriteMaterial's
* vertex shader to animate between staring and ending position.
*/
basePositionData: Float32Array;
/**
* THREE.js BufferAttribute for the basePositionData.
*/
basePositionAttribute: THREE.BufferAttribute;
/**
* Color data for the sprite vertices. There are four color channels (RGBA)
* and that data is repeated for each of the sprite's four vertecies. So
* the length of this array will be 16 times the capacity.
*
* The alpha channel of this attribute does NOT indicate the tranparency level
* of the sprite. That is controlled by the opacity attribute. Rather, the
* alpha chanel of the color data controls how much the color is to be
* applied to the sprite.
*
* A value of 0 (the default) for the alpha channel means the sprite should
* retain its original color.
*/
colorData: Uint8Array;
/**
* THREE.js BufferAttribute for the colorData.
*/
colorAttribute: THREE.BufferAttribute;
/**
* Base color data for the sprite vertices. Same dimensions and semantics as
* colorData. This attribute is used by the vertex shader to animate between
* starting and ending color.
*/
baseColorData: Uint8Array;
/**
* THREE.js BufferAttribute for baseColorData.
*/
baseColorAttribute: THREE.BufferAttribute;
/**
* Stores the opacity of each sprite as a floating point number from 0-1.
* Due to WebGL's vertex-centric design, the opacity data ends up being
* repeated for each of the four vertices that make up a Sprite.
*
* TODO(jimbo): Switch to normalized Uint8.
*/
opacityData: Float32Array;
/**
* THREE.js BufferAttribute for the opacityData.
*/
opacityAttribute: THREE.BufferAttribute;
/**
* Stores the base opacity values for sprites. Same dimensionality and
* semantics as opacityData.
*/
baseOpacityData: Float32Array;
/**
* THREE.js BufferAttribute for the baseOpacityData.
*/
baseOpacityAttribute: THREE.BufferAttribute;
/**
* Ending timestamp in ms for animating sprite position and opacity changes.
* On or after this time, the sprite should appear at the position specified.
* At earlier times, the position should be interpolated.
*
* Due to the need for greater than 32bit precision to store a JavaScript
* timestamp (ms since Unix epoch), the values stored in this array are
* actually a diff between the real timestamp and the time when the SpriteMesh
* was constructed.
*
* The ShaderMaterial's vertex shader uses the data in timestampData and
* baseTimestampData to determine where to render the sprite at each frame
* and with what opacity.
*
* Due to WebGL's vertex-centric nature, the size of this array will be four
* times the number of sprites, and each set of four values will be repeated.
*/
timestampData: Float32Array;
/**
* THREE.js BufferAttribute for the timestampData.
*/
timestampAttribute: THREE.BufferAttribute;
/**
* The base JavaScript timestamp (ms since SpriteMesh construction) for
* animating sprite position and opacity changes. Same dimensions as
* timestampData.
*/
baseTimestampData: Float32Array;
/**
* THREE.js BufferAttribute for the baseTimestampData.
*/
baseTimestampAttribute: THREE.BufferAttribute;
/**
* Indexes of face vertices for each sprite.
* @see SpriteMesh:positionData
*/
faceIndexData: Uint32Array;
/**
* THREE.js BufferAttribute for the faceIndexData.
*/
faceIndexAttribute: THREE.BufferAttribute;
/**
* The vertexIndex attribute tells the SpriteMaterial's vertex shader the
* index of the current vertex. The data array simply contains the numbers 0-N
* where N is the total number of vertices (4 * capacity).
*
* Ideally these index values would be unsigned integers, but WebGL attributes
* must be floats or vectors of floats.
*
* @see SpriteMaterial:vertexShader
*/
vertexIndexData: Float32Array;
/**
* THREE.js BufferAttribute for the vertexIndexData.
*/
vertexIndexAttribute: THREE.BufferAttribute;
/**
* Numeric value indicating which texture is currently being used by the
* sprite. The default value is 0, meaning the default texture. 1 means the
* sprite texture.
*
* TODO(jimbo): Switch to normalized Uint8.
*/
textureIndexData: Float32Array;
/**
* THREE.js BufferAttribute for the textureIndexData.
*/
textureIndexAttribute: THREE.BufferAttribute;
/**
* Numeric value indicating which texture was previously used by the sprite.
* The default value is 0, meaning the default texture. 1 means the sprite
* texture.
*
* TODO(jimbo): Switch to normalized Uint8.
*/
baseTextureIndexData: Float32Array;
/**
* THREE.js BufferAttribute for the baseTextureIndexData.
*/
baseTextureIndexAttribute: THREE.BufferAttribute;
/**
* Ending timestamp in ms for animating sprite texture changes. On or after
* this time, the sprite should appear to be fully using the texture
* indicated in the textureIndex. At earlier times, the pixel value will be
* interpolated between the textureIndex texture and the baseTextureIndex
* texture.
*
* Due to the need for greater than 32bit precision to store a JavaScript
* timestamp (ms since Unix epoch), the values stored in this array are
* actually a diff between the real timestamp and the time when the SpriteMesh
* was constructed.
*/
textureTimestampData: Float32Array;
/**
* THREE.js BufferAttribute for the textureTimestampData.
*/
textureTimestampAttribute: THREE.BufferAttribute;
/**
* The base JavaScript textureTimestamp (ms since SpriteMesh construction) for
* animating sprite position and opacity changes. Same dimensions as
* textureTimestampData.
*/
baseTextureTimestampData: Float32Array;
/**
* THREE.js BufferAttribute for the baseTextureTimestampData.
*/
baseTextureTimestampAttribute: THREE.BufferAttribute;
/**
* The THREE.js BufferGeometry containing all relevant Sprite rendering data
* as BufferAttributes.
*/
geometry: THREE.BufferGeometry;
/**
* Custom sprite material for rendering sprites.
*/
material: SpriteMaterial;
/**
* The default texture to apply to sprites in the absense of any other data.
*/
defaultTexture: THREE.Texture;
/**
* Canvas backing the default texture.
*/
defaultTextureCanvas: HTMLCanvasElement;
/**
* Sprite texture atlas for loaded sprite image data.
*/
spriteAtlas: SpriteAtlas;
/**
* JavaScript timestamp when this object was created
*/
constructionTimestamp: number;
/**
* Callback to be invoked before the mesh is rendered.
*
* TODO(jimbo): After THREE upgraded to r81+, remove this type polyfill.
*/
onBeforeRender: (...ignore: any[]) => void;
/**
* Initialize the mesh with the given capacity.
*/
constructor(capacity: number, imageWidth = 32, imageHeight = 32) {
// Initialize THREE.js Mesh. This will create a default geometry and
// material, which we override below.
super();
this.capacity = capacity;
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
this.nextIndex = 0;
this.spriteWidth = this.imageWidth / this.imageHeight;
this.spriteHeight = 1;
this.geometry = new THREE.BufferGeometry();
// Position and base. 4 vertices per sprite, 3 positions per vertex.
this.positionData = new Float32Array(POSITIONS_PER_SPRITE * capacity);
this.positionAttribute = new THREE.BufferAttribute(this.positionData, 3);
this.positionAttribute.setDynamic(true);
this.geometry.addAttribute('position', this.positionAttribute);
this.basePositionData = new Float32Array(POSITIONS_PER_SPRITE * capacity);
this.basePositionAttribute =
new THREE.BufferAttribute(this.basePositionData, 3);
this.basePositionAttribute.setDynamic(true);
this.geometry.addAttribute('basePosition', this.basePositionAttribute);
// Color and base. 4 vertices per sprite, 4 color channels per vertex.
this.colorData = new Uint8Array(COLORS_PER_SPRITE * capacity);
this.colorAttribute = new THREE.BufferAttribute(this.colorData, 4);
// TODO(jimbo): Add 'normalized' to BufferAttribute's typings upstream.
(this.colorAttribute as any).normalized = true;
this.colorAttribute.setDynamic(true);
this.geometry.addAttribute('color', this.colorAttribute);
this.baseColorData = new Uint8Array(COLORS_PER_SPRITE * capacity);
this.baseColorAttribute = new THREE.BufferAttribute(this.baseColorData, 4);
// TODO(jimbo): Add 'normalized' to BufferAttribute's typings upstream.
(this.baseColorAttribute as any).normalized = true;
this.baseColorAttribute.setDynamic(true);
this.geometry.addAttribute('baseColor', this.baseColorAttribute);
// Opacity and base opacity. 4 vertices per sprite.
this.opacityData = new Float32Array(VERTICES_PER_SPRITE * capacity);
this.opacityAttribute = new THREE.BufferAttribute(this.opacityData, 1);
this.opacityAttribute.setDynamic(true);
this.geometry.addAttribute('opacity', this.opacityAttribute);
this.baseOpacityData = new Float32Array(VERTICES_PER_SPRITE * capacity);
this.baseOpacityAttribute =
new THREE.BufferAttribute(this.baseOpacityData, 1);
this.baseOpacityAttribute.setDynamic(true);
this.geometry.addAttribute('baseOpacity', this.baseOpacityAttribute);
// Timestamp and base timestamp. 4 vertices per sprite.
this.timestampData = new Float32Array(VERTICES_PER_SPRITE * capacity);
this.timestampAttribute = new THREE.BufferAttribute(this.timestampData, 1);
this.timestampAttribute.setDynamic(true);
this.geometry.addAttribute('timestamp', this.timestampAttribute);
this.baseTimestampData = new Float32Array(VERTICES_PER_SPRITE * capacity);
this.baseTimestampAttribute =
new THREE.BufferAttribute(this.baseTimestampData, 1);
this.baseTimestampAttribute.setDynamic(true);
this.geometry.addAttribute('baseTimestamp', this.baseTimestampAttribute);
// 2 faces per sprite, 3 indicies per face.
this.faceIndexData = new Uint32Array(FACE_INDICES_PER_SPRITE * capacity);
for (let i = 0; i < capacity; i++) {
const faceOffsetIndex = FACE_INDICES_PER_SPRITE * i;
const vertexOffsetIndex = VERTICES_PER_SPRITE * i;
// ABC face.
this.faceIndexData[faceOffsetIndex + 0] = vertexOffsetIndex + AV;
this.faceIndexData[faceOffsetIndex + 1] = vertexOffsetIndex + BV;
this.faceIndexData[faceOffsetIndex + 2] = vertexOffsetIndex + CV;
// ACD face.
this.faceIndexData[faceOffsetIndex + 3] = vertexOffsetIndex + AV;
this.faceIndexData[faceOffsetIndex + 4] = vertexOffsetIndex + CV;
this.faceIndexData[faceOffsetIndex + 5] = vertexOffsetIndex + DV;
}
this.faceIndexAttribute = new THREE.BufferAttribute(this.faceIndexData, 1);
this.geometry.setIndex(this.faceIndexAttribute);
// Texture index and base texture index. 4 vertices per sprite.
this.textureIndexData = new Float32Array(VERTICES_PER_SPRITE * capacity);
this.textureIndexAttribute =
new THREE.BufferAttribute(this.textureIndexData, 1);
this.textureIndexAttribute.setDynamic(true);
this.geometry.addAttribute('textureIndex', this.textureIndexAttribute);
this.baseTextureIndexData =
new Float32Array(VERTICES_PER_SPRITE * capacity);
this.baseTextureIndexAttribute =
new THREE.BufferAttribute(this.baseTextureIndexData, 1);
this.baseTextureIndexAttribute.setDynamic(true);
this.geometry.addAttribute(
'baseTextureIndex', this.baseTextureIndexAttribute);
// Texture timestamp and base texture timestamp. 4 vertices per sprite.
this.textureTimestampData =
new Float32Array(VERTICES_PER_SPRITE * capacity);
this.textureTimestampAttribute =
new THREE.BufferAttribute(this.textureTimestampData, 1);
this.textureTimestampAttribute.setDynamic(true);
this.geometry.addAttribute(
'textureTimestamp', this.textureTimestampAttribute);
this.baseTextureTimestampData =
new Float32Array(VERTICES_PER_SPRITE * capacity);
this.baseTextureTimestampAttribute =
new THREE.BufferAttribute(this.baseTextureTimestampData, 1);
this.baseTextureTimestampAttribute.setDynamic(true);
this.geometry.addAttribute(
'baseTextureTimestamp', this.baseTextureTimestampAttribute);
// Fill in the vertexIndex attribute with the values 0-N.
const totalVertices = VERTICES_PER_SPRITE * capacity;
this.vertexIndexData = new Float32Array(totalVertices);
for (let i = 0; i < totalVertices; i++) {
this.vertexIndexData[i] = i;
}
this.vertexIndexAttribute =
new THREE.BufferAttribute(this.vertexIndexData, 1);
this.geometry.addAttribute('vertexIndex', this.vertexIndexAttribute);
// Create the default texture and its backing canvas.
this.defaultTextureCanvas = this.createDefaultTextureCanvas();
this.defaultTexture = new THREE.Texture(this.defaultTextureCanvas);
this.defaultTexture.minFilter = THREE.LinearFilter;
this.defaultTexture.magFilter = THREE.NearestFilter;
this.defaultTexture.needsUpdate = true;
// Setup the dynamic texture and its backing canvas.
this.spriteAtlas = new SpriteAtlas(capacity, imageWidth, imageHeight);
this.material = new SpriteMaterial(this.defaultTexture, this.spriteAtlas);
this.onBeforeRender = () => {
this.material.updateAtlasUniforms();
};
this.constructionTimestamp = Date.now();
this.time = this.constructionTimestamp;
// Prevents clipping by the frustum (whole shape disappears). An alternative
// would be to add the mesh as a child of the camera (and the camera as a
// child of the scene) but changing the frustum culling is something we can
// do here irrespective of the scene and camera used.
// See http://threejs.org/docs/#Reference/Core/Object3D.frustumCulled
this.frustumCulled = false;
}
/**
* Create and return a new Sprite.
*/
createSprite() {
return new Sprite(this, this.nextIndex++);
}
public get time(): number {
return this.material.time + this.constructionTimestamp;
}
public set time(time: number) {
this.material.time = time - this.constructionTimestamp;
}
/**
* Create the default texture and backing canvas.
*/
createDefaultTextureCanvas() {
const canvas = this.defaultTextureCanvas = document.createElement('canvas');
const width = canvas.width = this.imageWidth;
const height = canvas.height = this.imageHeight;
const context = canvas.getContext('2d')!;
// Draw in a default SVG.
const image = new Image();
image.onload = () => {
context.drawImage(image, 0, 0, width, height);
this.defaultTexture.needsUpdate = true;
};
image.src = URL.createObjectURL(
new Blob([DOT_SVG], {type: 'image/svg+xml;charset=utf-8'}));
return canvas;
}
/**
* Get the X component of the specified Sprite's position.
*/
getX(spriteIndex: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
return this.positionData[positionOffsetIndex + AX];
}
/**
* Set the X component of the specified Sprite's position.
*/
setX(spriteIndex: number, x: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
this.positionData[positionOffsetIndex + AX] = x;
this.positionData[positionOffsetIndex + BX] = x + this.spriteWidth;
this.positionData[positionOffsetIndex + CX] = x + this.spriteWidth;
this.positionData[positionOffsetIndex + DX] = x;
this.positionAttribute.needsUpdate = true;
}
/**
* Get the Y component of the specified Sprite's position.
*/
getY(spriteIndex: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
return this.positionData[positionOffsetIndex + AY];
}
/**
* Set the Y component of the specified Sprite's position.
*/
setY(spriteIndex: number, y: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
this.positionData[positionOffsetIndex + AY] = y;
this.positionData[positionOffsetIndex + BY] = y;
this.positionData[positionOffsetIndex + CY] = y + this.spriteHeight;
this.positionData[positionOffsetIndex + DY] = y + this.spriteHeight;
this.positionAttribute.needsUpdate = true;
}
/**
* Get the Z component of the specified Sprite's position.
*/
getZ(spriteIndex: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
return this.positionData[positionOffsetIndex + AZ];
}
/**
* Set the Z component of the specified Sprite's position.
*/
setZ(spriteIndex: number, z: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
this.positionData[positionOffsetIndex + AZ] = z;
this.positionData[positionOffsetIndex + BZ] = z;
this.positionData[positionOffsetIndex + CZ] = z;
this.positionData[positionOffsetIndex + DZ] = z;
this.positionAttribute.needsUpdate = true;
}
/**
* Get the R channel of the specified Sprite's color.
*/
getR(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.colorData[colorOffsetIndex + AR];
}
/**
* Set the R channel of the specified Sprite's color.
*/
setR(spriteIndex: number, r: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.colorData[colorOffsetIndex + AR] = r;
this.colorData[colorOffsetIndex + BR] = r;
this.colorData[colorOffsetIndex + CR] = r;
this.colorData[colorOffsetIndex + DR] = r;
this.colorAttribute.needsUpdate = true;
}
/**
* Get the G channel of the specified Sprite's color.
*/
getG(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.colorData[colorOffsetIndex + AG];
}
/**
* Set the G channel of the specified Sprite's color.
*/
setG(spriteIndex: number, g: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.colorData[colorOffsetIndex + AG] = g;
this.colorData[colorOffsetIndex + BG] = g;
this.colorData[colorOffsetIndex + CG] = g;
this.colorData[colorOffsetIndex + DG] = g;
this.colorAttribute.needsUpdate = true;
}
/**
* Get the B channel of the specified Sprite's color.
*/
getB(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.colorData[colorOffsetIndex + AB];
}
/**
* Set the B channel of the specified Sprite's color.
*/
setB(spriteIndex: number, b: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.colorData[colorOffsetIndex + AB] = b;
this.colorData[colorOffsetIndex + BB] = b;
this.colorData[colorOffsetIndex + CB] = b;
this.colorData[colorOffsetIndex + DB] = b;
this.colorAttribute.needsUpdate = true;
}
/**
* Get the A channel of the specified Sprite's color.
*/
getA(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.colorData[colorOffsetIndex + AA];
}
/**
* Set the A channel of the specified Sprite's color.
*/
setA(spriteIndex: number, a: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.colorData[colorOffsetIndex + AA] = a;
this.colorData[colorOffsetIndex + BA] = a;
this.colorData[colorOffsetIndex + CA] = a;
this.colorData[colorOffsetIndex + DA] = a;
this.colorAttribute.needsUpdate = true;
}
/**
* Get the X component of the specified Sprite's base position.
*/
getBaseX(spriteIndex: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
return this.basePositionData[positionOffsetIndex + AX];
}
/**
* Set the X component of the specified Sprite's base position.
*/
setBaseX(spriteIndex: number, baseX: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
this.basePositionData[positionOffsetIndex + AX] = baseX;
this.basePositionData[positionOffsetIndex + BX] = baseX + this.spriteWidth;
this.basePositionData[positionOffsetIndex + CX] = baseX + this.spriteWidth;
this.basePositionData[positionOffsetIndex + DX] = baseX;
this.basePositionAttribute.needsUpdate = true;
}
/**
* Get the Y component of the specified Sprite's base position.
*/
getBaseY(spriteIndex: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
return this.basePositionData[positionOffsetIndex + AY];
}
/**
* Set the Y component of the specified Sprite's base position.
*/
setBaseY(spriteIndex: number, baseY: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
this.basePositionData[positionOffsetIndex + AY] = baseY;
this.basePositionData[positionOffsetIndex + BY] = baseY;
this.basePositionData[positionOffsetIndex + CY] = baseY + this.spriteHeight;
this.basePositionData[positionOffsetIndex + DY] = baseY + this.spriteHeight;
this.basePositionAttribute.needsUpdate = true;
}
/**
* Get the Z component of the specified Sprite's base position.
*/
getBaseZ(spriteIndex: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
return this.basePositionData[positionOffsetIndex + AZ];
}
/**
* Set the Z component of the specified Sprite's base position.
*/
setBaseZ(spriteIndex: number, baseZ: number) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
this.basePositionData[positionOffsetIndex + AZ] = baseZ;
this.basePositionData[positionOffsetIndex + BZ] = baseZ;
this.basePositionData[positionOffsetIndex + CZ] = baseZ;
this.basePositionData[positionOffsetIndex + DZ] = baseZ;
this.basePositionAttribute.needsUpdate = true;
}
/**
* Get the R channel of the specified Sprite's base color.
*/
getBaseR(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.baseColorData[colorOffsetIndex + AR];
}
/**
* Set the R channel of the specified Sprite's base color.
*/
setBaseR(spriteIndex: number, baseR: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.baseColorData[colorOffsetIndex + AR] = baseR;
this.baseColorData[colorOffsetIndex + BR] = baseR;
this.baseColorData[colorOffsetIndex + CR] = baseR;
this.baseColorData[colorOffsetIndex + DR] = baseR;
this.baseColorAttribute.needsUpdate = true;
}
/**
* Get the G channel of the specified Sprite's base color.
*/
getBaseG(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.baseColorData[colorOffsetIndex + AG];
}
/**
* Set the G channel of the specified Sprite's base color.
*/
setBaseG(spriteIndex: number, baseG: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.baseColorData[colorOffsetIndex + AG] = baseG;
this.baseColorData[colorOffsetIndex + BG] = baseG;
this.baseColorData[colorOffsetIndex + CG] = baseG;
this.baseColorData[colorOffsetIndex + DG] = baseG;
this.baseColorAttribute.needsUpdate = true;
}
/**
* Get the B channel of the specified Sprite's base color.
*/
getBaseB(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.baseColorData[colorOffsetIndex + AB];
}
/**
* Set the B channel of the specified Sprite's base color.
*/
setBaseB(spriteIndex: number, baseB: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.baseColorData[colorOffsetIndex + AB] = baseB;
this.baseColorData[colorOffsetIndex + BB] = baseB;
this.baseColorData[colorOffsetIndex + CB] = baseB;
this.baseColorData[colorOffsetIndex + DB] = baseB;
this.baseColorAttribute.needsUpdate = true;
}
/**
* Get the A channel of the specified Sprite's base color.
*/
getBaseA(spriteIndex: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
return this.baseColorData[colorOffsetIndex + AA];
}
/**
* Set the A channel of the specified Sprite's base color.
*/
setBaseA(spriteIndex: number, baseA: number) {
const colorOffsetIndex = spriteIndex * COLORS_PER_SPRITE;
this.baseColorData[colorOffsetIndex + AA] = baseA;
this.baseColorData[colorOffsetIndex + BA] = baseA;
this.baseColorData[colorOffsetIndex + CA] = baseA;
this.baseColorData[colorOffsetIndex + DA] = baseA;
this.baseColorAttribute.needsUpdate = true;
}
/**
* Get the opacity of the specified Sprite.
*/
getOpacity(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.opacityData[vertexOffsetIndex + AV];
}
/**
* Set the opacity of the specified Sprite.
*/
setOpacity(spriteIndex: number, opacity: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
this.opacityData[vertexOffsetIndex + AV] = opacity;
this.opacityData[vertexOffsetIndex + BV] = opacity;
this.opacityData[vertexOffsetIndex + CV] = opacity;
this.opacityData[vertexOffsetIndex + DV] = opacity;
this.opacityAttribute.needsUpdate = true;
}
/**
* Get the base opacity of the specified Sprite.
*/
getBaseOpacity(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.baseOpacityData[vertexOffsetIndex + AV];
}
/**
* Set the base opacity of the specified Sprite.
*/
setBaseOpacity(spriteIndex: number, baseOpacity: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
this.baseOpacityData[vertexOffsetIndex + AV] = baseOpacity;
this.baseOpacityData[vertexOffsetIndex + BV] = baseOpacity;
this.baseOpacityData[vertexOffsetIndex + CV] = baseOpacity;
this.baseOpacityData[vertexOffsetIndex + DV] = baseOpacity;
this.baseOpacityAttribute.needsUpdate = true;
}
/**
* Get the Sprite's current timestamp.
*/
getTimestamp(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.timestampData[vertexOffsetIndex + AV] +
this.constructionTimestamp;
}
/**
* Set the Sprite's current timestamp.
*/
setTimestamp(spriteIndex: number, timestamp: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
const diffTimestamp = timestamp - this.constructionTimestamp;
this.timestampData[vertexOffsetIndex + AV] = diffTimestamp;
this.timestampData[vertexOffsetIndex + BV] = diffTimestamp;
this.timestampData[vertexOffsetIndex + CV] = diffTimestamp;
this.timestampData[vertexOffsetIndex + DV] = diffTimestamp;
this.timestampAttribute.needsUpdate = true;
}
/**
* Get the Sprite's base timestamp.
*/
getBaseTimestamp(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.baseTimestampData[vertexOffsetIndex + AV] +
this.constructionTimestamp;
}
/**
* Set the Sprite's base timestamp.
*/
setBaseTimestamp(spriteIndex: number, baseTimestamp: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
const diffTimestamp = baseTimestamp - this.constructionTimestamp;
this.baseTimestampData[vertexOffsetIndex + AV] = diffTimestamp;
this.baseTimestampData[vertexOffsetIndex + BV] = diffTimestamp;
this.baseTimestampData[vertexOffsetIndex + CV] = diffTimestamp;
this.baseTimestampData[vertexOffsetIndex + DV] = diffTimestamp;
this.baseTimestampAttribute.needsUpdate = true;
}
/**
* Get the textureIndex of the specified Sprite.
*/
getTextureIndex(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.textureIndexData[vertexOffsetIndex + AV];
}
/**
* Set the textureIndex of the specified Sprite.
*/
setTextureIndex(spriteIndex: number, textureIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
this.textureIndexData[vertexOffsetIndex + AV] = textureIndex;
this.textureIndexData[vertexOffsetIndex + BV] = textureIndex;
this.textureIndexData[vertexOffsetIndex + CV] = textureIndex;
this.textureIndexData[vertexOffsetIndex + DV] = textureIndex;
this.textureIndexAttribute.needsUpdate = true;
}
/**
* Get the base textureIndex of the specified Sprite.
*/
getBaseTextureIndex(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.baseTextureIndexData[vertexOffsetIndex + AV];
}
/**
* Set the base textureIndex of the specified Sprite.
*/
setBaseTextureIndex(spriteIndex: number, baseTextureIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
this.baseTextureIndexData[vertexOffsetIndex + AV] = baseTextureIndex;
this.baseTextureIndexData[vertexOffsetIndex + BV] = baseTextureIndex;
this.baseTextureIndexData[vertexOffsetIndex + CV] = baseTextureIndex;
this.baseTextureIndexData[vertexOffsetIndex + DV] = baseTextureIndex;
this.baseTextureIndexAttribute.needsUpdate = true;
}
/**
* Get the Sprite's current textureTimestamp.
*/
getTextureTimestamp(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.textureTimestampData[vertexOffsetIndex + AV] +
this.constructionTimestamp;
}
/**
* Set the Sprite's current textureTimestamp.
*/
setTextureTimestamp(spriteIndex: number, textureTimestamp: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
const diff = textureTimestamp - this.constructionTimestamp;
this.textureTimestampData[vertexOffsetIndex + AV] = diff;
this.textureTimestampData[vertexOffsetIndex + BV] = diff;
this.textureTimestampData[vertexOffsetIndex + CV] = diff;
this.textureTimestampData[vertexOffsetIndex + DV] = diff;
this.textureTimestampAttribute.needsUpdate = true;
}
/**
* Get the Sprite's base textureTimestamp.
*/
getBaseTextureTimestamp(spriteIndex: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
return this.baseTextureTimestampData[vertexOffsetIndex + AV] +
this.constructionTimestamp;
}
/**
* Set the Sprite's base textureTimestamp.
*/
setBaseTextureTimestamp(spriteIndex: number, baseTextureTimestamp: number) {
const vertexOffsetIndex = spriteIndex * VERTICES_PER_SPRITE;
const diff = baseTextureTimestamp - this.constructionTimestamp;
this.baseTextureTimestampData[vertexOffsetIndex + AV] = diff;
this.baseTextureTimestampData[vertexOffsetIndex + BV] = diff;
this.baseTextureTimestampData[vertexOffsetIndex + CV] = diff;
this.baseTextureTimestampData[vertexOffsetIndex + DV] = diff;
this.baseTextureTimestampAttribute.needsUpdate = true;
}
/**
* Rebase the current position, color, and opacity of the specified Sprite
* into the base position and opacity at the timestamp specified. If no
* timestamp is specified, then the SpriteMesh's current time is used.
*
* At a high level, the purpose of this function is to prepare the sprite for
* the next animation. Suppose we've finished animating, and now the sprite
* is about to have new positions set.
*
* Calling this method will interpolate values according to the material's
* easing method so that the next animation will smoothly pick up where this
* one finished.
*/
rebase(spriteIndex: number, timestamp?: number) {
timestamp = timestamp === undefined ? this.time : timestamp;
// To determine the new base timestamp, we have to apply the same easing
// logic used by the shader. So the new base will not be a simple linear
// interpolation, but rather the effective time the shader would use at
// this frame.
const oldBaseTimestamp = this.getBaseTimestamp(spriteIndex);
const currentTimestamp = this.getTimestamp(spriteIndex);
// Proportion of current values to apply to base. 0 means use entirely base,
// 1 means entirely current values.
const blend = timestamp >= currentTimestamp ?
1 :
timestamp <= oldBaseTimestamp ?
0 :
this.material.applyEasing(
(timestamp - oldBaseTimestamp) /
(currentTimestamp - oldBaseTimestamp));
// Convenience method for linear interpolation.
const lerp = (v0: number, v1: number) => {
return v0 * blend + v1 * (1 - blend);
};
// Apply blending to update base position, color, and opacity.
this.setBaseX(
spriteIndex, lerp(this.getX(spriteIndex), this.getBaseX(spriteIndex)));
this.setBaseY(
spriteIndex, lerp(this.getY(spriteIndex), this.getBaseY(spriteIndex)));
this.setBaseZ(
spriteIndex, lerp(this.getZ(spriteIndex), this.getBaseZ(spriteIndex)));
this.setBaseR(
spriteIndex, lerp(this.getR(spriteIndex), this.getBaseR(spriteIndex)));
this.setBaseG(
spriteIndex, lerp(this.getG(spriteIndex), this.getBaseG(spriteIndex)));
this.setBaseB(
spriteIndex, lerp(this.getB(spriteIndex), this.getBaseB(spriteIndex)));
this.setBaseA(
spriteIndex, lerp(this.getA(spriteIndex), this.getBaseA(spriteIndex)));
this.setBaseOpacity(
spriteIndex,
lerp(this.getOpacity(spriteIndex), this.getBaseOpacity(spriteIndex)));
// When setting the new base timestamp, we should apply the same blending
// alogrithm except if the rebase timestamp is later than the sprite's
// current timestamp. In that case we should use the passed in value.
const newBaseTimestamp = timestamp >= currentTimestamp ?
timestamp :
lerp(currentTimestamp, oldBaseTimestamp);
this.setBaseTimestamp(spriteIndex, newBaseTimestamp);
}
/**
* Set image data for the selected sprite, invoke callback when finished.
*/
setSpriteImageData(
spriteIndex: number, imageData: SpriteImageData,
callback?: (spriteIndex: number) => any) {
this.spriteAtlas.setSpriteImageData(spriteIndex, imageData, callback);
}
/**
* Switch between the default and sprite texture over the duration specified.
*/
switchTextures(
spriteIndex: number, startTimestamp: number, endTimestamp: number) {
const oldTextureIndex = this.getTextureIndex(spriteIndex);
this.setBaseTextureIndex(spriteIndex, oldTextureIndex);
this.setTextureIndex(
spriteIndex,
oldTextureIndex === DEFAULT_TEXTURE_INDEX ? SPRITE_TEXTURE_INDEX :
DEFAULT_TEXTURE_INDEX);
this.setBaseTextureTimestamp(spriteIndex, startTimestamp);
this.setTextureTimestamp(spriteIndex, endTimestamp);
}
/**
* Given X and Y in world coordinates, determine which sprites (if any) span
* the line through this point perpendicular to the XY plane. This substitutes
* for full raycasting support, and presumes that the camera is looking down
* on the sprites in the XY plane from the Z axis.
*
* If no sprites intersect the point, then an empty array is returned.
*/
findSprites(x: number, y: number): number[] {
// This naive implementation is significantly slower than what could be
// achieved by maintaining a quadtree or octree.
const spriteIndexes: number[] = [];
for (let spriteIndex = 0; spriteIndex < this.capacity; spriteIndex++) {
const positionOffsetIndex = spriteIndex * POSITIONS_PER_SPRITE;
if (x >= this.positionData[positionOffsetIndex + AX] &&
x <= this.positionData[positionOffsetIndex + CX] &&
y >= this.positionData[positionOffsetIndex + AY] &&
y <= this.positionData[positionOffsetIndex + CY]) {
spriteIndexes.push(spriteIndex);
}
}
return spriteIndexes;
}
}
export const DOT_SVG = `
<svg version="1.1"
baseProfile="full"
width="128" height="128"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="linearGradient3774">
<stop
style="stop-color:#808080;stop-opacity:1;"
offset="0" />
<stop
style="stop-color:#555555;stop-opacity:1;"
offset="1" />
</linearGradient>
<radialGradient
xlink:href="#linearGradient3774"
id="radialGradient3780"
cx="80"
cy="40"
fx="80"
fy="40"
r="80"
gradientUnits="userSpaceOnUse"
spreadMethod="pad" />
</defs>
<circle cx="50%" cy="50%" r="50%" fill="url(#radialGradient3780)" />
</svg>
`; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* ## Import
*
* SQL Databases can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:sql/database:Database database1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Sql/servers/myserver/databases/database1
* ```
*/
export class Database extends pulumi.CustomResource {
/**
* Get an existing Database 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?: DatabaseState, opts?: pulumi.CustomResourceOptions): Database {
return new Database(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:sql/database:Database';
/**
* Returns true if the given object is an instance of Database. 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 Database {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Database.__pulumiType;
}
/**
* The name of the collation. Applies only if `createMode` is `Default`. Azure default is `SQL_LATIN1_GENERAL_CP1_CI_AS`. Changing this forces a new resource to be created.
*/
public readonly collation!: pulumi.Output<string>;
/**
* Specifies how to create the database. Valid values are: `Default`, `Copy`, `OnlineSecondary`, `NonReadableSecondary`, `PointInTimeRestore`, `Recovery`, `Restore` or `RestoreLongTermRetentionBackup`. Must be `Default` to create a new database. Defaults to `Default`. Please see [Azure SQL Database REST API](https://docs.microsoft.com/en-us/rest/api/sql/databases/createorupdate#createmode)
*/
public readonly createMode!: pulumi.Output<string | undefined>;
/**
* The creation date of the SQL Database.
*/
public /*out*/ readonly creationDate!: pulumi.Output<string>;
/**
* The default secondary location of the SQL Database.
*/
public /*out*/ readonly defaultSecondaryLocation!: pulumi.Output<string>;
/**
* The edition of the database to be created. Applies only if `createMode` is `Default`. Valid values are: `Basic`, `Standard`, `Premium`, `DataWarehouse`, `Business`, `BusinessCritical`, `Free`, `GeneralPurpose`, `Hyperscale`, `Premium`, `PremiumRS`, `Standard`, `Stretch`, `System`, `System2`, or `Web`. Please see [Azure SQL Database Service Tiers](https://azure.microsoft.com/en-gb/documentation/articles/sql-database-service-tiers/).
*/
public readonly edition!: pulumi.Output<string>;
/**
* The name of the elastic database pool.
*/
public readonly elasticPoolName!: pulumi.Output<string>;
public /*out*/ readonly encryption!: pulumi.Output<string>;
/**
* A `extendedAuditingPolicy` block as defined below.
*
* @deprecated the `extended_auditing_policy` block has been moved to `azurerm_mssql_server_extended_auditing_policy` and `azurerm_mssql_database_extended_auditing_policy`. This block will be removed in version 3.0 of the provider.
*/
public readonly extendedAuditingPolicy!: pulumi.Output<outputs.sql.DatabaseExtendedAuditingPolicy>;
/**
* A Database Import block as documented below. `createMode` must be set to `Default`.
*/
public readonly import!: pulumi.Output<outputs.sql.DatabaseImport | undefined>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* The maximum size that the database can grow to. Applies only if `createMode` is `Default`. Please see [Azure SQL Database Service Tiers](https://azure.microsoft.com/en-gb/documentation/articles/sql-database-service-tiers/).
*/
public readonly maxSizeBytes!: pulumi.Output<string>;
public readonly maxSizeGb!: pulumi.Output<string>;
/**
* The name of the database.
*/
public readonly name!: pulumi.Output<string>;
/**
* Read-only connections will be redirected to a high-available replica. Please see [Use read-only replicas to load-balance read-only query workloads](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out).
*/
public readonly readScale!: pulumi.Output<boolean | undefined>;
/**
* A GUID/UUID corresponding to a configured Service Level Objective for the Azure SQL database which can be used to configure a performance level.
* .
*/
public readonly requestedServiceObjectiveId!: pulumi.Output<string>;
/**
* The service objective name for the database. Valid values depend on edition and location and may include `S0`, `S1`, `S2`, `S3`, `P1`, `P2`, `P4`, `P6`, `P11` and `ElasticPool`. You can list the available names with the cli: `shell az sql db list-editions -l westus -o table`. For further information please see [Azure CLI - az sql db](https://docs.microsoft.com/en-us/cli/azure/sql/db?view=azure-cli-latest#az-sql-db-list-editions).
*/
public readonly requestedServiceObjectiveName!: pulumi.Output<string>;
/**
* The name of the resource group in which to create the database. This must be the same as Database Server resource group currently.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* The point in time for the restore. Only applies if `createMode` is `PointInTimeRestore` e.g. 2013-11-08T22:00:40Z
*/
public readonly restorePointInTime!: pulumi.Output<string>;
/**
* The name of the SQL Server on which to create the database.
*/
public readonly serverName!: pulumi.Output<string>;
/**
* The deletion date time of the source database. Only applies to deleted databases where `createMode` is `PointInTimeRestore`.
*/
public readonly sourceDatabaseDeletionDate!: pulumi.Output<string>;
/**
* The URI of the source database if `createMode` value is not `Default`.
*/
public readonly sourceDatabaseId!: pulumi.Output<string>;
/**
* A mapping of tags to assign to the resource.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Threat detection policy configuration. The `threatDetectionPolicy` block supports fields documented below.
*/
public readonly threatDetectionPolicy!: pulumi.Output<outputs.sql.DatabaseThreatDetectionPolicy>;
/**
* Whether or not this database is zone redundant, which means the replicas of this database will be spread across multiple availability zones.
*/
public readonly zoneRedundant!: pulumi.Output<boolean | undefined>;
/**
* Create a Database 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: DatabaseArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: DatabaseArgs | DatabaseState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as DatabaseState | undefined;
inputs["collation"] = state ? state.collation : undefined;
inputs["createMode"] = state ? state.createMode : undefined;
inputs["creationDate"] = state ? state.creationDate : undefined;
inputs["defaultSecondaryLocation"] = state ? state.defaultSecondaryLocation : undefined;
inputs["edition"] = state ? state.edition : undefined;
inputs["elasticPoolName"] = state ? state.elasticPoolName : undefined;
inputs["encryption"] = state ? state.encryption : undefined;
inputs["extendedAuditingPolicy"] = state ? state.extendedAuditingPolicy : undefined;
inputs["import"] = state ? state.import : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["maxSizeBytes"] = state ? state.maxSizeBytes : undefined;
inputs["maxSizeGb"] = state ? state.maxSizeGb : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["readScale"] = state ? state.readScale : undefined;
inputs["requestedServiceObjectiveId"] = state ? state.requestedServiceObjectiveId : undefined;
inputs["requestedServiceObjectiveName"] = state ? state.requestedServiceObjectiveName : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["restorePointInTime"] = state ? state.restorePointInTime : undefined;
inputs["serverName"] = state ? state.serverName : undefined;
inputs["sourceDatabaseDeletionDate"] = state ? state.sourceDatabaseDeletionDate : undefined;
inputs["sourceDatabaseId"] = state ? state.sourceDatabaseId : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["threatDetectionPolicy"] = state ? state.threatDetectionPolicy : undefined;
inputs["zoneRedundant"] = state ? state.zoneRedundant : undefined;
} else {
const args = argsOrState as DatabaseArgs | undefined;
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.serverName === undefined) && !opts.urn) {
throw new Error("Missing required property 'serverName'");
}
inputs["collation"] = args ? args.collation : undefined;
inputs["createMode"] = args ? args.createMode : undefined;
inputs["edition"] = args ? args.edition : undefined;
inputs["elasticPoolName"] = args ? args.elasticPoolName : undefined;
inputs["extendedAuditingPolicy"] = args ? args.extendedAuditingPolicy : undefined;
inputs["import"] = args ? args.import : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["maxSizeBytes"] = args ? args.maxSizeBytes : undefined;
inputs["maxSizeGb"] = args ? args.maxSizeGb : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["readScale"] = args ? args.readScale : undefined;
inputs["requestedServiceObjectiveId"] = args ? args.requestedServiceObjectiveId : undefined;
inputs["requestedServiceObjectiveName"] = args ? args.requestedServiceObjectiveName : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["restorePointInTime"] = args ? args.restorePointInTime : undefined;
inputs["serverName"] = args ? args.serverName : undefined;
inputs["sourceDatabaseDeletionDate"] = args ? args.sourceDatabaseDeletionDate : undefined;
inputs["sourceDatabaseId"] = args ? args.sourceDatabaseId : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["threatDetectionPolicy"] = args ? args.threatDetectionPolicy : undefined;
inputs["zoneRedundant"] = args ? args.zoneRedundant : undefined;
inputs["creationDate"] = undefined /*out*/;
inputs["defaultSecondaryLocation"] = undefined /*out*/;
inputs["encryption"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Database.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Database resources.
*/
export interface DatabaseState {
/**
* The name of the collation. Applies only if `createMode` is `Default`. Azure default is `SQL_LATIN1_GENERAL_CP1_CI_AS`. Changing this forces a new resource to be created.
*/
collation?: pulumi.Input<string>;
/**
* Specifies how to create the database. Valid values are: `Default`, `Copy`, `OnlineSecondary`, `NonReadableSecondary`, `PointInTimeRestore`, `Recovery`, `Restore` or `RestoreLongTermRetentionBackup`. Must be `Default` to create a new database. Defaults to `Default`. Please see [Azure SQL Database REST API](https://docs.microsoft.com/en-us/rest/api/sql/databases/createorupdate#createmode)
*/
createMode?: pulumi.Input<string>;
/**
* The creation date of the SQL Database.
*/
creationDate?: pulumi.Input<string>;
/**
* The default secondary location of the SQL Database.
*/
defaultSecondaryLocation?: pulumi.Input<string>;
/**
* The edition of the database to be created. Applies only if `createMode` is `Default`. Valid values are: `Basic`, `Standard`, `Premium`, `DataWarehouse`, `Business`, `BusinessCritical`, `Free`, `GeneralPurpose`, `Hyperscale`, `Premium`, `PremiumRS`, `Standard`, `Stretch`, `System`, `System2`, or `Web`. Please see [Azure SQL Database Service Tiers](https://azure.microsoft.com/en-gb/documentation/articles/sql-database-service-tiers/).
*/
edition?: pulumi.Input<string>;
/**
* The name of the elastic database pool.
*/
elasticPoolName?: pulumi.Input<string>;
encryption?: pulumi.Input<string>;
/**
* A `extendedAuditingPolicy` block as defined below.
*
* @deprecated the `extended_auditing_policy` block has been moved to `azurerm_mssql_server_extended_auditing_policy` and `azurerm_mssql_database_extended_auditing_policy`. This block will be removed in version 3.0 of the provider.
*/
extendedAuditingPolicy?: pulumi.Input<inputs.sql.DatabaseExtendedAuditingPolicy>;
/**
* A Database Import block as documented below. `createMode` must be set to `Default`.
*/
import?: pulumi.Input<inputs.sql.DatabaseImport>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* The maximum size that the database can grow to. Applies only if `createMode` is `Default`. Please see [Azure SQL Database Service Tiers](https://azure.microsoft.com/en-gb/documentation/articles/sql-database-service-tiers/).
*/
maxSizeBytes?: pulumi.Input<string>;
maxSizeGb?: pulumi.Input<string>;
/**
* The name of the database.
*/
name?: pulumi.Input<string>;
/**
* Read-only connections will be redirected to a high-available replica. Please see [Use read-only replicas to load-balance read-only query workloads](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out).
*/
readScale?: pulumi.Input<boolean>;
/**
* A GUID/UUID corresponding to a configured Service Level Objective for the Azure SQL database which can be used to configure a performance level.
* .
*/
requestedServiceObjectiveId?: pulumi.Input<string>;
/**
* The service objective name for the database. Valid values depend on edition and location and may include `S0`, `S1`, `S2`, `S3`, `P1`, `P2`, `P4`, `P6`, `P11` and `ElasticPool`. You can list the available names with the cli: `shell az sql db list-editions -l westus -o table`. For further information please see [Azure CLI - az sql db](https://docs.microsoft.com/en-us/cli/azure/sql/db?view=azure-cli-latest#az-sql-db-list-editions).
*/
requestedServiceObjectiveName?: pulumi.Input<string>;
/**
* The name of the resource group in which to create the database. This must be the same as Database Server resource group currently.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* The point in time for the restore. Only applies if `createMode` is `PointInTimeRestore` e.g. 2013-11-08T22:00:40Z
*/
restorePointInTime?: pulumi.Input<string>;
/**
* The name of the SQL Server on which to create the database.
*/
serverName?: pulumi.Input<string>;
/**
* The deletion date time of the source database. Only applies to deleted databases where `createMode` is `PointInTimeRestore`.
*/
sourceDatabaseDeletionDate?: pulumi.Input<string>;
/**
* The URI of the source database if `createMode` value is not `Default`.
*/
sourceDatabaseId?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Threat detection policy configuration. The `threatDetectionPolicy` block supports fields documented below.
*/
threatDetectionPolicy?: pulumi.Input<inputs.sql.DatabaseThreatDetectionPolicy>;
/**
* Whether or not this database is zone redundant, which means the replicas of this database will be spread across multiple availability zones.
*/
zoneRedundant?: pulumi.Input<boolean>;
}
/**
* The set of arguments for constructing a Database resource.
*/
export interface DatabaseArgs {
/**
* The name of the collation. Applies only if `createMode` is `Default`. Azure default is `SQL_LATIN1_GENERAL_CP1_CI_AS`. Changing this forces a new resource to be created.
*/
collation?: pulumi.Input<string>;
/**
* Specifies how to create the database. Valid values are: `Default`, `Copy`, `OnlineSecondary`, `NonReadableSecondary`, `PointInTimeRestore`, `Recovery`, `Restore` or `RestoreLongTermRetentionBackup`. Must be `Default` to create a new database. Defaults to `Default`. Please see [Azure SQL Database REST API](https://docs.microsoft.com/en-us/rest/api/sql/databases/createorupdate#createmode)
*/
createMode?: pulumi.Input<string>;
/**
* The edition of the database to be created. Applies only if `createMode` is `Default`. Valid values are: `Basic`, `Standard`, `Premium`, `DataWarehouse`, `Business`, `BusinessCritical`, `Free`, `GeneralPurpose`, `Hyperscale`, `Premium`, `PremiumRS`, `Standard`, `Stretch`, `System`, `System2`, or `Web`. Please see [Azure SQL Database Service Tiers](https://azure.microsoft.com/en-gb/documentation/articles/sql-database-service-tiers/).
*/
edition?: pulumi.Input<string>;
/**
* The name of the elastic database pool.
*/
elasticPoolName?: pulumi.Input<string>;
/**
* A `extendedAuditingPolicy` block as defined below.
*
* @deprecated the `extended_auditing_policy` block has been moved to `azurerm_mssql_server_extended_auditing_policy` and `azurerm_mssql_database_extended_auditing_policy`. This block will be removed in version 3.0 of the provider.
*/
extendedAuditingPolicy?: pulumi.Input<inputs.sql.DatabaseExtendedAuditingPolicy>;
/**
* A Database Import block as documented below. `createMode` must be set to `Default`.
*/
import?: pulumi.Input<inputs.sql.DatabaseImport>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* The maximum size that the database can grow to. Applies only if `createMode` is `Default`. Please see [Azure SQL Database Service Tiers](https://azure.microsoft.com/en-gb/documentation/articles/sql-database-service-tiers/).
*/
maxSizeBytes?: pulumi.Input<string>;
maxSizeGb?: pulumi.Input<string>;
/**
* The name of the database.
*/
name?: pulumi.Input<string>;
/**
* Read-only connections will be redirected to a high-available replica. Please see [Use read-only replicas to load-balance read-only query workloads](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out).
*/
readScale?: pulumi.Input<boolean>;
/**
* A GUID/UUID corresponding to a configured Service Level Objective for the Azure SQL database which can be used to configure a performance level.
* .
*/
requestedServiceObjectiveId?: pulumi.Input<string>;
/**
* The service objective name for the database. Valid values depend on edition and location and may include `S0`, `S1`, `S2`, `S3`, `P1`, `P2`, `P4`, `P6`, `P11` and `ElasticPool`. You can list the available names with the cli: `shell az sql db list-editions -l westus -o table`. For further information please see [Azure CLI - az sql db](https://docs.microsoft.com/en-us/cli/azure/sql/db?view=azure-cli-latest#az-sql-db-list-editions).
*/
requestedServiceObjectiveName?: pulumi.Input<string>;
/**
* The name of the resource group in which to create the database. This must be the same as Database Server resource group currently.
*/
resourceGroupName: pulumi.Input<string>;
/**
* The point in time for the restore. Only applies if `createMode` is `PointInTimeRestore` e.g. 2013-11-08T22:00:40Z
*/
restorePointInTime?: pulumi.Input<string>;
/**
* The name of the SQL Server on which to create the database.
*/
serverName: pulumi.Input<string>;
/**
* The deletion date time of the source database. Only applies to deleted databases where `createMode` is `PointInTimeRestore`.
*/
sourceDatabaseDeletionDate?: pulumi.Input<string>;
/**
* The URI of the source database if `createMode` value is not `Default`.
*/
sourceDatabaseId?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Threat detection policy configuration. The `threatDetectionPolicy` block supports fields documented below.
*/
threatDetectionPolicy?: pulumi.Input<inputs.sql.DatabaseThreatDetectionPolicy>;
/**
* Whether or not this database is zone redundant, which means the replicas of this database will be spread across multiple availability zones.
*/
zoneRedundant?: pulumi.Input<boolean>;
} | the_stack |
// This folder includes api convenience that we use for accessing
// MediaWiki Action API and REST API
import { wikiToDomain } from '@/shared/utility-shared';
import * as _ from 'underscore';
import update from 'immutability-helper';
const axios = require('axios');
const MAX_MWAPI_LIMIT:number = 50;
const userAgent = process.env.USER_AGENT || 'WikiLoop DoubleCheck Dev';
const Bottleneck = require('bottleneck');
const moreHeaders = {
// "Origin": "http://localhost:3000",
'Content-Type': 'application/json; charset=UTF-8',
};
/**
"pageid": 48410011,
"ns": 0,
"title": "2020 United States presidential election",
"type": "page",
"timestamp": "2020-03-28T19:51:23Z"
*/
export interface MwPageInfo {
pageid?:string,
ns?:string,
title?:string,
timestamp?:string,
}
/**
* MediaWiki Action API Client Utility
*
* TODO(xinbenlv): change to instance instead of static functions
*
* @doc https://www.mediawiki.org/wiki/API:Main_page
*/
export class MwActionApiClient {
private static bottleneck = new Bottleneck({
minTime: 100,
});
public static async getMwPageInfosByTitles(wiki:string, titles:string[]):Promise<MwPageInfo[]> {
console.assert(titles && titles.length > 0 && titles.length <= MAX_MWAPI_LIMIT, `Parameter titles needs to has a length between 1 to ${MAX_MWAPI_LIMIT}}, but was ${titles.length}.`);
const params = {
action: 'query',
format: 'json',
prop: 'pageprops',
titles: titles.join('|'),
};
const endpoint = `https://${wikiToDomain[wiki]}/w/api.php`;
const result = await MwActionApiClient.bottleneck.schedule(
async () => await axios.get(endpoint, { params, headers: { ...moreHeaders } }));
if (Object.keys(result.data.query?.pages).length) {
return Object.keys(result.data.query.pages).map((pageId) => {
return result.data.query.pages[pageId];
});
}
return [];
}
public static async getPageViewsByTitles(wiki:string, titles:string[], days:number = 60):Promise<object> {
console.assert(titles && titles.length > 0 && titles.length <= MAX_MWAPI_LIMIT, `Parameter titles needs to has a length between 1 to ${MAX_MWAPI_LIMIT}}, but was ${titles.length}.`);
const params =
{
action: 'query',
format: 'json',
prop: 'pageviews',
titles: titles.join('|'),
pvipdays: days,
};
const endpoint = `https://${wikiToDomain[wiki]}/w/api.php`;
const ret = {};
const result = await MwActionApiClient.bottleneck.schedule(
async () => await axios.get(endpoint, { params, headers: { 'User-Agent': userAgent } }));
console.assert(Object.keys(result.data.query?.pages).length === titles.length);
for (let i = 0; i < Object.keys(result.data.query.pages).length; i++) {
const pageId = Object.keys(result.data.query.pages)[i];
const pageviewsOfPage = result.data.query.pages[pageId].pageviews;
const title = result.data.query.pages[pageId].title;
let pageviewCount = 0;
if (pageviewsOfPage) {
pageviewCount = Object.values(pageviewsOfPage).reduce((a: number, b:number) => a + b, 0) as number;
}
ret[title] = pageviewCount;
}
return ret;
}
public static async getRevisionIdsByTitle(
wiki:string, pageTitle: string,
startRevId: number = null, limit:number = MAX_MWAPI_LIMIT):Promise<object> {
// TODO(xinbenlv) validate
// https://www.mediawiki.org/wiki/Special:ApiSandbox#action=query&format=json&prop=revisions&titles=API%3AGeosearch&rvprop=timestamp%7Cuser%7Ccomment%7Cids&rvslots=main&rvlimit=500&rvdir=older
const query: any = {
action: 'query',
format: 'json',
prop: 'revisions',
titles: pageTitle,
rvprop: 'ids',
rvslots: 'main',
rvlimit: limit,
rvdir: 'older',
};
if (startRevId) {query.rvstart = startRevId;}
const searchParams = new URLSearchParams(query);
const url = new URL(`https://${wikiToDomain[wiki]}/w/api.php?${searchParams.toString()}`);
console.log('Url = ', url);
try {
const revisionsJson = (await MwActionApiClient.bottleneck.schedule(async () => await axios.get(url.toString(), {
headers: { ...moreHeaders },
}))).data;
const pageId = Object.keys(revisionsJson.query.pages)[0];
if (revisionsJson.query.pages[pageId].revisions) {return revisionsJson.query.pages[pageId].revisions.map((item) => item.revid);} else {return [];}
} catch (e) {
console.warn(e);
return [];
}
}
/**
* Get the last-est revisions. This is the only endpoint where MediaWiki
* allows querying querying various pages.
*
* @params ctx see {@link getRawRecentChanges}
* @return raw object of recentChanges.
*/
public static getLatestRevisionIds = async function(ctx) {
const ctx2 = update(ctx, {
limit: { $set: MAX_MWAPI_LIMIT },
});
const raw = await MwActionApiClient.getRawRecentChanges(ctx2);
const revIds = raw.query.recentchanges.map((rc) => rc.revid);
return _.sample(revIds, ctx.limit);
};
/**
* Get the last-est revisions. This is the only endpoint where MediaWiki
* allows querying querying various pages.
*
* @params ctx see {@link getRawRecentChanges}
* @return raw object of recentChanges.
*/
public static getLatestOresRevisionIds = async function(ctx) {
const cloneCtx = { ...ctx };
cloneCtx.limit = MAX_MWAPI_LIMIT;
const raw = await MwActionApiClient.getRawRecentChanges(cloneCtx);
const result = raw.query.recentchanges
.filter((rc) =>
rc.oresscores.damaging && rc.oresscores.goodfaith &&
rc.oresscores.damaging.true >= 0.5 && rc.oresscores.goodfaith.false >= 0.5)
.map((rc) => rc.revid);
// TODO(xinbenlv): when we add test, allow deterministic behavior with seed.
return _.sample(result, ctx.limit);
};
/**
* Get the last-est revisions. This is the only endpoint where MediaWiki
* allows querying querying various pages.
* @param
* @returns raw object of recentChanges.
*/
public static getRawRecentChanges = async function({ wiki = 'enwiki', direction, timestamp, limit = 500, bad = false, isLast = false }) {
const searchParams = new URLSearchParams(
{
action: 'query',
format: 'json',
list: 'recentchanges',
formatversion: '2',
rcnamespace: '0',
rcprop: 'title|timestamp|ids|oresscores|flags|tags|sizes|comment|user',
rcshow: '!bot',
rclimit: '1',
rctype: 'edit',
rctoponly: '1',
origin: '*' // TODO(xinbenlv, #371): for some reason it doesn't work for wikidatawiki. We need to further debug it.
});
if (bad) {searchParams.set('rcshow', '!bot|oresreview');}
if (isLast) {searchParams.set('rctoponly', '1');}
if (direction) {searchParams.set('rcdir', direction || 'older');}
if (timestamp) {searchParams.set('rcstart', timestamp || (new Date().getTime() / 1000));}
searchParams.set('rclimit', limit.toString());
const url = new URL(`https://${wikiToDomain[wiki]}/w/api.php?${searchParams.toString()}`);
console.log(`Requesting ${wiki} for Media Action API: ${url.toString()}`);
console.log(`Try sandbox request here: ${new URL(`https://${wikiToDomain[wiki]}/wiki/Special:ApiSandbox#${searchParams.toString()}`)}`);
const response = await MwActionApiClient.bottleneck.schedule(async () => await axios.get(url.toString(), {
headers: { ...moreHeaders },
}));
const recentChangesJson = response.data;
/** Sample response
{
"batchcomplete":"",
"continue":{
"rccontinue":"20190701214931|1167038199",
"continue":"-||info"
},
"query":{
"recentchanges":[
{
"type":"edit",
"ns":0,
"title":"Multiprocessor system architecture",
"pageid":58955273,
"revid":904396518,
"old_revid":904395753,
"rcid":1167038198,
"user":"Dhtwiki",
"userid":9475572,
"timestamp":"2019-07-01T21:49:32Z",
"comment":"Putting images at bottom, side by side, to prevent impinging on References section"
}
// ...
]
}
} */
return recentChangesJson;
}
public static getLastRevisionsByTitles = async function(titles:string[], wiki = 'enwiki', rvcontinue = null) {
const query: any = {
action: 'query',
format: 'json',
prop: 'revisions',
titles: titles.join('|'),
rvprop: 'ids|timestamp|flags|comment|user|oresscores|tags|userid|roles|flagged',
};
if (rvcontinue) {
query.rvcontinue = rvcontinue;
}
const searchParams = new URLSearchParams(query);
const url = new URL(`https://${wikiToDomain[wiki]}/w/api.php?${searchParams.toString()}`);
return (await MwActionApiClient.bottleneck.schedule(async () => await axios.get(url.toString(), {
headers: { ...moreHeaders },
}))).data;
}
public static getDiffByWikiRevId = async function(wiki:string, revId:number) {
const query: any = {
action: 'compare',
format: 'json',
fromrev: `${revId}`,
torelative: 'prev',
origin: '*', // https://www.mediawiki.org/wiki/API:Cross-site_requests
};
const searchParams = new URLSearchParams(query);
const url = new URL(`https://${wikiToDomain[wiki]}/w/api.php?${searchParams.toString()}`);
const result = (await MwActionApiClient.bottleneck.schedule(async () => await axios.get(url.toString(), {
headers: { ...moreHeaders },
}))).data;
return result.compare['*'];
}
/**
* Given a wiki, using a title to get all it's category children
* please note this function handles the "continue" call to MediaWiki Action API
* it is in charge of making all follow up queries.
*
* @param wiki
* @param entryArticle
*/
public static getCategoryChildren = async function(wiki, entryArticle):Promise<MwPageInfo[]> {
const endpoint = `https://${wikiToDomain[wiki]}/w/api.php`;
const result = [];
const params = {
action: 'query',
format: 'json',
list: 'categorymembers',
formatversion: '2',
cmtitle: entryArticle,
cmprop: 'ids|timestamp|title',
cmnamespace: '0|14',
cmlimit: '500',
};
let ret = null;
do {
ret = await axios.get(endpoint, { params, headers: { ...moreHeaders } });
/** json
{
"batchcomplete": true,
"continue": {
"cmcontinue": "page|0f53aa04354b3131430443294f394543293f042d45435331434f394543011f01c4dcc1dcbedc0d|61561742",
"continue": "-||"
},
"query": {
"categorymembers": [
{
"pageid": 48410011,
"ns": 0,
"title": "2020 United States presidential election",
"timestamp": "2020-03-28T19:51:23Z"
}
],
}
}
*/
if (ret.data?.query?.categorymembers?.length > 0) {
ret.data.query.categorymembers.forEach((item) => console.log(`${JSON.stringify(item.title, null, 2)}`));
result.push(...ret.data.query.categorymembers);
if (ret.data?.continue?.cmcontinue) {(params as any).cmcontinue = ret.data.continue.cmcontinue;}
} else {
return result;
}
} while (ret.data?.continue?.cmcontinue);
return result;
}
/**
* Given a wiki, using a title to get all it's category children
* please note this function handles the "continue" call to MediaWiki Action API
* it is in charge of making all follow up queries.
*
* @param wiki
* @param entryArticle
*/
public static getLinkChildren = async function(wiki, entryArticle):Promise<string[]> {
try {
const endpoint = `https://${wikiToDomain[wiki]}/w/api.php`;
const result:string[] = [];
const params = {
action: 'query',
format: 'json',
prop: 'links',
formatversion: '2',
plnamespace: '0',
titles: entryArticle,
pllimit: '500',
};
let ret = null;
do {
ret = await axios.get(endpoint, { params, headers: { ...moreHeaders } });
/** json
{
"continue": {
"plcontinue": "9228|0|2010_TK7",
"continue": "||"
},
"query": {
"pages": {
"9228": {
"pageid": 9228,
"ns": 0,
"title": "Earth",
"links": [
{
"ns": 0,
"title": "2002 AA29"
},
{
"ns": 0,
"title": "2006 RH120"
}
]
}
}
}
}
*/
if (ret.data?.query?.pages && Object.keys(ret.data?.query?.pages).length === 1) {
const pageId = Object.keys(ret.data?.query?.pages)[0];
const links = ret.data.query.pages[pageId].links;
if (links) {result.push(...links.map((link) => link.title));}
if (ret.data?.continue?.plcontinue) {(params as any).plcontinue = ret.data.continue.plcontinue;} else {break;}
} else {
break;
}
} while (ret.data?.continue?.plcontinue);
return result;
} catch (e) {
console.warn(e);
return [];
}
}
} | the_stack |
import { arrayPickIndices, cantorPairing } from '../../mol-data/util';
import { LinkedIndex, SortedArray } from '../../mol-data/int';
import { AssignableArrayLike } from '../../mol-util/type-helpers';
/**
* Represent a graph using vertex adjacency list.
*
* Edges of the i-th vertex are stored in the arrays a and b
* for indices in the range [offset[i], offset[i+1]).
*
* Edge properties are indexed same as in the arrays a and b.
*/
export interface IntAdjacencyGraph<VertexIndex extends number, EdgeProps extends IntAdjacencyGraph.EdgePropsBase, Props = any> {
readonly offset: ArrayLike<number>,
readonly a: ArrayLike<VertexIndex>,
readonly b: ArrayLike<VertexIndex>,
readonly vertexCount: number,
readonly edgeCount: number,
readonly edgeProps: Readonly<EdgeProps>,
readonly props?: Props
/**
* Get the edge index between i-th and j-th vertex.
* -1 if the edge does not exist.
*
* Because the a and b arrays contains each edge twice,
* this always returns the smaller of the indices.
*
* `getEdgeIndex(i, j) === getEdgeIndex(j, i)`
*/
getEdgeIndex(i: VertexIndex, j: VertexIndex): number,
/**
* Get the edge index between i-th and j-th vertex.
* -1 if the edge does not exist.
*
* `getEdgeIndex(i, j) !== getEdgeIndex(j, i)`
*/
getDirectedEdgeIndex(i: VertexIndex, j: VertexIndex): number,
getVertexEdgeCount(i: VertexIndex): number
}
export namespace IntAdjacencyGraph {
export type EdgePropsBase = { [name: string]: ArrayLike<any> }
export function areEqual<I extends number, P extends IntAdjacencyGraph.EdgePropsBase>(a: IntAdjacencyGraph<I, P>, b: IntAdjacencyGraph<I, P>) {
if (a === b) return true;
if (a.vertexCount !== b.vertexCount || a.edgeCount !== b.edgeCount) return false;
const { a: aa, b: ab, offset: ao } = a;
const { a: ba, b: bb, offset: bo } = b;
for (let i = 0, _i = a.a.length; i < _i; i++) {
if (aa[i] !== ba[i]) return false;
}
for (let i = 0, _i = a.b.length; i < _i; i++) {
if (ab[i] !== bb[i]) return false;
}
for (let i = 0, _i = a.offset.length; i < _i; i++) {
if (ao[i] !== bo[i]) return false;
}
for (const k of Object.keys(a.edgeProps)) {
const pa = a.edgeProps[k], pb = b.edgeProps[k];
if (!pb) return false;
for (let i = 0, _i = pa.length; i < _i; i++) {
if (pa[i] !== pb[i]) return false;
}
}
return true;
}
class IntGraphImpl<VertexIndex extends number, EdgeProps extends IntAdjacencyGraph.EdgePropsBase, Props> implements IntAdjacencyGraph<VertexIndex, EdgeProps, Props> {
readonly vertexCount: number;
readonly edgeProps: EdgeProps;
getEdgeIndex(i: VertexIndex, j: VertexIndex): number {
let a, b;
if (i < j) {
a = i; b = j;
} else {
a = j; b = i;
}
for (let t = this.offset[a], _t = this.offset[a + 1]; t < _t; t++) {
if (this.b[t] === b) return t;
}
return -1;
}
getDirectedEdgeIndex(i: VertexIndex, j: VertexIndex): number {
for (let t = this.offset[i], _t = this.offset[i + 1]; t < _t; t++) {
if (this.b[t] === j) return t;
}
return -1;
}
getVertexEdgeCount(i: VertexIndex): number {
return this.offset[i + 1] - this.offset[i];
}
constructor(public offset: ArrayLike<number>, public a: ArrayLike<VertexIndex>, public b: ArrayLike<VertexIndex>, public edgeCount: number, edgeProps?: EdgeProps, public props?: Props) {
this.vertexCount = offset.length - 1;
this.edgeProps = (edgeProps || {}) as EdgeProps;
}
}
export function create<VertexIndex extends number, EdgeProps extends IntAdjacencyGraph.EdgePropsBase, Props>(offset: ArrayLike<number>, a: ArrayLike<VertexIndex>, b: ArrayLike<VertexIndex>, edgeCount: number, edgeProps?: EdgeProps, props?: Props): IntAdjacencyGraph<VertexIndex, EdgeProps, Props> {
return new IntGraphImpl(offset, a, b, edgeCount, edgeProps, props) as IntAdjacencyGraph<VertexIndex, EdgeProps, Props>;
}
export class EdgeBuilder<VertexIndex extends number> {
private bucketFill: Int32Array;
private current = 0;
private curA: number = 0;
private curB: number = 0;
offsets: Int32Array;
edgeCount: number;
/** the size of the A and B arrays */
slotCount: number;
a: AssignableArrayLike<VertexIndex>;
b: AssignableArrayLike<VertexIndex>;
createGraph<EdgeProps extends IntAdjacencyGraph.EdgePropsBase, Props>(edgeProps: EdgeProps, props?: Props) {
return create<VertexIndex, EdgeProps, Props>(this.offsets, this.a, this.b, this.edgeCount, edgeProps, props);
}
/**
* @example
* const property = new Int32Array(builder.slotCount);
* for (let i = 0; i < builder.edgeCount; i++) {
* builder.addNextEdge();
* builder.assignProperty(property, srcProp[i]);
* }
* return builder.createGraph({ property });
*/
addNextEdge() {
const a = this.xs[this.current], b = this.ys[this.current];
const oa = this.offsets[a] + this.bucketFill[a];
const ob = this.offsets[b] + this.bucketFill[b];
this.a[oa] = a;
this.b[oa] = b;
this.bucketFill[a]++;
this.a[ob] = b;
this.b[ob] = a;
this.bucketFill[b]++;
this.current++;
this.curA = oa;
this.curB = ob;
}
/** Builds property-less graph */
addAllEdges() {
for (let i = 0; i < this.edgeCount; i++) {
this.addNextEdge();
}
}
assignProperty<T>(prop: { [i: number]: T }, value: T) {
prop[this.curA] = value;
prop[this.curB] = value;
}
constructor(public vertexCount: number, public xs: ArrayLike<VertexIndex>, public ys: ArrayLike<VertexIndex>) {
this.edgeCount = xs.length;
this.offsets = new Int32Array(this.vertexCount + 1);
this.bucketFill = new Int32Array(this.vertexCount);
const bucketSizes = new Int32Array(this.vertexCount);
for (let i = 0, _i = this.xs.length; i < _i; i++) bucketSizes[this.xs[i]]++;
for (let i = 0, _i = this.ys.length; i < _i; i++) bucketSizes[this.ys[i]]++;
let offset = 0;
for (let i = 0; i < this.vertexCount; i++) {
this.offsets[i] = offset;
offset += bucketSizes[i];
}
this.offsets[this.vertexCount] = offset;
this.slotCount = offset;
this.a = new Int32Array(offset) as unknown as AssignableArrayLike<VertexIndex>;
this.b = new Int32Array(offset) as unknown as AssignableArrayLike<VertexIndex>;
}
}
export class DirectedEdgeBuilder<VertexIndex extends number> {
private bucketFill: Int32Array;
private current = 0;
private curA: number = 0;
offsets: Int32Array;
edgeCount: number;
/** the size of the A and B arrays */
slotCount: number;
a: Int32Array;
b: Int32Array;
createGraph<EdgeProps extends IntAdjacencyGraph.EdgePropsBase>(edgeProps: EdgeProps) {
return create(this.offsets, this.a, this.b, this.edgeCount, edgeProps);
}
/**
* @example
* const property = new Int32Array(builder.slotCount);
* for (let i = 0; i < builder.edgeCount; i++) {
* builder.addNextEdge();
* builder.assignProperty(property, srcProp[i]);
* }
* return builder.createGraph({ property });
*/
addNextEdge() {
const a = this.xs[this.current], b = this.ys[this.current];
const oa = this.offsets[a] + this.bucketFill[a];
this.a[oa] = a;
this.b[oa] = b;
this.bucketFill[a]++;
this.current++;
this.curA = oa;
}
/** Builds property-less graph */
addAllEdges() {
for (let i = 0; i < this.edgeCount; i++) {
this.addNextEdge();
}
}
assignProperty<T>(prop: { [i: number]: T }, value: T) {
prop[this.curA] = value;
}
constructor(public vertexCount: number, public xs: ArrayLike<VertexIndex>, public ys: ArrayLike<VertexIndex>) {
this.edgeCount = xs.length;
this.offsets = new Int32Array(this.vertexCount + 1);
this.bucketFill = new Int32Array(this.vertexCount);
const bucketSizes = new Int32Array(this.vertexCount);
for (let i = 0, _i = this.xs.length; i < _i; i++) bucketSizes[this.xs[i]]++;
let offset = 0;
for (let i = 0; i < this.vertexCount; i++) {
this.offsets[i] = offset;
offset += bucketSizes[i];
}
this.offsets[this.vertexCount] = offset;
this.slotCount = offset;
this.a = new Int32Array(offset);
this.b = new Int32Array(offset);
}
}
export class UniqueEdgeBuilder<VertexIndex extends number> {
private xs: VertexIndex[] = [];
private ys: VertexIndex[] = [];
private included = new Set<number>();
addEdge(i: VertexIndex, j: VertexIndex) {
let u = i, v = j;
if (i > j) { u = j; v = i; }
const id = cantorPairing(u, v);
if (this.included.has(id)) return false;
this.included.add(id);
this.xs[this.xs.length] = u;
this.ys[this.ys.length] = v;
return true;
}
getGraph(): IntAdjacencyGraph<VertexIndex, {}> {
return fromVertexPairs(this.vertexCount, this.xs, this.ys);
}
// if we cant to add custom props as well
getEdgeBuiler() {
return new EdgeBuilder(this.vertexCount, this.xs, this.ys);
}
constructor(public vertexCount: number) {
}
}
export function fromVertexPairs<V extends number>(vertexCount: number, xs: V[], ys: V[]) {
const graphBuilder = new IntAdjacencyGraph.EdgeBuilder(vertexCount, xs, ys);
graphBuilder.addAllEdges();
return graphBuilder.createGraph({});
}
export function induceByVertices<V extends number, P extends IntAdjacencyGraph.EdgePropsBase>(graph: IntAdjacencyGraph<V, P>, vertexIndices: ArrayLike<number>): IntAdjacencyGraph<V, P> {
const { b, offset, vertexCount, edgeProps } = graph;
const vertexMap = new Int32Array(vertexCount);
for (let i = 0, _i = vertexIndices.length; i < _i; i++) vertexMap[vertexIndices[i]] = i + 1;
let newEdgeCount = 0;
for (let i = 0; i < vertexCount; i++) {
if (vertexMap[i] === 0) continue;
for (let j = offset[i], _j = offset[i + 1]; j < _j; j++) {
if (b[j] > i && vertexMap[b[j]] !== 0) newEdgeCount++;
}
}
const newOffsets = new Int32Array(vertexIndices.length + 1);
const edgeIndices = new Int32Array(2 * newEdgeCount);
const newA = new Int32Array(2 * newEdgeCount) as unknown as AssignableArrayLike<V>;
const newB = new Int32Array(2 * newEdgeCount) as unknown as AssignableArrayLike<V>;
let eo = 0, vo = 0;
for (let i = 0; i < vertexCount; i++) {
if (vertexMap[i] === 0) continue;
const aa = vertexMap[i] - 1;
for (let j = offset[i], _j = offset[i + 1]; j < _j; j++) {
const bb = vertexMap[b[j]];
if (bb === 0) continue;
newA[eo] = aa as V;
newB[eo] = bb - 1 as V;
edgeIndices[eo] = j;
eo++;
}
newOffsets[++vo] = eo;
}
const newEdgeProps = {} as P;
for (const key of Object.keys(edgeProps) as (keyof P)[]) {
newEdgeProps[key] = arrayPickIndices(edgeProps[key], edgeIndices) as P[keyof P];
}
return create(newOffsets, newA, newB, newEdgeCount, newEdgeProps);
}
export function connectedComponents(graph: IntAdjacencyGraph<any, any>): { componentCount: number, componentIndex: Int32Array } {
const vCount = graph.vertexCount;
if (vCount === 0) return { componentCount: 0, componentIndex: new Int32Array(0) };
if (graph.edgeCount === 0) {
const componentIndex = new Int32Array(vCount);
for (let i = 0, _i = vCount; i < _i; i++) {
componentIndex[i] = i;
}
return { componentCount: vCount, componentIndex };
}
const componentIndex = new Int32Array(vCount);
for (let i = 0, _i = vCount; i < _i; i++) componentIndex[i] = -1;
let currentComponent = 0;
componentIndex[0] = currentComponent;
const { offset, b: neighbor } = graph;
const stack = [0];
const list = LinkedIndex(vCount);
list.remove(0);
while (stack.length > 0) {
const v = stack.pop()!;
const cIdx = componentIndex[v];
for (let eI = offset[v], _eI = offset[v + 1]; eI < _eI; eI++) {
const n = neighbor[eI];
if (!list.has(n)) continue;
list.remove(n);
stack.push(n);
componentIndex[n] = cIdx;
}
// check if we visited all vertices.
// If not, create a new component and continue.
if (stack.length === 0 && list.head >= 0) {
stack.push(list.head);
componentIndex[list.head] = ++currentComponent;
list.remove(list.head);
}
}
return { componentCount: vCount, componentIndex };
}
/**
* Check if any vertex in `verticesA` is connected to any vertex in `verticesB`
* via at most `maxDistance` edges.
*
* Returns true if verticesA and verticesB are intersecting.
*/
export function areVertexSetsConnected(graph: IntAdjacencyGraph<any, any>, verticesA: SortedArray<number>, verticesB: SortedArray<number>, maxDistance: number): boolean {
// check if A and B are intersecting, this handles maxDistance = 0
if (SortedArray.areIntersecting(verticesA, verticesB)) return true;
if (maxDistance < 1) return false;
const visited = new Set<number>();
for (let i = 0, il = verticesA.length; i < il; ++i) {
visited.add(verticesA[i]);
}
return areVertexSetsConnectedImpl(graph, verticesA, verticesB, maxDistance, visited);
}
}
function areVertexSetsConnectedImpl(graph: IntAdjacencyGraph<any, any>, frontier: ArrayLike<number>, target: SortedArray<number>, distance: number, visited: Set<number>): boolean {
const { b: neighbor, offset } = graph;
const newFrontier: number[] = [];
for (let i = 0, il = frontier.length; i < il; ++i) {
const src = frontier[i];
for (let j = offset[src], jl = offset[src + 1]; j < jl; ++j) {
const other = neighbor[j];
if (visited.has(other)) continue;
if (SortedArray.has(target, other)) return true;
visited.add(other);
newFrontier[newFrontier.length] = other;
}
}
return distance > 1 ? areVertexSetsConnectedImpl(graph, newFrontier, target, distance - 1, visited) : false;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.